diff --git a/neutrino-core/pom.xml b/neutrino-core/pom.xml deleted file mode 100644 index 759d652c..00000000 --- a/neutrino-core/pom.xml +++ /dev/null @@ -1,59 +0,0 @@ - - - - neutrino-proxy - fun.asgc.neutrino - ${revision} - ../pom.xml - - 4.0.0 - - neutrino-core - - - - io.netty - netty-all - - - commons-fileupload - commons-fileupload - - - org.yaml - snakeyaml - - - com.zaxxer - HikariCP - test - - - mysql - mysql-connector-java - test - - - org.xerial - sqlite-jdbc - test - - - org.apache.velocity - velocity-engine-core - 2.2 - - - org.dom4j - dom4j - 2.1.3 - - - org.quartz-scheduler - quartz - 2.3.1 - - - diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/Autowired.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/Autowired.java deleted file mode 100644 index dbb5cf77..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/Autowired.java +++ /dev/null @@ -1,43 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.annotation; - -import fun.asgc.neutrino.core.bean.BeanMatchMode; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -@Target({ElementType.FIELD, ElementType.PARAMETER}) -@Retention(RetentionPolicy.RUNTIME) -public @interface Autowired { - String value() default ""; - BeanMatchMode matchMode() default BeanMatchMode.ByTypeName; - Class[] parameterTypes() default {}; -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/Bean.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/Bean.java deleted file mode 100644 index dd3c9c64..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/Bean.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.annotation; - -import fun.asgc.neutrino.core.aop.support.Singleton; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.METHOD}) -@Singleton -public @interface Bean { - String value() default ""; -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/Component.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/Component.java deleted file mode 100644 index 023d0832..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/Component.java +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.annotation; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.TYPE) -public @interface Component { - String value() default ""; -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/Configuration.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/Configuration.java deleted file mode 100644 index 1f223fa2..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/Configuration.java +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.annotation; - -import java.lang.annotation.*; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -@Target(ElementType.TYPE) -@Retention(RetentionPolicy.RUNTIME) -@Component -@Documented -public @interface Configuration { - - /** - * 文件 - * @return - */ - String file() default ""; - - /** - * 前缀 - * @return - */ - String prefix() default ""; - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/Destroy.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/Destroy.java deleted file mode 100644 index 1ea7c5c8..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/Destroy.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.annotation; - -import java.lang.annotation.*; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.METHOD) -@Documented -public @interface Destroy { - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/EnableJob.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/EnableJob.java deleted file mode 100644 index db697d41..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/EnableJob.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.annotation; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * - * @author: 启用job - * @date: 2022/9/4 - */ -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.TYPE) -public @interface EnableJob { - boolean value() default true; -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/Init.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/Init.java deleted file mode 100644 index 4e404ae9..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/Init.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.annotation; - -import java.lang.annotation.*; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.METHOD) -@Documented -public @interface Init { - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/Lazy.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/Lazy.java deleted file mode 100644 index a48b6ed4..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/Lazy.java +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.annotation; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE,ElementType.METHOD}) -public @interface Lazy { - boolean value() default true; -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/Match.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/Match.java deleted file mode 100644 index fa08112d..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/Match.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.annotation; - -import java.lang.annotation.*; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -@Target({ElementType.TYPE}) -@Retention(RetentionPolicy.RUNTIME) -@Documented -public @interface Match { - String type(); -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/NeutrinoApplication.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/NeutrinoApplication.java deleted file mode 100644 index 34d7fdad..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/NeutrinoApplication.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.annotation; - -import java.lang.annotation.*; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -@Target(ElementType.TYPE) -@Retention(RetentionPolicy.RUNTIME) -@Documented -@Component -@NonIntercept -public @interface NeutrinoApplication { - String[] scanBasePackages() default {}; - String environmentVariableKey() default ""; -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/NonIntercept.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/NonIntercept.java deleted file mode 100644 index fff1f552..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/NonIntercept.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.annotation; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * 用于指定一个bean不需要拦截.这个标注只是一个建议 - * 1、bean是一个接口,将强制采用aop代理 - * 2、bean采用factoryBean实例化,由factoryBean决定是否代理 - * @author: aoshiguchen - * @date: 2022/7/4 - */ -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.TYPE) -public @interface NonIntercept { - boolean value() default true; -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/Order.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/Order.java deleted file mode 100644 index cd727fa3..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/Order.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.annotation; - -import java.lang.annotation.*; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD}) -@Documented -public @interface Order { - int value() default Integer.MAX_VALUE; -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/Param.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/Param.java deleted file mode 100644 index 728cf91e..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/Param.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.annotation; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * - * @author: aoshiguchen - * @date: 2022/8/6 - */ -@Target({ElementType.PARAMETER}) -@Retention(RetentionPolicy.RUNTIME) -public @interface Param { - String value() default ""; -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/PreLoad.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/PreLoad.java deleted file mode 100644 index f6961304..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/PreLoad.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.annotation; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/31 - */ -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.TYPE) -public @interface PreLoad { - String value() default "preLoad"; -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/Subscribe.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/Subscribe.java deleted file mode 100644 index eb29afbb..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/Subscribe.java +++ /dev/null @@ -1,18 +0,0 @@ -package fun.asgc.neutrino.core.annotation; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * @author: aoshiguchen - * @date: 2022/10/10 - */ -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.TYPE) -public @interface Subscribe { - boolean enable() default true; - String topic() default ""; - String[] tags() default {}; -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/Value.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/Value.java deleted file mode 100644 index 3eaea44b..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/annotation/Value.java +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.annotation; - -import java.lang.annotation.*; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -@Target(ElementType.FIELD) -@Retention(RetentionPolicy.RUNTIME) -@Documented -public @interface Value { - - String value() default ""; - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/Aop.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/Aop.java deleted file mode 100644 index ee47df7d..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/Aop.java +++ /dev/null @@ -1,163 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop; - -import fun.asgc.neutrino.core.aop.interceptor.Interceptor; -import fun.asgc.neutrino.core.aop.interceptor.InterceptorFactory; -import fun.asgc.neutrino.core.aop.proxy.Proxy; -import fun.asgc.neutrino.core.aop.proxy.ProxyFactory; -import fun.asgc.neutrino.core.cache.Cache; -import fun.asgc.neutrino.core.cache.MemoryCache; -import fun.asgc.neutrino.core.util.Assert; -import fun.asgc.neutrino.core.util.ClassUtil; -import fun.asgc.neutrino.core.util.LockUtil; - -import java.lang.reflect.Method; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/24 - */ -@SuppressWarnings("all") -public class Aop { - private static ProxyStrategy proxyStrategy = ProxyStrategy.AUTO; - private static final Cache, Object> proxyBeanCache = new MemoryCache<>(); - private static final Cache/*targetType*/, Cache/*proxyType*/, Object>> otherProxyBeanCache = new MemoryCache<>(); - - /** - * 被代理类型与代理类同源,即生成的代理类可以用被代理类的类型接收 - * @param clazz - * @param - * @return - * @throws Exception - */ - public static T get(Class clazz) throws Exception { - return (T)LockUtil.doubleCheckProcess(() -> !proxyBeanCache.containsKey(clazz), - clazz, - () -> proxyBeanCache.set(clazz, getProxyFactory(clazz).get(clazz)), - () -> proxyBeanCache.get(clazz) - ); - } - - /** - * 1、当且仅当被代理类型与代理类类型相等时,该方法与上面的方法等价 - * 2、否则,生成的代理类类型是被代理类的超类,也就是只代理超类的可代理方法 - * @param targetType - * @param proxyType - * @param - * @param

- * @return - * @throws Exception - */ - public static P get(Class targetType, Class

proxyType) throws Exception { - Assert.notNull(targetType, "被代理类类型不能为空!"); - Assert.notNull(proxyType, "代理类类型不能为空!"); - if (targetType == proxyType) { - return get(proxyType); - } - if (!proxyType.isAssignableFrom(targetType)) { - throw new RuntimeException(String.format("期望的代理类类型[%s]不是目标类型[%s]的超类!", proxyType.getName(), targetType.getName())); - } - return (P)LockUtil.doubleCheckProcess( - () -> !otherProxyBeanCache.containsKey(targetType) || !otherProxyBeanCache.get(targetType).containsKey(proxyType), - targetType, - () -> { - if (!otherProxyBeanCache.containsKey(targetType)) { - otherProxyBeanCache.set(targetType, new MemoryCache<>()); - } - otherProxyBeanCache.get(targetType).set(proxyType, getProxyFactory(targetType, proxyType).get(targetType, proxyType)); - }, - () -> otherProxyBeanCache.get(targetType).get(proxyType) - ); - } - - /** - * 获取代理工厂 - * 1、如果被代理类是一个接口,则采用jdk动态代理,减少避免不必要的字节码编译开销 - * 2、其他情况则采用子类代理(AsgcProxy) - * @return - */ - private static ProxyFactory getProxyFactory(Class clazz) { - if (proxyStrategy == ProxyStrategy.AUTO) { - if (ClassUtil.isInterface(clazz)) { - return Proxy.getProxyFactory(ProxyStrategy.JDK_DYNAMIC_PROXY); - } - return Proxy.getProxyFactory(ProxyStrategy.ASGC_PROXY); - } - return Proxy.getProxyFactory(proxyStrategy); - } - - /** - * 获取代理工厂 - * 1、如果被代理类是一个接口,则采用jdk动态代理,减少避免不必要的字节码编译开销 - * 2、其他情况则采用子类代理(AsgcProxy) - * @return - */ - private static ProxyFactory getProxyFactory(Class targetType, Class proxyType) { - if (targetType == proxyType) { - return getProxyFactory(targetType); - } - if (proxyStrategy == ProxyStrategy.AUTO) { - if (ClassUtil.isInterface(proxyType)) { - return Proxy.getProxyFactory(ProxyStrategy.JDK_DYNAMIC_PROXY); - } - return Proxy.getProxyFactory(ProxyStrategy.ASGC_PROXY); - } - return Proxy.getProxyFactory(proxyStrategy); - } - - /** - * 设置代理策略 - * @param proxyStrategy - */ - public static synchronized void setProxyStrategy(ProxyStrategy proxyStrategy) { - Assert.notNull(proxyStrategy, "代理策略不能为空!"); - Aop.proxyStrategy = proxyStrategy; - } - - /** - * 注册全局拦截器 - * @param clazz - */ - public static void intercept(Class interceptorType) { - InterceptorFactory.registerGlobalInterceptor(interceptorType); - } - - /** - * 注册类级别的拦截器 - * @param targetType - * @param interceptorType - */ - public static void intercept(Class targetType, Class interceptorType) { - InterceptorFactory.registerInterceptor(targetType, interceptorType); - } - - /** - * 注册方法级别的拦截器 - * @param targetMethod - * @param interceptorType - */ - public static void intercept(Method targetMethod, Class interceptorType) { - InterceptorFactory.registerInterceptor(targetMethod, interceptorType); - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/AopCallback.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/AopCallback.java deleted file mode 100644 index e8d14ff8..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/AopCallback.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop; - -/** - * aop回调 - * @author: aoshiguchen - * @date: 2022/6/30 - */ -@FunctionalInterface -public interface AopCallback { - /** - * 回调 - * @return - */ - T callback() throws Exception; -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/Intercept.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/Intercept.java deleted file mode 100644 index 676aa20f..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/Intercept.java +++ /dev/null @@ -1,76 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop; - -import fun.asgc.neutrino.core.aop.interceptor.ExceptionHandler; -import fun.asgc.neutrino.core.aop.interceptor.Filter; -import fun.asgc.neutrino.core.aop.interceptor.Interceptor; -import fun.asgc.neutrino.core.aop.interceptor.ResultAdvice; - -import java.lang.annotation.*; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/24 - */ -@Inherited -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE, ElementType.METHOD}) -public @interface Intercept { - /** - * 指定拦截器 - * @return - */ - Class[] value() default {}; - - /** - * 排除拦截器 - * @return - */ - Class[] exclude() default {}; - - /** - * 忽略一切全局拦截器 - * @return - */ - boolean ignoreGlobal() default false; - - /** - * 指定过滤器 - * @return - */ - Class[] filter() default {}; - - /** - * 指定异常处理器 - * @return - */ - Class[] exceptionHandler() default {}; - - /** - * 指定结果处理器 - * @return - */ - Class[] resultAdvice() default {}; -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/Invocation.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/Invocation.java deleted file mode 100644 index 86b1a96a..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/Invocation.java +++ /dev/null @@ -1,93 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop; - -import fun.asgc.neutrino.core.aop.interceptor.Interceptor; -import fun.asgc.neutrino.core.aop.interceptor.InterceptorFactory; -import fun.asgc.neutrino.core.aop.proxy.ProxyCache; -import fun.asgc.neutrino.core.util.CollectionUtil; -import fun.asgc.neutrino.core.util.TypeUtil; -import lombok.extern.slf4j.Slf4j; - -import java.lang.reflect.Method; -import java.util.List; -import java.util.function.Supplier; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/24 - */ -@Slf4j -public class Invocation { - private Class targetClass; - private Method targetMethod; - private Object proxy; - private AopCallback callback; - private Object[] args; - private List interceptors; - private volatile int index = 0; - private Object returnValue; - - public Invocation(Long methodId, Object proxy, AopCallback callback, Object... args) { - this.targetMethod = ProxyCache.getMethod(methodId); - this.targetClass = this.targetMethod.getDeclaringClass(); - this.proxy = proxy; - this.callback = callback; - this.args = args; - this.interceptors = InterceptorFactory.getListByTargetMethod(this.targetMethod); - this.returnValue = TypeUtil.getDefaultValue(this.targetMethod.getReturnType()); - } - - public void invoke() throws Exception { - if (CollectionUtil.notEmpty(this.interceptors) && index < this.interceptors.size()) { - this.interceptors.get(index++).intercept(this); - } else { - returnValue = callback.callback(); - returnValue = TypeUtil.conversion(returnValue, this.targetMethod.getReturnType()); - } - } - - public T getReturnValue() { - return (T)returnValue; - } - - public Class getReturnType() { - return targetMethod.getReturnType(); - } - - public void setReturnValue(Object returnValue) { - this.returnValue = returnValue; - } - - public Class getTargetClass() { - return targetClass; - } - - public Method getTargetMethod() { - return targetMethod; - } - - public Object[] getArgs() { - return args; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/ProxyStrategy.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/ProxyStrategy.java deleted file mode 100644 index 7c0da4f0..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/ProxyStrategy.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop; - -/** - * 代理策略 - * @author: aoshiguchen - * @date: 2022/6/24 - */ - -import lombok.AllArgsConstructor; -import lombok.Getter; - -@Getter -@AllArgsConstructor -@SuppressWarnings("all") -public enum ProxyStrategy { - // 在该模式下,代理策略由框架根据一定策略自动选择 - AUTO(0, "自动选择"), - JDK_DYNAMIC_PROXY(1, "JDK动态代理"), - ASGC_PROXY(2, "asgc子类代理"); - - private Integer strategy; - private String desc; -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/AsgcCompiler.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/AsgcCompiler.java deleted file mode 100644 index 503f7a55..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/AsgcCompiler.java +++ /dev/null @@ -1,350 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop.compiler; - -import com.google.common.collect.Lists; -import fun.asgc.neutrino.core.aop.compiler.internal.SpringBootJarClassLoader; -import fun.asgc.neutrino.core.base.GlobalConfig; -import fun.asgc.neutrino.core.util.CollectionUtil; -import fun.asgc.neutrino.core.util.FileUtil; -import fun.asgc.neutrino.core.util.SystemUtil; -import lombok.extern.slf4j.Slf4j; - -import javax.tools.*; -import java.io.File; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.*; -import java.util.stream.Collectors; - -/** - * asgc编译器 - * @author: aoshiguchen - * @date: 2022/8/17 - */ -@Slf4j -@SuppressWarnings("all") -public class AsgcCompiler { - private final JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler(); - private final DiagnosticCollector collector; - private final StandardJavaFileManager standardJavaFileManager; - private final List options = new ArrayList<>(); - private final List defaultClassPathList = new ArrayList<>(); - private final List classpathList = new ArrayList<>(); - private final Collection compilationUnits = new ArrayList(); - private boolean isSaveSourceCodeFile; - private boolean isSaveClassFile; - private String generatorCodeSavePath; - private DynamicClassLoader dynamicClassLoader; - private SpringBootJarClassLoader springBootJarClassLoader; - - private final List> errors = new ArrayList>(); - private final List> warnings = new ArrayList>(); - - /** - * 构造编译器 - */ - public AsgcCompiler() { - this(ClassLoader.getSystemClassLoader()); - } - - /** - * 构造编译器 - * @param classLoader - */ - public AsgcCompiler(ClassLoader classLoader) { - if (null == javaCompiler) { - throw new RuntimeException("Can not load JavaCompiler from javax.tools.ToolProvider#getSystemJavaCompiler(),\n please confirm the application running in JDK not JRE."); - } - this.springBootJarClassLoader = new SpringBootJarClassLoader(classLoader); -// if (SystemUtil.isStartupFromJar() && GlobalConfig.isIsUseSpringBootJar()) { -// try { -// log.debug("使用LaunchedURLClassLoader jar路径:{}", SystemUtil.getCurrentJarFilePath()); -// parent = new SpringBootJarClassLoader(classLoader); -// log.debug("使用LaunchedURLClassLoader instance:{}", parent); -// } catch (Exception e) { -// // ignore -// log.error("使用LaunchedURLClassLoader异常", e); -// } -// } - this.collector = new DiagnosticCollector<>(); - this.standardJavaFileManager = javaCompiler.getStandardFileManager(collector, null, null); - this.isSaveClassFile = false; - this.generatorCodeSavePath = GlobalConfig.getGeneratorCodeSavePath(); - this.dynamicClassLoader = new DynamicClassLoader(springBootJarClassLoader, this); - - addOption("-Xlint:unchecked"); - addOption("-implicit:class"); - addOption("-source", "1.8"); - addOption("-target", "1.8"); - } - - /** - * 添加类路径 - * @param classpath - */ - public void addClasspath(String classpath) { - if (this.classpathList.contains(classpath)) { - return; - } - this.classpathList.add(classpath); - } - - /** - * 设置是否保存类文件 - * @param saveClassFile - */ - public void setSaveClassFile(boolean saveClassFile) { - this.isSaveClassFile = saveClassFile; - } - - /** - * 设置是否保存源代码文件 - * @param saveSourceCodeFile - */ - public void setSaveSourceCodeFile(boolean saveSourceCodeFile) { - isSaveSourceCodeFile = saveSourceCodeFile; - } - - /** - * 设置保存代码路径 - * @param generatorCodeSavePath - */ - public void setGeneratorCodeSavePath(String generatorCodeSavePath) { - this.generatorCodeSavePath = generatorCodeSavePath; - } - - /** - * 获取options - * @return - */ - private List getOptions() { - List list = Lists.newArrayList(options); - List cp = getClasspathList(); - if (!CollectionUtil.isEmpty(cp)) { - list.add("-classpath"); - list.add(cp.stream().collect(Collectors.joining(File.pathSeparator))); - } - return list; - } - - /** - * 添加option - * @param option - */ - private void addOption(String option) { - this.options.add(option); - } - - /** - * 添加option - * @param key - * @param val - */ - private void addOption(String key, String val) { - this.options.add(key); - this.options.add(val); - } - - /** - * 添加源代码 - * @param className - * @param source - */ - private void addSource(String className, String source) { - addSource(new StringSource(className, source)); - } - - /** - * 添加源代码 - * @param javaFileObject - */ - private void addSource(JavaFileObject javaFileObject) { - compilationUnits.add(javaFileObject); - } - - public void addDependSpringBootJar(String path) { - try { - this.springBootJarClassLoader.addJar(path); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * 编译代码 - * @param className 类名 - * @param sourceCode 源代码 - */ - public Class compile(String className, String sourceCode) throws ClassNotFoundException { - log.info("options:" + getOptions()); - int index = className.lastIndexOf("."); - String pkg = ""; - String simpleClassName = className; - if (index >= 0) { - pkg = className.substring(0, index); - simpleClassName = className.substring(index + 1); - } - JavaFileManager javaFileManager = new DynamicJavaFileManager(standardJavaFileManager, dynamicClassLoader); - Iterable compilationUnits = Lists.newArrayList(new StringSource(className, sourceCode)); - if (GlobalConfig.isSaveGeneratorCode()) { - javaFileManager = standardJavaFileManager; - File file = FileUtil.save(GlobalConfig.getGeneratorCodeSavePath() + pkg.replaceAll("\\.", "/"), simpleClassName + ".java", sourceCode); - compilationUnits = standardJavaFileManager.getJavaFileObjects(file); - addClasspath(GlobalConfig.getGeneratorCodeSavePath()); - } - - Boolean result = javaCompiler.getTask(null, javaFileManager, collector, getOptions(), null, compilationUnits).call(); - if (!result || collector.getDiagnostics().size() > 0) { - if (!result || collector.getDiagnostics().size() > 0) { - for (Diagnostic diagnostic : collector.getDiagnostics()) { - switch (diagnostic.getKind()) { - case NOTE: - case MANDATORY_WARNING: - case WARNING: - warnings.add(diagnostic); - break; - case OTHER: - case ERROR: - default: - errors.add(diagnostic); - break; - } - } - - log(); - } - } - - return dynamicClassLoader.findClass(className); - } - - /** - * 获取编译诊断信息 - * @param diagnostics - * @return - */ - private List diagnosticToString(List> diagnostics) { - - List diagnosticMessages = new ArrayList(); - - for (Diagnostic diagnostic : diagnostics) { - diagnosticMessages.add( - "line: " + diagnostic.getLineNumber() + ", message: " + diagnostic.getMessage(Locale.US)); - } - - return diagnosticMessages; - - } - - /** - * 获取异常信息 - * @return - */ - public List getErrors() { - return diagnosticToString(errors); - } - - /** - * 获取警告信息 - * @return - */ - public List getWarnings() { - return diagnosticToString(warnings); - } - - /** - * 打印编译日志 - */ - private void log() { - List warnings = getWarnings(); - List errors = getErrors(); -// if (!CollectionUtil.isEmpty(warnings)) { -// log.warn(warnings.stream().collect(Collectors.joining())); -// } - if (!CollectionUtil.isEmpty(errors)) { - log.error(errors.stream().collect(Collectors.joining())); - } - } - - /** - * 获取URL类路径加载器 - * @return - */ - private URLClassLoader getURLClassLoader() { - ClassLoader ret = Thread.currentThread().getContextClassLoader(); - if (null == ret) { - ret = AsgcCompiler.class.getClassLoader(); - } - return (ret instanceof URLClassLoader) ? (URLClassLoader)ret : null; - } - - /** - * 获取类路径列表 - * @return - */ - public List getClasspathList() { - List classpathList = new ArrayList<>(); - List defaultClasspathList = getDefaultClasspathList(); - List customClasspathList = this.classpathList; - if (!CollectionUtil.isEmpty(defaultClasspathList)) { - classpathList.addAll(defaultClasspathList); - } - if (!CollectionUtil.isEmpty(customClasspathList)) { - classpathList.addAll(customClasspathList); - } - return classpathList; - } - - /** - * 获取默认的类路径列表 - * @return - */ - private synchronized List getDefaultClasspathList() { - if (!CollectionUtil.isEmpty(defaultClassPathList)) { - return defaultClassPathList; - } - URLClassLoader classLoader = getURLClassLoader(); - if (null == classLoader) { - return defaultClassPathList; - } - - boolean isWindows = SystemUtil.isWindows(); - for (URL url : classLoader.getURLs()) { - String path = url.getFile(); - - // 如果是 windows 系统,去除前缀字符 '/' - if (isWindows && path.startsWith("/")) { - path = path.substring(1); - } - - // 去除后缀字符 '/' - if (path.length() > 1 && (path.endsWith("/") || path.endsWith(File.separator))) { - path = path.substring(0, path.length() - 1); - } - - defaultClassPathList.add(path); - } - - return defaultClassPathList; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/CustomJavaFileObject.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/CustomJavaFileObject.java deleted file mode 100644 index 5423370f..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/CustomJavaFileObject.java +++ /dev/null @@ -1,128 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop.compiler; - -import fun.asgc.neutrino.core.aop.compiler.internal.SpringBootJarParser; - -import javax.lang.model.element.Modifier; -import javax.lang.model.element.NestingKind; -import javax.tools.JavaFileObject; -import java.io.*; -import java.net.URI; - -/** - * 自定义java文件对象 - * @author: aoshiguchen - * @date: 2022/8/25 - */ -public class CustomJavaFileObject implements JavaFileObject { - private final String binaryName; - private final URI uri; - private final String name; - - public CustomJavaFileObject(String binaryName, URI uri) { - this.uri = uri; - this.binaryName = binaryName; - name = uri.getPath() == null ? uri.getSchemeSpecificPart() : uri.getPath(); // for FS based URI the path is not null, for JAR URI the scheme specific part is not null - } - - @Override - public URI toUri() { - return uri; - } - - @Override - public InputStream openInputStream() throws IOException { - InputStream in = SpringBootJarParser.getInputStream(uri); - if (null != in) { - return in; - } - return uri.toURL().openStream(); - } - - @Override - public OutputStream openOutputStream() { - throw new UnsupportedOperationException(); - } - - @Override - public String getName() { - return name; - } - - @Override - public Reader openReader(boolean ignoreEncodingErrors) { - throw new UnsupportedOperationException(); - } - - @Override - public CharSequence getCharContent(boolean ignoreEncodingErrors) { - throw new UnsupportedOperationException(); - } - - @Override - public Writer openWriter() throws IOException { - throw new UnsupportedOperationException(); - } - - @Override - public long getLastModified() { - return 0; - } - - @Override - public boolean delete() { - throw new UnsupportedOperationException(); - } - - @Override - public Kind getKind() { - return Kind.CLASS; - } - - @Override - public boolean isNameCompatible(String simpleName, Kind kind) { - String baseName = simpleName + kind.extension; - return kind.equals(getKind()) - && (baseName.equals(getName()) - || getName().endsWith("/" + baseName)); - } - - @Override - public NestingKind getNestingKind() { - throw new UnsupportedOperationException(); - } - - @Override - public Modifier getAccessLevel() { - throw new UnsupportedOperationException(); - } - - public String binaryName() { - return binaryName; - } - - @Override - public String toString() { - return this.getClass().getName() + "[" + this.toUri() + "]"; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/DynamicClassLoader.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/DynamicClassLoader.java deleted file mode 100644 index d25ed611..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/DynamicClassLoader.java +++ /dev/null @@ -1,193 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop.compiler; - -import fun.asgc.neutrino.core.util.ArrayUtil; -import fun.asgc.neutrino.core.util.CollectionUtil; -import fun.asgc.neutrino.core.util.FileUtil; - -import java.io.File; -import java.io.FileFilter; -import java.io.IOException; -import java.net.JarURLConnection; -import java.net.URISyntaxException; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.*; -import java.util.jar.JarEntry; -import java.util.jar.JarFile; - -/** - * 动态类加载器 - * @author: aoshiguchen - * @date: 2022/8/25 - */ -public class DynamicClassLoader extends ClassLoader { - private final Map byteCodes = new HashMap<>(); - private AsgcCompiler compiler; - private Map> classMap = new HashMap<>(); - - public DynamicClassLoader(ClassLoader classLoader) { - super(classLoader); - } - - public DynamicClassLoader(ClassLoader classLoader, AsgcCompiler compiler) { - super(classLoader); - this.compiler = compiler; - } - - public void registerCompiledSource(MemoryByteCode byteCode) { - byteCodes.put(byteCode.getClassName(), byteCode); - } - - @Override - protected Class findClass(String name) throws ClassNotFoundException { - if (classMap.containsKey(name)) { - return classMap.get(name); - } - MemoryByteCode byteCode = byteCodes.get(name); - if (null != byteCode) { - return super.defineClass(name, byteCode.getByteCode(), 0, byteCode.getByteCode().length); - } - if (null != this.compiler) { - Class ret = doFindClass(name, compiler.getClasspathList()); - if (null != ret) { - return ret; - } - } - return super.findClass(name); - } - - private Class doFindClass(String name, List classpathList) throws ClassNotFoundException { - if (CollectionUtil.isEmpty(classpathList)) { - return null; - } - String packageName = ""; - if (name.lastIndexOf(".") != -1) { - packageName = name.substring(0, name.lastIndexOf(".")); - } - for (String path : classpathList) { - try { - URL url = new URL("file:" + path); - if (path.endsWith(".jar")) { - url = new URL("jar:file:" + path + "!/"); - } - Set> classSet = scan(packageName, url); - if (CollectionUtil.isEmpty(classSet)) { - continue; - } - Optional> classOptional = classSet.stream().filter(c -> c.getName().equals(name)).findFirst(); - if (classOptional.isPresent()) { - return classOptional.get(); - } - } catch (Exception e) { - // ignore - } - } - return null; - } - - public Set> scan(String packageName, URL url) throws IOException, ClassNotFoundException, URISyntaxException { - Set> result = new HashSet<>(); - if (null == url) { - return result; - } - String packagePath = packageName.replace(".", "/"); - URLClassLoader urlClassLoader = new URLClassLoader(new URL[]{url}, Thread.currentThread().getContextClassLoader()); - String protocol = url.getProtocol(); - if ("jar".equals(protocol)) { - JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection(); - JarFile jarFile = jarURLConnection.getJarFile(); - Enumeration entries = jarFile.entries(); - while (entries.hasMoreElements()) { - JarEntry jarEntry = entries.nextElement(); - String name = jarEntry.getName(); - int index = name.indexOf(packagePath); - if (index != -1 && name.endsWith(".class")) { - String replace = name.substring(index, name.length() - 6).replace("/", "."); - Class clazz = urlClassLoader.loadClass(replace); - result.add(clazz); - } - } - } else if ("file".endsWith(protocol)) { - String path = url.getPath(); - String targetPath = path + "/" + packagePath; - addClasses(targetPath, result, packageName); - } - return result; - } - - private synchronized void addClasses(String path, Set> classes, String packageName) throws ClassNotFoundException, URISyntaxException { - File[] files = new File(path).listFiles(new FileFilter() { - @Override - public boolean accept(File file) { - return (file.isFile() && file.getName().endsWith(".class")) || file.isDirectory(); - } - }); - if (ArrayUtil.isEmpty(files)) { - return; - } - - for (File file : files) { - String fileName = file.getName(); - if (file.isFile()) { - String className = fileName.substring(0, fileName.lastIndexOf(".")); - String fullClassName = packageName + "." + className; - Class clazz = null; - try { - clazz = Thread.currentThread().getContextClassLoader().loadClass(fullClassName); - } catch (ClassNotFoundException e) { - if (this.classMap.containsKey(fullClassName)) { - clazz = this.classMap.get(fileName); - } else { - byte[] byteCode = FileUtil.readBytes(file); - clazz = super.defineClass(fullClassName, byteCode, 0, byteCode.length); - this.classMap.put(fullClassName, clazz); - } - } - if (null != clazz) { - classes.add(clazz); - } - } else { - String subPackagePath = path + "/" + fileName; - String subPackageName = packageName + "." + fileName; - addClasses(subPackagePath, classes, subPackageName); - } - } - } - - public Map> getClasses() throws ClassNotFoundException { - Map> classes = new HashMap<>(); - for (MemoryByteCode byteCode : byteCodes.values()) { - classes.put(byteCode.getClassName(), findClass(byteCode.getClassName())); - } - return classes; - } - - public Map getByteCodes() { - Map result = new HashMap<>(byteCodes.size()); - for (Map.Entry entry : byteCodes.entrySet()) { - result.put(entry.getKey(), entry.getValue().getByteCode()); - } - return result; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/DynamicJavaFileManager.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/DynamicJavaFileManager.java deleted file mode 100644 index a42b66e1..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/DynamicJavaFileManager.java +++ /dev/null @@ -1,142 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop.compiler; - -import javax.tools.*; -import java.io.IOException; -import java.util.*; - -/** - * 动态java文件管理器 - * @author: aoshiguchen - * @date: 2022/8/17 - */ -public class DynamicJavaFileManager extends ForwardingJavaFileManager { - private static final String[] superLocationNames = { StandardLocation.PLATFORM_CLASS_PATH.name(), - /** JPMS StandardLocation.SYSTEM_MODULES **/ - "SYSTEM_MODULES" }; - private final PackageInternalsFinder finder; - private final DynamicClassLoader classLoader; - private final List byteCodes = new ArrayList(); - - public DynamicJavaFileManager(JavaFileManager fileManager, DynamicClassLoader classLoader) { - super(fileManager); - this.classLoader = classLoader; - this.finder = new PackageInternalsFinder(classLoader); - } - - @Override - public JavaFileObject getJavaFileForOutput(JavaFileManager.Location location, String className, - JavaFileObject.Kind kind, FileObject sibling) throws IOException { - - for (MemoryByteCode byteCode : byteCodes) { - if (byteCode.getClassName().equals(className)) { - return byteCode; - } - } - - MemoryByteCode innerClass = new MemoryByteCode(className); - byteCodes.add(innerClass); - classLoader.registerCompiledSource(innerClass); - return innerClass; - - } - @Override - public ClassLoader getClassLoader(JavaFileManager.Location location) { - return classLoader; - } - - @Override - public String inferBinaryName(Location location, JavaFileObject file) { - if (file instanceof CustomJavaFileObject) { - return ((CustomJavaFileObject) file).binaryName(); - } else { - /** - * if it's not CustomJavaFileObject, then it's coming from standard file manager - * - let it handle the file - */ - return super.inferBinaryName(location, file); - } - } - - @Override - public Iterable list(Location location, String packageName, Set kinds, - boolean recurse) throws IOException { - if (location instanceof StandardLocation) { - String locationName = ((StandardLocation) location).name(); - for (String name : superLocationNames) { - if (name.equals(locationName)) { - return super.list(location, packageName, kinds, recurse); - } - } - } - - // merge JavaFileObjects from specified ClassLoader - if (location == StandardLocation.CLASS_PATH && kinds.contains(JavaFileObject.Kind.CLASS)) { - return new IterableJoin<>(super.list(location, packageName, kinds, recurse), - finder.find(packageName)); - } - - return super.list(location, packageName, kinds, recurse); - } - - static class IterableJoin implements Iterable { - private final Iterable first, next; - - public IterableJoin(Iterable first, Iterable next) { - this.first = first; - this.next = next; - } - - @Override - public Iterator iterator() { - return new IteratorJoin(first.iterator(), next.iterator()); - } - } - - static class IteratorJoin implements Iterator { - private final Iterator first, next; - - public IteratorJoin(Iterator first, Iterator next) { - this.first = first; - this.next = next; - } - - @Override - public boolean hasNext() { - return first.hasNext() || next.hasNext(); - } - - @Override - public T next() { - if (first.hasNext()) { - return first.next(); - } - return next.next(); - } - - @Override - public void remove() { - throw new UnsupportedOperationException("remove"); - } - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/MemoryByteCode.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/MemoryByteCode.java deleted file mode 100644 index 16f3b363..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/MemoryByteCode.java +++ /dev/null @@ -1,80 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop.compiler; - -import javax.tools.SimpleJavaFileObject; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.net.URI; -import java.net.URISyntaxException; - -/** - * 内存字节码 - * @author: aoshiguchen - * @date: 2022/8/25 - */ -public class MemoryByteCode extends SimpleJavaFileObject { - private static final char PKG_SEPARATOR = '.'; - private static final char DIR_SEPARATOR = '/'; - private static final String CLASS_FILE_SUFFIX = ".class"; - - private ByteArrayOutputStream byteArrayOutputStream; - private byte[] byteCode; - - public MemoryByteCode(String className) { - super(URI.create("byte:///" + className.replace(PKG_SEPARATOR, DIR_SEPARATOR) - + Kind.CLASS.extension), Kind.CLASS); - } - - public MemoryByteCode(String className, ByteArrayOutputStream byteArrayOutputStream) - throws URISyntaxException { - this(className); - this.byteArrayOutputStream = byteArrayOutputStream; - } - - public MemoryByteCode(String className, byte[] byteCode) - throws URISyntaxException { - this(className); - this.byteCode = byteCode; - } - - @Override - public OutputStream openOutputStream() throws IOException { - if (byteArrayOutputStream == null) { - byteArrayOutputStream = new ByteArrayOutputStream(); - } - return byteArrayOutputStream; - } - - public byte[] getByteCode() { - return null == byteCode ? byteArrayOutputStream.toByteArray() : byteCode; - } - - public String getClassName() { - String className = getName(); - className = className.replace(DIR_SEPARATOR, PKG_SEPARATOR); - className = className.substring(1, className.indexOf(CLASS_FILE_SUFFIX)); - return className; - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/PackageInternalsFinder.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/PackageInternalsFinder.java deleted file mode 100644 index 24c65628..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/PackageInternalsFinder.java +++ /dev/null @@ -1,130 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop.compiler; - -import javax.tools.JavaFileObject; -import java.io.File; -import java.io.IOException; -import java.net.JarURLConnection; -import java.net.URI; -import java.net.URL; -import java.net.URLDecoder; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Enumeration; -import java.util.List; -import java.util.jar.JarEntry; - -/** - * 包内部查询器 - * @author: aoshiguchen - * @date: 2022/8/25 - */ -public class PackageInternalsFinder { - private final ClassLoader classLoader; - private static final String CLASS_FILE_EXTENSION = ".class"; - - public PackageInternalsFinder(ClassLoader classLoader) { - this.classLoader = classLoader; - } - - public List find(String packageName) throws IOException { - String javaPackageName = packageName.replaceAll("\\.", "/"); - - List result = new ArrayList<>(); - - Enumeration urlEnumeration = classLoader.getResources(javaPackageName); - while (urlEnumeration.hasMoreElements()) { // one URL for each jar on the classpath that has the given package - URL packageFolderURL = urlEnumeration.nextElement(); - result.addAll(listUnder(packageName, packageFolderURL)); - } - - return result; - } - - private Collection listUnder(String packageName, URL packageFolderURL) { - File directory = new File(decode(packageFolderURL.getFile())); - if (directory.isDirectory()) { // browse local .class files - useful for local execution - return processDir(packageName, directory); - } else { // browse a jar file - return processJar(packageFolderURL); - } // maybe there can be something else for more involved class loaders - } - - private List processJar(URL packageFolderURL) { - List result = new ArrayList(); - try { - String jarUri = packageFolderURL.toExternalForm().substring(0, packageFolderURL.toExternalForm().lastIndexOf("!/")); - - JarURLConnection jarConn = (JarURLConnection) packageFolderURL.openConnection(); - String rootEntryName = jarConn.getEntryName(); - int rootEnd = rootEntryName.length() + 1; - - Enumeration entryEnum = jarConn.getJarFile().entries(); - while (entryEnum.hasMoreElements()) { - JarEntry jarEntry = entryEnum.nextElement(); - String name = jarEntry.getName(); - if (name.startsWith(rootEntryName) && name.indexOf('/', rootEnd) == -1 && name.endsWith(CLASS_FILE_EXTENSION)) { - URI uri = URI.create(jarUri + "!/" + name); - String binaryName = name.replaceAll("/", "."); - binaryName = binaryName.replaceAll(CLASS_FILE_EXTENSION + "$", ""); - - result.add(new CustomJavaFileObject(binaryName, uri)); - } - } - } catch (Exception e) { - throw new RuntimeException("Wasn't able to open " + packageFolderURL + " as a jar file", e); - } - return result; - } - - private List processDir(String packageName, File directory) { - List result = new ArrayList(); - - File[] childFiles = directory.listFiles(); - if (childFiles != null) { - for (File childFile : childFiles) { - if (childFile.isFile()) { - // We only want the .class files. - if (childFile.getName().endsWith(CLASS_FILE_EXTENSION)) { - String binaryName = packageName + "." + childFile.getName(); - binaryName = binaryName.replaceAll(CLASS_FILE_EXTENSION + "$", ""); - - result.add(new CustomJavaFileObject(binaryName, childFile.toURI())); - } - } - } - } - - return result; - } - - private String decode(String filePath) { - try { - return URLDecoder.decode(filePath, "utf-8"); - } catch (Exception e) { - // ignore, return original string - } - - return filePath; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/StringSource.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/StringSource.java deleted file mode 100644 index a6f3ad18..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/StringSource.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop.compiler; - -import javax.tools.SimpleJavaFileObject; -import java.io.IOException; -import java.net.URI; - -/** - * 字符串源码 - * @author: aoshiguchen - * @date: 2022/8/25 - */ -public class StringSource extends SimpleJavaFileObject { - private final String contents; - - public StringSource(String className, String contents) { - super(URI.create("string:///" + className.replace('.', '/') + Kind.SOURCE.extension), Kind.SOURCE); - this.contents = contents; - } - - @Override - public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { - return contents; - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/SpringBootJarClassLoader.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/SpringBootJarClassLoader.java deleted file mode 100644 index b4ab6421..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/SpringBootJarClassLoader.java +++ /dev/null @@ -1,109 +0,0 @@ -package fun.asgc.neutrino.core.aop.compiler.internal; - - -import fun.asgc.neutrino.core.aop.compiler.internal.archive.Archive; -import fun.asgc.neutrino.core.aop.compiler.internal.archive.JarFileArchive; - -import java.io.File; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -/** - * {@link ClassLoader} used by the {@link Launcher}. - * - * @author Phillip Webb - * @author Dave Syer - * @author Andy Wilkinson - * @since 1.0.0 - */ -public class SpringBootJarClassLoader extends URLClassLoader { - protected static final String BOOT_CLASSPATH_INDEX_ATTRIBUTE = "Spring-Boot-Classpath-Index"; - protected static final String DEFAULT_CLASSPATH_INDEX_FILE_NAME = "classpath.idx"; - - static { - ClassLoader.registerAsParallelCapable(); - } - - /** - * Create a new {@link SpringBootJarClassLoader} instance. - * @param parent the parent class loader for delegation - */ - public SpringBootJarClassLoader(ClassLoader parent) { - super(new URL[0], parent); - } - - /** - * Create a new {@link SpringBootJarClassLoader} instance. - */ - public SpringBootJarClassLoader() { - super(new URL[0], ClassLoader.getSystemClassLoader()); - } - - public void addJar(String path) throws Exception { - Archive archive = createArchive(path); - Iterator archives = getClassPathArchivesIterator(archive); - List urls = new ArrayList<>(50); - while (archives.hasNext()) { - urls.add(archives.next().getUrl()); - } - urls.forEach(url -> addURL(url)); - } - - private Archive createArchive(String path) throws Exception { - if (path == null) { - throw new IllegalStateException("Unable to determine code source archive"); - } - File root = new File(path); - if (!root.exists()) { - throw new IllegalStateException("Unable to determine code source archive from " + root); - } - return new JarFileArchive(root); - } - - protected Iterator getClassPathArchivesIterator(Archive archive) throws Exception { - Archive.EntryFilter searchFilter = this::isSearchCandidate; - Iterator archives = archive.getNestedArchives(searchFilter, - (entry) -> isNestedArchive(entry)); - archives = applyClassPathArchivePostProcessing(archives); - return archives; - } - - private Iterator applyClassPathArchivePostProcessing(Iterator archives) throws Exception { - List list = new ArrayList<>(); - while (archives.hasNext()) { - list.add(archives.next()); - } - return list.iterator(); - } - - static final Archive.EntryFilter NESTED_ARCHIVE_ENTRY_FILTER = (entry) -> { - if (entry.isDirectory()) { - return entry.getName().equals("BOOT-INF/classes/"); - } - return entry.getName().startsWith("BOOT-INF/lib/"); - }; - - protected boolean isNestedArchive(Archive.Entry entry) { - return NESTED_ARCHIVE_ENTRY_FILTER.matches(entry); - } - - /** - * Determine if the specified entry is a candidate for further searching. - * @param entry the entry to check - * @return {@code true} if the entry is a candidate for further searching - * @since 2.3.0 - */ - protected boolean isSearchCandidate(Archive.Entry entry) { - if (getArchiveEntryPathPrefix() == null) { - return true; - } - return entry.getName().startsWith(getArchiveEntryPathPrefix()); - } - - protected String getArchiveEntryPathPrefix() { - return "BOOT-INF/"; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/SpringBootJarParser.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/SpringBootJarParser.java deleted file mode 100644 index 6f0a380a..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/SpringBootJarParser.java +++ /dev/null @@ -1,48 +0,0 @@ -package fun.asgc.neutrino.core.aop.compiler.internal; - -import fun.asgc.neutrino.core.aop.compiler.internal.jar.JarFile; -import fun.asgc.neutrino.core.aop.compiler.internal.jar.JarURLConnection; - -import java.io.File; -import java.io.InputStream; -import java.net.URI; -import java.net.URL; - -/** - * @author: aoshiguchen - * @date: 2023/2/23 - */ -public final class SpringBootJarParser { - - /** - * 根据一个URI从SpringBoot jar包中解析出输入流 - * 1、先尝试直接获取流,若能获取则到此结束 - * 2、若不能获取,且URI标识定位的是一个jar包,则进行处理(只处理SpringBoot情况的jar) - * @param uri - * @return - */ - public static InputStream getInputStream(URI uri) { - try { - return uri.toURL().openStream(); - } catch (Exception e) { - try { - if (uri.getScheme().equals("jar")) { - URL url = uri.toURL(); - String path = url.getPath(); - int index = path.indexOf("!"); - if (index >= 0) { - path = path.substring(0, index); - } - if (path.startsWith("file:")) { - path = path.substring(5); - } - JarFile jarFile = new JarFile(new File(path)); - return JarURLConnection.get(url, jarFile).getInputStream(); - } - } catch (Exception e1) { - // ignore - } - } - return null; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/archive/Archive.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/archive/Archive.java deleted file mode 100644 index 9be22c70..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/archive/Archive.java +++ /dev/null @@ -1,97 +0,0 @@ -package fun.asgc.neutrino.core.aop.compiler.internal.archive; - -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Iterator; -import java.util.jar.Manifest; - -/** - * An archive that can be launched by the {@link Launcher}. - * - * @author Phillip Webb - * @since 1.0.0 - * @see JarFileArchive - */ -public interface Archive extends Iterable, AutoCloseable { - - /** - * Returns a URL that can be used to load the archive. - * @return the archive URL - * @throws MalformedURLException if the URL is malformed - */ - URL getUrl() throws MalformedURLException; - - /** - * Returns the manifest of the archive. - * @return the manifest - * @throws IOException if the manifest cannot be read - */ - Manifest getManifest() throws IOException; - - /** - * Returns nested {@link Archive}s for entries that match the specified filters. - * @param searchFilter filter used to limit when additional sub-entry searching is - * required or {@code null} if all entries should be considered. - * @param includeFilter filter used to determine which entries should be included in - * the result or {@code null} if all entries should be included - * @return the nested archives - * @throws IOException on IO error - * @since 2.3.0 - */ - Iterator getNestedArchives(EntryFilter searchFilter, EntryFilter includeFilter) throws IOException; - - /** - * Return if the archive is exploded (already unpacked). - * @return if the archive is exploded - * @since 2.3.0 - */ - default boolean isExploded() { - return false; - } - - /** - * Closes the {@code Archive}, releasing any open resources. - * @throws Exception if an error occurs during close processing - * @since 2.2.0 - */ - @Override - default void close() throws Exception { - - } - - /** - * Represents a single entry in the archive. - */ - interface Entry { - - /** - * Returns {@code true} if the entry represents a directory. - * @return if the entry is a directory - */ - boolean isDirectory(); - - /** - * Returns the name of the entry. - * @return the name of the entry - */ - String getName(); - - } - - /** - * Strategy interface to filter {@link Entry Entries}. - */ - @FunctionalInterface - interface EntryFilter { - - /** - * Apply the jar entry filter. - * @param entry the entry to filter - * @return {@code true} if the filter matches - */ - boolean matches(Entry entry); - - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/archive/ExplodedArchive.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/archive/ExplodedArchive.java deleted file mode 100644 index 3377a110..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/archive/ExplodedArchive.java +++ /dev/null @@ -1,318 +0,0 @@ -package fun.asgc.neutrino.core.aop.compiler.internal.archive; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URL; -import java.util.*; -import java.util.jar.Manifest; - -/** - * {@link Archive} implementation backed by an exploded archive directory. - * - * @author Phillip Webb - * @author Andy Wilkinson - * @author Madhura Bhave - * @since 1.0.0 - */ -public class ExplodedArchive implements Archive { - - private static final Set SKIPPED_NAMES = new HashSet<>(Arrays.asList(".", "..")); - - private final File root; - - private final boolean recursive; - - private final File manifestFile; - - private Manifest manifest; - - /** - * Create a new {@link ExplodedArchive} instance. - * @param root the root directory - */ - public ExplodedArchive(File root) { - this(root, true); - } - - /** - * Create a new {@link ExplodedArchive} instance. - * @param root the root directory - * @param recursive if recursive searching should be used to locate the manifest. - * Defaults to {@code true}, directories with a large tree might want to set this to - * {@code false}. - */ - public ExplodedArchive(File root, boolean recursive) { - if (!root.exists() || !root.isDirectory()) { - throw new IllegalArgumentException("Invalid source directory " + root); - } - this.root = root; - this.recursive = recursive; - this.manifestFile = getManifestFile(root); - } - - private File getManifestFile(File root) { - File metaInf = new File(root, "META-INF"); - return new File(metaInf, "MANIFEST.MF"); - } - - @Override - public URL getUrl() throws MalformedURLException { - return this.root.toURI().toURL(); - } - - @Override - public Manifest getManifest() throws IOException { - if (this.manifest == null && this.manifestFile.exists()) { - try (FileInputStream inputStream = new FileInputStream(this.manifestFile)) { - this.manifest = new Manifest(inputStream); - } - } - return this.manifest; - } - - @Override - public Iterator getNestedArchives(EntryFilter searchFilter, EntryFilter includeFilter) throws IOException { - return new ArchiveIterator(this.root, this.recursive, searchFilter, includeFilter); - } - - @Override -// @Deprecated(since = "2.3.10", forRemoval = false) - public Iterator iterator() { - return new EntryIterator(this.root, this.recursive, null, null); - } - - protected Archive getNestedArchive(Entry entry) { - File file = ((FileEntry) entry).getFile(); - return (file.isDirectory() ? new ExplodedArchive(file) : new SimpleJarFileArchive((FileEntry) entry)); - } - - @Override - public boolean isExploded() { - return true; - } - - @Override - public String toString() { - try { - return getUrl().toString(); - } - catch (Exception ex) { - return "exploded archive"; - } - } - - /** - * File based {@link Entry} {@link Iterator}. - */ - private abstract static class AbstractIterator implements Iterator { - - private static final Comparator entryComparator = Comparator.comparing(File::getAbsolutePath); - - private final File root; - - private final boolean recursive; - - private final EntryFilter searchFilter; - - private final EntryFilter includeFilter; - - private final Deque> stack = new LinkedList<>(); - - private FileEntry current; - - private final String rootUrl; - - AbstractIterator(File root, boolean recursive, EntryFilter searchFilter, EntryFilter includeFilter) { - this.root = root; - this.rootUrl = this.root.toURI().getPath(); - this.recursive = recursive; - this.searchFilter = searchFilter; - this.includeFilter = includeFilter; - this.stack.add(listFiles(root)); - this.current = poll(); - } - - @Override - public boolean hasNext() { - return this.current != null; - } - - @Override - public T next() { - FileEntry entry = this.current; - if (entry == null) { - throw new NoSuchElementException(); - } - this.current = poll(); - return adapt(entry); - } - - private FileEntry poll() { - while (!this.stack.isEmpty()) { - while (this.stack.peek().hasNext()) { - File file = this.stack.peek().next(); - if (SKIPPED_NAMES.contains(file.getName())) { - continue; - } - FileEntry entry = getFileEntry(file); - if (isListable(entry)) { - this.stack.addFirst(listFiles(file)); - } - if (this.includeFilter == null || this.includeFilter.matches(entry)) { - return entry; - } - } - this.stack.poll(); - } - return null; - } - - private FileEntry getFileEntry(File file) { - URI uri = file.toURI(); - String name = uri.getPath().substring(this.rootUrl.length()); - try { - return new FileEntry(name, file, uri.toURL()); - } - catch (MalformedURLException ex) { - throw new IllegalStateException(ex); - } - } - - private boolean isListable(FileEntry entry) { - return entry.isDirectory() && (this.recursive || entry.getFile().getParentFile().equals(this.root)) - && (this.searchFilter == null || this.searchFilter.matches(entry)) - && (this.includeFilter == null || !this.includeFilter.matches(entry)); - } - - private Iterator listFiles(File file) { - File[] files = file.listFiles(); - if (files == null) { - return Collections.emptyIterator(); - } - Arrays.sort(files, entryComparator); - return Arrays.asList(files).iterator(); - } - - @Override - public void remove() { - throw new UnsupportedOperationException("remove"); - } - - protected abstract T adapt(FileEntry entry); - - } - - private static class EntryIterator extends AbstractIterator { - - EntryIterator(File root, boolean recursive, EntryFilter searchFilter, EntryFilter includeFilter) { - super(root, recursive, searchFilter, includeFilter); - } - - @Override - protected Entry adapt(FileEntry entry) { - return entry; - } - - } - - private static class ArchiveIterator extends AbstractIterator { - - ArchiveIterator(File root, boolean recursive, EntryFilter searchFilter, EntryFilter includeFilter) { - super(root, recursive, searchFilter, includeFilter); - } - - @Override - protected Archive adapt(FileEntry entry) { - File file = entry.getFile(); - return (file.isDirectory() ? new ExplodedArchive(file) : new SimpleJarFileArchive(entry)); - } - - } - - /** - * {@link Entry} backed by a File. - */ - private static class FileEntry implements Entry { - - private final String name; - - private final File file; - - private final URL url; - - FileEntry(String name, File file, URL url) { - this.name = name; - this.file = file; - this.url = url; - } - - File getFile() { - return this.file; - } - - @Override - public boolean isDirectory() { - return this.file.isDirectory(); - } - - @Override - public String getName() { - return this.name; - } - - URL getUrl() { - return this.url; - } - - } - - /** - * {@link Archive} implementation backed by a simple JAR file that doesn't itself - * contain nested archives. - */ - private static class SimpleJarFileArchive implements Archive { - - private final URL url; - - SimpleJarFileArchive(FileEntry file) { - this.url = file.getUrl(); - } - - @Override - public URL getUrl() throws MalformedURLException { - return this.url; - } - - @Override - public Manifest getManifest() throws IOException { - return null; - } - - @Override - public Iterator getNestedArchives(EntryFilter searchFilter, EntryFilter includeFilter) - throws IOException { - return Collections.emptyIterator(); - } - - @Override -// @Deprecated(since = "2.3.10", forRemoval = false) - public Iterator iterator() { - return Collections.emptyIterator(); - } - - @Override - public String toString() { - try { - return getUrl().toString(); - } - catch (Exception ex) { - return "jar archive"; - } - } - - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/archive/JarFileArchive.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/archive/JarFileArchive.java deleted file mode 100755 index 327642dd..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/archive/JarFileArchive.java +++ /dev/null @@ -1,290 +0,0 @@ -package fun.asgc.neutrino.core.aop.compiler.internal.archive; - -import fun.asgc.neutrino.core.aop.compiler.internal.jar.JarFile; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.nio.file.*; -import java.nio.file.attribute.FileAttribute; -import java.nio.file.attribute.PosixFilePermission; -import java.nio.file.attribute.PosixFilePermissions; -import java.util.EnumSet; -import java.util.Iterator; -import java.util.UUID; -import java.util.jar.JarEntry; -import java.util.jar.Manifest; - -/** - * {@link Archive} implementation backed by a {@link JarFile}. - * - * @author Phillip Webb - * @author Andy Wilkinson - * @since 1.0.0 - */ -public class JarFileArchive implements Archive { - - private static final String UNPACK_MARKER = "UNPACK:"; - - private static final int BUFFER_SIZE = 32 * 1024; - - private static final FileAttribute[] NO_FILE_ATTRIBUTES = {}; - - private static final EnumSet DIRECTORY_PERMISSIONS = EnumSet.of(PosixFilePermission.OWNER_READ, - PosixFilePermission.OWNER_WRITE, PosixFilePermission.OWNER_EXECUTE); - - private static final EnumSet FILE_PERMISSIONS = EnumSet.of(PosixFilePermission.OWNER_READ, - PosixFilePermission.OWNER_WRITE); - - private final JarFile jarFile; - - private URL url; - - private Path tempUnpackDirectory; - - public JarFileArchive(File file) throws IOException { - this(file, file.toURI().toURL()); - } - - public JarFileArchive(File file, URL url) throws IOException { - this(new JarFile(file)); - this.url = url; - } - - public JarFileArchive(JarFile jarFile) { - this.jarFile = jarFile; - } - - @Override - public URL getUrl() throws MalformedURLException { - if (this.url != null) { - return this.url; - } - return this.jarFile.getUrl(); - } - - @Override - public Manifest getManifest() throws IOException { - return this.jarFile.getManifest(); - } - - @Override - public Iterator getNestedArchives(EntryFilter searchFilter, EntryFilter includeFilter) throws IOException { - return new NestedArchiveIterator(this.jarFile.iterator(), searchFilter, includeFilter); - } - - @Override -// @Deprecated(since = "2.3.10", forRemoval = false) - public Iterator iterator() { - return new EntryIterator(this.jarFile.iterator(), null, null); - } - - @Override - public void close() throws IOException { - this.jarFile.close(); - } - - protected Archive getNestedArchive(Entry entry) throws IOException { - JarEntry jarEntry = ((JarFileEntry) entry).getJarEntry(); - if (jarEntry.getComment().startsWith(UNPACK_MARKER)) { - return getUnpackedNestedArchive(jarEntry); - } - try { - JarFile jarFile = this.jarFile.getNestedJarFile(jarEntry); - return new JarFileArchive(jarFile); - } - catch (Exception ex) { - throw new IllegalStateException("Failed to get nested archive for entry " + entry.getName(), ex); - } - } - - private Archive getUnpackedNestedArchive(JarEntry jarEntry) throws IOException { - String name = jarEntry.getName(); - if (name.lastIndexOf('/') != -1) { - name = name.substring(name.lastIndexOf('/') + 1); - } - Path path = getTempUnpackDirectory().resolve(name); - if (!Files.exists(path) || Files.size(path) != jarEntry.getSize()) { - unpack(jarEntry, path); - } - return new JarFileArchive(path.toFile(), path.toUri().toURL()); - } - - private Path getTempUnpackDirectory() { - if (this.tempUnpackDirectory == null) { - Path tempDirectory = Paths.get(System.getProperty("java.io.tmpdir")); - this.tempUnpackDirectory = createUnpackDirectory(tempDirectory); - } - return this.tempUnpackDirectory; - } - - private Path createUnpackDirectory(Path parent) { - int attempts = 0; - while (attempts++ < 1000) { - String fileName = Paths.get(this.jarFile.getName()).getFileName().toString(); - Path unpackDirectory = parent.resolve(fileName + "-spring-boot-libs-" + UUID.randomUUID()); - try { - createDirectory(unpackDirectory); - return unpackDirectory; - } - catch (IOException ex) { - } - } - throw new IllegalStateException("Failed to create unpack directory in directory '" + parent + "'"); - } - - private void unpack(JarEntry entry, Path path) throws IOException { - createFile(path); - path.toFile().deleteOnExit(); - try (InputStream inputStream = this.jarFile.getInputStream(entry); - OutputStream outputStream = Files.newOutputStream(path, StandardOpenOption.WRITE, - StandardOpenOption.TRUNCATE_EXISTING)) { - byte[] buffer = new byte[BUFFER_SIZE]; - int bytesRead; - while ((bytesRead = inputStream.read(buffer)) != -1) { - outputStream.write(buffer, 0, bytesRead); - } - outputStream.flush(); - } - } - - private void createDirectory(Path path) throws IOException { - Files.createDirectory(path, getFileAttributes(path.getFileSystem(), DIRECTORY_PERMISSIONS)); - } - - private void createFile(Path path) throws IOException { - Files.createFile(path, getFileAttributes(path.getFileSystem(), FILE_PERMISSIONS)); - } - - private FileAttribute[] getFileAttributes(FileSystem fileSystem, EnumSet ownerReadWrite) { - if (!fileSystem.supportedFileAttributeViews().contains("posix")) { - return NO_FILE_ATTRIBUTES; - } - return new FileAttribute[] { PosixFilePermissions.asFileAttribute(ownerReadWrite) }; - } - - @Override - public String toString() { - try { - return getUrl().toString(); - } - catch (Exception ex) { - return "jar archive"; - } - } - - /** - * Abstract base class for iterator implementations. - */ - private abstract static class AbstractIterator implements Iterator { - - private final Iterator iterator; - - private final EntryFilter searchFilter; - - private final EntryFilter includeFilter; - - private Entry current; - - AbstractIterator(Iterator iterator, EntryFilter searchFilter, EntryFilter includeFilter) { - this.iterator = iterator; - this.searchFilter = searchFilter; - this.includeFilter = includeFilter; - this.current = poll(); - } - - @Override - public boolean hasNext() { - return this.current != null; - } - - @Override - public T next() { - T result = adapt(this.current); - this.current = poll(); - return result; - } - - private Entry poll() { - while (this.iterator.hasNext()) { - JarFileEntry candidate = new JarFileEntry(this.iterator.next()); - if ((this.searchFilter == null || this.searchFilter.matches(candidate)) - && (this.includeFilter == null || this.includeFilter.matches(candidate))) { - return candidate; - } - } - return null; - } - - protected abstract T adapt(Entry entry); - - } - - /** - * {@link Entry} iterator implementation backed by {@link JarEntry}. - */ - private static class EntryIterator extends AbstractIterator { - - EntryIterator(Iterator iterator, EntryFilter searchFilter, EntryFilter includeFilter) { - super(iterator, searchFilter, includeFilter); - } - - @Override - protected Entry adapt(Entry entry) { - return entry; - } - - } - - /** - * Nested {@link Archive} iterator implementation backed by {@link JarEntry}. - */ - private class NestedArchiveIterator extends AbstractIterator { - - NestedArchiveIterator(Iterator iterator, EntryFilter searchFilter, EntryFilter includeFilter) { - super(iterator, searchFilter, includeFilter); - } - - @Override - protected Archive adapt(Entry entry) { - try { - return getNestedArchive(entry); - } - catch (IOException ex) { - throw new IllegalStateException(ex); - } - } - - } - - /** - * {@link Entry} implementation backed by a {@link JarEntry}. - */ - private static class JarFileEntry implements Entry { - - private final JarEntry jarEntry; - - JarFileEntry(JarEntry jarEntry) { - this.jarEntry = jarEntry; - } - - JarEntry getJarEntry() { - return this.jarEntry; - } - - @Override - public boolean isDirectory() { - return this.jarEntry.isDirectory(); - } - - @Override - public String getName() { - return this.jarEntry.getName(); - } - - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/data/RandomAccessData.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/data/RandomAccessData.java deleted file mode 100644 index b55aef44..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/data/RandomAccessData.java +++ /dev/null @@ -1,58 +0,0 @@ -package fun.asgc.neutrino.core.aop.compiler.internal.data; - -import java.io.EOFException; -import java.io.IOException; -import java.io.InputStream; - -/** - * Interface that provides read-only random access to some underlying data. - * Implementations must allow concurrent reads in a thread-safe manner. - * - * @author Phillip Webb - * @since 1.0.0 - */ -public interface RandomAccessData { - - /** - * Returns an {@link InputStream} that can be used to read the underlying data. The - * caller is responsible close the underlying stream. - * @return a new input stream that can be used to read the underlying data. - * @throws IOException if the stream cannot be opened - */ - InputStream getInputStream() throws IOException; - - /** - * Returns a new {@link RandomAccessData} for a specific subsection of this data. - * @param offset the offset of the subsection - * @param length the length of the subsection - * @return the subsection data - */ - RandomAccessData getSubsection(long offset, long length); - - /** - * Reads all the data and returns it as a byte array. - * @return the data - * @throws IOException if the data cannot be read - */ - byte[] read() throws IOException; - - /** - * Reads the {@code length} bytes of data starting at the given {@code offset}. - * @param offset the offset from which data should be read - * @param length the number of bytes to be read - * @return the data - * @throws IOException if the data cannot be read - * @throws IndexOutOfBoundsException if offset is beyond the end of the file or - * subsection - * @throws EOFException if offset plus length is greater than the length of the file - * or subsection - */ - byte[] read(long offset, long length) throws IOException; - - /** - * Returns the size of the data. - * @return the size - */ - long getSize(); - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/data/RandomAccessDataFile.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/data/RandomAccessDataFile.java deleted file mode 100644 index a77ce34d..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/data/RandomAccessDataFile.java +++ /dev/null @@ -1,241 +0,0 @@ -package fun.asgc.neutrino.core.aop.compiler.internal.data; - -import java.io.*; - -/** - * {@link RandomAccessData} implementation backed by a {@link RandomAccessFile}. - * - * @author Phillip Webb - * @author Andy Wilkinson - * @since 1.0.0 - */ -public class RandomAccessDataFile implements RandomAccessData { - - private final FileAccess fileAccess; - - private final long offset; - - private final long length; - - /** - * Create a new {@link RandomAccessDataFile} backed by the specified file. - * @param file the underlying file - * @throws IllegalArgumentException if the file is null or does not exist - */ - public RandomAccessDataFile(File file) { - if (file == null) { - throw new IllegalArgumentException("File must not be null"); - } - this.fileAccess = new FileAccess(file); - this.offset = 0L; - this.length = file.length(); - } - - /** - * Private constructor used to create a {@link #getSubsection(long, long) subsection}. - * @param fileAccess provides access to the underlying file - * @param offset the offset of the section - * @param length the length of the section - */ - private RandomAccessDataFile(FileAccess fileAccess, long offset, long length) { - this.fileAccess = fileAccess; - this.offset = offset; - this.length = length; - } - - /** - * Returns the underlying File. - * @return the underlying file - */ - public File getFile() { - return this.fileAccess.file; - } - - @Override - public InputStream getInputStream() throws IOException { - return new DataInputStream(); - } - - @Override - public RandomAccessData getSubsection(long offset, long length) { - if (offset < 0 || length < 0 || offset + length > this.length) { - throw new IndexOutOfBoundsException(); - } - return new RandomAccessDataFile(this.fileAccess, this.offset + offset, length); - } - - @Override - public byte[] read() throws IOException { - return read(0, this.length); - } - - @Override - public byte[] read(long offset, long length) throws IOException { - if (offset > this.length) { - throw new IndexOutOfBoundsException(); - } - if (offset + length > this.length) { - throw new EOFException(); - } - byte[] bytes = new byte[(int) length]; - read(bytes, offset, 0, bytes.length); - return bytes; - } - - private int readByte(long position) throws IOException { - if (position >= this.length) { - return -1; - } - return this.fileAccess.readByte(this.offset + position); - } - - private int read(byte[] bytes, long position, int offset, int length) throws IOException { - if (position > this.length) { - return -1; - } - return this.fileAccess.read(bytes, this.offset + position, offset, length); - } - - @Override - public long getSize() { - return this.length; - } - - public void close() throws IOException { - this.fileAccess.close(); - } - - /** - * {@link InputStream} implementation for the {@link RandomAccessDataFile}. - */ - private class DataInputStream extends InputStream { - - private int position; - - @Override - public int read() throws IOException { - int read = RandomAccessDataFile.this.readByte(this.position); - if (read > -1) { - moveOn(1); - } - return read; - } - - @Override - public int read(byte[] b) throws IOException { - return read(b, 0, (b != null) ? b.length : 0); - } - - @Override - public int read(byte[] b, int off, int len) throws IOException { - if (b == null) { - throw new NullPointerException("Bytes must not be null"); - } - return doRead(b, off, len); - } - - /** - * Perform the actual read. - * @param b the bytes to read or {@code null} when reading a single byte - * @param off the offset of the byte array - * @param len the length of data to read - * @return the number of bytes read into {@code b} or the actual read byte if - * {@code b} is {@code null}. Returns -1 when the end of the stream is reached - * @throws IOException in case of I/O errors - */ - int doRead(byte[] b, int off, int len) throws IOException { - if (len == 0) { - return 0; - } - int cappedLen = cap(len); - if (cappedLen <= 0) { - return -1; - } - return (int) moveOn(RandomAccessDataFile.this.read(b, this.position, off, cappedLen)); - } - - @Override - public long skip(long n) throws IOException { - return (n <= 0) ? 0 : moveOn(cap(n)); - } - - @Override - public int available() throws IOException { - return (int) RandomAccessDataFile.this.length - this.position; - } - - /** - * Cap the specified value such that it cannot exceed the number of bytes - * remaining. - * @param n the value to cap - * @return the capped value - */ - private int cap(long n) { - return (int) Math.min(RandomAccessDataFile.this.length - this.position, n); - } - - /** - * Move the stream position forwards the specified amount. - * @param amount the amount to move - * @return the amount moved - */ - private long moveOn(int amount) { - this.position += amount; - return amount; - } - - } - - private static final class FileAccess { - - private final Object monitor = new Object(); - - private final File file; - - private RandomAccessFile randomAccessFile; - - private FileAccess(File file) { - this.file = file; - openIfNecessary(); - } - - private int read(byte[] bytes, long position, int offset, int length) throws IOException { - synchronized (this.monitor) { - openIfNecessary(); - this.randomAccessFile.seek(position); - return this.randomAccessFile.read(bytes, offset, length); - } - } - - private void openIfNecessary() { - if (this.randomAccessFile == null) { - try { - this.randomAccessFile = new RandomAccessFile(this.file, "r"); - } - catch (FileNotFoundException ex) { - throw new IllegalArgumentException( - String.format("File %s must exist", this.file.getAbsolutePath())); - } - } - } - - private void close() throws IOException { - synchronized (this.monitor) { - if (this.randomAccessFile != null) { - this.randomAccessFile.close(); - this.randomAccessFile = null; - } - } - } - - private int readByte(long position) throws IOException { - synchronized (this.monitor) { - openIfNecessary(); - this.randomAccessFile.seek(position); - return this.randomAccessFile.read(); - } - } - - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/AbstractJarFile.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/AbstractJarFile.java deleted file mode 100644 index eed7b062..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/AbstractJarFile.java +++ /dev/null @@ -1,62 +0,0 @@ -package fun.asgc.neutrino.core.aop.compiler.internal.jar; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.security.Permission; - -/** - * Base class for extended variants of {@link java.util.jar.JarFile}. - * - * @author Phillip Webb - */ -abstract class AbstractJarFile extends java.util.jar.JarFile { - - /** - * Create a new {@link AbstractJarFile}. - * @param file the root jar file. - * @throws IOException on IO error - */ - AbstractJarFile(File file) throws IOException { - super(file); - } - - /** - * Return a URL that can be used to access this JAR file. NOTE: the specified URL - * cannot be serialized and or cloned. - * @return the URL - * @throws MalformedURLException if the URL is malformed - */ - abstract URL getUrl() throws MalformedURLException; - - /** - * Return the {@link JarFileType} of this instance. - * @return the jar file type - */ - abstract JarFileType getType(); - - /** - * Return the security permission for this JAR. - * @return the security permission. - */ - abstract Permission getPermission(); - - /** - * Return an {@link InputStream} for the entire jar contents. - * @return the contents input stream - * @throws IOException on IO error - */ - abstract InputStream getInputStream() throws IOException; - - /** - * The type of a {@link JarFile}. - */ - enum JarFileType { - - DIRECT, NESTED_DIRECTORY, NESTED_JAR - - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/AsciiBytes.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/AsciiBytes.java deleted file mode 100644 index 06caea44..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/AsciiBytes.java +++ /dev/null @@ -1,239 +0,0 @@ -package fun.asgc.neutrino.core.aop.compiler.internal.jar; - -import java.nio.charset.StandardCharsets; - -/** - * Simple wrapper around a byte array that represents an ASCII. Used for performance - * reasons to save constructing Strings for ZIP data. - * - * @author Phillip Webb - * @author Andy Wilkinson - */ -final class AsciiBytes { - - private static final String EMPTY_STRING = ""; - - private static final int[] INITIAL_BYTE_BITMASK = { 0x7F, 0x1F, 0x0F, 0x07 }; - - private static final int SUBSEQUENT_BYTE_BITMASK = 0x3F; - - private final byte[] bytes; - - private final int offset; - - private final int length; - - private String string; - - private int hash; - - /** - * Create a new {@link AsciiBytes} from the specified String. - * @param string the source string - */ - AsciiBytes(String string) { - this(string.getBytes(StandardCharsets.UTF_8)); - this.string = string; - } - - /** - * Create a new {@link AsciiBytes} from the specified bytes. NOTE: underlying bytes - * are not expected to change. - * @param bytes the source bytes - */ - AsciiBytes(byte[] bytes) { - this(bytes, 0, bytes.length); - } - - /** - * Create a new {@link AsciiBytes} from the specified bytes. NOTE: underlying bytes - * are not expected to change. - * @param bytes the source bytes - * @param offset the offset - * @param length the length - */ - AsciiBytes(byte[] bytes, int offset, int length) { - if (offset < 0 || length < 0 || (offset + length) > bytes.length) { - throw new IndexOutOfBoundsException(); - } - this.bytes = bytes; - this.offset = offset; - this.length = length; - } - - int length() { - return this.length; - } - - boolean startsWith(AsciiBytes prefix) { - if (this == prefix) { - return true; - } - if (prefix.length > this.length) { - return false; - } - for (int i = 0; i < prefix.length; i++) { - if (this.bytes[i + this.offset] != prefix.bytes[i + prefix.offset]) { - return false; - } - } - return true; - } - - boolean endsWith(AsciiBytes postfix) { - if (this == postfix) { - return true; - } - if (postfix.length > this.length) { - return false; - } - for (int i = 0; i < postfix.length; i++) { - if (this.bytes[this.offset + (this.length - 1) - i] != postfix.bytes[postfix.offset + (postfix.length - 1) - - i]) { - return false; - } - } - return true; - } - - AsciiBytes substring(int beginIndex) { - return substring(beginIndex, this.length); - } - - AsciiBytes substring(int beginIndex, int endIndex) { - int length = endIndex - beginIndex; - if (this.offset + length > this.bytes.length) { - throw new IndexOutOfBoundsException(); - } - return new AsciiBytes(this.bytes, this.offset + beginIndex, length); - } - - boolean matches(CharSequence name, char suffix) { - int charIndex = 0; - int nameLen = name.length(); - int totalLen = nameLen + ((suffix != 0) ? 1 : 0); - for (int i = this.offset; i < this.offset + this.length; i++) { - int b = this.bytes[i]; - int remainingUtfBytes = getNumberOfUtfBytes(b) - 1; - b &= INITIAL_BYTE_BITMASK[remainingUtfBytes]; - for (int j = 0; j < remainingUtfBytes; j++) { - b = (b << 6) + (this.bytes[++i] & SUBSEQUENT_BYTE_BITMASK); - } - char c = getChar(name, suffix, charIndex++); - if (b <= 0xFFFF) { - if (c != b) { - return false; - } - } - else { - if (c != ((b >> 0xA) + 0xD7C0)) { - return false; - } - c = getChar(name, suffix, charIndex++); - if (c != ((b & 0x3FF) + 0xDC00)) { - return false; - } - } - } - return charIndex == totalLen; - } - - private char getChar(CharSequence name, char suffix, int index) { - if (index < name.length()) { - return name.charAt(index); - } - if (index == name.length()) { - return suffix; - } - return 0; - } - - private int getNumberOfUtfBytes(int b) { - if ((b & 0x80) == 0) { - return 1; - } - int numberOfUtfBytes = 0; - while ((b & 0x80) != 0) { - b <<= 1; - numberOfUtfBytes++; - } - return numberOfUtfBytes; - } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (this == obj) { - return true; - } - if (obj.getClass() == AsciiBytes.class) { - AsciiBytes other = (AsciiBytes) obj; - if (this.length == other.length) { - for (int i = 0; i < this.length; i++) { - if (this.bytes[this.offset + i] != other.bytes[other.offset + i]) { - return false; - } - } - return true; - } - } - return false; - } - - @Override - public int hashCode() { - int hash = this.hash; - if (hash == 0 && this.bytes.length > 0) { - for (int i = this.offset; i < this.offset + this.length; i++) { - int b = this.bytes[i]; - int remainingUtfBytes = getNumberOfUtfBytes(b) - 1; - b &= INITIAL_BYTE_BITMASK[remainingUtfBytes]; - for (int j = 0; j < remainingUtfBytes; j++) { - b = (b << 6) + (this.bytes[++i] & SUBSEQUENT_BYTE_BITMASK); - } - if (b <= 0xFFFF) { - hash = 31 * hash + b; - } - else { - hash = 31 * hash + ((b >> 0xA) + 0xD7C0); - hash = 31 * hash + ((b & 0x3FF) + 0xDC00); - } - } - this.hash = hash; - } - return hash; - } - - @Override - public String toString() { - if (this.string == null) { - if (this.length == 0) { - this.string = EMPTY_STRING; - } - else { - this.string = new String(this.bytes, this.offset, this.length, StandardCharsets.UTF_8); - } - } - return this.string; - } - - static String toString(byte[] bytes) { - return new String(bytes, StandardCharsets.UTF_8); - } - - static int hashCode(CharSequence charSequence) { - // We're compatible with String's hashCode() - if (charSequence instanceof StringSequence) { - // ... but save making an unnecessary String for StringSequence - return charSequence.hashCode(); - } - return charSequence.toString().hashCode(); - } - - static int hashCode(int hash, char suffix) { - return (suffix != 0) ? (31 * hash + suffix) : hash; - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/Bytes.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/Bytes.java deleted file mode 100644 index 99fabb53..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/Bytes.java +++ /dev/null @@ -1,21 +0,0 @@ -package fun.asgc.neutrino.core.aop.compiler.internal.jar; - -/** - * Utilities for dealing with bytes from ZIP files. - * - * @author Phillip Webb - */ -final class Bytes { - - private Bytes() { - } - - static long littleEndianValue(byte[] bytes, int offset, int length) { - long value = 0; - for (int i = length - 1; i >= 0; i--) { - value = ((value << 8) | (bytes[offset + i] & 0xFF)); - } - return value; - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/CentralDirectoryEndRecord.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/CentralDirectoryEndRecord.java deleted file mode 100644 index 75fa2761..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/CentralDirectoryEndRecord.java +++ /dev/null @@ -1,242 +0,0 @@ -package fun.asgc.neutrino.core.aop.compiler.internal.jar; - -import fun.asgc.neutrino.core.aop.compiler.internal.data.RandomAccessData; - -import java.io.IOException; - -/** - * A ZIP File "End of central directory record" (EOCD). - * - * @author Phillip Webb - * @author Andy Wilkinson - * @author Camille Vienot - * @see Zip File Format - */ -class CentralDirectoryEndRecord { - - private static final int MINIMUM_SIZE = 22; - - private static final int MAXIMUM_COMMENT_LENGTH = 0xFFFF; - - private static final int MAXIMUM_SIZE = MINIMUM_SIZE + MAXIMUM_COMMENT_LENGTH; - - private static final int SIGNATURE = 0x06054b50; - - private static final int COMMENT_LENGTH_OFFSET = 20; - - private static final int READ_BLOCK_SIZE = 256; - - private final Zip64End zip64End; - - private byte[] block; - - private int offset; - - private int size; - - /** - * Create a new {@link CentralDirectoryEndRecord} instance from the specified - * {@link RandomAccessData}, searching backwards from the end until a valid block is - * located. - * @param data the source data - * @throws IOException in case of I/O errors - */ - CentralDirectoryEndRecord(RandomAccessData data) throws IOException { - this.block = createBlockFromEndOfData(data, READ_BLOCK_SIZE); - this.size = MINIMUM_SIZE; - this.offset = this.block.length - this.size; - while (!isValid()) { - this.size++; - if (this.size > this.block.length) { - if (this.size >= MAXIMUM_SIZE || this.size > data.getSize()) { - throw new IOException( - "Unable to find ZIP central directory records after reading " + this.size + " bytes"); - } - this.block = createBlockFromEndOfData(data, this.size + READ_BLOCK_SIZE); - } - this.offset = this.block.length - this.size; - } - long startOfCentralDirectoryEndRecord = data.getSize() - this.size; - Zip64Locator zip64Locator = Zip64Locator.find(data, startOfCentralDirectoryEndRecord); - this.zip64End = (zip64Locator != null) ? new Zip64End(data, zip64Locator) : null; - } - - private byte[] createBlockFromEndOfData(RandomAccessData data, int size) throws IOException { - int length = (int) Math.min(data.getSize(), size); - return data.read(data.getSize() - length, length); - } - - private boolean isValid() { - if (this.block.length < MINIMUM_SIZE || Bytes.littleEndianValue(this.block, this.offset + 0, 4) != SIGNATURE) { - return false; - } - // Total size must be the structure size + comment - long commentLength = Bytes.littleEndianValue(this.block, this.offset + COMMENT_LENGTH_OFFSET, 2); - return this.size == MINIMUM_SIZE + commentLength; - } - - /** - * Returns the location in the data that the archive actually starts. For most files - * the archive data will start at 0, however, it is possible to have prefixed bytes - * (often used for startup scripts) at the beginning of the data. - * @param data the source data - * @return the offset within the data where the archive begins - */ - long getStartOfArchive(RandomAccessData data) { - long length = Bytes.littleEndianValue(this.block, this.offset + 12, 4); - long specifiedOffset = (this.zip64End != null) ? this.zip64End.centralDirectoryOffset - : Bytes.littleEndianValue(this.block, this.offset + 16, 4); - long zip64EndSize = (this.zip64End != null) ? this.zip64End.getSize() : 0L; - int zip64LocSize = (this.zip64End != null) ? Zip64Locator.ZIP64_LOCSIZE : 0; - long actualOffset = data.getSize() - this.size - length - zip64EndSize - zip64LocSize; - return actualOffset - specifiedOffset; - } - - /** - * Return the bytes of the "Central directory" based on the offset indicated in this - * record. - * @param data the source data - * @return the central directory data - */ - RandomAccessData getCentralDirectory(RandomAccessData data) { - if (this.zip64End != null) { - return this.zip64End.getCentralDirectory(data); - } - long offset = Bytes.littleEndianValue(this.block, this.offset + 16, 4); - long length = Bytes.littleEndianValue(this.block, this.offset + 12, 4); - return data.getSubsection(offset, length); - } - - /** - * Return the number of ZIP entries in the file. - * @return the number of records in the zip - */ - int getNumberOfRecords() { - if (this.zip64End != null) { - return this.zip64End.getNumberOfRecords(); - } - long numberOfRecords = Bytes.littleEndianValue(this.block, this.offset + 10, 2); - return (int) numberOfRecords; - } - - String getComment() { - int commentLength = (int) Bytes.littleEndianValue(this.block, this.offset + COMMENT_LENGTH_OFFSET, 2); - AsciiBytes comment = new AsciiBytes(this.block, this.offset + COMMENT_LENGTH_OFFSET + 2, commentLength); - return comment.toString(); - } - - boolean isZip64() { - return this.zip64End != null; - } - - /** - * A Zip64 end of central directory record. - * - * @see Chapter - * 4.3.14 of Zip64 specification - */ - private static final class Zip64End { - - private static final int ZIP64_ENDTOT = 32; // total number of entries - - private static final int ZIP64_ENDSIZ = 40; // central directory size in bytes - - private static final int ZIP64_ENDOFF = 48; // offset of first CEN header - - private final Zip64Locator locator; - - private final long centralDirectoryOffset; - - private final long centralDirectoryLength; - - private final int numberOfRecords; - - private Zip64End(RandomAccessData data, Zip64Locator locator) throws IOException { - this.locator = locator; - byte[] block = data.read(locator.getZip64EndOffset(), 56); - this.centralDirectoryOffset = Bytes.littleEndianValue(block, ZIP64_ENDOFF, 8); - this.centralDirectoryLength = Bytes.littleEndianValue(block, ZIP64_ENDSIZ, 8); - this.numberOfRecords = (int) Bytes.littleEndianValue(block, ZIP64_ENDTOT, 8); - } - - /** - * Return the size of this zip 64 end of central directory record. - * @return size of this zip 64 end of central directory record - */ - private long getSize() { - return this.locator.getZip64EndSize(); - } - - /** - * Return the bytes of the "Central directory" based on the offset indicated in - * this record. - * @param data the source data - * @return the central directory data - */ - private RandomAccessData getCentralDirectory(RandomAccessData data) { - return data.getSubsection(this.centralDirectoryOffset, this.centralDirectoryLength); - } - - /** - * Return the number of entries in the zip64 archive. - * @return the number of records in the zip - */ - private int getNumberOfRecords() { - return this.numberOfRecords; - } - - } - - /** - * A Zip64 end of central directory locator. - * - * @see Chapter - * 4.3.15 of Zip64 specification - */ - private static final class Zip64Locator { - - static final int SIGNATURE = 0x07064b50; - - static final int ZIP64_LOCSIZE = 20; // locator size - - static final int ZIP64_LOCOFF = 8; // offset of zip64 end - - private final long zip64EndOffset; - - private final long offset; - - private Zip64Locator(long offset, byte[] block) { - this.offset = offset; - this.zip64EndOffset = Bytes.littleEndianValue(block, ZIP64_LOCOFF, 8); - } - - /** - * Return the size of the zip 64 end record located by this zip64 end locator. - * @return size of the zip 64 end record located by this zip64 end locator - */ - private long getZip64EndSize() { - return this.offset - this.zip64EndOffset; - } - - /** - * Return the offset to locate {@link Zip64End}. - * @return offset of the Zip64 end of central directory record - */ - private long getZip64EndOffset() { - return this.zip64EndOffset; - } - - private static Zip64Locator find(RandomAccessData data, long centralDirectoryEndOffset) throws IOException { - long offset = centralDirectoryEndOffset - ZIP64_LOCSIZE; - if (offset >= 0) { - byte[] block = data.read(offset, ZIP64_LOCSIZE); - if (Bytes.littleEndianValue(block, 0, 4) == SIGNATURE) { - return new Zip64Locator(offset, block); - } - } - return null; - } - - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/CentralDirectoryFileHeader.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/CentralDirectoryFileHeader.java deleted file mode 100644 index 340289c2..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/CentralDirectoryFileHeader.java +++ /dev/null @@ -1,206 +0,0 @@ -package fun.asgc.neutrino.core.aop.compiler.internal.jar; - -import fun.asgc.neutrino.core.aop.compiler.internal.data.RandomAccessData; - -import java.io.IOException; -import java.time.ZoneId; -import java.time.ZonedDateTime; -import java.time.temporal.ChronoField; -import java.time.temporal.ChronoUnit; -import java.time.temporal.ValueRange; - -/** - * A ZIP File "Central directory file header record" (CDFH). - * - * @author Phillip Webb - * @author Andy Wilkinson - * @author Dmytro Nosan - * @see Zip File Format - */ - -final class CentralDirectoryFileHeader implements FileHeader { - - private static final AsciiBytes SLASH = new AsciiBytes("/"); - - private static final byte[] NO_EXTRA = {}; - - private static final AsciiBytes NO_COMMENT = new AsciiBytes(""); - - private byte[] header; - - private int headerOffset; - - private AsciiBytes name; - - private byte[] extra; - - private AsciiBytes comment; - - private long localHeaderOffset; - - CentralDirectoryFileHeader() { - } - - CentralDirectoryFileHeader(byte[] header, int headerOffset, AsciiBytes name, byte[] extra, AsciiBytes comment, - long localHeaderOffset) { - this.header = header; - this.headerOffset = headerOffset; - this.name = name; - this.extra = extra; - this.comment = comment; - this.localHeaderOffset = localHeaderOffset; - } - - void load(byte[] data, int dataOffset, RandomAccessData variableData, long variableOffset, JarEntryFilter filter) - throws IOException { - // Load fixed part - this.header = data; - this.headerOffset = dataOffset; - long compressedSize = Bytes.littleEndianValue(data, dataOffset + 20, 4); - long uncompressedSize = Bytes.littleEndianValue(data, dataOffset + 24, 4); - long nameLength = Bytes.littleEndianValue(data, dataOffset + 28, 2); - long extraLength = Bytes.littleEndianValue(data, dataOffset + 30, 2); - long commentLength = Bytes.littleEndianValue(data, dataOffset + 32, 2); - long localHeaderOffset = Bytes.littleEndianValue(data, dataOffset + 42, 4); - // Load variable part - dataOffset += 46; - if (variableData != null) { - data = variableData.read(variableOffset + 46, nameLength + extraLength + commentLength); - dataOffset = 0; - } - this.name = new AsciiBytes(data, dataOffset, (int) nameLength); - if (filter != null) { - this.name = filter.apply(this.name); - } - this.extra = NO_EXTRA; - this.comment = NO_COMMENT; - if (extraLength > 0) { - this.extra = new byte[(int) extraLength]; - System.arraycopy(data, (int) (dataOffset + nameLength), this.extra, 0, this.extra.length); - } - this.localHeaderOffset = getLocalHeaderOffset(compressedSize, uncompressedSize, localHeaderOffset, this.extra); - if (commentLength > 0) { - this.comment = new AsciiBytes(data, (int) (dataOffset + nameLength + extraLength), (int) commentLength); - } - } - - private long getLocalHeaderOffset(long compressedSize, long uncompressedSize, long localHeaderOffset, byte[] extra) - throws IOException { - if (localHeaderOffset != 0xFFFFFFFFL) { - return localHeaderOffset; - } - int extraOffset = 0; - while (extraOffset < extra.length - 2) { - int id = (int) Bytes.littleEndianValue(extra, extraOffset, 2); - int length = (int) Bytes.littleEndianValue(extra, extraOffset, 2); - extraOffset += 4; - if (id == 1) { - int localHeaderExtraOffset = 0; - if (compressedSize == 0xFFFFFFFFL) { - localHeaderExtraOffset += 4; - } - if (uncompressedSize == 0xFFFFFFFFL) { - localHeaderExtraOffset += 4; - } - return Bytes.littleEndianValue(extra, extraOffset + localHeaderExtraOffset, 8); - } - extraOffset += length; - } - throw new IOException("Zip64 Extended Information Extra Field not found"); - } - - AsciiBytes getName() { - return this.name; - } - - @Override - public boolean hasName(CharSequence name, char suffix) { - return this.name.matches(name, suffix); - } - - boolean isDirectory() { - return this.name.endsWith(SLASH); - } - - @Override - public int getMethod() { - return (int) Bytes.littleEndianValue(this.header, this.headerOffset + 10, 2); - } - - long getTime() { - long datetime = Bytes.littleEndianValue(this.header, this.headerOffset + 12, 4); - return decodeMsDosFormatDateTime(datetime); - } - - /** - * Decode MS-DOS Date Time details. See - * Microsoft's documentation for more details of the format. - * @param datetime the date and time - * @return the date and time as milliseconds since the epoch - */ - private long decodeMsDosFormatDateTime(long datetime) { - int year = getChronoValue(((datetime >> 25) & 0x7f) + 1980, ChronoField.YEAR); - int month = getChronoValue((datetime >> 21) & 0x0f, ChronoField.MONTH_OF_YEAR); - int day = getChronoValue((datetime >> 16) & 0x1f, ChronoField.DAY_OF_MONTH); - int hour = getChronoValue((datetime >> 11) & 0x1f, ChronoField.HOUR_OF_DAY); - int minute = getChronoValue((datetime >> 5) & 0x3f, ChronoField.MINUTE_OF_HOUR); - int second = getChronoValue((datetime << 1) & 0x3e, ChronoField.SECOND_OF_MINUTE); - return ZonedDateTime.of(year, month, day, hour, minute, second, 0, ZoneId.systemDefault()) - .toInstant() - .truncatedTo(ChronoUnit.SECONDS) - .toEpochMilli(); - } - - long getCrc() { - return Bytes.littleEndianValue(this.header, this.headerOffset + 16, 4); - } - - @Override - public long getCompressedSize() { - return Bytes.littleEndianValue(this.header, this.headerOffset + 20, 4); - } - - @Override - public long getSize() { - return Bytes.littleEndianValue(this.header, this.headerOffset + 24, 4); - } - - byte[] getExtra() { - return this.extra; - } - - boolean hasExtra() { - return this.extra.length > 0; - } - - AsciiBytes getComment() { - return this.comment; - } - - @Override - public long getLocalHeaderOffset() { - return this.localHeaderOffset; - } - - @Override - public CentralDirectoryFileHeader clone() { - byte[] header = new byte[46]; - System.arraycopy(this.header, this.headerOffset, header, 0, header.length); - return new CentralDirectoryFileHeader(header, 0, this.name, header, this.comment, this.localHeaderOffset); - } - - static CentralDirectoryFileHeader fromRandomAccessData(RandomAccessData data, long offset, JarEntryFilter filter) - throws IOException { - CentralDirectoryFileHeader fileHeader = new CentralDirectoryFileHeader(); - byte[] bytes = data.read(offset, 46); - fileHeader.load(bytes, 0, data, offset, filter); - return fileHeader; - } - - private static int getChronoValue(long value, ChronoField field) { - ValueRange range = field.range(); - return Math.toIntExact(Math.min(Math.max(value, range.getMinimum()), range.getMaximum())); - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/CentralDirectoryParser.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/CentralDirectoryParser.java deleted file mode 100644 index 3e81183b..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/CentralDirectoryParser.java +++ /dev/null @@ -1,85 +0,0 @@ -package fun.asgc.neutrino.core.aop.compiler.internal.jar; - -import fun.asgc.neutrino.core.aop.compiler.internal.data.RandomAccessData; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -/** - * Parses the central directory from a JAR file. - * - * @author Phillip Webb - * @author Andy Wilkinson - * @see CentralDirectoryVisitor - */ -class CentralDirectoryParser { - - private static final int CENTRAL_DIRECTORY_HEADER_BASE_SIZE = 46; - - private final List visitors = new ArrayList<>(); - - T addVisitor(T visitor) { - this.visitors.add(visitor); - return visitor; - } - - /** - * Parse the source data, triggering {@link CentralDirectoryVisitor visitors}. - * @param data the source data - * @param skipPrefixBytes if prefix bytes should be skipped - * @return the actual archive data without any prefix bytes - * @throws IOException on error - */ - RandomAccessData parse(RandomAccessData data, boolean skipPrefixBytes) throws IOException { - CentralDirectoryEndRecord endRecord = new CentralDirectoryEndRecord(data); - if (skipPrefixBytes) { - data = getArchiveData(endRecord, data); - } - RandomAccessData centralDirectoryData = endRecord.getCentralDirectory(data); - visitStart(endRecord, centralDirectoryData); - parseEntries(endRecord, centralDirectoryData); - visitEnd(); - return data; - } - - private void parseEntries(CentralDirectoryEndRecord endRecord, RandomAccessData centralDirectoryData) - throws IOException { - byte[] bytes = centralDirectoryData.read(0, centralDirectoryData.getSize()); - CentralDirectoryFileHeader fileHeader = new CentralDirectoryFileHeader(); - int dataOffset = 0; - for (int i = 0; i < endRecord.getNumberOfRecords(); i++) { - fileHeader.load(bytes, dataOffset, null, 0, null); - visitFileHeader(dataOffset, fileHeader); - dataOffset += CENTRAL_DIRECTORY_HEADER_BASE_SIZE + fileHeader.getName().length() - + fileHeader.getComment().length() + fileHeader.getExtra().length; - } - } - - private RandomAccessData getArchiveData(CentralDirectoryEndRecord endRecord, RandomAccessData data) { - long offset = endRecord.getStartOfArchive(data); - if (offset == 0) { - return data; - } - return data.getSubsection(offset, data.getSize() - offset); - } - - private void visitStart(CentralDirectoryEndRecord endRecord, RandomAccessData centralDirectoryData) { - for (CentralDirectoryVisitor visitor : this.visitors) { - visitor.visitStart(endRecord, centralDirectoryData); - } - } - - private void visitFileHeader(long dataOffset, CentralDirectoryFileHeader fileHeader) { - for (CentralDirectoryVisitor visitor : this.visitors) { - visitor.visitFileHeader(fileHeader, dataOffset); - } - } - - private void visitEnd() { - for (CentralDirectoryVisitor visitor : this.visitors) { - visitor.visitEnd(); - } - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/CentralDirectoryVisitor.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/CentralDirectoryVisitor.java deleted file mode 100644 index af1e84ed..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/CentralDirectoryVisitor.java +++ /dev/null @@ -1,18 +0,0 @@ -package fun.asgc.neutrino.core.aop.compiler.internal.jar; - -import fun.asgc.neutrino.core.aop.compiler.internal.data.RandomAccessData; - -/** - * Callback visitor triggered by {@link CentralDirectoryParser}. - * - * @author Phillip Webb - */ -interface CentralDirectoryVisitor { - - void visitStart(CentralDirectoryEndRecord endRecord, RandomAccessData centralDirectoryData); - - void visitFileHeader(CentralDirectoryFileHeader fileHeader, long dataOffset); - - void visitEnd(); - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/FileHeader.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/FileHeader.java deleted file mode 100644 index 9180d093..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/FileHeader.java +++ /dev/null @@ -1,48 +0,0 @@ -package fun.asgc.neutrino.core.aop.compiler.internal.jar; - -import java.util.zip.ZipEntry; - -/** - * A file header record that has been loaded from a Jar file. - * - * @author Phillip Webb - * @see JarEntry - * @see CentralDirectoryFileHeader - */ -interface FileHeader { - - /** - * Returns {@code true} if the header has the given name. - * @param name the name to test - * @param suffix an additional suffix (or {@code 0}) - * @return {@code true} if the header has the given name - */ - boolean hasName(CharSequence name, char suffix); - - /** - * Return the offset of the load file header within the archive data. - * @return the local header offset - */ - long getLocalHeaderOffset(); - - /** - * Return the compressed size of the entry. - * @return the compressed size. - */ - long getCompressedSize(); - - /** - * Return the uncompressed size of the entry. - * @return the uncompressed size. - */ - long getSize(); - - /** - * Return the method used to compress the data. - * @return the zip compression method - * @see ZipEntry#STORED - * @see ZipEntry#DEFLATED - */ - int getMethod(); - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/Handler.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/Handler.java deleted file mode 100644 index 44b60ebd..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/Handler.java +++ /dev/null @@ -1,448 +0,0 @@ -package fun.asgc.neutrino.core.aop.compiler.internal.jar; - -import java.io.File; -import java.io.IOException; -import java.lang.ref.SoftReference; -import java.net.*; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.regex.Pattern; - -/** - * {@link URLStreamHandler} for Spring Boot loader {@link JarFile}s. - * - * @author Phillip Webb - * @author Andy Wilkinson - * @since 1.0.0 - * @see JarFile#registerUrlProtocolHandler() - */ -public class Handler extends URLStreamHandler { - - // NOTE: in order to be found as a URL protocol handler, this class must be public, - // must be named Handler and must be in a package ending '.jar' - - private static final String JAR_PROTOCOL = "jar:"; - - private static final String FILE_PROTOCOL = "file:"; - - private static final String TOMCAT_WARFILE_PROTOCOL = "war:file:"; - - private static final String SEPARATOR = "!/"; - - private static final Pattern SEPARATOR_PATTERN = Pattern.compile(SEPARATOR, Pattern.LITERAL); - - private static final String CURRENT_DIR = "/./"; - - private static final Pattern CURRENT_DIR_PATTERN = Pattern.compile(CURRENT_DIR, Pattern.LITERAL); - - private static final String PARENT_DIR = "/../"; - - private static final String PROTOCOL_HANDLER = "java.protocol.handler.pkgs"; - - private static final String[] FALLBACK_HANDLERS = { "sun.net.www.protocol.jar.Handler" }; - - private static URL jarContextUrl; - - private static SoftReference> rootFileCache; - - static { - rootFileCache = new SoftReference<>(null); - } - - private final JarFile jarFile; - - private URLStreamHandler fallbackHandler; - - public Handler() { - this(null); - } - - public Handler(JarFile jarFile) { - this.jarFile = jarFile; - } - - @Override - protected URLConnection openConnection(URL url) throws IOException { - if (this.jarFile != null && isUrlInJarFile(url, this.jarFile)) { - return fun.asgc.neutrino.core.aop.compiler.internal.jar.JarURLConnection.get(url, this.jarFile); - } - try { - return fun.asgc.neutrino.core.aop.compiler.internal.jar.JarURLConnection.get(url, getRootJarFileFromUrl(url)); - } - catch (Exception ex) { - return openFallbackConnection(url, ex); - } - } - - private boolean isUrlInJarFile(URL url, JarFile jarFile) throws MalformedURLException { - // Try the path first to save building a new url string each time - return url.getPath().startsWith(jarFile.getUrl().getPath()) - && url.toString().startsWith(jarFile.getUrlString()); - } - - private URLConnection openFallbackConnection(URL url, Exception reason) throws IOException { - try { - URLConnection connection = openFallbackTomcatConnection(url); - connection = (connection != null) ? connection : openFallbackContextConnection(url); - return (connection != null) ? connection : openFallbackHandlerConnection(url); - } - catch (Exception ex) { - if (reason instanceof IOException) { - log(false, "Unable to open fallback handler", ex); - IOException ioException = (IOException)reason; - throw ioException; - } - log(true, "Unable to open fallback handler", ex); - if (reason instanceof RuntimeException) { - RuntimeException runtimeException = (RuntimeException)reason; - throw runtimeException; - } - throw new IllegalStateException(reason); - } - } - - /** - * Attempt to open a Tomcat formatted 'jar:war:file:...' URL. This method allows us to - * use our own nested JAR support to open the content rather than the logic in - * {@code sun.net.www.protocol.jar.URLJarFile} which will extract the nested jar to - * the temp folder to that its content can be accessed. - * @param url the URL to open - * @return a {@link URLConnection} or {@code null} - */ - private URLConnection openFallbackTomcatConnection(URL url) { - String file = url.getFile(); - if (isTomcatWarUrl(file)) { - file = file.substring(TOMCAT_WARFILE_PROTOCOL.length()); - file = file.replaceFirst("\\*/", "!/"); - try { - URLConnection connection = openConnection(new URL("jar:file:" + file)); - connection.getInputStream().close(); - return connection; - } - catch (IOException ex) { - } - } - return null; - } - - private boolean isTomcatWarUrl(String file) { - if (file.startsWith(TOMCAT_WARFILE_PROTOCOL) || !file.contains("*/")) { - try { - URLConnection connection = new URL(file).openConnection(); - if (connection.getClass().getName().startsWith("org.apache.catalina")) { - return true; - } - } - catch (Exception ex) { - } - } - return false; - } - - /** - * Attempt to open a fallback connection by using a context URL captured before the - * jar handler was replaced with our own version. Since this method doesn't use - * reflection it won't trigger "illegal reflective access operation has occurred" - * warnings on Java 13+. - * @param url the URL to open - * @return a {@link URLConnection} or {@code null} - */ - private URLConnection openFallbackContextConnection(URL url) { - try { - if (jarContextUrl != null) { - return new URL(jarContextUrl, url.toExternalForm()).openConnection(); - } - } - catch (Exception ex) { - } - return null; - } - - /** - * Attempt to open a fallback connection by using reflection to access Java's default - * jar {@link URLStreamHandler}. - * @param url the URL to open - * @return the {@link URLConnection} - * @throws Exception if not connection could be opened - */ - private URLConnection openFallbackHandlerConnection(URL url) throws Exception { - URLStreamHandler fallbackHandler = getFallbackHandler(); - return new URL(null, url.toExternalForm(), fallbackHandler).openConnection(); - } - - private URLStreamHandler getFallbackHandler() { - if (this.fallbackHandler != null) { - return this.fallbackHandler; - } - for (String handlerClassName : FALLBACK_HANDLERS) { - try { - Class handlerClass = Class.forName(handlerClassName); - this.fallbackHandler = (URLStreamHandler) handlerClass.getDeclaredConstructor().newInstance(); - return this.fallbackHandler; - } - catch (Exception ex) { - // Ignore - } - } - throw new IllegalStateException("Unable to find fallback handler"); - } - - private void log(boolean warning, String message, Exception cause) { - try { - Level level = warning ? Level.WARNING : Level.FINEST; - Logger.getLogger(getClass().getName()).log(level, message, cause); - } - catch (Exception ex) { - if (warning) { - System.err.println("WARNING: " + message); - } - } - } - - @Override - protected void parseURL(URL context, String spec, int start, int limit) { - if (spec.regionMatches(true, 0, JAR_PROTOCOL, 0, JAR_PROTOCOL.length())) { - setFile(context, getFileFromSpec(spec.substring(start, limit))); - } - else { - setFile(context, getFileFromContext(context, spec.substring(start, limit))); - } - } - - private String getFileFromSpec(String spec) { - int separatorIndex = spec.lastIndexOf("!/"); - if (separatorIndex == -1) { - throw new IllegalArgumentException("No !/ in spec '" + spec + "'"); - } - try { - new URL(spec.substring(0, separatorIndex)); - return spec; - } - catch (MalformedURLException ex) { - throw new IllegalArgumentException("Invalid spec URL '" + spec + "'", ex); - } - } - - private String getFileFromContext(URL context, String spec) { - String file = context.getFile(); - if (spec.startsWith("/")) { - return trimToJarRoot(file) + SEPARATOR + spec.substring(1); - } - if (file.endsWith("/")) { - return file + spec; - } - int lastSlashIndex = file.lastIndexOf('/'); - if (lastSlashIndex == -1) { - throw new IllegalArgumentException("No / found in context URL's file '" + file + "'"); - } - return file.substring(0, lastSlashIndex + 1) + spec; - } - - private String trimToJarRoot(String file) { - int lastSeparatorIndex = file.lastIndexOf(SEPARATOR); - if (lastSeparatorIndex == -1) { - throw new IllegalArgumentException("No !/ found in context URL's file '" + file + "'"); - } - return file.substring(0, lastSeparatorIndex); - } - - private void setFile(URL context, String file) { - String path = normalize(file); - String query = null; - int queryIndex = path.lastIndexOf('?'); - if (queryIndex != -1) { - query = path.substring(queryIndex + 1); - path = path.substring(0, queryIndex); - } - setURL(context, JAR_PROTOCOL, null, -1, null, null, path, query, context.getRef()); - } - - private String normalize(String file) { - if (!file.contains(CURRENT_DIR) && !file.contains(PARENT_DIR)) { - return file; - } - int afterLastSeparatorIndex = file.lastIndexOf(SEPARATOR) + SEPARATOR.length(); - String afterSeparator = file.substring(afterLastSeparatorIndex); - afterSeparator = replaceParentDir(afterSeparator); - afterSeparator = replaceCurrentDir(afterSeparator); - return file.substring(0, afterLastSeparatorIndex) + afterSeparator; - } - - private String replaceParentDir(String file) { - int parentDirIndex; - while ((parentDirIndex = file.indexOf(PARENT_DIR)) >= 0) { - int precedingSlashIndex = file.lastIndexOf('/', parentDirIndex - 1); - if (precedingSlashIndex >= 0) { - file = file.substring(0, precedingSlashIndex) + file.substring(parentDirIndex + 3); - } - else { - file = file.substring(parentDirIndex + 4); - } - } - return file; - } - - private String replaceCurrentDir(String file) { - return CURRENT_DIR_PATTERN.matcher(file).replaceAll("/"); - } - - @Override - protected int hashCode(URL u) { - return hashCode(u.getProtocol(), u.getFile()); - } - - private int hashCode(String protocol, String file) { - int result = (protocol != null) ? protocol.hashCode() : 0; - int separatorIndex = file.indexOf(SEPARATOR); - if (separatorIndex == -1) { - return result + file.hashCode(); - } - String source = file.substring(0, separatorIndex); - String entry = canonicalize(file.substring(separatorIndex + 2)); - try { - result += new URL(source).hashCode(); - } - catch (MalformedURLException ex) { - result += source.hashCode(); - } - result += entry.hashCode(); - return result; - } - - @Override - protected boolean sameFile(URL u1, URL u2) { - if (!u1.getProtocol().equals("jar") || !u2.getProtocol().equals("jar")) { - return false; - } - int separator1 = u1.getFile().indexOf(SEPARATOR); - int separator2 = u2.getFile().indexOf(SEPARATOR); - if (separator1 == -1 || separator2 == -1) { - return super.sameFile(u1, u2); - } - String nested1 = u1.getFile().substring(separator1 + SEPARATOR.length()); - String nested2 = u2.getFile().substring(separator2 + SEPARATOR.length()); - if (!nested1.equals(nested2)) { - String canonical1 = canonicalize(nested1); - String canonical2 = canonicalize(nested2); - if (!canonical1.equals(canonical2)) { - return false; - } - } - String root1 = u1.getFile().substring(0, separator1); - String root2 = u2.getFile().substring(0, separator2); - try { - return super.sameFile(new URL(root1), new URL(root2)); - } - catch (MalformedURLException ex) { - // Continue - } - return super.sameFile(u1, u2); - } - - private String canonicalize(String path) { - return SEPARATOR_PATTERN.matcher(path).replaceAll("/"); - } - - public JarFile getRootJarFileFromUrl(URL url) throws IOException { - String spec = url.getFile(); - int separatorIndex = spec.indexOf(SEPARATOR); - if (separatorIndex == -1) { - throw new MalformedURLException("Jar URL does not contain !/ separator"); - } - String name = spec.substring(0, separatorIndex); - return getRootJarFile(name); - } - - private JarFile getRootJarFile(String name) throws IOException { - try { - if (!name.startsWith(FILE_PROTOCOL)) { - throw new IllegalStateException("Not a file URL"); - } - File file = new File(URI.create(name)); - Map cache = rootFileCache.get(); - JarFile result = (cache != null) ? cache.get(file) : null; - if (result == null) { - result = new JarFile(file); - addToRootFileCache(file, result); - } - return result; - } - catch (Exception ex) { - throw new IOException("Unable to open root Jar file '" + name + "'", ex); - } - } - - /** - * Add the given {@link JarFile} to the root file cache. - * @param sourceFile the source file to add - * @param jarFile the jar file. - */ - static void addToRootFileCache(File sourceFile, JarFile jarFile) { - Map cache = rootFileCache.get(); - if (cache == null) { - cache = new ConcurrentHashMap<>(); - rootFileCache = new SoftReference<>(cache); - } - cache.put(sourceFile, jarFile); - } - - /** - * If possible, capture a URL that is configured with the original jar handler so that - * we can use it as a fallback context later. We can only do this if we know that we - * can reset the handlers after. - */ - static void captureJarContextUrl() { - if (canResetCachedUrlHandlers()) { - String handlers = System.getProperty(PROTOCOL_HANDLER); - try { - System.clearProperty(PROTOCOL_HANDLER); - try { - resetCachedUrlHandlers(); - jarContextUrl = new URL("jar:file:context.jar!/"); - URLConnection connection = jarContextUrl.openConnection(); - if (connection instanceof fun.asgc.neutrino.core.aop.compiler.internal.jar.JarURLConnection) { - jarContextUrl = null; - } - } - catch (Exception ex) { - } - } - finally { - if (handlers == null) { - System.clearProperty(PROTOCOL_HANDLER); - } - else { - System.setProperty(PROTOCOL_HANDLER, handlers); - } - } - resetCachedUrlHandlers(); - } - } - - private static boolean canResetCachedUrlHandlers() { - try { - resetCachedUrlHandlers(); - return true; - } - catch (Error ex) { - return false; - } - } - - private static void resetCachedUrlHandlers() { - URL.setURLStreamHandlerFactory(null); - } - - /** - * Set if a generic static exception can be thrown when a URL cannot be connected. - * This optimization is used during class loading to save creating lots of exceptions - * which are then swallowed. - * @param useFastConnectionExceptions if fast connection exceptions can be used. - */ - public static void setUseFastConnectionExceptions(boolean useFastConnectionExceptions) { - JarURLConnection.setUseFastExceptions(useFastConnectionExceptions); - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/JarEntry.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/JarEntry.java deleted file mode 100644 index 9a6235a0..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/JarEntry.java +++ /dev/null @@ -1,104 +0,0 @@ -package fun.asgc.neutrino.core.aop.compiler.internal.jar; - -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; -import java.security.CodeSigner; -import java.security.cert.Certificate; -import java.util.jar.Attributes; -import java.util.jar.Manifest; - -/** - * Extended variant of {@link java.util.jar.JarEntry} returned by {@link JarFile}s. - * - * @author Phillip Webb - * @author Andy Wilkinson - */ -class JarEntry extends java.util.jar.JarEntry implements FileHeader { - - private final int index; - - private final AsciiBytes name; - - private final AsciiBytes headerName; - - private final JarFile jarFile; - - private final long localHeaderOffset; - - private volatile JarEntryCertification certification; - - JarEntry(JarFile jarFile, int index, CentralDirectoryFileHeader header, AsciiBytes nameAlias) { - super((nameAlias != null) ? nameAlias.toString() : header.getName().toString()); - this.index = index; - this.name = (nameAlias != null) ? nameAlias : header.getName(); - this.headerName = header.getName(); - this.jarFile = jarFile; - this.localHeaderOffset = header.getLocalHeaderOffset(); - setCompressedSize(header.getCompressedSize()); - setMethod(header.getMethod()); - setCrc(header.getCrc()); - setComment(header.getComment().toString()); - setSize(header.getSize()); - setTime(header.getTime()); - if (header.hasExtra()) { - setExtra(header.getExtra()); - } - } - - int getIndex() { - return this.index; - } - - AsciiBytes getAsciiBytesName() { - return this.name; - } - - @Override - public boolean hasName(CharSequence name, char suffix) { - return this.headerName.matches(name, suffix); - } - - /** - * Return a {@link URL} for this {@link JarEntry}. - * @return the URL for the entry - * @throws MalformedURLException if the URL is not valid - */ - URL getUrl() throws MalformedURLException { - return new URL(this.jarFile.getUrl(), getName()); - } - - @Override - public Attributes getAttributes() throws IOException { - Manifest manifest = this.jarFile.getManifest(); - return (manifest != null) ? manifest.getAttributes(getName()) : null; - } - - @Override - public Certificate[] getCertificates() { - return getCertification().getCertificates(); - } - - @Override - public CodeSigner[] getCodeSigners() { - return getCertification().getCodeSigners(); - } - - private JarEntryCertification getCertification() { - if (!this.jarFile.isSigned()) { - return JarEntryCertification.NONE; - } - JarEntryCertification certification = this.certification; - if (certification == null) { - certification = this.jarFile.getCertification(this); - this.certification = certification; - } - return certification; - } - - @Override - public long getLocalHeaderOffset() { - return this.localHeaderOffset; - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/JarEntryCertification.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/JarEntryCertification.java deleted file mode 100644 index 51bef47a..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/JarEntryCertification.java +++ /dev/null @@ -1,42 +0,0 @@ -package fun.asgc.neutrino.core.aop.compiler.internal.jar; - -import java.security.CodeSigner; -import java.security.cert.Certificate; - -/** - * {@link Certificate} and {@link CodeSigner} details for a {@link JarEntry} from a signed - * {@link JarFile}. - * - * @author Phillip Webb - */ -class JarEntryCertification { - - static final JarEntryCertification NONE = new JarEntryCertification(null, null); - - private final Certificate[] certificates; - - private final CodeSigner[] codeSigners; - - JarEntryCertification(Certificate[] certificates, CodeSigner[] codeSigners) { - this.certificates = certificates; - this.codeSigners = codeSigners; - } - - Certificate[] getCertificates() { - return (this.certificates != null) ? this.certificates.clone() : null; - } - - CodeSigner[] getCodeSigners() { - return (this.codeSigners != null) ? this.codeSigners.clone() : null; - } - - static JarEntryCertification from(java.util.jar.JarEntry certifiedEntry) { - Certificate[] certificates = (certifiedEntry != null) ? certifiedEntry.getCertificates() : null; - CodeSigner[] codeSigners = (certifiedEntry != null) ? certifiedEntry.getCodeSigners() : null; - if (certificates == null && codeSigners == null) { - return NONE; - } - return new JarEntryCertification(certificates, codeSigners); - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/JarEntryFilter.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/JarEntryFilter.java deleted file mode 100644 index e036d174..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/JarEntryFilter.java +++ /dev/null @@ -1,19 +0,0 @@ -package fun.asgc.neutrino.core.aop.compiler.internal.jar; - -/** - * Interface that can be used to filter and optionally rename jar entries. - * - * @author Phillip Webb - */ -interface JarEntryFilter { - - /** - * Apply the jar entry filter. - * @param name the current entry name. This may be different that the original entry - * name if a previous filter has been applied - * @return the new name of the entry or {@code null} if the entry should not be - * included. - */ - AsciiBytes apply(AsciiBytes name); - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/JarFile.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/JarFile.java deleted file mode 100644 index ac1eaade..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/JarFile.java +++ /dev/null @@ -1,460 +0,0 @@ -package fun.asgc.neutrino.core.aop.compiler.internal.jar; - -import fun.asgc.neutrino.core.aop.compiler.internal.data.RandomAccessData; -import fun.asgc.neutrino.core.aop.compiler.internal.data.RandomAccessDataFile; - -import java.io.File; -import java.io.FilePermission; -import java.io.IOException; -import java.io.InputStream; -import java.lang.ref.SoftReference; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLStreamHandler; -import java.net.URLStreamHandlerFactory; -import java.security.Permission; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.Spliterator; -import java.util.Spliterators; -import java.util.function.Supplier; -import java.util.jar.Manifest; -import java.util.stream.Stream; -import java.util.stream.StreamSupport; -import java.util.zip.ZipEntry; - -/** - * Extended variant of {@link java.util.jar.JarFile} that behaves in the same way but - * offers the following additional functionality. - *

    - *
  • A nested {@link JarFile} can be {@link #getNestedJarFile(ZipEntry) obtained} based - * on any directory entry.
  • - *
  • A nested {@link JarFile} can be {@link #getNestedJarFile(ZipEntry) obtained} for - * embedded JAR files (as long as their entry is not compressed).
  • - *
- * - * @author Phillip Webb - * @author Andy Wilkinson - * @since 1.0.0 - */ -public class JarFile extends AbstractJarFile implements Iterable { - - private static final String MANIFEST_NAME = "META-INF/MANIFEST.MF"; - - private static final String PROTOCOL_HANDLER = "java.protocol.handler.pkgs"; - - private static final String HANDLERS_PACKAGE = "org.springframework.boot.loader"; - - private static final AsciiBytes META_INF = new AsciiBytes("META-INF/"); - - private static final AsciiBytes SIGNATURE_FILE_EXTENSION = new AsciiBytes(".SF"); - - private static final String READ_ACTION = "read"; - - private final RandomAccessDataFile rootFile; - - private final String pathFromRoot; - - private final RandomAccessData data; - - private final JarFileType type; - - private URL url; - - private String urlString; - - private final JarFileEntries entries; - - private final Supplier manifestSupplier; - - private SoftReference manifest; - - private boolean signed; - - private String comment; - - private volatile boolean closed; - - private volatile JarFileWrapper wrapper; - - /** - * Create a new {@link JarFile} backed by the specified file. - * @param file the root jar file - * @throws IOException if the file cannot be read - */ - public JarFile(File file) throws IOException { - this(new RandomAccessDataFile(file)); - } - - /** - * Create a new {@link JarFile} backed by the specified file. - * @param file the root jar file - * @throws IOException if the file cannot be read - */ - JarFile(RandomAccessDataFile file) throws IOException { - this(file, "", file, JarFileType.DIRECT); - } - - /** - * Private constructor used to create a new {@link JarFile} either directly or from a - * nested entry. - * @param rootFile the root jar file - * @param pathFromRoot the name of this file - * @param data the underlying data - * @param type the type of the jar file - * @throws IOException if the file cannot be read - */ - private JarFile(RandomAccessDataFile rootFile, String pathFromRoot, RandomAccessData data, JarFileType type) - throws IOException { - this(rootFile, pathFromRoot, data, null, type, null); - } - - private JarFile(RandomAccessDataFile rootFile, String pathFromRoot, RandomAccessData data, JarEntryFilter filter, - JarFileType type, Supplier manifestSupplier) throws IOException { - super(rootFile.getFile()); - super.close(); - this.rootFile = rootFile; - this.pathFromRoot = pathFromRoot; - CentralDirectoryParser parser = new CentralDirectoryParser(); - this.entries = parser.addVisitor(new JarFileEntries(this, filter)); - this.type = type; - parser.addVisitor(centralDirectoryVisitor()); - try { - this.data = parser.parse(data, filter == null); - } - catch (RuntimeException ex) { - try { - this.rootFile.close(); - super.close(); - } - catch (IOException ioex) { - } - throw ex; - } - this.manifestSupplier = (manifestSupplier != null) ? manifestSupplier : () -> { - try (InputStream inputStream = getInputStream(MANIFEST_NAME)) { - if (inputStream == null) { - return null; - } - return new Manifest(inputStream); - } - catch (IOException ex) { - throw new RuntimeException(ex); - } - }; - } - - private CentralDirectoryVisitor centralDirectoryVisitor() { - return new CentralDirectoryVisitor() { - - @Override - public void visitStart(CentralDirectoryEndRecord endRecord, RandomAccessData centralDirectoryData) { - JarFile.this.comment = endRecord.getComment(); - } - - @Override - public void visitFileHeader(CentralDirectoryFileHeader fileHeader, long dataOffset) { - AsciiBytes name = fileHeader.getName(); - if (name.startsWith(META_INF) && name.endsWith(SIGNATURE_FILE_EXTENSION)) { - JarFile.this.signed = true; - } - } - - @Override - public void visitEnd() { - } - - }; - } - - JarFileWrapper getWrapper() throws IOException { - JarFileWrapper wrapper = this.wrapper; - if (wrapper == null) { - wrapper = new JarFileWrapper(this); - this.wrapper = wrapper; - } - return wrapper; - } - - @Override - Permission getPermission() { - return new FilePermission(this.rootFile.getFile().getPath(), READ_ACTION); - } - - protected final RandomAccessDataFile getRootJarFile() { - return this.rootFile; - } - - RandomAccessData getData() { - return this.data; - } - - @Override - public Manifest getManifest() throws IOException { - Manifest manifest = (this.manifest != null) ? this.manifest.get() : null; - if (manifest == null) { - try { - manifest = this.manifestSupplier.get(); - } - catch (RuntimeException ex) { - throw new IOException(ex); - } - this.manifest = new SoftReference<>(manifest); - } - return manifest; - } - - @Override - public Enumeration entries() { - return new JarEntryEnumeration(this.entries.iterator()); - } - - @Override - public Stream stream() { - Spliterator spliterator = Spliterators.spliterator(iterator(), size(), - Spliterator.ORDERED | Spliterator.DISTINCT | Spliterator.IMMUTABLE | Spliterator.NONNULL); - return StreamSupport.stream(spliterator, false); - } - - /** - * Return an iterator for the contained entries. - * @since 2.3.0 - * @see Iterable#iterator() - */ - @Override - @SuppressWarnings({ "unchecked", "rawtypes" }) - public Iterator iterator() { - return (Iterator) this.entries.iterator(this::ensureOpen); - } - - public JarEntry getJarEntry(CharSequence name) { - return this.entries.getEntry(name); - } - - @Override - public JarEntry getJarEntry(String name) { - return (JarEntry) getEntry(name); - } - - public boolean containsEntry(String name) { - return this.entries.containsEntry(name); - } - - @Override - public ZipEntry getEntry(String name) { - ensureOpen(); - return this.entries.getEntry(name); - } - - @Override - InputStream getInputStream() throws IOException { - return this.data.getInputStream(); - } - - @Override - public synchronized InputStream getInputStream(ZipEntry entry) throws IOException { - ensureOpen(); - if (entry instanceof JarEntry) { - JarEntry jarEntry = (JarEntry) entry; - return this.entries.getInputStream(jarEntry); - } - return getInputStream((entry != null) ? entry.getName() : null); - } - - InputStream getInputStream(String name) throws IOException { - return this.entries.getInputStream(name); - } - - /** - * Return a nested {@link JarFile} loaded from the specified entry. - * @param entry the zip entry - * @return a {@link JarFile} for the entry - * @throws IOException if the nested jar file cannot be read - */ - public synchronized JarFile getNestedJarFile(ZipEntry entry) throws IOException { - return getNestedJarFile((JarEntry) entry); - } - - /** - * Return a nested {@link JarFile} loaded from the specified entry. - * @param entry the zip entry - * @return a {@link JarFile} for the entry - * @throws IOException if the nested jar file cannot be read - */ - public synchronized JarFile getNestedJarFile(JarEntry entry) throws IOException { - try { - return createJarFileFromEntry(entry); - } - catch (Exception ex) { - throw new IOException("Unable to open nested jar file '" + entry.getName() + "'", ex); - } - } - - private JarFile createJarFileFromEntry(JarEntry entry) throws IOException { - if (entry.isDirectory()) { - return createJarFileFromDirectoryEntry(entry); - } - return createJarFileFromFileEntry(entry); - } - - private JarFile createJarFileFromDirectoryEntry(JarEntry entry) throws IOException { - AsciiBytes name = entry.getAsciiBytesName(); - JarEntryFilter filter = (candidate) -> { - if (candidate.startsWith(name) && !candidate.equals(name)) { - return candidate.substring(name.length()); - } - return null; - }; - return new JarFile(this.rootFile, this.pathFromRoot + "!/" + entry.getName().substring(0, name.length() - 1), - this.data, filter, JarFileType.NESTED_DIRECTORY, this.manifestSupplier); - } - - private JarFile createJarFileFromFileEntry(JarEntry entry) throws IOException { - if (entry.getMethod() != ZipEntry.STORED) { - throw new IllegalStateException( - "Unable to open nested entry '" + entry.getName() + "'. It has been compressed and nested " - + "jar files must be stored without compression. Please check the " - + "mechanism used to create your executable jar file"); - } - RandomAccessData entryData = this.entries.getEntryData(entry.getName()); - return new JarFile(this.rootFile, this.pathFromRoot + "!/" + entry.getName(), entryData, - JarFileType.NESTED_JAR); - } - - @Override - public String getComment() { - ensureOpen(); - return this.comment; - } - - @Override - public int size() { - ensureOpen(); - return this.entries.getSize(); - } - - @Override - public void close() throws IOException { - if (this.closed) { - return; - } - super.close(); - if (this.type == JarFileType.DIRECT) { - this.rootFile.close(); - } - this.closed = true; - } - - private void ensureOpen() { - if (this.closed) { - throw new IllegalStateException("zip file closed"); - } - } - - boolean isClosed() { - return this.closed; - } - - String getUrlString() throws MalformedURLException { - if (this.urlString == null) { - this.urlString = getUrl().toString(); - } - return this.urlString; - } - - @Override - public URL getUrl() throws MalformedURLException { - if (this.url == null) { - String file = this.rootFile.getFile().toURI() + this.pathFromRoot + "!/"; - file = file.replace("file:////", "file://"); // Fix UNC paths - this.url = new URL("jar", "", -1, file, new Handler(this)); - } - return this.url; - } - - @Override - public String toString() { - return getName(); - } - - @Override - public String getName() { - return this.rootFile.getFile() + this.pathFromRoot; - } - - boolean isSigned() { - return this.signed; - } - - JarEntryCertification getCertification(JarEntry entry) { - try { - return this.entries.getCertification(entry); - } - catch (IOException ex) { - throw new IllegalStateException(ex); - } - } - - public void clearCache() { - this.entries.clearCache(); - } - - protected String getPathFromRoot() { - return this.pathFromRoot; - } - - @Override - JarFileType getType() { - return this.type; - } - - /** - * Register a {@literal 'java.protocol.handler.pkgs'} property so that a - * {@link URLStreamHandler} will be located to deal with jar URLs. - */ - public static void registerUrlProtocolHandler() { - Handler.captureJarContextUrl(); - String handlers = System.getProperty(PROTOCOL_HANDLER, ""); - System.setProperty(PROTOCOL_HANDLER, - ((handlers == null || handlers.isEmpty()) ? HANDLERS_PACKAGE : handlers + "|" + HANDLERS_PACKAGE)); - resetCachedUrlHandlers(); - } - - /** - * Reset any cached handlers just in case a jar protocol has already been used. We - * reset the handler by trying to set a null {@link URLStreamHandlerFactory} which - * should have no effect other than clearing the handlers cache. - */ - private static void resetCachedUrlHandlers() { - try { - URL.setURLStreamHandlerFactory(null); - } - catch (Error ex) { - // Ignore - } - } - - /** - * An {@link Enumeration} on {@linkplain java.util.jar.JarEntry jar entries}. - */ - private static class JarEntryEnumeration implements Enumeration { - - private final Iterator iterator; - - JarEntryEnumeration(Iterator iterator) { - this.iterator = iterator; - } - - @Override - public boolean hasMoreElements() { - return this.iterator.hasNext(); - } - - @Override - public java.util.jar.JarEntry nextElement() { - return this.iterator.next(); - } - - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/JarFileEntries.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/JarFileEntries.java deleted file mode 100644 index f7e1aadd..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/JarFileEntries.java +++ /dev/null @@ -1,470 +0,0 @@ -package fun.asgc.neutrino.core.aop.compiler.internal.jar; - -import fun.asgc.neutrino.core.aop.compiler.internal.data.RandomAccessData; - -import java.io.IOException; -import java.io.InputStream; -import java.util.*; -import java.util.jar.Attributes; -import java.util.jar.Attributes.Name; -import java.util.jar.JarInputStream; -import java.util.jar.Manifest; -import java.util.zip.ZipEntry; - -/** - * Provides access to entries from a {@link JarFile}. In order to reduce memory - * consumption entry details are stored using arrays. The {@code hashCodes} array stores - * the hash code of the entry name, the {@code centralDirectoryOffsets} provides the - * offset to the central directory record and {@code positions} provides the original - * order position of the entry. The arrays are stored in hashCode order so that a binary - * search can be used to find a name. - *

- * A typical Spring Boot application will have somewhere in the region of 10,500 entries - * which should consume about 122K. - * - * @author Phillip Webb - * @author Andy Wilkinson - */ -class JarFileEntries implements CentralDirectoryVisitor, Iterable { - - private static final Runnable NO_VALIDATION = () -> { - }; - - private static final String META_INF_PREFIX = "META-INF/"; - - private static final Name MULTI_RELEASE = new Name("Multi-Release"); - - private static final int BASE_VERSION = 8; - - private static final int RUNTIME_VERSION = 1;// TODO Runtime.version().feature(); - - private static final long LOCAL_FILE_HEADER_SIZE = 30; - - private static final char SLASH = '/'; - - private static final char NO_SUFFIX = 0; - - protected static final int ENTRY_CACHE_SIZE = 25; - - private final JarFile jarFile; - - private final JarEntryFilter filter; - - private RandomAccessData centralDirectoryData; - - private int size; - - private int[] hashCodes; - - private Offsets centralDirectoryOffsets; - - private int[] positions; - - private Boolean multiReleaseJar; - - private JarEntryCertification[] certifications; - - private final Map entriesCache = Collections - .synchronizedMap(new LinkedHashMap(16, 0.75f, true) { - - @Override - protected boolean removeEldestEntry(Map.Entry eldest) { - return size() >= ENTRY_CACHE_SIZE; - } - - }); - - JarFileEntries(JarFile jarFile, JarEntryFilter filter) { - this.jarFile = jarFile; - this.filter = filter; - } - - @Override - public void visitStart(CentralDirectoryEndRecord endRecord, RandomAccessData centralDirectoryData) { - int maxSize = endRecord.getNumberOfRecords(); - this.centralDirectoryData = centralDirectoryData; - this.hashCodes = new int[maxSize]; - this.centralDirectoryOffsets = Offsets.from(endRecord); - this.positions = new int[maxSize]; - } - - @Override - public void visitFileHeader(CentralDirectoryFileHeader fileHeader, long dataOffset) { - AsciiBytes name = applyFilter(fileHeader.getName()); - if (name != null) { - add(name, dataOffset); - } - } - - private void add(AsciiBytes name, long dataOffset) { - this.hashCodes[this.size] = name.hashCode(); - this.centralDirectoryOffsets.set(this.size, dataOffset); - this.positions[this.size] = this.size; - this.size++; - } - - @Override - public void visitEnd() { - sort(0, this.size - 1); - int[] positions = this.positions; - this.positions = new int[positions.length]; - for (int i = 0; i < this.size; i++) { - this.positions[positions[i]] = i; - } - } - - int getSize() { - return this.size; - } - - private void sort(int left, int right) { - // Quick sort algorithm, uses hashCodes as the source but sorts all arrays - if (left < right) { - int pivot = this.hashCodes[left + (right - left) / 2]; - int i = left; - int j = right; - while (i <= j) { - while (this.hashCodes[i] < pivot) { - i++; - } - while (this.hashCodes[j] > pivot) { - j--; - } - if (i <= j) { - swap(i, j); - i++; - j--; - } - } - if (left < j) { - sort(left, j); - } - if (right > i) { - sort(i, right); - } - } - } - - private void swap(int i, int j) { - swap(this.hashCodes, i, j); - this.centralDirectoryOffsets.swap(i, j); - swap(this.positions, i, j); - } - - @Override - public Iterator iterator() { - return new EntryIterator(NO_VALIDATION); - } - - Iterator iterator(Runnable validator) { - return new EntryIterator(validator); - } - - boolean containsEntry(CharSequence name) { - return getEntry(name, FileHeader.class, true) != null; - } - - JarEntry getEntry(CharSequence name) { - return getEntry(name, JarEntry.class, true); - } - - InputStream getInputStream(String name) throws IOException { - FileHeader entry = getEntry(name, FileHeader.class, false); - return getInputStream(entry); - } - - InputStream getInputStream(FileHeader entry) throws IOException { - if (entry == null) { - return null; - } - InputStream inputStream = getEntryData(entry).getInputStream(); - if (entry.getMethod() == ZipEntry.DEFLATED) { - inputStream = new ZipInflaterInputStream(inputStream, (int) entry.getSize()); - } - return inputStream; - } - - RandomAccessData getEntryData(String name) throws IOException { - FileHeader entry = getEntry(name, FileHeader.class, false); - if (entry == null) { - return null; - } - return getEntryData(entry); - } - - private RandomAccessData getEntryData(FileHeader entry) throws IOException { - // aspectjrt-1.7.4.jar has a different ext bytes length in the - // local directory to the central directory. We need to re-read - // here to skip them - RandomAccessData data = this.jarFile.getData(); - byte[] localHeader = data.read(entry.getLocalHeaderOffset(), LOCAL_FILE_HEADER_SIZE); - long nameLength = Bytes.littleEndianValue(localHeader, 26, 2); - long extraLength = Bytes.littleEndianValue(localHeader, 28, 2); - return data.getSubsection(entry.getLocalHeaderOffset() + LOCAL_FILE_HEADER_SIZE + nameLength + extraLength, - entry.getCompressedSize()); - } - - private T getEntry(CharSequence name, Class type, boolean cacheEntry) { - T entry = doGetEntry(name, type, cacheEntry, null); - if (!isMetaInfEntry(name) && isMultiReleaseJar()) { - int version = RUNTIME_VERSION; - AsciiBytes nameAlias = (entry instanceof JarEntry) ? ((JarEntry)entry).getAsciiBytesName() - : new AsciiBytes(name.toString()); - while (version > BASE_VERSION) { - T versionedEntry = doGetEntry("META-INF/versions/" + version + "/" + name, type, cacheEntry, nameAlias); - if (versionedEntry != null) { - return versionedEntry; - } - version--; - } - } - return entry; - } - - private boolean isMetaInfEntry(CharSequence name) { - return name.toString().startsWith(META_INF_PREFIX); - } - - private boolean isMultiReleaseJar() { - Boolean multiRelease = this.multiReleaseJar; - if (multiRelease != null) { - return multiRelease; - } - try { - Manifest manifest = this.jarFile.getManifest(); - if (manifest == null) { - multiRelease = false; - } - else { - Attributes attributes = manifest.getMainAttributes(); - multiRelease = attributes.containsKey(MULTI_RELEASE); - } - } - catch (IOException ex) { - multiRelease = false; - } - this.multiReleaseJar = multiRelease; - return multiRelease; - } - - private T doGetEntry(CharSequence name, Class type, boolean cacheEntry, - AsciiBytes nameAlias) { - int hashCode = AsciiBytes.hashCode(name); - T entry = getEntry(hashCode, name, NO_SUFFIX, type, cacheEntry, nameAlias); - if (entry == null) { - hashCode = AsciiBytes.hashCode(hashCode, SLASH); - entry = getEntry(hashCode, name, SLASH, type, cacheEntry, nameAlias); - } - return entry; - } - - private T getEntry(int hashCode, CharSequence name, char suffix, Class type, - boolean cacheEntry, AsciiBytes nameAlias) { - int index = getFirstIndex(hashCode); - while (index >= 0 && index < this.size && this.hashCodes[index] == hashCode) { - T entry = getEntry(index, type, cacheEntry, nameAlias); - if (entry.hasName(name, suffix)) { - return entry; - } - index++; - } - return null; - } - - @SuppressWarnings("unchecked") - private T getEntry(int index, Class type, boolean cacheEntry, AsciiBytes nameAlias) { - try { - long offset = this.centralDirectoryOffsets.get(index); - FileHeader cached = this.entriesCache.get(index); - FileHeader entry = (cached != null) ? cached - : CentralDirectoryFileHeader.fromRandomAccessData(this.centralDirectoryData, offset, this.filter); - if (CentralDirectoryFileHeader.class.equals(entry.getClass()) && type.equals(JarEntry.class)) { - entry = new JarEntry(this.jarFile, index, (CentralDirectoryFileHeader) entry, nameAlias); - } - if (cacheEntry && cached != entry) { - this.entriesCache.put(index, entry); - } - return (T) entry; - } - catch (IOException ex) { - throw new IllegalStateException(ex); - } - } - - private int getFirstIndex(int hashCode) { - int index = Arrays.binarySearch(this.hashCodes, 0, this.size, hashCode); - if (index < 0) { - return -1; - } - while (index > 0 && this.hashCodes[index - 1] == hashCode) { - index--; - } - return index; - } - - void clearCache() { - this.entriesCache.clear(); - } - - private AsciiBytes applyFilter(AsciiBytes name) { - return (this.filter != null) ? this.filter.apply(name) : name; - } - - JarEntryCertification getCertification(JarEntry entry) throws IOException { - JarEntryCertification[] certifications = this.certifications; - if (certifications == null) { - certifications = new JarEntryCertification[this.size]; - // We fall back to use JarInputStream to obtain the certs. This isn't that - // fast, but hopefully doesn't happen too often. - try (JarInputStream certifiedJarStream = new JarInputStream(this.jarFile.getData().getInputStream())) { - java.util.jar.JarEntry certifiedEntry; - while ((certifiedEntry = certifiedJarStream.getNextJarEntry()) != null) { - // Entry must be closed to trigger a read and set entry certificates - certifiedJarStream.closeEntry(); - int index = getEntryIndex(certifiedEntry.getName()); - if (index != -1) { - certifications[index] = JarEntryCertification.from(certifiedEntry); - } - } - } - this.certifications = certifications; - } - JarEntryCertification certification = certifications[entry.getIndex()]; - return (certification != null) ? certification : JarEntryCertification.NONE; - } - - private int getEntryIndex(CharSequence name) { - int hashCode = AsciiBytes.hashCode(name); - int index = getFirstIndex(hashCode); - while (index >= 0 && index < this.size && this.hashCodes[index] == hashCode) { - FileHeader candidate = getEntry(index, FileHeader.class, false, null); - if (candidate.hasName(name, NO_SUFFIX)) { - return index; - } - index++; - } - return -1; - } - - private static void swap(int[] array, int i, int j) { - int temp = array[i]; - array[i] = array[j]; - array[j] = temp; - } - - private static void swap(long[] array, int i, int j) { - long temp = array[i]; - array[i] = array[j]; - array[j] = temp; - } - - /** - * Iterator for contained entries. - */ - private final class EntryIterator implements Iterator { - - private final Runnable validator; - - private int index = 0; - - private EntryIterator(Runnable validator) { - this.validator = validator; - validator.run(); - } - - @Override - public boolean hasNext() { - this.validator.run(); - return this.index < JarFileEntries.this.size; - } - - @Override - public JarEntry next() { - this.validator.run(); - if (!hasNext()) { - throw new NoSuchElementException(); - } - int entryIndex = JarFileEntries.this.positions[this.index]; - this.index++; - return getEntry(entryIndex, JarEntry.class, false, null); - } - - } - - /** - * Interface to manage offsets to central directory records. Regular zip files are - * backed by an {@code int[]} based implementation, Zip64 files are backed by a - * {@code long[]} and will consume more memory. - */ - private interface Offsets { - - void set(int index, long value); - - long get(int index); - - void swap(int i, int j); - - static Offsets from(CentralDirectoryEndRecord endRecord) { - int size = endRecord.getNumberOfRecords(); - return endRecord.isZip64() ? new Zip64Offsets(size) : new ZipOffsets(size); - } - - } - - /** - * {@link Offsets} implementation for regular zip files. - */ - private static final class ZipOffsets implements Offsets { - - private final int[] offsets; - - private ZipOffsets(int size) { - this.offsets = new int[size]; - } - - @Override - public void swap(int i, int j) { - JarFileEntries.swap(this.offsets, i, j); - } - - @Override - public void set(int index, long value) { - this.offsets[index] = (int) value; - } - - @Override - public long get(int index) { - return this.offsets[index]; - } - - } - - /** - * {@link Offsets} implementation for zip64 files. - */ - private static final class Zip64Offsets implements Offsets { - - private final long[] offsets; - - private Zip64Offsets(int size) { - this.offsets = new long[size]; - } - - @Override - public void swap(int i, int j) { - JarFileEntries.swap(this.offsets, i, j); - } - - @Override - public void set(int index, long value) { - this.offsets[index] = value; - } - - @Override - public long get(int index) { - return this.offsets[index]; - } - - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/JarFileWrapper.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/JarFileWrapper.java deleted file mode 100644 index f3b8cf3b..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/JarFileWrapper.java +++ /dev/null @@ -1,110 +0,0 @@ -package fun.asgc.neutrino.core.aop.compiler.internal.jar; - -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.security.Permission; -import java.util.Enumeration; -import java.util.jar.JarEntry; -import java.util.jar.Manifest; -import java.util.stream.Stream; -import java.util.zip.ZipEntry; - -/** - * A wrapper used to create a copy of a {@link JarFile} so that it can be safely closed - * without closing the original. - * - * @author Phillip Webb - */ -class JarFileWrapper extends AbstractJarFile { - - private final JarFile parent; - - JarFileWrapper(JarFile parent) throws IOException { - super(parent.getRootJarFile().getFile()); - this.parent = parent; - super.close(); - } - - @Override - URL getUrl() throws MalformedURLException { - return this.parent.getUrl(); - } - - @Override - JarFileType getType() { - return this.parent.getType(); - } - - @Override - Permission getPermission() { - return this.parent.getPermission(); - } - - @Override - public Manifest getManifest() throws IOException { - return this.parent.getManifest(); - } - - @Override - public Enumeration entries() { - return this.parent.entries(); - } - - @Override - public Stream stream() { - return this.parent.stream(); - } - - @Override - public JarEntry getJarEntry(String name) { - return this.parent.getJarEntry(name); - } - - @Override - public ZipEntry getEntry(String name) { - return this.parent.getEntry(name); - } - - @Override - InputStream getInputStream() throws IOException { - return this.parent.getInputStream(); - } - - @Override - public synchronized InputStream getInputStream(ZipEntry ze) throws IOException { - return this.parent.getInputStream(ze); - } - - @Override - public String getComment() { - return this.parent.getComment(); - } - - @Override - public int size() { - return this.parent.size(); - } - - @Override - public String toString() { - return this.parent.toString(); - } - - @Override - public String getName() { - return this.parent.getName(); - } - - static JarFile unwrap(java.util.jar.JarFile jarFile) { - if (jarFile instanceof JarFile) { - return (JarFile)jarFile; - } - if (jarFile instanceof JarFileWrapper) { - return unwrap(((JarFileWrapper)jarFile).parent); - } - throw new IllegalStateException("Not a JarFile or Wrapper"); - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/JarURLConnection.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/JarURLConnection.java deleted file mode 100644 index b9b16c7e..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/JarURLConnection.java +++ /dev/null @@ -1,369 +0,0 @@ -package fun.asgc.neutrino.core.aop.compiler.internal.jar; - -import java.io.*; -import java.net.*; -import java.security.Permission; - -/** - * {@link java.net.JarURLConnection} used to support {@link JarFile#getUrl()}. - * - * @author Phillip Webb - * @author Andy Wilkinson - * @author Rostyslav Dudka - */ -public final class JarURLConnection extends java.net.JarURLConnection { - - private static final ThreadLocal useFastExceptions = new ThreadLocal<>(); - - private static final FileNotFoundException FILE_NOT_FOUND_EXCEPTION = new FileNotFoundException( - "Jar file or entry not found"); - - private static final IllegalStateException NOT_FOUND_CONNECTION_EXCEPTION = new IllegalStateException( - FILE_NOT_FOUND_EXCEPTION); - - private static final String SEPARATOR = "!/"; - - private static final URL EMPTY_JAR_URL; - - static { - try { - EMPTY_JAR_URL = new URL("jar:", null, 0, "file:!/", new URLStreamHandler() { - @Override - protected URLConnection openConnection(URL u) throws IOException { - // Stub URLStreamHandler to prevent the wrong JAR Handler from being - // Instantiated and cached. - return null; - } - }); - } - catch (MalformedURLException ex) { - throw new IllegalStateException(ex); - } - } - - private static final JarEntryName EMPTY_JAR_ENTRY_NAME = new JarEntryName(new StringSequence("")); - - private static final JarURLConnection NOT_FOUND_CONNECTION = JarURLConnection.notFound(); - - private final AbstractJarFile jarFile; - - private Permission permission; - - private URL jarFileUrl; - - private final JarEntryName jarEntryName; - - private java.util.jar.JarEntry jarEntry; - - private JarURLConnection(URL url, AbstractJarFile jarFile, JarEntryName jarEntryName) throws IOException { - // What we pass to super is ultimately ignored - super(EMPTY_JAR_URL); - this.url = url; - this.jarFile = jarFile; - this.jarEntryName = jarEntryName; - } - - @Override - public void connect() throws IOException { - if (this.jarFile == null) { - throw FILE_NOT_FOUND_EXCEPTION; - } - if (!this.jarEntryName.isEmpty() && this.jarEntry == null) { - this.jarEntry = this.jarFile.getJarEntry(getEntryName()); - if (this.jarEntry == null) { - throwFileNotFound(this.jarEntryName, this.jarFile); - } - } - this.connected = true; - } - - @Override - public java.util.jar.JarFile getJarFile() throws IOException { - connect(); - return this.jarFile; - } - - @Override - public URL getJarFileURL() { - if (this.jarFile == null) { - throw NOT_FOUND_CONNECTION_EXCEPTION; - } - if (this.jarFileUrl == null) { - this.jarFileUrl = buildJarFileUrl(); - } - return this.jarFileUrl; - } - - private URL buildJarFileUrl() { - try { - String spec = this.jarFile.getUrl().getFile(); - if (spec.endsWith(SEPARATOR)) { - spec = spec.substring(0, spec.length() - SEPARATOR.length()); - } - if (!spec.contains(SEPARATOR)) { - return new URL(spec); - } - return new URL("jar:" + spec); - } - catch (MalformedURLException ex) { - throw new IllegalStateException(ex); - } - } - - @Override - public java.util.jar.JarEntry getJarEntry() throws IOException { - if (this.jarEntryName == null || this.jarEntryName.isEmpty()) { - return null; - } - connect(); - return this.jarEntry; - } - - @Override - public String getEntryName() { - if (this.jarFile == null) { - throw NOT_FOUND_CONNECTION_EXCEPTION; - } - return this.jarEntryName.toString(); - } - - @Override - public InputStream getInputStream() throws IOException { - if (this.jarFile == null) { - throw FILE_NOT_FOUND_EXCEPTION; - } - if (this.jarEntryName.isEmpty() && this.jarFile.getType() == JarFile.JarFileType.DIRECT) { - throw new IOException("no entry name specified"); - } - connect(); - InputStream inputStream = (this.jarEntryName.isEmpty() ? this.jarFile.getInputStream() - : this.jarFile.getInputStream(this.jarEntry)); - if (inputStream == null) { - throwFileNotFound(this.jarEntryName, this.jarFile); - } - return inputStream; - } - - private void throwFileNotFound(Object entry, AbstractJarFile jarFile) throws FileNotFoundException { - if (Boolean.TRUE.equals(useFastExceptions.get())) { - throw FILE_NOT_FOUND_EXCEPTION; - } - throw new FileNotFoundException("JAR entry " + entry + " not found in " + jarFile.getName()); - } - - @Override - public int getContentLength() { - long length = getContentLengthLong(); - if (length > Integer.MAX_VALUE) { - return -1; - } - return (int) length; - } - - @Override - public long getContentLengthLong() { - if (this.jarFile == null) { - return -1; - } - try { - if (this.jarEntryName.isEmpty()) { - return this.jarFile.size(); - } - java.util.jar.JarEntry entry = getJarEntry(); - return (entry != null) ? (int) entry.getSize() : -1; - } - catch (IOException ex) { - return -1; - } - } - - @Override - public Object getContent() throws IOException { - connect(); - return this.jarEntryName.isEmpty() ? this.jarFile : super.getContent(); - } - - @Override - public String getContentType() { - return (this.jarEntryName != null) ? this.jarEntryName.getContentType() : null; - } - - @Override - public Permission getPermission() throws IOException { - if (this.jarFile == null) { - throw FILE_NOT_FOUND_EXCEPTION; - } - if (this.permission == null) { - this.permission = this.jarFile.getPermission(); - } - return this.permission; - } - - @Override - public long getLastModified() { - if (this.jarFile == null || this.jarEntryName.isEmpty()) { - return 0; - } - try { - java.util.jar.JarEntry entry = getJarEntry(); - return (entry != null) ? entry.getTime() : 0; - } - catch (IOException ex) { - return 0; - } - } - - static void setUseFastExceptions(boolean useFastExceptions) { - JarURLConnection.useFastExceptions.set(useFastExceptions); - } - - public static JarURLConnection get(URL url, JarFile jarFile) throws IOException { - StringSequence spec = new StringSequence(url.getFile()); - int index = indexOfRootSpec(spec, jarFile.getPathFromRoot()); - if (index == -1) { - return (Boolean.TRUE.equals(useFastExceptions.get()) ? NOT_FOUND_CONNECTION - : new JarURLConnection(url, null, EMPTY_JAR_ENTRY_NAME)); - } - int separator; - while ((separator = spec.indexOf(SEPARATOR, index)) > 0) { - JarEntryName entryName = JarEntryName.get(spec.subSequence(index, separator)); - JarEntry jarEntry = jarFile.getJarEntry(entryName.toCharSequence()); - if (jarEntry == null) { - return JarURLConnection.notFound(jarFile, entryName); - } - jarFile = jarFile.getNestedJarFile(jarEntry); - index = separator + SEPARATOR.length(); - } - JarEntryName jarEntryName = JarEntryName.get(spec, index); - if (Boolean.TRUE.equals(useFastExceptions.get()) && !jarEntryName.isEmpty() - && !jarFile.containsEntry(jarEntryName.toString())) { - return NOT_FOUND_CONNECTION; - } - return new JarURLConnection(url, jarFile.getWrapper(), jarEntryName); - } - - private static int indexOfRootSpec(StringSequence file, String pathFromRoot) { - int separatorIndex = file.indexOf(SEPARATOR); - if (separatorIndex < 0 || !file.startsWith(pathFromRoot, separatorIndex)) { - return -1; - } - return separatorIndex + SEPARATOR.length() + pathFromRoot.length(); - } - - private static JarURLConnection notFound() { - try { - return notFound(null, null); - } - catch (IOException ex) { - throw new IllegalStateException(ex); - } - } - - private static JarURLConnection notFound(JarFile jarFile, JarEntryName jarEntryName) throws IOException { - if (Boolean.TRUE.equals(useFastExceptions.get())) { - return NOT_FOUND_CONNECTION; - } - return new JarURLConnection(null, jarFile, jarEntryName); - } - - /** - * A JarEntryName parsed from a URL String. - */ - static class JarEntryName { - - private final StringSequence name; - - private String contentType; - - JarEntryName(StringSequence spec) { - this.name = decode(spec); - } - - private StringSequence decode(StringSequence source) { - if (source.isEmpty() || (source.indexOf('%') < 0)) { - return source; - } - ByteArrayOutputStream bos = new ByteArrayOutputStream(source.length()); - write(source.toString(), bos); - // AsciiBytes is what is used to store the JarEntries so make it symmetric - return new StringSequence(AsciiBytes.toString(bos.toByteArray())); - } - - private void write(String source, ByteArrayOutputStream outputStream) { - int length = source.length(); - for (int i = 0; i < length; i++) { - int c = source.charAt(i); - if (c > 127) { - try { - String encoded = URLEncoder.encode(String.valueOf((char) c), "UTF-8"); - write(encoded, outputStream); - } - catch (UnsupportedEncodingException ex) { - throw new IllegalStateException(ex); - } - } - else { - if (c == '%') { - if ((i + 2) >= length) { - throw new IllegalArgumentException( - "Invalid encoded sequence \"" + source.substring(i) + "\""); - } - c = decodeEscapeSequence(source, i); - i += 2; - } - outputStream.write(c); - } - } - } - - private char decodeEscapeSequence(String source, int i) { - int hi = Character.digit(source.charAt(i + 1), 16); - int lo = Character.digit(source.charAt(i + 2), 16); - if (hi == -1 || lo == -1) { - throw new IllegalArgumentException("Invalid encoded sequence \"" + source.substring(i) + "\""); - } - return ((char) ((hi << 4) + lo)); - } - - CharSequence toCharSequence() { - return this.name; - } - - @Override - public String toString() { - return this.name.toString(); - } - - boolean isEmpty() { - return this.name.isEmpty(); - } - - String getContentType() { - if (this.contentType == null) { - this.contentType = deduceContentType(); - } - return this.contentType; - } - - private String deduceContentType() { - // Guess the content type, don't bother with streams as mark is not supported - String type = isEmpty() ? "x-java/jar" : null; - type = (type != null) ? type : guessContentTypeFromName(toString()); - type = (type != null) ? type : "content/unknown"; - return type; - } - - static JarEntryName get(StringSequence spec) { - return get(spec, 0); - } - - static JarEntryName get(StringSequence spec, int beginIndex) { - if (spec.length() <= beginIndex) { - return EMPTY_JAR_ENTRY_NAME; - } - return new JarEntryName(spec.subSequence(beginIndex)); - } - - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/StringSequence.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/StringSequence.java deleted file mode 100644 index 4c2ab911..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/StringSequence.java +++ /dev/null @@ -1,142 +0,0 @@ -package fun.asgc.neutrino.core.aop.compiler.internal.jar; - -import java.util.Objects; - -/** - * A {@link CharSequence} backed by a single shared {@link String}. Unlike a regular - * {@link String}, {@link #subSequence(int, int)} operations will not copy the underlying - * character array. - * - * @author Phillip Webb - */ -final class StringSequence implements CharSequence { - - private final String source; - - private final int start; - - private final int end; - - private int hash; - - StringSequence(String source) { - this(source, 0, (source != null) ? source.length() : -1); - } - - StringSequence(String source, int start, int end) { - Objects.requireNonNull(source, "Source must not be null"); - if (start < 0) { - throw new StringIndexOutOfBoundsException(start); - } - if (end > source.length()) { - throw new StringIndexOutOfBoundsException(end); - } - this.source = source; - this.start = start; - this.end = end; - } - - StringSequence subSequence(int start) { - return subSequence(start, length()); - } - - @Override - public StringSequence subSequence(int start, int end) { - int subSequenceStart = this.start + start; - int subSequenceEnd = this.start + end; - if (subSequenceStart > this.end) { - throw new StringIndexOutOfBoundsException(start); - } - if (subSequenceEnd > this.end) { - throw new StringIndexOutOfBoundsException(end); - } - if (start == 0 && subSequenceEnd == this.end) { - return this; - } - return new StringSequence(this.source, subSequenceStart, subSequenceEnd); - } - - /** - * Returns {@code true} if the sequence is empty. Public to be compatible with JDK 15. - * @return {@code true} if {@link #length()} is {@code 0}, otherwise {@code false} - */ - public boolean isEmpty() { - return length() == 0; - } - - @Override - public int length() { - return this.end - this.start; - } - - @Override - public char charAt(int index) { - return this.source.charAt(this.start + index); - } - - int indexOf(char ch) { - return this.source.indexOf(ch, this.start) - this.start; - } - - int indexOf(String str) { - return this.source.indexOf(str, this.start) - this.start; - } - - int indexOf(String str, int fromIndex) { - return this.source.indexOf(str, this.start + fromIndex) - this.start; - } - - boolean startsWith(String prefix) { - return startsWith(prefix, 0); - } - - boolean startsWith(String prefix, int offset) { - int prefixLength = prefix.length(); - int length = length(); - if (length - prefixLength - offset < 0) { - return false; - } - return this.source.startsWith(prefix, this.start + offset); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!(obj instanceof CharSequence)) { - return false; - } - CharSequence other = (CharSequence)obj; - int n = length(); - if (n != other.length()) { - return false; - } - int i = 0; - while (n-- != 0) { - if (charAt(i) != other.charAt(i)) { - return false; - } - i++; - } - return true; - } - - @Override - public int hashCode() { - int hash = this.hash; - if (hash == 0 && length() > 0) { - for (int i = this.start; i < this.end; i++) { - hash = 31 * hash + this.source.charAt(i); - } - this.hash = hash; - } - return hash; - } - - @Override - public String toString() { - return this.source.substring(this.start, this.end); - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/ZipInflaterInputStream.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/ZipInflaterInputStream.java deleted file mode 100644 index f526f359..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/compiler/internal/jar/ZipInflaterInputStream.java +++ /dev/null @@ -1,72 +0,0 @@ -package fun.asgc.neutrino.core.aop.compiler.internal.jar; - -import java.io.EOFException; -import java.io.IOException; -import java.io.InputStream; -import java.util.zip.Inflater; -import java.util.zip.InflaterInputStream; - -/** - * {@link InflaterInputStream} that supports the writing of an extra "dummy" byte (which - * is required with JDK 6) and returns accurate available() results. - * - * @author Phillip Webb - */ -class ZipInflaterInputStream extends InflaterInputStream { - - private int available; - - private boolean extraBytesWritten; - - ZipInflaterInputStream(InputStream inputStream, int size) { - super(inputStream, new Inflater(true), getInflaterBufferSize(size)); - this.available = size; - } - - @Override - public int available() throws IOException { - if (this.available < 0) { - return super.available(); - } - return this.available; - } - - @Override - public int read(byte[] b, int off, int len) throws IOException { - int result = super.read(b, off, len); - if (result != -1) { - this.available -= result; - } - return result; - } - - @Override - public void close() throws IOException { - super.close(); - this.inf.end(); - } - - @Override - protected void fill() throws IOException { - try { - super.fill(); - } - catch (EOFException ex) { - if (this.extraBytesWritten) { - throw ex; - } - this.len = 1; - this.buf[0] = 0x0; - this.extraBytesWritten = true; - this.inf.setInput(this.buf, 0, this.len); - } - } - - private static int getInflaterBufferSize(long size) { - size += 2; // inflater likes some space - size = (size > 65536) ? 8192 : size; - size = (size <= 0) ? 4096 : size; - return (int) size; - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/interceptor/DefaultInterceptor.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/interceptor/DefaultInterceptor.java deleted file mode 100644 index 6caf1ac1..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/interceptor/DefaultInterceptor.java +++ /dev/null @@ -1,145 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop.interceptor; - -import fun.asgc.neutrino.core.aop.Invocation; -import fun.asgc.neutrino.core.util.Assert; -import fun.asgc.neutrino.core.util.CollectionUtil; -import fun.asgc.neutrino.core.util.TypeUtil; -import lombok.extern.slf4j.Slf4j; - -import java.util.ArrayList; -import java.util.List; - -/** - * 默认的拦截器实现 - * @author: aoshiguchen - * @date: 2022/6/30 - */ -@Slf4j -public class DefaultInterceptor implements Interceptor { - private final List filterList = new ArrayList<>(); - private final List resultAdviceList = new ArrayList<>(); - private final List exceptionHandlerList = new ArrayList<>(); - private String name; - - public DefaultInterceptor() { - this.name = this.getClass().getSimpleName(); - } - - public DefaultInterceptor(String name) { - this.name = name; - } - - @Override - public void intercept(Invocation inv) throws Exception { - try { - log.debug("拦截器:{} class:{} method:{} args:{} before", this.name, inv.getTargetClass().getName(), inv.getTargetMethod().getName(), inv.getArgs()); - if (CollectionUtil.notEmpty(filterList)) { - for (Filter filter : filterList) { - if (filter.filtration(inv.getTargetClass(), inv.getTargetMethod(), inv.getArgs())) { - return; - } - } - } - inv.invoke(); - Object result = inv.getReturnValue(); - log.debug("拦截器:{} class:{} method:{} args:{} result:{} after", this.name, inv.getTargetClass().getName(), inv.getTargetMethod().getName(), inv.getArgs(), result); - - if (CollectionUtil.notEmpty(resultAdviceList)) { - for (ResultAdvice advice : resultAdviceList) { - result = advice.advice(inv.getTargetClass(), inv.getTargetMethod(), result); - } - } - if (null == result) { - result = TypeUtil.getDefaultValue(inv.getReturnType()); - } - inv.setReturnValue(result); - - log.debug("拦截器:{} class:{} method:{} args:{} result:{} finished.", this.name, inv.getTargetClass().getName(), inv.getTargetMethod().getName(), inv.getArgs(), result); - } catch (Exception e) { - log.debug("拦截器:{} class:{} method:{} args:{} exception.", this.name, inv.getTargetClass().getName(), inv.getTargetMethod().getName(), inv.getArgs()); - if (CollectionUtil.notEmpty(exceptionHandlerList)) { - for (ExceptionHandler handler : exceptionHandlerList) { - if (handler.support(e)) { - Object result = handler.handle(e); - if (null != result) { - inv.setReturnValue(result); - } - return; - } - } - } - throw e; - } - } - - /** - * 注册过滤器 - * @param filter - */ - public synchronized void registerFilter(Filter filter) { - Assert.notNull(filter, "过滤器不能为空!"); - this.filterList.add(filter); - } - - /** - * 注册过滤器 - * @param filterList - */ - public synchronized void registerFilter(List filterList) { - Assert.notEmpty(filterList, "过滤器不能为空!"); - this.filterList.addAll(filterList); - } - - /** - * 注册结果处理器 - * @param resultAdvice - */ - public synchronized void registerResultAdvice(ResultAdvice resultAdvice) { - Assert.notNull(resultAdvice, "结果处理器不能为空!"); - this.resultAdviceList.add(resultAdvice); - } - - /** - * 注册结果处理器 - * @param resultAdviceList - */ - public synchronized void registerResultAdvice(List resultAdviceList) { - Assert.notEmpty(resultAdviceList, "结果处理器不能为空!"); - this.resultAdviceList.addAll(resultAdviceList); - } - - /** - * 注册异常处理器 - * @param exceptionHandler - */ - public synchronized void registerExceptionHandler(ExceptionHandler exceptionHandler) { - Assert.notNull(exceptionHandler, "异常处理器不能为空!"); - this.exceptionHandlerList.add(exceptionHandler); - } - - public synchronized void registerExceptionHandler(List exceptionHandlerList) { - Assert.notEmpty(exceptionHandlerList, "异常处理器不能为空!"); - this.exceptionHandlerList.addAll(exceptionHandlerList); - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/interceptor/ExceptionHandler.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/interceptor/ExceptionHandler.java deleted file mode 100644 index bb25a465..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/interceptor/ExceptionHandler.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop.interceptor; - -/** - * 异常处理器 - * @author: aoshiguchen - * @date: 2022/6/27 - */ -public interface ExceptionHandler { - - /** - * 是否支持处理该异常 - * @param e - * @return - */ - boolean support(Exception e); - - /** - * 异常处理 - * @param e - * @return - */ - Object handle(Exception e); -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/interceptor/ExceptionHandlerWrapper.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/interceptor/ExceptionHandlerWrapper.java deleted file mode 100644 index 95b1a23f..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/interceptor/ExceptionHandlerWrapper.java +++ /dev/null @@ -1,84 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop.interceptor; - -import fun.asgc.neutrino.core.util.Assert; -import fun.asgc.neutrino.core.util.LockUtil; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/7 - */ -public class ExceptionHandlerWrapper implements ExceptionHandler { - /** - * 过滤器实例 - */ - private volatile ExceptionHandler instance; - /** - * 过滤器类型 - */ - private Class type; - - private ExceptionHandlerWrapper() { - - } - - private ExceptionHandler getInstance() { - // 若未实例化,则在此先实例化 - return LockUtil.doubleCheckProcessForNoException( - () -> null == instance, - this, - () -> instance = InterceptorFactory.getOrNewExceptionHandler(type), - () -> instance - ); - } - - @Override - public boolean support(Exception e) { - return getInstance().support(e); - } - - @Override - public Object handle(Exception e) { - return getInstance().handle(e); - } - - public static ExceptionHandlerWrapper create(Class type) { - Assert.notNull(type, "异常处理器类型不能为空!"); - ExceptionHandlerWrapper wrapper = new ExceptionHandlerWrapper(); - wrapper.type = type; - return wrapper; - } - - public static ExceptionHandlerWrapper create(ExceptionHandler instance) { - Assert.notNull(instance, "异常处理器实例不能为空!"); - ExceptionHandlerWrapper wrapper = new ExceptionHandlerWrapper(); - wrapper.instance = instance; - wrapper.type = instance.getClass(); - return wrapper; - } - - public Class getType() { - return type; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/interceptor/Filter.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/interceptor/Filter.java deleted file mode 100644 index 104e6013..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/interceptor/Filter.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop.interceptor; - -import java.lang.reflect.Method; - -/** - * 过滤器 - * @author: aoshiguchen - * @date: 2022/6/27 - */ -public interface Filter { - - /** - * 是否过滤 - * @param targetClass - * @param targetMethod - * @param args - * @return - */ - default boolean filtration(Class targetClass, Method targetMethod, Object[] args) { - return false; - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/interceptor/FilterWrapper.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/interceptor/FilterWrapper.java deleted file mode 100644 index 09432f4f..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/interceptor/FilterWrapper.java +++ /dev/null @@ -1,81 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop.interceptor; - -import fun.asgc.neutrino.core.util.Assert; -import fun.asgc.neutrino.core.util.LockUtil; - -import java.lang.reflect.Method; - -/** - * filter包装器 - * @author: aoshiguchen - * @date: 2022/7/7 - */ -public class FilterWrapper implements Filter { - /** - * 过滤器实例 - */ - private volatile Filter instance; - /** - * 过滤器类型 - */ - private Class type; - - private FilterWrapper() { - - } - - private Filter getInstance() { - // 若未实例化,则在此先实例化 - return LockUtil.doubleCheckProcessForNoException( - () -> null == instance, - this, - () -> instance = InterceptorFactory.getOrNewFilter(type), - () -> instance - ); - } - - @Override - public boolean filtration(Class targetClass, Method targetMethod, Object[] args) { - return getInstance().filtration(targetClass, targetMethod, args); - } - - public static FilterWrapper create(Class type) { - Assert.notNull(type, "过滤器类型不能为空!"); - FilterWrapper wrapper = new FilterWrapper(); - wrapper.type = type; - return wrapper; - } - - public static FilterWrapper create(Filter instance) { - Assert.notNull(instance, "过滤器实例不能为空!"); - FilterWrapper wrapper = new FilterWrapper(); - wrapper.instance = instance; - wrapper.type = instance.getClass(); - return wrapper; - } - - public Class getType() { - return type; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/interceptor/InnerGlobalInterceptor.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/interceptor/InnerGlobalInterceptor.java deleted file mode 100644 index 53c2ca05..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/interceptor/InnerGlobalInterceptor.java +++ /dev/null @@ -1,93 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop.interceptor; - -import fun.asgc.neutrino.core.aop.Invocation; -import lombok.extern.slf4j.Slf4j; - -import java.util.List; - -/** - * 内部的全局拦截器 - * @author: aoshiguchen - * @date: aoshiguchen - */ -@Slf4j -public class InnerGlobalInterceptor implements Interceptor { - /** - * 拦截器包装器 - */ - private static final DefaultInterceptor interceptorWrapper = new DefaultInterceptor(InnerGlobalInterceptor.class.getSimpleName()); - - public InnerGlobalInterceptor() { - - } - - @Override - public void intercept(Invocation inv) throws Exception { - interceptorWrapper.intercept(inv); - } - - /** - * 注册过滤器 - * @param filter - */ - public static synchronized void registerFilter(Filter filter) { - interceptorWrapper.registerFilter(filter); - } - - /** - * 注册过滤器 - * @param filterList - */ - public static synchronized void registerFilter(List filterList) { - interceptorWrapper.registerFilter(filterList); - } - - /** - * 注册结果处理器 - * @param resultAdvice - */ - public static synchronized void registerResultAdvice(ResultAdvice resultAdvice) { - interceptorWrapper.registerResultAdvice(resultAdvice); - } - - /** - * 注册结果处理器 - * @param resultAdviceList - */ - public static synchronized void registerResultAdvice(List resultAdviceList) { - interceptorWrapper.registerResultAdvice(resultAdviceList); - } - - /** - * 注册异常处理器 - * @param exceptionHandler - */ - public static synchronized void registerExceptionHandler(ExceptionHandler exceptionHandler) { - interceptorWrapper.registerExceptionHandler(exceptionHandler); - } - - public static synchronized void registerExceptionHandler(List exceptionHandlerList) { - interceptorWrapper.registerExceptionHandler(exceptionHandlerList); - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/interceptor/Interceptor.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/interceptor/Interceptor.java deleted file mode 100644 index d799d054..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/interceptor/Interceptor.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop.interceptor; - -import fun.asgc.neutrino.core.aop.Invocation; - -/** - * @author: aoshiguchen - * @date: 2022/6/24 - */ -public interface Interceptor { - /** - * 拦截方法 - * @param inv - */ - void intercept(Invocation inv) throws Exception; -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/interceptor/InterceptorFactory.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/interceptor/InterceptorFactory.java deleted file mode 100644 index 8f4f223e..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/interceptor/InterceptorFactory.java +++ /dev/null @@ -1,489 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop.interceptor; - -import fun.asgc.neutrino.core.aop.support.Async; -import fun.asgc.neutrino.core.aop.support.AsyncInterceptor; -import fun.asgc.neutrino.core.aop.support.Singleton; -import fun.asgc.neutrino.core.aop.Intercept; -import fun.asgc.neutrino.core.aop.support.SingletonInterceptor; -import fun.asgc.neutrino.core.base.GlobalConfig; -import fun.asgc.neutrino.core.cache.Cache; -import fun.asgc.neutrino.core.cache.MemoryCache; -import fun.asgc.neutrino.core.util.*; - -import java.lang.reflect.Method; -import java.util.*; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -/** - * 拦截器工厂 - * @author: aoshiguchen - * @date: 2022/6/24 - */ -public class InterceptorFactory { - private static final Cache, Interceptor> interceptorCache = new MemoryCache<>(); - private static final List globalInterceptorList = Collections.synchronizedList(new ArrayList<>()); - private static final Map, List> classInterceptorListMap = new HashMap<>(); - private static final Map> methodInterceptorListMap = new HashMap<>(); - private static final Cache, Filter> filterCache = new MemoryCache<>(); - private static final Cache, ResultAdvice> resultAdviceCache = new MemoryCache<>(); - private static final Cache, ExceptionHandler> exceptionHandlerCache = new MemoryCache<>(); - - static { - registerGlobalInterceptor(InnerGlobalInterceptor.class); - } - - /** - * 获取或新建缓存bean实例 - * @param clazz - * @param cache - * @param - * @return - */ - private static T getOrNewCacheBean(Class clazz, Cache cache) { - return (T)LockUtil.doubleCheckProcessForNoException(() -> !cache.containsKey(clazz), - clazz, - () -> { - try { - Object obj = null; - if (GlobalConfig.isContainerStartup()) { - obj = BeanManager.getBean(clazz); - } - if (null == obj) { - obj = clazz.newInstance(); - } - cache.set(clazz, obj); - } catch (InstantiationException|IllegalAccessException e) { - throw e; - } - }, - () -> cache.get(clazz) - ); - } - - /** - * 获取拦截器实例 - * @param clazz - * @param - * @return - */ - public static T getOrNew(Class clazz) { - return (T)getOrNewCacheBean(clazz, interceptorCache); - } - - /** - * 获取过滤器实例 - * @param clazz - * @param - * @return - */ - public static T getOrNewFilter(Class clazz) { - return (T)getOrNewCacheBean(clazz, filterCache); - } - - /** - * 获取过滤器列表 - * @param classes - * @param - * @return - */ - public static List getOrNewFilterList(Class[] classes) { - if (ArrayUtil.isEmpty(classes)) { - return null; - } - return Stream.of(classes).map(c -> (T)getOrNewFilter(c)).filter(Objects::nonNull).collect(Collectors.toList()); - } - - /** - * 获取结果处理器实例 - * @param clazz - * @param - * @return - */ - public static T getOrNewResultAdvice(Class clazz) { - return (T)getOrNewCacheBean(clazz, resultAdviceCache); - } - - /** - * 获取结果处理器列表 - * @param classes - * @param - * @return - */ - public static List getOrNewResultAdviceList(Class[] classes) { - if (ArrayUtil.isEmpty(classes)) { - return null; - } - return Stream.of(classes).map(c -> (T)getOrNewResultAdvice(c)).filter(Objects::nonNull).collect(Collectors.toList()); - } - - /** - * 获取异常处理器实例 - * @param clazz - * @param - * @return - */ - public static T getOrNewExceptionHandler(Class clazz) { - return (T)getOrNewCacheBean(clazz, exceptionHandlerCache); - } - - /** - * 获取异常处理器列表 - * @param classes - * @param - * @return - */ - public static List getOrNewExceptionHandlerList(Class[] classes) { - if (ArrayUtil.isEmpty(classes)) { - return null; - } - return Stream.of(classes).map(c -> (T)getOrNewExceptionHandler(c)).filter(Objects::nonNull).collect(Collectors.toList()); - } - - /** - * 获取拦截器实例 - * @param clazz - * @return - */ - public static Interceptor get(Class clazz) { - return InterceptorWrapper.create(clazz); - } - - /** - * 获取过滤器实例 - * @param clazz - * @param - * @return - */ - private static T getFilter(Class clazz) { - return (T)getOrNewCacheBean(clazz, filterCache); - } - - /** - * 获取过滤器列表 - * @param classes - * @param - * @return - */ - private static List getFilterList(Class[] classes) { - if (ArrayUtil.isEmpty(classes)) { - return null; - } - return Stream.of(classes).map(c -> (T)getFilter(c)).filter(Objects::nonNull).collect(Collectors.toList()); - } - - /** - * 获取结果处理器实例 - * @param clazz - * @param - * @return - */ - private static T getResultAdvice(Class clazz) { - return (T)getOrNewCacheBean(clazz, resultAdviceCache); - } - - /** - * 获取结果处理器列表 - * @param classes - * @param - * @return - */ - private static List getResultAdviceList(Class[] classes) { - if (ArrayUtil.isEmpty(classes)) { - return null; - } - return Stream.of(classes).map(c -> (T)getResultAdvice(c)).filter(Objects::nonNull).collect(Collectors.toList()); - } - - /** - * 获取异常处理器实例 - * @param clazz - * @param - * @return - */ - private static T getExceptionHandler(Class clazz) { - return (T)getOrNewCacheBean(clazz, exceptionHandlerCache); - } - - /** - * 获取异常处理器列表 - * @param classes - * @param - * @return - */ - private static List getExceptionHandlerList(Class[] classes) { - if (ArrayUtil.isEmpty(classes)) { - return null; - } - return Stream.of(classes).map(c -> (T)getExceptionHandler(c)).filter(Objects::nonNull).collect(Collectors.toList()); - } - - /** - * 获取目标方法的拦截器实例集合 - * @param targetMethod - * @return - */ - public static List getListByTargetMethod(Method targetMethod) { - Assert.notNull(targetMethod, "目标方法不能为空!"); - - List interceptors = new ArrayList<>(); - interceptors.addAll(globalInterceptorList); - if (classInterceptorListMap.containsKey(targetMethod.getDeclaringClass())) { - interceptors.addAll(classInterceptorListMap.get(targetMethod.getDeclaringClass())); - } - addInterceptorByAnnotation(interceptors, ClassUtil.getAnnotation(targetMethod.getDeclaringClass(), Intercept.class)); - addInterceptorByAnnotation(interceptors, ClassUtil.getAnnotation(targetMethod, Intercept.class)); - if (CollectionUtil.notEmpty(methodInterceptorListMap.get(targetMethod))) { - interceptors.addAll(methodInterceptorListMap.get(targetMethod)); - } - // 如果被代理方法所属类是一个接口,那么该接口所有继承接口链路上的注解都对该方法生效 - if (ClassUtil.isInterface(targetMethod.getDeclaringClass())) { - List> interfaceList = ReflectUtil.getInterfaceAll(targetMethod.getDeclaringClass()); - if (CollectionUtil.notEmpty(interfaceList)) { - for (Class clazz : interfaceList) { - addInterceptorByAnnotation(interceptors, ClassUtil.getAnnotation(clazz, Intercept.class)); - } - } - } - Singleton singleton = ClassUtil.getSingletonAnnotation(targetMethod); - if (null != singleton && singleton.value()) { - SingletonInterceptor interceptor = getOrNew(SingletonInterceptor.class); - interceptors.add(interceptor); - } - Async async = ClassUtil.getAsyncAnnotation(targetMethod); - if (null != async && async.value()) { - AsyncInterceptor interceptor = getOrNew(AsyncInterceptor.class); - interceptors.add(interceptor); - } - return interceptors; - } - - /** - * 根据拦截器注解,将拦截器添加到拦截器集合中 - * @param interceptors - * @param intercept - */ - private static void addInterceptorByAnnotation(List interceptors, Intercept intercept) { - if (null == interceptors || null == intercept) { - return; - } - if (ArrayUtil.notEmpty(intercept.filter()) || ArrayUtil.notEmpty(intercept.resultAdvice()) || ArrayUtil.notEmpty(intercept.exceptionHandler())) { - DefaultInterceptor interceptor = new DefaultInterceptor(); - List filterList = getFilterList(intercept.filter()); - List resultAdviceList = getResultAdviceList(intercept.resultAdvice()); - List exceptionHandlerList = getExceptionHandlerList(intercept.exceptionHandler()); - if (CollectionUtil.notEmpty(filterList)) { - interceptor.registerFilter(filterList); - } - if (CollectionUtil.notEmpty(resultAdviceList)) { - interceptor.registerResultAdvice(resultAdviceList); - } - if (CollectionUtil.notEmpty(exceptionHandlerList)) { - interceptor.registerExceptionHandler(exceptionHandlerList); - } - interceptors.add(interceptor); - } - if (ArrayUtil.notEmpty(intercept.value())) { - for (Class clazz : intercept.value()) { - Interceptor interceptor = getOrNew(clazz); - if (null != interceptor && !interceptors.contains(interceptor)) { - interceptors.add(interceptor); - } - } - } - if (ArrayUtil.notEmpty(intercept.exclude())) { - for (Class clazz : intercept.exclude()) { - Interceptor interceptor = get(clazz); - removeInterceptor(interceptors, interceptor); - } - } - if (intercept.ignoreGlobal()) { - removeInterceptor(interceptors, globalInterceptorList); - } - } - - /** - * 注册拦截器 - 全局 - * @param clazz - */ - public static synchronized void registerGlobalInterceptor(Class clazz) { - Assert.notNull(clazz, "class不能为空!"); - Interceptor interceptor = get(clazz); - if (!containsInterceptor(globalInterceptorList, interceptor)) { - globalInterceptorList.add(interceptor); - } - } - - /** - * 注册类的拦截器 - * @param targetType - * @param interceptorType - */ - public static synchronized void registerInterceptor(Class targetType, Class interceptorType) { - Assert.notNull(targetType, "目标类型不能为空不能为空!"); - Assert.notNull(interceptorType, "拦截器类型不能为空不能为空!"); - if (!classInterceptorListMap.containsKey(targetType)) { - classInterceptorListMap.put(targetType, new ArrayList<>()); - } - Interceptor interceptor = get(interceptorType); - if (!containsInterceptor(classInterceptorListMap.get(targetType), interceptor)) { - classInterceptorListMap.get(targetType).add(interceptor); - } - } - - /** - * 注册方法的拦截器 - * @param targetMethod - * @param interceptorType - */ - public static synchronized void registerInterceptor(Method targetMethod, Class interceptorType) { - Assert.notNull(targetMethod, "目标方法不能为空不能为空!"); - Assert.notNull(interceptorType, "拦截器类型不能为空不能为空!"); - if (!methodInterceptorListMap.containsKey(targetMethod)) { - methodInterceptorListMap.put(targetMethod, new ArrayList<>()); - } - Interceptor interceptor = get(interceptorType); - if (!containsInterceptor(methodInterceptorListMap.get(targetMethod), interceptor)) { - methodInterceptorListMap.get(targetMethod).add(interceptor); - } - } - - - /** - * 删除指定拦截器 - * @param list - * @param removeList - */ - private static void removeInterceptor(List list, List removeList) { - if (CollectionUtil.isEmpty(list) || CollectionUtil.isEmpty(removeList)) { - return; - } - removeList.forEach(item -> removeInterceptor(list, item)); - } - - private static boolean containsInterceptor(List list, Interceptor interceptor) { - if (CollectionUtil.isEmpty(list) || null == interceptor) { - return false; - } - Iterator iter = list.iterator(); - while (iter.hasNext()) { - Interceptor item = iter.next(); - if (typeEquals(item, interceptor)) { - return true; - } - } - return false; - } - - /** - * 删除指定拦截器 - * @param list - * @param interceptor - */ - private static void removeInterceptor(List list, Interceptor interceptor) { - if (CollectionUtil.isEmpty(list) || null == interceptor) { - return; - } - Iterator iter = list.iterator(); - while (iter.hasNext()) { - Interceptor item = iter.next(); - if (typeEquals(item, interceptor)) { - iter.remove(); - return; - } - } - } - - private static boolean typeEquals(Interceptor a, Interceptor b) { - if (a == b) { - return true; - } - if (null == a || null == b) { - return false; - } - Class type1 = a.getClass(); - Class type2 = b.getClass(); - if (a instanceof InterceptorWrapper) { - type1 = ((InterceptorWrapper)a).getType(); - } - if (b instanceof InterceptorWrapper) { - type2 = ((InterceptorWrapper)b).getType(); - } - return type1 == type2; - } - - private static boolean typeEquals(Filter a, Filter b) { - if (a == b) { - return true; - } - if (null == a || null == b) { - return false; - } - Class type1 = a.getClass(); - Class type2 = b.getClass(); - if (a instanceof FilterWrapper) { - type1 = ((FilterWrapper)a).getType(); - } - if (b instanceof FilterWrapper) { - type2 = ((FilterWrapper)b).getType(); - } - return type1 == type2; - } - - private static boolean typeEquals(ResultAdvice a, ResultAdvice b) { - if (a == b) { - return true; - } - if (null == a || null == b) { - return false; - } - Class type1 = a.getClass(); - Class type2 = b.getClass(); - if (a instanceof ResultAdviceWrapper) { - type1 = ((ResultAdviceWrapper)a).getType(); - } - if (b instanceof ResultAdviceWrapper) { - type2 = ((ResultAdviceWrapper)b).getType(); - } - return type1 == type2; - } - - private static boolean typeEquals(ExceptionHandler a, ExceptionHandler b) { - if (a == b) { - return true; - } - if (null == a || null == b) { - return false; - } - Class type1 = a.getClass(); - Class type2 = b.getClass(); - if (a instanceof ExceptionHandlerWrapper) { - type1 = ((ExceptionHandlerWrapper)a).getType(); - } - if (b instanceof ExceptionHandlerWrapper) { - type2 = ((ExceptionHandlerWrapper)b).getType(); - } - return type1 == type2; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/interceptor/InterceptorWrapper.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/interceptor/InterceptorWrapper.java deleted file mode 100644 index 70fc7d10..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/interceptor/InterceptorWrapper.java +++ /dev/null @@ -1,84 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop.interceptor; - -import fun.asgc.neutrino.core.aop.Invocation; -import fun.asgc.neutrino.core.util.Assert; -import fun.asgc.neutrino.core.util.LockUtil; - -/** - * 拦截器包装器 - * 用于支持拦截器以type或者实例形式注册 - * - * 以type类型注册时,拦截器的实例化时机延迟到首次调用 - * @author: aoshiguchen - * @date: 2022/7/6 - */ -public class InterceptorWrapper implements Interceptor { - /** - * 拦截器实例 - */ - private volatile Interceptor instance; - /** - * 拦截器类型 - */ - private Class type; - - private InterceptorWrapper() { - - } - - - private Interceptor getInstance() { - // 若未实例化,则在此先实例化 - return LockUtil.doubleCheckProcessForNoException( - () -> null == instance, - this, - () -> instance = InterceptorFactory.getOrNew(type), - () -> instance - ); - } - - @Override - public void intercept(Invocation inv) throws Exception { - getInstance().intercept(inv); - } - - public static InterceptorWrapper create(Class type) { - Assert.notNull(type, "拦截器类型不能为空!"); - InterceptorWrapper wrapper = new InterceptorWrapper(); - wrapper.type = type; - return wrapper; - } - - public static InterceptorWrapper create(Interceptor instance) { - Assert.notNull(instance, "拦截器实例不能为空!"); - InterceptorWrapper wrapper = new InterceptorWrapper(); - wrapper.instance = instance; - wrapper.type = instance.getClass(); - return wrapper; - } - - public Class getType() { - return type; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/interceptor/ResultAdvice.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/interceptor/ResultAdvice.java deleted file mode 100644 index 2e4e10c7..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/interceptor/ResultAdvice.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop.interceptor; - -import java.lang.reflect.Method; - -/** - * 结果处理 - * @author: aoshiguchen - * @date: 2022/6/27 - */ -public interface ResultAdvice { - - /** - * 结果处理 - * @param targetClass - * @param targetMethod - * @param result - * @return - */ - default Object advice(Class targetClass, Method targetMethod, Object result) { - return result; - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/interceptor/ResultAdviceWrapper.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/interceptor/ResultAdviceWrapper.java deleted file mode 100644 index ce767e25..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/interceptor/ResultAdviceWrapper.java +++ /dev/null @@ -1,82 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop.interceptor; - -import fun.asgc.neutrino.core.util.Assert; -import fun.asgc.neutrino.core.util.LockUtil; - -import java.lang.reflect.Method; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/7 - */ -public class ResultAdviceWrapper implements ResultAdvice { - /** - * 过滤器实例 - */ - private volatile ResultAdvice instance; - /** - * 过滤器类型 - */ - private Class type; - - private ResultAdviceWrapper() { - - } - - private ResultAdvice getInstance() { - // 若未实例化,则在此先实例化 - return LockUtil.doubleCheckProcessForNoException( - () -> null == instance, - this, - () -> instance = InterceptorFactory.getOrNewResultAdvice(type), - () -> instance - ); - } - - @Override - public Object advice(Class targetClass, Method targetMethod, Object result) { - return getInstance().advice(targetClass, targetMethod, result); - } - - - public static ResultAdviceWrapper create(Class type) { - Assert.notNull(type, "过滤器类型不能为空!"); - ResultAdviceWrapper wrapper = new ResultAdviceWrapper(); - wrapper.type = type; - return wrapper; - } - - public static ResultAdviceWrapper create(ResultAdvice instance) { - Assert.notNull(instance, "过滤器实例不能为空!"); - ResultAdviceWrapper wrapper = new ResultAdviceWrapper(); - wrapper.instance = instance; - wrapper.type = instance.getClass(); - return wrapper; - } - - public Class getType() { - return type; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/proxy/AsgcProxyFactory.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/proxy/AsgcProxyFactory.java deleted file mode 100644 index 8153a264..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/proxy/AsgcProxyFactory.java +++ /dev/null @@ -1,96 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop.proxy; - -import fun.asgc.neutrino.core.aop.compiler.AsgcCompiler; -import fun.asgc.neutrino.core.base.GlobalConfig; -import fun.asgc.neutrino.core.util.*; -import lombok.extern.slf4j.Slf4j; - -import java.util.concurrent.atomic.AtomicLong; -import java.util.stream.Stream; - -/** - * Asgc代理(子类代理) - * @author: aoshiguchen - * @date: 2022/6/24 - */ -@Slf4j -public class AsgcProxyFactory implements ProxyFactory { - private static final String SYMBOLIC = "AsgcProxy$$"; - private static final String classNameTemplate = "%s" + SYMBOLIC + "%s"; - private static AtomicLong proxyClassCounter = new AtomicLong(); - private AsgcCompiler compiler = new AsgcCompiler(); - - @Override - public T get(Class targetType) throws Exception { - Assert.notNull(targetType, "被代理类不能为空!"); - Assert.isTrue(canProxy(targetType), String.format("类[%s]无法被代理!", targetType.getName())); - return doGet(targetType, targetType); - } - - @Override - public boolean canProxy(Class clazz) { - return ClassUtil.isInterface(clazz) || - (!ClassUtil.isFinal(clazz) - && !ClassUtil.isAbstract(clazz) - && ClassUtil.isPublic(clazz) - && !ClassUtil.isStatic(clazz) - && !ClassUtil.isInterface(clazz) - && Stream.of(clazz.getConstructors()).filter(e -> e.getParameterCount() == 0).count() > 0); - } - - @Override - public P get(Class targetType, Class

proxyType) throws Exception { - Assert.notNull(targetType, "被代理类不能为空!"); - Assert.notNull(proxyType, "代理类类型不能为空!"); - Assert.isTrue(canProxy(targetType, proxyType), String.format("类[targetType:%s, proxyType:%s]无法被代理!", targetType.getName(), proxyType.getName())); - return doGet(targetType, proxyType); - } - - @Override - public boolean canProxy(Class targetType, Class proxyType) { - return canProxy(targetType) && proxyType.isAssignableFrom(targetType); - } - - @Override - public boolean isProxyClass(Class clazz) { - return null != clazz && clazz.getSimpleName().contains(SYMBOLIC); - } - - private P doGet(Class targetType, Class

proxyType) throws ReflectiveOperationException { - ProxyClass proxyClass = new ProxyClass(targetType); - proxyClass.setName(generateClassName(targetType)); - String sourceCode = AsgcProxyGenerator.getInstance().generator(proxyClass.getName(), targetType, proxyType); - proxyClass.setSourceCode(sourceCode); - if (GlobalConfig.isPrintGeneratorCode()) { - log.debug("类:{} 的代理类源码:\n{}", targetType.getName(), sourceCode); - } - Class

retClass = (Class

)compiler.compile(proxyClass.getClassName(), proxyClass.getSourceCode()); - P obj = retClass.newInstance(); - return obj; - } - - private String generateClassName(Class clazz) { - return String.format(classNameTemplate, clazz.getSimpleName(), proxyClassCounter.incrementAndGet()); - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/proxy/AsgcProxyGenerator.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/proxy/AsgcProxyGenerator.java deleted file mode 100644 index 3abfc094..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/proxy/AsgcProxyGenerator.java +++ /dev/null @@ -1,181 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop.proxy; - -import fun.asgc.neutrino.core.aop.Invocation; -import fun.asgc.neutrino.core.util.*; -import lombok.Data; -import lombok.experimental.Accessors; -import org.apache.velocity.Template; -import org.apache.velocity.VelocityContext; -import org.apache.velocity.app.VelocityEngine; -import sun.management.MethodInfo; - -import java.io.StringWriter; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.lang.reflect.Parameter; -import java.util.*; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/6 - */ -@SuppressWarnings("all") -public class AsgcProxyGenerator { - private static final AsgcProxyGenerator instance = new AsgcProxyGenerator(); - private VelocityEngine engine; - private Template template; - - private AsgcProxyGenerator() { - engine = new VelocityEngine(); - engine.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); - engine.init(); - template = engine.getTemplate("tpl/AsgcProxy.tpl"); - } - - private String render(Map map) { - VelocityContext context = new VelocityContext(map); - StringWriter stringWriter = new StringWriter(); - template.merge(context, stringWriter); - return stringWriter.toString(); - } - - public String generator(String proxyClassName, Class targetType) { - return generator(proxyClassName, targetType, targetType); - } - - public String generator(String proxyClassName, Class targetType, Class proxyType) { - Map map = new HashMap<>(); - map.put("package", targetType.getPackage().getName()); - List> importList = new ArrayList<>(); - map.put("importList", importList); - appendImport(importList, Invocation.class); - appendImport(importList, ProxyCache.class); - map.put("proxyClassName", proxyClassName); - map.put("targetType", targetType); - map.put("targetIsInterface", ClassUtil.isInterface(targetType)); - - List methodInfoList = new ArrayList<>(); - map.put("methodInfoList", methodInfoList); - - Method[] methods = proxyType.getMethods(); - if (ArrayUtil.notEmpty(methods)) { - for (Method method : methods) { - if (Modifier.isFinal(method.getModifiers()) || - Modifier.isStatic(method.getModifiers()) || - method.isSynthetic() - ) { - continue; - } - Long methodId = ProxyCache.setMethod(method); - Class returnType = method.getReturnType(); - boolean isVoid = returnType == void.class; - appendImport(importList, returnType); - if (ArrayUtil.notEmpty(method.getParameters())) { - Stream.of(method.getParameters()).forEach(parameter -> appendImport(importList, parameter.getType())); - } - Set> exceptionTypes = ReflectUtil.getExceptionTypes(method); - boolean isThrow = CollectionUtil.notEmpty(exceptionTypes); - String throwsString = isThrow ? " throws " + buildTypeNameString(exceptionTypes) + " ": " "; - if (CollectionUtil.notEmpty(exceptionTypes)) { - exceptionTypes.forEach(exceptionType -> appendImport(importList, exceptionType)); - } - - String parameterNamesString = buildParameterNamesString(method.getParameters()); - methodInfoList.add(new MethodInfo() - .setMethodId(methodId) - .setReturnType(returnType) - .setVoid(isVoid) - .setMethodName(method.getName()) - .setParametersString(buildParametersString(method.getParameters())) - .setThrowsString(throwsString) - .setThrow(isThrow) - .setParameterNamesString(parameterNamesString) - ); - } - } - return render(map); - } - - public static AsgcProxyGenerator getInstance() { - return instance; - } - - private String buildParametersString(Parameter[] parameters) { - if (ArrayUtil.isEmpty(parameters)) { - return ""; - } - return Stream.of(parameters).map(item -> item.getType().getSimpleName() + " " + item.getName()).collect(Collectors.joining(", ")); - } - - private String buildTypeNameString(Set> classes) { - if (CollectionUtil.isEmpty(classes)) { - return ""; - } - return classes.stream().map(Class::getSimpleName).collect(Collectors.joining(",")); - } - - private String buildParameterNamesString(Parameter[] parameters) { - if (ArrayUtil.isEmpty(parameters)) { - return ""; - } - return Stream.of(parameters).map(Parameter::getName).collect(Collectors.joining(", ")); - } - - /** - * 追加import语句,java.lang包下不需要import - * @param importClasses - * @param clazz - */ - private synchronized void appendImport(List> importClasses, Class clazz) { - if (importClasses.contains(clazz) || - clazz.getName().startsWith("java.lang.") || - TypeUtil.isNormalBasicType(clazz) || - clazz == void.class - ) { - return; - } - if (clazz.isArray()) { - appendImport(importClasses, clazz.getComponentType()); - return; - } - - importClasses.add(clazz); - } - - @Accessors(chain = true) - @Data - public static class MethodInfo { - private Long methodId; - private Class returnType; - private boolean isVoid; - private String methodName; - private String parametersString; - private String throwsString; - private boolean isThrow; - private String parameterNamesString; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/proxy/JdkDynamicProxyFactory.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/proxy/JdkDynamicProxyFactory.java deleted file mode 100644 index 5c013cdb..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/proxy/JdkDynamicProxyFactory.java +++ /dev/null @@ -1,106 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop.proxy; - -import fun.asgc.neutrino.core.aop.Invocation; -import fun.asgc.neutrino.core.util.*; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.util.Set; - -/** - * JDK动态代理 - * @author: aoshiguchen - * @date: 2022/6/29 - */ -public class JdkDynamicProxyFactory implements ProxyFactory { - - @Override - public T get(Class clazz) throws Exception { - Assert.notNull(clazz, "被代理类不能为空!"); - Assert.isTrue(canProxy(clazz), String.format("类[%s]无法被代理!", clazz.getName())); - return doGet(clazz); - } - - private T doGet(Class clazz) throws ReflectiveOperationException { - return (T) Proxy.newProxyInstance(clazz.getClassLoader(), - new Class[]{clazz}, - new JdkDynamicProxy(null) - ); - } - - @Override - public boolean canProxy(Class clazz) { - return ClassUtil.isInterface(clazz); - } - - @Override - public P get(Class targetType, Class

proxyType) throws Exception { - Assert.notNull(targetType, "被代理类不能为空!"); - Assert.notNull(proxyType, "代理类类型不能为空!"); - Assert.isTrue(canProxy(targetType, proxyType), String.format("类[targetType:%s, proxyType:%s]无法被代理!", targetType.getName(), proxyType.getName())); - return (P) Proxy.newProxyInstance(targetType.getClassLoader(), - new Class[]{proxyType}, - new JdkDynamicProxy(targetType.newInstance()) - ); - } - - @Override - public boolean canProxy(Class targetType, Class proxyType) { - return ClassUtil.isInterface(proxyType) && proxyType.isAssignableFrom(targetType); - } - - @Override - public boolean isProxyClass(Class clazz) { - return Proxy.isProxyClass(clazz); - } - - private static class JdkDynamicProxy implements InvocationHandler { - private Object target; - public JdkDynamicProxy(Object target) { - this.target = target; - } - @Override - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - Long methodId = ProxyCache.setMethod(method); - Invocation inv = new Invocation(methodId, proxy, () -> { - if (null != target) { - return method.invoke(target, args); - } - return null; - }, args); - try { - inv.invoke(); - } catch (Exception e) { - Set> exceptionTypes = ReflectUtil.getExceptionTypes(method); - if (CollectionUtil.notEmpty(exceptionTypes) && exceptionTypes.contains(e.getClass())) { - throw e; - } else { - e.printStackTrace(); - } - } - return inv.getReturnValue(); - } - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/proxy/Proxy.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/proxy/Proxy.java deleted file mode 100644 index 37745dfb..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/proxy/Proxy.java +++ /dev/null @@ -1,43 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop.proxy; - -import fun.asgc.neutrino.core.aop.ProxyStrategy; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/24 - */ -public class Proxy { - private static final ProxyFactory subClassProxyFactory = new AsgcProxyFactory(); - private static final ProxyFactory jdkDynamicProxyFactory = new JdkDynamicProxyFactory(); - - public static ProxyFactory getProxyFactory(ProxyStrategy strategy) { - switch (strategy) { - case ASGC_PROXY: return subClassProxyFactory; - case JDK_DYNAMIC_PROXY: return jdkDynamicProxyFactory; - default: return null; - } - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/proxy/ProxyCache.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/proxy/ProxyCache.java deleted file mode 100644 index c4624307..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/proxy/ProxyCache.java +++ /dev/null @@ -1,66 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop.proxy; - -import fun.asgc.neutrino.core.util.CollectionUtil; -import fun.asgc.neutrino.core.util.ReflectUtil; - -import java.lang.reflect.Method; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.atomic.AtomicLong; - -/** - * 代理缓存 - * @author: aoshiguchen - * @date: 2022/6/24 - */ -public class ProxyCache { - private static final AtomicLong methodId = new AtomicLong(); - private static final Map methodCache = Collections.synchronizedMap(new HashMap<>()); - private static final Map>> methodExceptionTypesCache = Collections.synchronizedMap(new HashMap<>()); - - public static Long generateMethodId() { - return methodId.incrementAndGet(); - } - - public static Long setMethod(Method method) { - Long id = generateMethodId(); - methodCache.put(id, method); - methodExceptionTypesCache.put(id, ReflectUtil.getExceptionTypes(method)); - return id; - } - - public static Method getMethod(Long id) { - return methodCache.get(id); - } - - public static boolean checkMethodThrow(Long id, Exception e) { - Set> exceptionTypes = methodExceptionTypesCache.get(id); - if (CollectionUtil.isEmpty(exceptionTypes)) { - return false; - } - return exceptionTypes.contains(e.getClass()) || e instanceof RuntimeException; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/proxy/ProxyClass.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/proxy/ProxyClass.java deleted file mode 100644 index fd1d8d01..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/proxy/ProxyClass.java +++ /dev/null @@ -1,76 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop.proxy; - -import fun.asgc.neutrino.core.util.StringUtil; -import lombok.Data; - -import java.util.Map; - -/** - * - * @author: 代理类 - * @date: 2022/6/24 - */ -@Data -public class ProxyClass { - /** - * 被代理的目标 - */ - private Class target; - /** - * 包名 - */ - private String pkg; - /** - * 类名 - */ - private String name; - /** - * 源代码 - */ - private String sourceCode; - /** - * 字节码 - */ - private Map byteCode; - /** - * 字节码被加载后的代理类 - */ - private Class clazz; - - public ProxyClass(Class target) { - this.target = target; - this.pkg = target.getPackage().getName(); - } - - public ProxyClass() { - - } - - public String getClassName() { - if (StringUtil.isEmpty(pkg)) { - return name; - } - return String.format("%s.%s", pkg, name); - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/proxy/ProxyFactory.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/proxy/ProxyFactory.java deleted file mode 100644 index ff088cdc..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/proxy/ProxyFactory.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop.proxy; - -/** - * @author: aoshiguchen - * @date: 2022/6/24 - */ -public interface ProxyFactory { - - /** - * 获取一个类的代理实例 - * @param clazz - * @param - * @return - */ - T get(Class clazz) throws Exception; - - /** - * 是否能被代理 - * @param clazz - * @return - */ - boolean canProxy(Class clazz); - - /** - * 获取一个类的代理类实例 - * @param targetType - * @param proxyType - * @param - * @param

- * @return - * @throws Exception - */ - P get(Class targetType, Class

proxyType) throws Exception; - - /** - * 是否能被代理 - * @param targetType - * @param proxyType - * @return - */ - boolean canProxy(Class targetType, Class proxyType); - - /** - * 判断指定类是否由当前代理策略产生 - * @param clazz - * @return - */ - boolean isProxyClass(Class clazz); -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/support/Async.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/support/Async.java deleted file mode 100644 index ed48a93e..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/support/Async.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop.support; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/8 - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE, ElementType.METHOD}) -public @interface Async { - boolean value() default true; -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/support/AsyncInterceptor.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/support/AsyncInterceptor.java deleted file mode 100644 index ed6ce1be..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/support/AsyncInterceptor.java +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop.support; - -import fun.asgc.neutrino.core.aop.Invocation; -import fun.asgc.neutrino.core.aop.interceptor.Interceptor; -import fun.asgc.neutrino.core.base.CustomThreadFactory; - -import java.util.concurrent.*; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * 异步拦截器 - * @author: aoshiguchen - * @date: 2022/7/8 - */ -public class AsyncInterceptor implements Interceptor { - private static final ExecutorService executorService = new ThreadPoolExecutor(10, 50, - 10L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), new CustomThreadFactory("Async")); - - @Override - public void intercept(Invocation inv) throws Exception { - executorService.submit(() -> { - try { - inv.invoke(); - } catch (Exception e) { - e.printStackTrace(); - } - }); - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/support/Singleton.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/support/Singleton.java deleted file mode 100644 index db3e779b..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/support/Singleton.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop.support; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * @author: aoshiguchen - * @date: 2022/7/8 - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE, ElementType.METHOD}) -public @interface Singleton { - boolean value() default true; -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/support/SingletonInterceptor.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/support/SingletonInterceptor.java deleted file mode 100644 index 7f46fc4d..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/aop/support/SingletonInterceptor.java +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop.support; - -import fun.asgc.neutrino.core.aop.Invocation; -import fun.asgc.neutrino.core.aop.interceptor.Interceptor; -import fun.asgc.neutrino.core.util.LockUtil; - -import java.lang.reflect.Method; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * 单例拦截器 - * @author: aoshiguchen - * @date: 2022/7/8 - */ -public class SingletonInterceptor implements Interceptor { - private static final Map cache = new ConcurrentHashMap<>(); - - @Override - public void intercept(Invocation inv) throws Exception { - LockUtil.doubleCheckProcess( - () -> !cache.containsKey(inv.getTargetMethod()), - inv.getTargetMethod(), - () -> { - inv.invoke(); - cache.put(inv.getTargetMethod(), inv.getReturnValue()); - } - ); - inv.setReturnValue(cache.get(inv.getTargetMethod())); - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/Channel.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/Channel.java deleted file mode 100644 index 82d67ae2..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/Channel.java +++ /dev/null @@ -1,47 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.base; - -/** - * @author: aoshiguchen - * @date: 2022/9/29 - */ -public interface Channel { - - /** - * 注册接收者 - * @param receiver 接收者 - */ - void registerReceiver(R receiver); - - /** - * 注销接收者 - * @param receiver 接收者 - */ - void unRegisterReceiver(R receiver); - - /** - * 发布消息 - * @param msg 消息 - */ - void publish(D msg); -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/ChannelConnector.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/ChannelConnector.java deleted file mode 100644 index e1068166..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/ChannelConnector.java +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.base; - -/** - * 该接口用于将多个channel连接,实现消息广播 - * 应用场景: - * 项目初期,为了快速实现功能,不考虑多节点,可能不会接入太多的第三方依赖,如:redis、rocketMQ等。 - * 但是要保证后期需要的时候能够快速接入,而不需要对现有逻辑做太大的改动。 - * - * 那么,前期你可以使用ApplicationEventChannel,来做业务解藕。 - * 当多次迭代后需要引入RocketMQ,则直接让ApplicationEventChannel连接RocketMQChannel,从而大大减少开发工作。 - * - * 该方案适用于异步、解耦、削峰,不适用与事务消息、延时消息. - * - * 需要注意的是,该连接是单向连接。 - * 如:A连接B,则经过A的消息会广播给B,而经过B的消息不会广播给A - * 如果需要,B也需要实现该接口,并且连接A - * - * @author: aoshiguchen - * @date: 2022/10/7 - */ -public interface ChannelConnector { - /** - * 连接channel - * @param channel channel - */ - void connectChannel(C channel); - - /** - * 断开连接channel - * @param channel channel - */ - void disconnectChannel(C channel); -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/CodeBlock.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/CodeBlock.java deleted file mode 100644 index cf416022..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/CodeBlock.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.base; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -@FunctionalInterface -public interface CodeBlock { - - /** - * 执行 - */ - void execute() throws Exception; -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/Convert.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/Convert.java deleted file mode 100644 index 5c70ce36..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/Convert.java +++ /dev/null @@ -1,82 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.base; - -import com.google.common.collect.Lists; -import fun.asgc.neutrino.core.util.CollectionUtil; - -import java.util.List; - -/** - * 转换器 - * @author: aoshiguchen - * @date: 2022/6/27 - */ -public interface Convert { - - /** - * 从目标内容转换为原内容 - * @param target - * @return - */ - S from(T target); - - /** - * 从原内容转换为目标内容 - * @param source - * @return - */ - T to(S source); - - /** - * 从目标内容转换为原内容 - * @param targetList - * @return - */ - default List from(List targetList) { - List list = Lists.newArrayList(); - if (CollectionUtil.isEmpty(targetList)) { - return list; - } - for (T target : targetList) { - list.add(from(target)); - } - return list; - } - - /** - * 从原内容转换为目标内容 - * @param sourceList - * @return - */ - default List to(List sourceList) { - List list = Lists.newArrayList(); - if (CollectionUtil.isEmpty(sourceList)) { - return list; - } - for (S source : sourceList) { - list.add(to(source)); - } - return list; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/CustomThreadFactory.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/CustomThreadFactory.java deleted file mode 100644 index dcbd5e61..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/CustomThreadFactory.java +++ /dev/null @@ -1,55 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.base; - -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * - * @author: aoshiguchen - * @date: 2022/9/4 - */ -public class CustomThreadFactory implements ThreadFactory { - private final ThreadGroup group; - private final AtomicInteger threadNumber = new AtomicInteger(1); - private final String namePrefix; - - public CustomThreadFactory(String prefix) { - SecurityManager s = System.getSecurityManager(); - group = (s != null) ? s.getThreadGroup() : - Thread.currentThread().getThreadGroup(); - namePrefix = prefix + "-thread-"; - } - - @Override - public Thread newThread(Runnable r) { - Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); - if (t.isDaemon()) { - t.setDaemon(false); - } - if (t.getPriority() != Thread.NORM_PRIORITY) { - t.setPriority(Thread.NORM_PRIORITY); - } - return t; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/DefaultDispatcher.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/DefaultDispatcher.java deleted file mode 100644 index 9e38fb43..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/DefaultDispatcher.java +++ /dev/null @@ -1,112 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.base; - -import com.alibaba.fastjson.JSONObject; -import fun.asgc.neutrino.core.annotation.Match; -import fun.asgc.neutrino.core.util.Assert; -import fun.asgc.neutrino.core.util.CollectionUtil; -import fun.asgc.neutrino.core.util.StringUtil; -import fun.asgc.neutrino.core.util.TypeUtil; -import lombok.extern.slf4j.Slf4j; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.function.Function; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -@Slf4j -public class DefaultDispatcher implements Dispatcher { - - /** - * 调度器名称 - */ - private String name; - - /** - * 处理器映射 - */ - private Map> handlerMap; - /** - * 匹配器 - */ - private Function matcher; - - public DefaultDispatcher(String name, List> handlerList, Function matcher) { - Assert.notNull(name, "名称不能为空!"); - Assert.notNull(matcher, "匹配器不能为空!"); - if (CollectionUtil.isEmpty(handlerList)) { - log.error("{} 处理器列表为空.", name); - return; - } - this.name = name == null ? "" : name; - this.handlerMap = new HashMap<>(); - this.matcher = matcher; - - for (Handler handler : handlerList) { - Match match = handler.getClass().getAnnotation(Match.class); - if (null == match) { - log.warn("{} 类: {} 缺失Match注解", this.name, handler.getClass().getName()); - continue; - } - if (StringUtil.isEmpty(match.type())) { - log.warn("{} 类: {} match注解缺失type参数!", this.name, handler.getClass().getName()); - continue; - } - if (handlerMap.containsKey(match.type())) { - log.warn("{} 类: {} match注解type值{} 存在重复!", this.name, handler.getClass().getName(), match.type()); - continue; - } - handlerMap.put(match.type(), handler); - } - log.info("{} 处理器初始化完成", this.name); - } - - @Override - public void dispatch(Context context, Data data) { - if (CollectionUtil.isEmpty(handlerMap)) { - return; - } - String type = matcher.apply(data); - if (null == type) { - log.warn("{} 获取匹配类型失败 data:{}", this.name, JSONObject.toJSONString(data)); - return; - } - Handler handler = handlerMap.get(type); - if (null == handler) { -// log.debug("{} 找不到匹配的处理器 type:{}", this.name, type); - return; - } - String handlerName = handler.name(); - if (StringUtil.isEmpty(handlerName)) { - handlerName = TypeUtil.getSimpleName(handler.getClass()); - } - log.debug("{} 处理器[{}]执行.", this.name, handlerName); - handler.handle(context, data); - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/Dispatcher.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/Dispatcher.java deleted file mode 100644 index 1300fe04..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/Dispatcher.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.base; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -public interface Dispatcher { - - /** - * 调度 - * @param context - * @param data - */ - void dispatch(Context context, Data data); -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/GlobalConfig.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/GlobalConfig.java deleted file mode 100644 index 8ad8d938..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/GlobalConfig.java +++ /dev/null @@ -1,103 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.base; - -import fun.asgc.neutrino.core.constant.MetaDataConstant; - -/** - * 全局配置 - * @author: aoshiguchen - * @date: 2022/7/7 - */ -public class GlobalConfig { - /** - * 是否打印自动生成的代码 - */ - private static volatile boolean isPrintGeneratorCode = false; - /** - * 是否是容器启动 - */ - private static volatile boolean isContainerStartup = false; - /** - * 是否保存生成的代码 - * 只是一个建议。 - * 当程序是普通运行时,采纳建议。 - * 当程序是以jar方式运行时,强制保存生成的代码 - */ - private static volatile boolean isSaveGeneratorCode = false; - /** - * 是否使用SpringBoot方式的jar - */ - private static volatile boolean isUseSpringBootJar = true; - /** - * 自动生成代码保存路径 - */ - private static volatile String generatorCodeSavePath = "./lib/"; - /** - * mapper文件存放基础路径 - */ - private static volatile String mapperXmlFileBasePath = MetaDataConstant.CLASSPATH_RESOURCE_IDENTIFIER.concat("/mapper"); - - public static boolean isPrintGeneratorCode() { - return isPrintGeneratorCode; - } - - public static void setIsPrintGeneratorCode(boolean isPrintGeneratorCode) { - GlobalConfig.isPrintGeneratorCode = isPrintGeneratorCode; - } - - public static boolean isContainerStartup() { - return isContainerStartup; - } - - public static void setIsContainerStartup(boolean isContainerStartup) { - GlobalConfig.isContainerStartup = isContainerStartup; - } - - public static boolean isSaveGeneratorCode() { - return isSaveGeneratorCode; - } - - public static void setIsSaveGeneratorCode(boolean isSaveGeneratorCode) { - GlobalConfig.isSaveGeneratorCode = isSaveGeneratorCode; - } - - public static String getGeneratorCodeSavePath() { - return generatorCodeSavePath; - } - - public static void setGeneratorCodeSavePath(String generatorCodeSavePath) { - GlobalConfig.generatorCodeSavePath = generatorCodeSavePath; - } - - public static String getMapperXmlFileBasePath() { - return mapperXmlFileBasePath; - } - - public static boolean isIsPrintGeneratorCode() { - return isPrintGeneratorCode; - } - - public static boolean isIsUseSpringBootJar() { - return isUseSpringBootJar; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/Handler.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/Handler.java deleted file mode 100644 index ecc79098..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/Handler.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.base; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -public interface Handler { - - /** - * 处理 - * @param context - * @param data - */ - void handle(Context context, Data data); - - /** - * 名称 - * @return - */ - default String name() { - return ""; - }; -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/Identity.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/Identity.java deleted file mode 100644 index e640867e..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/Identity.java +++ /dev/null @@ -1,43 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.base; - -/** - * Identity 用于标识一个身份。 - * - * 当`isOnly()`为true时,该标识是一个唯一标识。 - * - * 如:身份证、财富、年龄都可以作为人的身份象征,但只有身份证是唯一标识。 - * 这个唯一性取决与理论上的定义,而非实际数据。 - * 例如有三个人,年龄分别是18、19、20,此时对于这三人而言,年龄是唯一的,但年龄这个标识我们仍然认为是非唯一标识。 - * 除非在特定场景下,这些数据固定不变、或者确保以后新增的数据也不会打破这一设定。 - * - * @author: aoshiguchen - * @date: 2022/7/1 - */ -public interface Identity { - /** - * 是否唯一标识 - * @return - */ - boolean isOnly(); -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/NvMap.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/NvMap.java deleted file mode 100644 index 98f68d03..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/NvMap.java +++ /dev/null @@ -1,557 +0,0 @@ -package fun.asgc.neutrino.core.base; - - -import fun.asgc.neutrino.core.util.TypeUtil; - -import java.io.Serializable; -import java.util.*; - -/** - * 用于统一参数配置
- *

- * 1、有序性(适用于方法参数)
- * 2、key为String类型时,忽略大小写、忽略分隔符(_、-),兼容启动命令传参 + 配置文件传参
- * 3、父级委托机制:如果存在父级,且当前实例查不到,则委托父级查找。(适用于配置优先级:启动参数 > 配置文件 > 默认值)
- *

- * - * 使用说明:
- * 1、take开头的方法,适用于配置层。利用parent委托机制,做优先级。 如5级配置:默认值 -> 内部配置文件 -> 环境变量 -> 外部配置文件 -> 启动参数
- * 2、inx开头的方法,适用于不关心参数名称,根据下标取值。如普通方法参数、sql顺序参数(非具名参数)
- * 3、get方法取值,没有委托机制,适用于sql具名参数、bean方法具名参数
- * 4、setAlias用于为一个key设置别名,用于解决应用层简化配置,避免冗长的配置名。
- * @author: aoshiguchen - * @date: 2023/3/1 - */ -public class NvMap implements Map , Serializable, Cloneable { - private HashMap aliasMap; - private LinkedHashMap _m; - private HashMap _k; - private Locale locale; - private String SEPARATOR = "_|-"; - private NvMap parent; - - private NvMap() { - this(null, 16, null); - } - - private NvMap(NvMap parent) { - this(parent, 16, null); - } - - public static NvMap of() { - return new NvMap<>(); - } - - public static NvMap of(NvMap parent) { - NvMap nvMap = new NvMap(parent); - nvMap.aliasMap.putAll(parent.aliasMap); - return nvMap; - } - - public NvMap set(K k, V v) { - if (this.aliasMap.containsKey(convertKey(k))) { - this.put(this.aliasMap.get(convertKey(k)), v); - } else { - this.put(k, v); - } - return this; - } - - public NvMap set(K k, K alias, V v) { - this.set(k, v); - this.setAlias(k, alias); - return this; - } - - public NvMap setAlias(K k, K alias) { - this.aliasMap.put(convertKey(alias), convertKey(k)); - return this; - } - - public NvMap(NvMap parent, int initialCapacity, Locale locale) { - this.parent = parent; - this._m = new LinkedHashMap(initialCapacity) { - @Override - public boolean containsKey(Object key) { - return NvMap.this.containsKey(key); - } - - @Override - protected boolean removeEldestEntry(Map.Entry eldest) { - boolean doRemove = NvMap.this.removeEldestEntry(eldest); - if (doRemove) { - _k.remove(convertKey(eldest.getKey())); - } - return doRemove; - } - }; - this._k = new HashMap<>(initialCapacity); - this.aliasMap = new HashMap<>(initialCapacity); - this.locale = (locale != null ? locale : Locale.getDefault()); - } - - @Override - public int size() { - return this._m.size(); - } - - public int stackSize() { - return this._m.size() + (null == parent ? 0 : parent.stackSize()); - } - - @Override - public boolean isEmpty() { - return this._m.isEmpty(); - } - - public boolean isStackEmpty() { - boolean res = this._m.isEmpty(); - if (res && null != parent) { - res = parent.isStackEmpty(); - } - return res; - } - - @Override - public boolean containsKey(Object key) { - return this._k.containsKey(convertKey(key)); - } - - public boolean stackContainsKey(K k) { - return this.containsKey(k) || (null != parent && parent.containsKey(k)); - } - - @Override - public boolean containsValue(Object value) { - return this._m.containsValue(value); - } - - public boolean stackContainsValue(Object value) { - return this.containsValue(value) || (null != parent && parent.containsValue(value)); - } - - public V stackGet(K k) { - V res = get(k); - if (null == res && null != parent) { - res = parent.stackGet(k); - } - return res; - } - - public V stackGetOrDefault(K k, V defaultValue) { - V res = this.stackGet(k); - if (null == res) { - res = defaultValue; - } - return res; - } - - @Override - public V put(K key, V value) { - K k = key; - if (null != k && k instanceof String) { - k = (K) convertKey((String) key); - } - K oldKey = this._k.put(k, key); - if (null != oldKey && !oldKey.equals(key)) { - this._m.remove(oldKey); - } - return this._m.put(key, value); - } - - @Override - public V remove(Object key) { - K k1 = null; - try { - k1 = (K) key; - } catch (Exception e) { - return null; - } - K k2 = null; - if (k1 instanceof String) { - k1 = (K) convertKey((String) k1); - k2 = this._k.remove(k1); - } else { - k2 = this._k.remove(k1); - } - if (null != k2) { - return this._m.remove(k2); - } - return null; - } - - @Override - public void putAll(Map m) { - if (m.isEmpty()) { - return; - } - m.forEach(this::put); - } - - @Override - public void clear() { - this._k.clear(); - this._m.clear(); - } - - @Override - public Set keySet() { - return this._m.keySet(); - } - - @Override - public Collection values() { - return this._m.values(); - } - - @Override - public Set> entrySet() { - return this._m.entrySet(); - } - - public Locale getLocale() { - return this.locale; - } - - protected String convertKey(String key) { - return key.toLowerCase(getLocale()).replaceAll(SEPARATOR, ""); - } - - protected K convertKey(Object k) { - K res = null; - try { - res = (K) convertKey((String) k); - } catch (Exception e) { - res = (K)k; - } - return res; - } - - protected boolean removeEldestEntry(Map.Entry eldest) { - return false; - } - - @Override - protected NvMap clone() { - NvMap res = new NvMap<>(); - if (null != parent) { - res.parent = parent.clone(); - } - res._m = (LinkedHashMap) _m.clone(); - res._k = (HashMap) _k.clone(); - res.aliasMap = (HashMap) aliasMap.clone(); - res.locale = locale; - return res; - } - - // ====== 为了方便取值操作,get方法保持Map接口原有语义,不支持栈式取值 ======= - @Override - public V get(Object key) { - V res = null; - if (this.aliasMap.containsKey(convertKey(key))) { - Object aliasKey = this.aliasMap.get(convertKey(key)); - res = this._m.get(this._k.get(convertKey(aliasKey))); - } - if (null == res) { - res = this._m.get(this._k.get(convertKey(key))); - } - return res; - } - - public V get(Object key, V defaultValue) { - V res = get(key); - if (null == res) { - res = defaultValue; - } - return res; - } - - public String getStr(K k) { - return TypeUtil.conversion(get(k), String.class); - } - - public String getStr(K k, String defaultValue) { - return TypeUtil.conversion(get(k, (V)defaultValue), String.class); - } - - public Byte getByte(K k) { - return TypeUtil.conversion(get(k), Byte.class); - } - - public Byte getByte(K k, Byte defaultValue) { - return TypeUtil.conversion(get(k, (V)defaultValue), Byte.class); - } - - public Character getChar(K k) { - return TypeUtil.conversion(get(k), Character.class); - } - - public Character getChar(K k, Character defaultValue) { - return TypeUtil.conversion(get(k, (V)defaultValue), Character.class); - } - - public Boolean getBool(K k) { - return TypeUtil.conversion(get(k), Boolean.class); - } - - public Boolean getBool(K k, Boolean defaultValue) { - return TypeUtil.conversion(get(k, (V)defaultValue), Boolean.class); - } - - public Short getShort(K k) { - return TypeUtil.conversion(get(k), Short.class); - } - - public Short getShort(K k, Short defaultValue) { - return TypeUtil.conversion(get(k, (V)defaultValue), Short.class); - } - - public Integer getInt(K k) { - return TypeUtil.conversion(get(k), Integer.class); - } - - public Integer getInt(K k, Integer defaultValue) { - return TypeUtil.conversion(get(k, (V)defaultValue), Integer.class); - } - - public Long getLong(K k) { - return TypeUtil.conversion(get(k), Long.class); - } - - public Long getLong(K k, Long defaultValue) { - return TypeUtil.conversion(get(k, (V)defaultValue), Long.class); - } - - public Float getFloat(K k) { - return TypeUtil.conversion(get(k), Float.class); - } - - public Float getFloat(K k, Float defaultValue) { - return TypeUtil.conversion(get(k, (V)defaultValue), Float.class); - } - - public Double getDouble(K k) { - return TypeUtil.conversion(get(k), Double.class); - } - - public Double getDouble(K k, Double defaultValue) { - return TypeUtil.conversion(get(k, (V)defaultValue), Double.class); - } - - public Date getDate(K k) { - return TypeUtil.conversion(get(k), Date.class); - } - - public Date getDate(K k, Date defaultValue) { - return TypeUtil.conversion(get(k, (V)defaultValue), Date.class); - } - - public K getAlias(K k) { - return this.aliasMap.get(convertKey(k)); - } - - public K stackGetAlias(K k) { - K res = getAlias(k); - if (null == res && null != parent) { - res = parent.stackGetAlias(k); - } - return res; - } - - // ====== 为了方便取值操作,take开头的方法,全部基于栈式取值 ======= - public V take(K k) { - V res = null; - K aliasK = this.getAlias(k); - if (null != aliasK) { - res = stackGet(aliasK); - } - if (null == res) { - res = stackGet(k); - } - return res; - } - - public V take(K k, V defaultValue) { - V res = take(k); - if (null == res ) { - res = defaultValue; - } - return res; - } - - public String takeStr(K k) { - return TypeUtil.conversion(take(k), String.class); - } - - public String takeStr(K k, String defaultValue) { - return TypeUtil.conversion(take(k, (V)defaultValue), String.class); - } - - public Byte takeByte(K k) { - return TypeUtil.conversion(take(k), Byte.class); - } - - public Byte takeByte(K k, Byte defaultValue) { - return TypeUtil.conversion(take(k, (V)defaultValue), Byte.class); - } - - public Character takeChar(K k) { - return TypeUtil.conversion(take(k), Character.class); - } - - public Character takeChar(K k, Character defaultValue) { - return TypeUtil.conversion(take(k, (V)defaultValue), Character.class); - } - - public Boolean takeBool(K k) { - return TypeUtil.conversion(take(k), Boolean.class); - } - - public Boolean takeBool(K k, Boolean defaultValue) { - return TypeUtil.conversion(take(k, (V)defaultValue), Boolean.class); - } - - public Short takeShort(K k) { - return TypeUtil.conversion(take(k), Short.class); - } - - public Short takeShort(K k, Short defaultValue) { - return TypeUtil.conversion(take(k, (V)defaultValue), Short.class); - } - - public Integer takeInt(K k) { - return TypeUtil.conversion(take(k), Integer.class); - } - - public Integer takeInt(K k, Integer defaultValue) { - return TypeUtil.conversion(take(k, (V)defaultValue), Integer.class); - } - - public Long takeLong(K k) { - return TypeUtil.conversion(take(k), Long.class); - } - - public Long takeLong(K k, Long defaultValue) { - return TypeUtil.conversion(take(k, (V)defaultValue), Long.class); - } - - public Float takeFloat(K k) { - return TypeUtil.conversion(take(k), Float.class); - } - - public Float takeFloat(K k, Float defaultValue) { - return TypeUtil.conversion(take(k, (V)defaultValue), Float.class); - } - - public Double takeDouble(K k) { - return TypeUtil.conversion(take(k), Double.class); - } - - public Double takeDouble(K k, Double defaultValue) { - return TypeUtil.conversion(take(k, (V)defaultValue), Double.class); - } - - public Date takeDate(K k) { - return TypeUtil.conversion(take(k), Date.class); - } - - public Date takeDate(K k, Date defaultValue) { - return TypeUtil.conversion(take(k, (V)defaultValue), Date.class); - } - - // ====== 为了方便取值操作,idx开头的方法,全部基于下标取值 ======= - public V idx(int i) { - if (i >= 0 && i < this.size()) { - return (V)this._m.values().toArray(new Object[]{})[i]; - } - return null; - } - - public V idx(int i, V defaultValue) { - V res = idx(i); - if (null == res) { - res = defaultValue; - } - return defaultValue; - } - - public String idxStr(int i) { - return TypeUtil.conversion(idx(i), String.class); - } - - public String idxStr(int i, String defaultValue) { - return TypeUtil.conversion(idx(i, (V)defaultValue), String.class); - } - - public Byte idxByte(int i) { - return TypeUtil.conversion(idx(i), Byte.class); - } - - public Byte idxByte(int i, Byte defaultValue) { - return TypeUtil.conversion(idx(i, (V)defaultValue), Byte.class); - } - - public Character idxChar(int i) { - return TypeUtil.conversion(idx(i), Character.class); - } - - public Character idxChar(int i, Character defaultValue) { - return TypeUtil.conversion(idx(i, (V)defaultValue), Character.class); - } - - public Boolean idxBool(int i) { - return TypeUtil.conversion(idx(i), Boolean.class); - } - - public Boolean idxBool(int i, Boolean defaultValue) { - return TypeUtil.conversion(idx(i, (V)defaultValue), Boolean.class); - } - - public Short idxShort(int i) { - return TypeUtil.conversion(idx(i), Short.class); - } - - public Short idxShort(int i, Short defaultValue) { - return TypeUtil.conversion(idx(i, (V)defaultValue), Short.class); - } - - public Integer idxInt(int i) { - return TypeUtil.conversion(idx(i), Integer.class); - } - - public Integer idxInt(int i, Integer defaultValue) { - return TypeUtil.conversion(idx(i, (V)defaultValue), Integer.class); - } - - public Long idxLong(int i) { - return TypeUtil.conversion(idx(i), Long.class); - } - - public Long idxLong(int i, Long defaultValue) { - return TypeUtil.conversion(idx(i, (V)defaultValue), Long.class); - } - - public Float idxFloat(int i) { - return TypeUtil.conversion(idx(i), Float.class); - } - - public Float idxFloat(int i, Float defaultValue) { - return TypeUtil.conversion(idx(i, (V)defaultValue), Float.class); - } - - public Double idxDouble(int i) { - return TypeUtil.conversion(idx(i), Double.class); - } - - public Double idxDouble(int i, Double defaultValue) { - return TypeUtil.conversion(idx(i, (V)defaultValue), Double.class); - } - - public Date idxDate(int i) { - return TypeUtil.conversion(idx(i), Date.class); - } - - public Date idxDate(int i, Date defaultValue) { - return TypeUtil.conversion(idx(i, (V)defaultValue), Date.class); - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/NvMaps.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/NvMaps.java deleted file mode 100644 index 1ef1d76a..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/NvMaps.java +++ /dev/null @@ -1,205 +0,0 @@ -package fun.asgc.neutrino.core.base; - -import com.alibaba.fastjson.JSONObject; -import fun.asgc.neutrino.core.constant.FileTypeEnum; -import fun.asgc.neutrino.core.constant.MetaDataConstant; -import fun.asgc.neutrino.core.util.*; -import org.yaml.snakeyaml.Yaml; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; - -/** - * 配置管理器 - * - *

- * 支持以下五级配置: - * 1、别名、默认值 - * 2、内部配置文件 - * 3、环境变量 - * 4、外部配置文件 - * 5、启动参数 - *

- * - *

- * 支持以下3种配置文件格式: - * 1、yml - * 2、properties - * 3、json - *

- * - *

- * 支持指定以下配置: - * 1、内部配置文件路径、格式 (可根据文件后缀自动识别格式) - * 2、环境变量前缀 (若指定了前缀,则只加载包含该前缀的环境变量) - * 3、外部配置文件路径、格式(可根据文件后缀自动识别格式) - * 4、启动参数前缀(若指定了前缀,则只加载包含该前缀的启动参数) - *

- * @author: aoshiguchen - * @date: 2023/3/5 - */ -public final class NvMaps { - private NvMap nvMap; - - private NvMaps() { - this.nvMap = NvMap.of(); - } - - public static NvMaps of() { - return new NvMaps(); - } - - public NvMaps stageDone() { - this.nvMap = NvMap.of(this.nvMap); - return this; - } - - public NvMap getNvMap() { - return this.nvMap; - } - - public NvMaps setKv(Object k, Object v) { - this.nvMap.set(k, v); - return this; - } - - public NvMaps setKv(Object k, Object alias, Object v) { - this.nvMap.set(k, alias, v); - return this; - } - - public NvMaps setAlias(Object k, Object alias) { - this.nvMap.setAlias(k, alias); - return this; - } - public NvMaps loadFile(String path) throws IOException { - if (StringUtil.isEmpty(path)) { - return this; - } - String suffix = FileUtil.getFileSuffix(path); - if (StringUtil.isEmpty(suffix)) { - return this; - } - suffix = suffix.toLowerCase(); - if (FileTypeEnum.YML.getSuffixSet().contains(suffix)) { - return loadFile(FileTypeEnum.YML, path); - } else if (FileTypeEnum.PROPERTIES.getSuffixSet().contains(suffix)) { - return loadFile(FileTypeEnum.PROPERTIES, path); - } else if (FileTypeEnum.JSON.getSuffixSet().contains(suffix)) { - return loadFile(FileTypeEnum.JSON, path); - } - return this; - } - public NvMaps loadYmlFile(String path) throws IOException { - return loadFile(FileTypeEnum.YML, path); - } - public NvMaps loadPropertiesFile(String path) throws IOException { - return loadFile(FileTypeEnum.PROPERTIES, path); - } - public NvMaps loadJsonFile(String path) throws IOException { - return loadFile(FileTypeEnum.JSON, path); - } - public NvMaps loadFile(FileTypeEnum fileType, String path) throws IOException { - try (InputStream in = FileUtil.getInputStream(path)){ - return loadFile(fileType, in); - } - } - public NvMaps loadFile(FileTypeEnum fileType, InputStream in) throws IOException { - if (null == fileType || null == in) { - return this; - } - if (fileType == FileTypeEnum.YML) { - Map map = new Yaml().load(in); - load(map); - } else if (fileType == FileTypeEnum.PROPERTIES) { - Properties properties = new Properties(); - properties.load(in); - load(properties); - } else if (fileType == FileTypeEnum.JSON) { - String content = FileUtil.readContentAsString(in); - JSONObject jsonObject = JSONObject.parseObject(content); - load(jsonObject); - } - return null; - } - - public NvMaps load(Properties properties) { - if (null == properties) { - return this; - } - for (String k : properties.stringPropertyNames()) { - this.setKv(k, properties.getProperty(k)); - } - return this; - } - - public NvMaps load(Map config) { - if (CollectionUtil.isEmpty(config)) { - return this; - } - for (String key : config.keySet()) { - Object value = config.get(key); - if (null != value && Map.class.isAssignableFrom(value.getClass())) { - load(key, (Map)config.get(key)); - } else { - this.setKv(key, value); - } - } - return this; - } - - private void load(String prefix, Map config) { - for (Object key : config.keySet()) { - String k = TypeUtil.conversion(key, String.class); - if (null == k) { - continue; - } - Object value = config.get(key); - if (null != value && Map.class.isAssignableFrom(value.getClass())) { - load(prefix.concat("." + k), (Map)config.get(key)); - } else { - this.setKv(prefix.concat("." + k), value); - } - } - } - - public NvMaps loadEnvironmentVariable(String envKey) { - String env = System.getenv(MetaDataConstant.ENVIRONMENT_VARIABLE_KEY); - if (StringUtil.isEmpty(env)) { - return this; - } - String[] tmp = env.split(File.pathSeparator); - if (ArrayUtil.isEmpty(tmp) || tmp.length < 2) { - return this; - } - load(kvListToMap(tmp)); - return this; - } - - public NvMaps loadMainArgs(String[] mainArgs) { - load(kvListToMap(mainArgs)); - return this; - } - - private Map kvListToMap(String[] args) { - Map map = new HashMap<>(); - if (ArrayUtil.isEmpty(args)) { - return map; - } - for (String kv : args) { - if (!StringUtil.isEmpty(kv)) { - int index = kv.indexOf("="); - if (index > 0 && index < kv.length() - 1) { - String key = kv.substring(0, index); - String val = kv.substring(index + 1); - map.put(key, val); - } - } - } - return map; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/OrderComparator.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/OrderComparator.java deleted file mode 100644 index e919eaf9..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/OrderComparator.java +++ /dev/null @@ -1,210 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.base; - -import fun.asgc.neutrino.core.util.ObjectUtil; -import org.apache.commons.lang3.ObjectUtils; - -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/27 - */ -public class OrderComparator implements Comparator { - - /** - * Shared default instance of {@code OrderComparator}. - */ - public static final OrderComparator INSTANCE = new OrderComparator(); - - - /** - * Build an adapted order comparator with the given source provider. - * @param sourceProvider the order source provider to use - * @return the adapted comparator - * @since 4.1 - */ - public Comparator withSourceProvider(final OrderSourceProvider sourceProvider) { - return new Comparator() { - @Override - public int compare(Object o1, Object o2) { - return doCompare(o1, o2, sourceProvider); - } - }; - } - - @Override - public int compare(Object o1, Object o2) { - return doCompare(o1, o2, null); - } - - private int doCompare(Object o1, Object o2, OrderSourceProvider sourceProvider) { - boolean p1 = (o1 instanceof PriorityOrdered); - boolean p2 = (o2 instanceof PriorityOrdered); - if (p1 && !p2) { - return -1; - } - else if (p2 && !p1) { - return 1; - } - - // Direct evaluation instead of Integer.compareTo to avoid unnecessary object creation. - int i1 = getOrder(o1, sourceProvider); - int i2 = getOrder(o2, sourceProvider); - return (i1 < i2) ? -1 : (i1 > i2) ? 1 : 0; - } - - /** - * Determine the order value for the given object. - *

The default implementation checks against the given {@link OrderSourceProvider} - * using {@link #findOrder} and falls back to a regular {@link #getOrder(Object)} call. - * @param obj the object to check - * @return the order value, or {@code Ordered.LOWEST_PRECEDENCE} as fallback - */ - private int getOrder(Object obj, OrderSourceProvider sourceProvider) { - Integer order = null; - if (sourceProvider != null) { - Object orderSource = sourceProvider.getOrderSource(obj); - if (orderSource != null && orderSource.getClass().isArray()) { - Object[] sources = ObjectUtil.toObjectArray(orderSource); - for (Object source : sources) { - order = findOrder(source); - if (order != null) { - break; - } - } - } - else { - order = findOrder(orderSource); - } - } - return (order != null ? order : getOrder(obj)); - } - - /** - * Determine the order value for the given object. - *

The default implementation checks against the {@link Ordered} interface - * through delegating to {@link #findOrder}. Can be overridden in subclasses. - * @param obj the object to check - * @return the order value, or {@code Ordered.LOWEST_PRECEDENCE} as fallback - */ - protected int getOrder(Object obj) { - Integer order = findOrder(obj); - return (order != null ? order : Ordered.LOWEST_PRECEDENCE); - } - - /** - * Find an order value indicated by the given object. - *

The default implementation checks against the {@link Ordered} interface. - * Can be overridden in subclasses. - * @param obj the object to check - * @return the order value, or {@code null} if none found - */ - protected Integer findOrder(Object obj) { - return (obj instanceof Ordered ? ((Ordered) obj).getOrder() : null); - } - - /** - * Determine a priority value for the given object, if any. - *

The default implementation always returns {@code null}. - * Subclasses may override this to give specific kinds of values a - * 'priority' characteristic, in addition to their 'order' semantics. - * A priority indicates that it may be used for selecting one object over - * another, in addition to serving for ordering purposes in a list/array. - * @param obj the object to check - * @return the priority value, or {@code null} if none - * @since 4.1 - */ - public Integer getPriority(Object obj) { - return null; - } - - - /** - * Sort the given List with a default OrderComparator. - *

Optimized to skip sorting for lists with size 0 or 1, - * in order to avoid unnecessary array extraction. - * @param list the List to sort - * @see java.util.Collections#sort(java.util.List, java.util.Comparator) - */ - public static void sort(List list) { - if (list.size() > 1) { - Collections.sort(list, INSTANCE); - } - } - - /** - * Sort the given array with a default OrderComparator. - *

Optimized to skip sorting for lists with size 0 or 1, - * in order to avoid unnecessary array extraction. - * @param array the array to sort - * @see java.util.Arrays#sort(Object[], java.util.Comparator) - */ - public static void sort(Object[] array) { - if (array.length > 1) { - Arrays.sort(array, INSTANCE); - } - } - - /** - * Sort the given array or List with a default OrderComparator, - * if necessary. Simply skips sorting when given any other value. - *

Optimized to skip sorting for lists with size 0 or 1, - * in order to avoid unnecessary array extraction. - * @param value the array or List to sort - * @see java.util.Arrays#sort(Object[], java.util.Comparator) - */ - public static void sortIfNecessary(Object value) { - if (value instanceof Object[]) { - sort((Object[]) value); - } - else if (value instanceof List) { - sort((List) value); - } - } - - - /** - * Strategy interface to provide an order source for a given object. - * @since 4.1 - */ - public interface OrderSourceProvider { - - /** - * Return an order source for the specified object, i.e. an object that - * should be checked for an order value as a replacement to the given object. - *

Can also be an array of order source objects. - *

If the returned object does not indicate any order, the comparator - * will fall back to checking the original object. - * @param obj the object to find an order source for - * @return the order source for that object, or {@code null} if none found - */ - Object getOrderSource(Object obj); - } - -} - diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/Ordered.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/Ordered.java deleted file mode 100644 index eaaec279..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/Ordered.java +++ /dev/null @@ -1,55 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.base; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/27 - */ -public interface Ordered { - /** - * Useful constant for the highest precedence value. - * @see java.lang.Integer#MIN_VALUE - */ - int HIGHEST_PRECEDENCE = Integer.MIN_VALUE; - - /** - * Useful constant for the lowest precedence value. - * @see java.lang.Integer#MAX_VALUE - */ - int LOWEST_PRECEDENCE = Integer.MAX_VALUE; - - - /** - * Get the order value of this object. - *

Higher values are interpreted as lower priority. As a consequence, - * the object with the lowest value has the highest priority (somewhat - * analogous to Servlet {@code load-on-startup} values). - *

Same order values will result in arbitrary sort positions for the - * affected objects. - * @return the order value - * @see #HIGHEST_PRECEDENCE - * @see #LOWEST_PRECEDENCE - */ - int getOrder(); -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/Orderly.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/Orderly.java deleted file mode 100644 index e0de553e..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/Orderly.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.base; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -/** - * @author: aoshiguchen - * @date: 2022/6/27 - */ -@Accessors(chain = true) -@AllArgsConstructor -@NoArgsConstructor -@Data -public class Orderly implements Comparable { - private T data; - private int order; - - @Override - public int compareTo(Orderly o) { - return getOrder() - o.getOrder(); - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/PriorityOrdered.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/PriorityOrdered.java deleted file mode 100644 index dd853338..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/PriorityOrdered.java +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.base; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/27 - */ -public interface PriorityOrdered extends Ordered { - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/Publisher.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/Publisher.java deleted file mode 100644 index 19eea0d1..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/Publisher.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.base; - -/** - * @author: aoshiguchen - * @date: 2022/9/29 - */ -public interface Publisher { - /** - * 发布消息 - * @param msg 消息 - */ - void publish(D msg); - - /** - * 绑定渠道 - * @param channel 渠道 - */ - void bindChannel(Ch channel); - - /** - * 解绑渠道 - * @param channel 渠道 - */ - void unbindChannel(Ch channel); -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/Receiver.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/Receiver.java deleted file mode 100644 index ff12f524..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/Receiver.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.base; - -/** - * @author: aoshiguchen - * @date: 2022/9/29 - */ -public interface Receiver { - - /** - * 接收消息 - * @param msg - */ - void receive(D msg); -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/event/ApplicationEvent.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/event/ApplicationEvent.java deleted file mode 100644 index 44a773de..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/event/ApplicationEvent.java +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.base.event; - -/** - * @author: aoshiguchen - * @date: 2022/9/28 - */ -public class ApplicationEvent implements Event { - - private D data; - private ApplicationEventContext context; - - public ApplicationEvent() { - this.context = new ApplicationEventContext(); - } - - @Override - public D data() { - return this.data; - } - - @Override - public ApplicationEventContext context() { - return this.context; - } - - public void setData(D data) { - this.data = data; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/event/ApplicationEventChannel.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/event/ApplicationEventChannel.java deleted file mode 100644 index 6506fb06..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/event/ApplicationEventChannel.java +++ /dev/null @@ -1,151 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.base.event; - -import fun.asgc.neutrino.core.base.ChannelConnector; -import fun.asgc.neutrino.core.base.CustomThreadFactory; -import fun.asgc.neutrino.core.base.Dispatcher; -import fun.asgc.neutrino.core.util.Assert; -import fun.asgc.neutrino.core.util.CollectionUtil; -import fun.asgc.neutrino.core.util.StringUtil; -import fun.asgc.neutrino.core.web.AntPathMatcher; - -import java.util.ArrayList; -import java.util.List; -import java.util.Set; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -/** - * @author: aoshiguchen - * @date: 2022/9/29 - */ -public class ApplicationEventChannel implements EventChannel,ApplicationEventReceiver,Dispatcher>>, ChannelConnector> { - private List> receiverList; - private ThreadPoolExecutor threadPoolExecutor; - private static final AntPathMatcher antPathMatcher = new AntPathMatcher(); - private List> channelList; - - public ApplicationEventChannel() { - this.receiverList = new ArrayList<>(); - this.channelList = new ArrayList<>(); - this.threadPoolExecutor = new ThreadPoolExecutor(5, 20, 10L, TimeUnit.SECONDS, - new LinkedBlockingQueue<>(), new CustomThreadFactory("ApplicationEventChannel")); - } - - @Override - public void registerReceiver(ApplicationEventReceiver receiver) { - Assert.notNull(receiver, "receiver不能为空!"); - if (this.receiverList.contains(receiver)) { - return; - } - this.receiverList.add(receiver); - } - - @Override - public void unRegisterReceiver(ApplicationEventReceiver receiver) { - Assert.notNull(receiver, "receiver不能为空!"); - if (!this.receiverList.contains(receiver)) { - return; - } - this.receiverList.remove(receiver); - } - - @Override - public void publish(ApplicationEvent msg) { - if (msg.context().channelList().contains(this)) { - return; - } - msg.context().channelList().add(this); - // 将消息推送给关注该channel的接受者 - this.receiverList.forEach(receiver -> { - threadPoolExecutor.submit(() -> { - if (match(msg, receiver)) { - receiver.receive(msg); - } - }); - }); - // 将消息广播到所有关联的channel中去 - this.channelList.forEach(channel -> channel.publish(msg)); - } - - @Override - public void connectChannel(ApplicationEventChannel channel) { - if (null == channel || this.channelList.contains(channel) || this == channel) { - return; - } - this.channelList.add(channel); - } - - @Override - public void disconnectChannel(ApplicationEventChannel channel) { - if (null == channel) { - return; - } - this.channelList.remove(channel); - } - - /** - * 判断指定消息和指定接受者是否匹配 - * @param msg 消息 - * @param receiver 接受者 - * @return 是否匹配 - */ - private boolean match(ApplicationEvent msg, ApplicationEventReceiver receiver) { - if (null == msg || null == receiver) { - return false; - } - return topicMatch(msg.context().topic(), receiver.getTopic()) && tagMatch(msg.context().tags(), receiver.getTags()); - } - - /** - * topic匹配起 - * @param eventTopic 事件主题 - * @param subscriptionTopic 订阅的主题 - * @return 是否匹配 - */ - private boolean topicMatch(String eventTopic, String subscriptionTopic) { - if (StringUtil.isEmpty(subscriptionTopic)) { - return true; - } - return antPathMatcher.match(subscriptionTopic, eventTopic == null ? "" : eventTopic); - } - - /** - * 标签匹配 - * @param eventTags 事件标签 - * @param subscriptionTags 关注的标签 - * @return 是否匹配 - */ - private boolean tagMatch(Set eventTags, Set subscriptionTags) { - if (CollectionUtil.isEmpty(subscriptionTags)) { - return true; - } - for (String tag : eventTags) { - if (subscriptionTags.contains(tag)) { - return true; - } - } - return false; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/event/ApplicationEventContext.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/event/ApplicationEventContext.java deleted file mode 100644 index 617a5206..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/event/ApplicationEventContext.java +++ /dev/null @@ -1,99 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.base.event; - -import fun.asgc.neutrino.core.base.Channel; -import fun.asgc.neutrino.core.util.StringUtil; - -import java.util.*; - -/** - * @author: aoshiguchen - * @date: 2022/9/28 - */ -public class ApplicationEventContext implements EventContext { - - private String id; - private String topic; - private Set tags; - private Object source; - private Date happenTime; - private Map attachData = new HashMap<>(); - private List channelList; - - public ApplicationEventContext() { - this.id = StringUtil.genUUID(); - this.happenTime = new Date(); - this.channelList = new ArrayList<>(); - } - - @Override - public Map attachData() { - return attachData; - } - - @Override - public String id() { - return id; - } - - @Override - public Date happenTime() { - return happenTime; - } - - public void setId(String id) { - this.id = id; - } - - @Override - public S source() { - return (S)source; - } - - @Override - public String topic() { - return topic; - } - - @Override - public Set tags() { - return tags; - } - - public void setTopic(String topic) { - this.topic = topic; - } - - public void setTags(Set tags) { - this.tags = tags; - } - - public void setSource(S source) { - this.source = source; - } - - @Override - public List channelList() { - return this.channelList; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/event/ApplicationEventPublisher.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/event/ApplicationEventPublisher.java deleted file mode 100644 index eed18869..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/event/ApplicationEventPublisher.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.base.event; - - -import fun.asgc.neutrino.core.util.Assert; - -import java.util.ArrayList; -import java.util.List; - -/** - * @author: aoshiguchen - * @date: 2022/9/29 - */ -public class ApplicationEventPublisher implements EventPublisher,ApplicationEventChannel> { - private List> channelList; - - public ApplicationEventPublisher() { - this.channelList = new ArrayList<>(); - } - - @Override - public void publish(ApplicationEvent msg) { - this.channelList.forEach(channel -> channel.publish(msg)); - } - - @Override - public void bindChannel(ApplicationEventChannel channel) { - Assert.notNull(channel, "channel不能为空!"); - if (!this.channelList.contains(channel)) { - this.channelList.add(channel); - } - } - - @Override - public void unbindChannel(ApplicationEventChannel channel) { - Assert.notNull(channel, "channel不能为空!"); - this.channelList.remove(channel); - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/event/ApplicationEventReceiver.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/event/ApplicationEventReceiver.java deleted file mode 100644 index c0b93134..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/event/ApplicationEventReceiver.java +++ /dev/null @@ -1,71 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.base.event; - -import com.alibaba.fastjson.JSONObject; -import lombok.extern.slf4j.Slf4j; - -import java.util.Set; - -/** - * @author: aoshiguchen - * @date: 2022/9/29 - */ -@Slf4j -public class ApplicationEventReceiver implements EventReceiver> { - private String topic; - private Set tags; - - public ApplicationEventReceiver() { - - } - - public ApplicationEventReceiver(String topic) { - this.topic = topic; - } - - public ApplicationEventReceiver(String topic, Set tags) { - this.topic = topic; - this.tags = tags; - } - - @Override - public void receive(ApplicationEvent msg) { - log.debug("ApplicationEventReceiver receive {}", JSONObject.toJSONString(msg.data())); - } - - public void setTopic(String topic) { - this.topic = topic; - } - - public void setTags(Set tags) { - this.tags = tags; - } - - public String getTopic() { - return topic; - } - - public Set getTags() { - return tags; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/event/Event.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/event/Event.java deleted file mode 100644 index 75209edb..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/event/Event.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.base.event; - -/** - * @author: aoshiguchen - * @date: 2022/9/28 - */ -public interface Event { - /** - * 获取数据 - * @return 数据 - */ - D data(); - - /** - * 获取事件上下文 - * @return 上下文 - */ - C context(); -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/event/EventChannel.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/event/EventChannel.java deleted file mode 100644 index cf73246c..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/event/EventChannel.java +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.base.event; - -import fun.asgc.neutrino.core.base.Channel; -import fun.asgc.neutrino.core.base.Dispatcher; - -/** - * @author: aoshiguchen - * @date: 2022/9/29 - */ -public interface EventChannel, R extends EventReceiver, Dis extends Dispatcher> extends Channel { - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/event/EventContext.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/event/EventContext.java deleted file mode 100644 index 09cefb44..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/event/EventContext.java +++ /dev/null @@ -1,79 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.base.event; - -import fun.asgc.neutrino.core.base.Channel; - -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * @author: wen.y - * @date: 2022/9/28 - */ -public interface EventContext { - /** - * 获取事件源 - * @return 事件源 - */ - T source(); - /** - * 事件主题 - * 用于订阅一级过滤 - * @return 主题 - */ - String topic(); - - /** - * 事件标签 - * 用于订阅二级过滤 - * @return 标签 - */ - Set tags(); - /** - * 附加数据 - * @return 附加数据 - */ - Map attachData(); - - /** - * 事件ID - * @return 事件ID - */ - String id(); - - /** - * 事件发生的时间 - * @return 事件发生的时间 - */ - Date happenTime(); - - /** - * channel列表 - * 1、如果为空,说明该事件未经过channel - * 2、该list代表事件在channel中的广播顺序 - * @return channel列表 - */ - List channelList(); -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/event/EventPublisher.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/event/EventPublisher.java deleted file mode 100644 index 595f16a6..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/event/EventPublisher.java +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.base.event; - -import fun.asgc.neutrino.core.base.Publisher; - -/** - * @author: aoshiguchen - * @date: 2022/9/28 - */ -public interface EventPublisher,Ch extends EventChannel> extends Publisher { - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/event/EventReceiver.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/event/EventReceiver.java deleted file mode 100644 index 1db4b7d4..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/event/EventReceiver.java +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.base.event; - - -import fun.asgc.neutrino.core.base.Receiver; - -/** - * @author: aoshiguchen - * @date: 2022/9/29 - */ -public interface EventReceiver> extends Receiver { - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/event/SimpleApplicationEventManager.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/event/SimpleApplicationEventManager.java deleted file mode 100644 index 02689313..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/event/SimpleApplicationEventManager.java +++ /dev/null @@ -1,81 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.base.event; - -import java.util.Set; - -/** - * 简单的应用事件管理器 - * @author: wen.u - * @date: 2022/10/10 - */ -public class SimpleApplicationEventManager { - private ApplicationEventChannel channel; - private ApplicationEventPublisher publisher; - private Object source; - - public SimpleApplicationEventManager() { - this.channel = new ApplicationEventChannel<>(); - this.publisher = new ApplicationEventPublisher<>(); - this.publisher.bindChannel(channel); - } - - public SimpleApplicationEventManager(Object source) { - this.channel = new ApplicationEventChannel<>(); - this.publisher = new ApplicationEventPublisher<>(); - this.publisher.bindChannel(channel); - this.source = source; - } - - public void publish(D data) { - this.publish(null, null, data); - } - - public void publish(String topic, D data) { - this.publish(topic, null, data); - } - - public void publish(String topic, Set tags, D data) { - ApplicationEvent event = new ApplicationEvent<>(); - event.setData(data); - event.context().setSource(source); - event.context().setTopic(topic); - event.context().setTags(tags); - this.publisher.publish(event); - } - - public void registerReceiver(ApplicationEventReceiver receiver) { - this.channel.registerReceiver(receiver); - } - - public ApplicationEventChannel getChannel() { - return channel; - } - - public ApplicationEventPublisher getPublisher() { - return publisher; - } - - public Object getSource() { - return source; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/type/MethodParameter.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/type/MethodParameter.java deleted file mode 100644 index 8dc48afc..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/type/MethodParameter.java +++ /dev/null @@ -1,654 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.base.type; - -import fun.asgc.neutrino.core.util.Assert; -import fun.asgc.neutrino.core.util.ObjectUtil; - -import java.lang.annotation.Annotation; -import java.lang.reflect.*; -import java.util.HashMap; -import java.util.Map; - -/** - * @author: aoshiguchen - * @date: 2022/9/25 - */ -public class MethodParameter { - - private static final Annotation[] EMPTY_ANNOTATION_ARRAY = new Annotation[0]; - - private static final Class javaUtilOptionalClass; - - static { - Class clazz; - try { - clazz = Class.forName("java.util.Optional"); - } - catch (ClassNotFoundException ex) { - // Java 8 not available - Optional references simply not supported then. - clazz = null; - } - javaUtilOptionalClass = clazz; - } - - - private final Method method; - - private final Constructor constructor; - - private final int parameterIndex; - - private int nestingLevel; - - /** Map from Integer level to Integer type index */ - Map typeIndexesPerLevel; - - /** The containing class. Could also be supplied by overriding {@link #getContainingClass()} */ - private volatile Class containingClass; - - private volatile Class parameterType; - - private volatile Type genericParameterType; - - private volatile Annotation[] parameterAnnotations; - - private volatile ParameterNameDiscoverer parameterNameDiscoverer; - - private volatile String parameterName; - - private volatile MethodParameter nestedMethodParameter; - - - /** - * Create a new {@code MethodParameter} for the given method, with nesting level 1. - * @param method the Method to specify a parameter for - * @param parameterIndex the index of the parameter: -1 for the method - * return type; 0 for the first method parameter; 1 for the second method - * parameter, etc. - */ - public MethodParameter(Method method, int parameterIndex) { - this(method, parameterIndex, 1); - } - - /** - * Create a new {@code MethodParameter} for the given method. - * @param method the Method to specify a parameter for - * @param parameterIndex the index of the parameter: -1 for the method - * return type; 0 for the first method parameter; 1 for the second method - * parameter, etc. - * @param nestingLevel the nesting level of the target type - * (typically 1; e.g. in case of a List of Lists, 1 would indicate the - * nested List, whereas 2 would indicate the element of the nested List) - */ - public MethodParameter(Method method, int parameterIndex, int nestingLevel) { - Assert.notNull(method, "Method must not be null"); - this.method = method; - this.parameterIndex = parameterIndex; - this.nestingLevel = nestingLevel; - this.constructor = null; - } - - /** - * Create a new MethodParameter for the given constructor, with nesting level 1. - * @param constructor the Constructor to specify a parameter for - * @param parameterIndex the index of the parameter - */ - public MethodParameter(Constructor constructor, int parameterIndex) { - this(constructor, parameterIndex, 1); - } - - /** - * Create a new MethodParameter for the given constructor. - * @param constructor the Constructor to specify a parameter for - * @param parameterIndex the index of the parameter - * @param nestingLevel the nesting level of the target type - * (typically 1; e.g. in case of a List of Lists, 1 would indicate the - * nested List, whereas 2 would indicate the element of the nested List) - */ - public MethodParameter(Constructor constructor, int parameterIndex, int nestingLevel) { - Assert.notNull(constructor, "Constructor must not be null"); - this.constructor = constructor; - this.parameterIndex = parameterIndex; - this.nestingLevel = nestingLevel; - this.method = null; - } - - /** - * Copy constructor, resulting in an independent MethodParameter object - * based on the same metadata and cache state that the original object was in. - * @param original the original MethodParameter object to copy from - */ - public MethodParameter(MethodParameter original) { - Assert.notNull(original, "Original must not be null"); - this.method = original.method; - this.constructor = original.constructor; - this.parameterIndex = original.parameterIndex; - this.nestingLevel = original.nestingLevel; - this.typeIndexesPerLevel = original.typeIndexesPerLevel; - this.containingClass = original.containingClass; - this.parameterType = original.parameterType; - this.genericParameterType = original.genericParameterType; - this.parameterAnnotations = original.parameterAnnotations; - this.parameterNameDiscoverer = original.parameterNameDiscoverer; - this.parameterName = original.parameterName; - } - - - /** - * Return the wrapped Method, if any. - *

Note: Either Method or Constructor is available. - * @return the Method, or {@code null} if none - */ - public Method getMethod() { - return this.method; - } - - /** - * Return the wrapped Constructor, if any. - *

Note: Either Method or Constructor is available. - * @return the Constructor, or {@code null} if none - */ - public Constructor getConstructor() { - return this.constructor; - } - - /** - * Return the class that declares the underlying Method or Constructor. - */ - public Class getDeclaringClass() { - return getMember().getDeclaringClass(); - } - - /** - * Return the wrapped member. - * @return the Method or Constructor as Member - */ - public Member getMember() { - // NOTE: no ternary expression to retain JDK <8 compatibility even when using - // the JDK 8 compiler (potentially selecting java.lang.reflect.Executable - // as common type, with that new base class not available on older JDKs) - if (this.method != null) { - return this.method; - } - else { - return this.constructor; - } - } - - /** - * Return the wrapped annotated element. - *

Note: This method exposes the annotations declared on the method/constructor - * itself (i.e. at the method/constructor level, not at the parameter level). - * @return the Method or Constructor as AnnotatedElement - */ - public AnnotatedElement getAnnotatedElement() { - // NOTE: no ternary expression to retain JDK <8 compatibility even when using - // the JDK 8 compiler (potentially selecting java.lang.reflect.Executable - // as common type, with that new base class not available on older JDKs) - if (this.method != null) { - return this.method; - } - else { - return this.constructor; - } - } - - /** - * Return the index of the method/constructor parameter. - * @return the parameter index (-1 in case of the return type) - */ - public int getParameterIndex() { - return this.parameterIndex; - } - - /** - * Increase this parameter's nesting level. - * @see #getNestingLevel() - */ - public void increaseNestingLevel() { - this.nestingLevel++; - } - - /** - * Decrease this parameter's nesting level. - * @see #getNestingLevel() - */ - public void decreaseNestingLevel() { - getTypeIndexesPerLevel().remove(this.nestingLevel); - this.nestingLevel--; - } - - /** - * Return the nesting level of the target type - * (typically 1; e.g. in case of a List of Lists, 1 would indicate the - * nested List, whereas 2 would indicate the element of the nested List). - */ - public int getNestingLevel() { - return this.nestingLevel; - } - - /** - * Set the type index for the current nesting level. - * @param typeIndex the corresponding type index - * (or {@code null} for the default type index) - * @see #getNestingLevel() - */ - public void setTypeIndexForCurrentLevel(int typeIndex) { - getTypeIndexesPerLevel().put(this.nestingLevel, typeIndex); - } - - /** - * Return the type index for the current nesting level. - * @return the corresponding type index, or {@code null} - * if none specified (indicating the default type index) - * @see #getNestingLevel() - */ - public Integer getTypeIndexForCurrentLevel() { - return getTypeIndexForLevel(this.nestingLevel); - } - - /** - * Return the type index for the specified nesting level. - * @param nestingLevel the nesting level to check - * @return the corresponding type index, or {@code null} - * if none specified (indicating the default type index) - */ - public Integer getTypeIndexForLevel(int nestingLevel) { - return getTypeIndexesPerLevel().get(nestingLevel); - } - - /** - * Obtain the (lazily constructed) type-indexes-per-level Map. - */ - private Map getTypeIndexesPerLevel() { - if (this.typeIndexesPerLevel == null) { - this.typeIndexesPerLevel = new HashMap(4); - } - return this.typeIndexesPerLevel; - } - - /** - * Return a variant of this {@code MethodParameter} which points to the - * same parameter but one nesting level deeper. This is effectively the - * same as {@link #increaseNestingLevel()}, just with an independent - * {@code MethodParameter} object (e.g. in case of the original being cached). - * @since 4.3 - */ - public MethodParameter nested() { - if (this.nestedMethodParameter != null) { - return this.nestedMethodParameter; - } - MethodParameter nestedParam = clone(); - nestedParam.nestingLevel = this.nestingLevel + 1; - this.nestedMethodParameter = nestedParam; - return nestedParam; - } - - /** - * Return whether this method parameter is declared as optional - * in the form of Java 8's {@link java.util.Optional}. - * @since 4.3 - */ - public boolean isOptional() { - return (getParameterType() == javaUtilOptionalClass); - } - - /** - * Return a variant of this {@code MethodParameter} which points to - * the same parameter but one nesting level deeper in case of a - * {@link java.util.Optional} declaration. - * @since 4.3 - * @see #isOptional() - * @see #nested() - */ - public MethodParameter nestedIfOptional() { - return (isOptional() ? nested() : this); - } - - /** - * Set a containing class to resolve the parameter type against. - */ - void setContainingClass(Class containingClass) { - this.containingClass = containingClass; - } - - /** - * Return the containing class for this method parameter. - * @return a specific containing class (potentially a subclass of the - * declaring class), or otherwise simply the declaring class itself - * @see #getDeclaringClass() - */ - public Class getContainingClass() { - return (this.containingClass != null ? this.containingClass : getDeclaringClass()); - } - - /** - * Set a resolved (generic) parameter type. - */ - void setParameterType(Class parameterType) { - this.parameterType = parameterType; - } - - /** - * Return the type of the method/constructor parameter. - * @return the parameter type (never {@code null}) - */ - public Class getParameterType() { - Class paramType = this.parameterType; - if (paramType == null) { - if (this.parameterIndex < 0) { - Method method = getMethod(); - paramType = (method != null ? method.getReturnType() : void.class); - } - else { - paramType = (this.method != null ? - this.method.getParameterTypes()[this.parameterIndex] : - this.constructor.getParameterTypes()[this.parameterIndex]); - } - this.parameterType = paramType; - } - return paramType; - } - - /** - * Return the generic type of the method/constructor parameter. - * @return the parameter type (never {@code null}) - * @since 3.0 - */ - public Type getGenericParameterType() { - Type paramType = this.genericParameterType; - if (paramType == null) { - if (this.parameterIndex < 0) { - Method method = getMethod(); - paramType = (method != null ? method.getGenericReturnType() : void.class); - } - else { - Type[] genericParameterTypes = (this.method != null ? - this.method.getGenericParameterTypes() : this.constructor.getGenericParameterTypes()); - int index = this.parameterIndex; - if (this.constructor != null && this.constructor.getDeclaringClass().isMemberClass() && - !Modifier.isStatic(this.constructor.getDeclaringClass().getModifiers()) && - genericParameterTypes.length == this.constructor.getParameterTypes().length - 1) { - // Bug in javac: type array excludes enclosing instance parameter - // for inner classes with at least one generic constructor parameter, - // so access it with the actual parameter index lowered by 1 - index = this.parameterIndex - 1; - } - paramType = (index >= 0 && index < genericParameterTypes.length ? - genericParameterTypes[index] : getParameterType()); - } - this.genericParameterType = paramType; - } - return paramType; - } - - /** - * Return the nested type of the method/constructor parameter. - * @return the parameter type (never {@code null}) - * @since 3.1 - * @see #getNestingLevel() - */ - public Class getNestedParameterType() { - if (this.nestingLevel > 1) { - Type type = getGenericParameterType(); - for (int i = 2; i <= this.nestingLevel; i++) { - if (type instanceof ParameterizedType) { - Type[] args = ((ParameterizedType) type).getActualTypeArguments(); - Integer index = getTypeIndexForLevel(i); - type = args[index != null ? index : args.length - 1]; - } - // TODO: Object.class if unresolvable - } - if (type instanceof Class) { - return (Class) type; - } - else if (type instanceof ParameterizedType) { - Type arg = ((ParameterizedType) type).getRawType(); - if (arg instanceof Class) { - return (Class) arg; - } - } - return Object.class; - } - else { - return getParameterType(); - } - } - - /** - * Return the nested generic type of the method/constructor parameter. - * @return the parameter type (never {@code null}) - * @since 4.2 - * @see #getNestingLevel() - */ - public Type getNestedGenericParameterType() { - if (this.nestingLevel > 1) { - Type type = getGenericParameterType(); - for (int i = 2; i <= this.nestingLevel; i++) { - if (type instanceof ParameterizedType) { - Type[] args = ((ParameterizedType) type).getActualTypeArguments(); - Integer index = getTypeIndexForLevel(i); - type = args[index != null ? index : args.length - 1]; - } - } - return type; - } - else { - return getGenericParameterType(); - } - } - - /** - * Return the annotations associated with the target method/constructor itself. - */ - public Annotation[] getMethodAnnotations() { - return adaptAnnotationArray(getAnnotatedElement().getAnnotations()); - } - - /** - * Return the method/constructor annotation of the given type, if available. - * @param annotationType the annotation type to look for - * @return the annotation object, or {@code null} if not found - */ - public A getMethodAnnotation(Class annotationType) { - return adaptAnnotation(getAnnotatedElement().getAnnotation(annotationType)); - } - - /** - * Return whether the method/constructor is annotated with the given type. - * @param annotationType the annotation type to look for - * @since 4.3 - * @see #getMethodAnnotation(Class) - */ - public boolean hasMethodAnnotation(Class annotationType) { - return getAnnotatedElement().isAnnotationPresent(annotationType); - } - - /** - * Return the annotations associated with the specific method/constructor parameter. - */ - public Annotation[] getParameterAnnotations() { - Annotation[] paramAnns = this.parameterAnnotations; - if (paramAnns == null) { - Annotation[][] annotationArray = (this.method != null ? - this.method.getParameterAnnotations() : this.constructor.getParameterAnnotations()); - int index = this.parameterIndex; - if (this.constructor != null && this.constructor.getDeclaringClass().isMemberClass() && - !Modifier.isStatic(this.constructor.getDeclaringClass().getModifiers()) && - annotationArray.length == this.constructor.getParameterTypes().length - 1) { - // Bug in javac in JDK <9: annotation array excludes enclosing instance parameter - // for inner classes, so access it with the actual parameter index lowered by 1 - index = this.parameterIndex - 1; - } - paramAnns = (index >= 0 && index < annotationArray.length ? - adaptAnnotationArray(annotationArray[index]) : EMPTY_ANNOTATION_ARRAY); - this.parameterAnnotations = paramAnns; - } - return paramAnns; - } - - /** - * Return {@code true} if the parameter has at least one annotation, - * {@code false} if it has none. - * @see #getParameterAnnotations() - */ - public boolean hasParameterAnnotations() { - return (getParameterAnnotations().length != 0); - } - - /** - * Return the parameter annotation of the given type, if available. - * @param annotationType the annotation type to look for - * @return the annotation object, or {@code null} if not found - */ - @SuppressWarnings("unchecked") - public A getParameterAnnotation(Class annotationType) { - Annotation[] anns = getParameterAnnotations(); - for (Annotation ann : anns) { - if (annotationType.isInstance(ann)) { - return (A) ann; - } - } - return null; - } - - /** - * Return whether the parameter is declared with the given annotation type. - * @param annotationType the annotation type to look for - * @see #getParameterAnnotation(Class) - */ - public boolean hasParameterAnnotation(Class annotationType) { - return (getParameterAnnotation(annotationType) != null); - } - - /** - * Initialize parameter name discovery for this method parameter. - *

This method does not actually try to retrieve the parameter name at - * this point; it just allows discovery to happen when the application calls - * {@link #getParameterName()} (if ever). - */ - public void initParameterNameDiscovery(ParameterNameDiscoverer parameterNameDiscoverer) { - this.parameterNameDiscoverer = parameterNameDiscoverer; - } - - /** - * Return the name of the method/constructor parameter. - * @return the parameter name (may be {@code null} if no - * parameter name metadata is contained in the class file or no - * {@link #initParameterNameDiscovery ParameterNameDiscoverer} - * has been set to begin with) - */ - public String getParameterName() { - ParameterNameDiscoverer discoverer = this.parameterNameDiscoverer; - if (discoverer != null) { - String[] parameterNames = (this.method != null ? - discoverer.getParameterNames(this.method) : discoverer.getParameterNames(this.constructor)); - if (parameterNames != null) { - this.parameterName = parameterNames[this.parameterIndex]; - } - this.parameterNameDiscoverer = null; - } - return this.parameterName; - } - - - /** - * A template method to post-process a given annotation instance before - * returning it to the caller. - *

The default implementation simply returns the given annotation as-is. - * @param annotation the annotation about to be returned - * @return the post-processed annotation (or simply the original one) - * @since 4.2 - */ - protected A adaptAnnotation(A annotation) { - return annotation; - } - - /** - * A template method to post-process a given annotation array before - * returning it to the caller. - *

The default implementation simply returns the given annotation array as-is. - * @param annotations the annotation array about to be returned - * @return the post-processed annotation array (or simply the original one) - * @since 4.2 - */ - protected Annotation[] adaptAnnotationArray(Annotation[] annotations) { - return annotations; - } - - - @Override - public boolean equals(Object other) { - if (this == other) { - return true; - } - if (!(other instanceof MethodParameter)) { - return false; - } - MethodParameter otherParam = (MethodParameter) other; - return (getContainingClass() == otherParam.getContainingClass() && - ObjectUtil.nullSafeEquals(this.typeIndexesPerLevel, otherParam.typeIndexesPerLevel) && - this.nestingLevel == otherParam.nestingLevel && - this.parameterIndex == otherParam.parameterIndex && - getMember().equals(otherParam.getMember())); - } - - @Override - public int hashCode() { - return (getMember().hashCode() * 31 + this.parameterIndex); - } - - @Override - public String toString() { - return (this.method != null ? "method '" + this.method.getName() + "'" : "constructor") + - " parameter " + this.parameterIndex; - } - - @Override - public MethodParameter clone() { - return new MethodParameter(this); - } - - - /** - * Create a new MethodParameter for the given method or constructor. - *

This is a convenience constructor for scenarios where a - * Method or Constructor reference is treated in a generic fashion. - * @param methodOrConstructor the Method or Constructor to specify a parameter for - * @param parameterIndex the index of the parameter - * @return the corresponding MethodParameter instance - */ - public static MethodParameter forMethodOrConstructor(Object methodOrConstructor, int parameterIndex) { - if (methodOrConstructor instanceof Method) { - return new MethodParameter((Method) methodOrConstructor, parameterIndex); - } - else if (methodOrConstructor instanceof Constructor) { - return new MethodParameter((Constructor) methodOrConstructor, parameterIndex); - } - else { - throw new IllegalArgumentException( - "Given object [" + methodOrConstructor + "] is neither a Method nor a Constructor"); - } - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/type/ParameterNameDiscoverer.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/type/ParameterNameDiscoverer.java deleted file mode 100644 index 4d713d97..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/type/ParameterNameDiscoverer.java +++ /dev/null @@ -1,51 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.base.type; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; - -/** - * @author: aoshiguchen - * @date: 2022/9/25 - */ -public interface ParameterNameDiscoverer { - - /** - * Return parameter names for this method, - * or {@code null} if they cannot be determined. - * @param method method to find parameter names for - * @return an array of parameter names if the names can be resolved, - * or {@code null} if they cannot - */ - String[] getParameterNames(Method method); - - /** - * Return parameter names for this constructor, - * or {@code null} if they cannot be determined. - * @param ctor constructor to find parameter names for - * @return an array of parameter names if the names can be resolved, - * or {@code null} if they cannot - */ - String[] getParameterNames(Constructor ctor); - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/type/ParameterizedTypeReference.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/type/ParameterizedTypeReference.java deleted file mode 100644 index 279d8322..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/type/ParameterizedTypeReference.java +++ /dev/null @@ -1,100 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.base.type; - -import fun.asgc.neutrino.core.util.Assert; - -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; - -/** - * @author: aoshiguchen - * @date: 2022/9/25 - */ -public abstract class ParameterizedTypeReference { - - private final Type type; - - - protected ParameterizedTypeReference() { - Class parameterizedTypeReferenceSubclass = findParameterizedTypeReferenceSubclass(getClass()); - Type type = parameterizedTypeReferenceSubclass.getGenericSuperclass(); - Assert.isInstanceOf(ParameterizedType.class, type, "Type must be a parameterized type"); - ParameterizedType parameterizedType = (ParameterizedType) type; - Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); - Assert.isTrue(actualTypeArguments.length == 1, "Number of type arguments must be 1"); - this.type = actualTypeArguments[0]; - } - - private ParameterizedTypeReference(Type type) { - this.type = type; - } - - - public Type getType() { - return this.type; - } - - @Override - public boolean equals(Object obj) { - return (this == obj || (obj instanceof ParameterizedTypeReference && - this.type.equals(((ParameterizedTypeReference) obj).type))); - } - - @Override - public int hashCode() { - return this.type.hashCode(); - } - - @Override - public String toString() { - return "ParameterizedTypeReference<" + this.type + ">"; - } - - - /** - * Build a {@code ParameterizedTypeReference} wrapping the given type. - * @param type a generic type (possibly obtained via reflection, - * e.g. from {@link java.lang.reflect.Method#getGenericReturnType()}) - * @return a corresponding reference which may be passed into - * {@code ParameterizedTypeReference}-accepting methods - * @since 4.3.12 - */ - public static ParameterizedTypeReference forType(Type type) { - return new ParameterizedTypeReference(type) { - }; - } - - private static Class findParameterizedTypeReferenceSubclass(Class child) { - Class parent = child.getSuperclass(); - if (Object.class == parent) { - throw new IllegalStateException("Expected ParameterizedTypeReference superclass"); - } - else if (ParameterizedTypeReference.class == parent) { - return child; - } - else { - return findParameterizedTypeReferenceSubclass(parent); - } - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/type/ResolvableType.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/type/ResolvableType.java deleted file mode 100644 index 5792cb80..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/type/ResolvableType.java +++ /dev/null @@ -1,1556 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.base.type; - -import fun.asgc.neutrino.core.base.type.SerializableTypeWrapper.FieldTypeProvider; -import fun.asgc.neutrino.core.base.type.SerializableTypeWrapper.MethodParameterTypeProvider; -import fun.asgc.neutrino.core.base.type.SerializableTypeWrapper.TypeProvider; -import fun.asgc.neutrino.core.util.Assert; -import fun.asgc.neutrino.core.util.ConcurrentReferenceHashMap; -import fun.asgc.neutrino.core.util.ObjectUtil; -import fun.asgc.neutrino.core.util.StringUtil; -import org.apache.commons.lang3.ClassUtils; - -import java.io.Serializable; -import java.lang.reflect.*; -import java.util.Arrays; -import java.util.Collection; -import java.util.IdentityHashMap; -import java.util.Map; - -/** - * @author: aoshiguchen - * @date: 2022/9/24 - */ -@SuppressWarnings("serial") -public class ResolvableType implements Serializable { - - /** - * {@code ResolvableType} returned when no value is available. {@code NONE} is used - * in preference to {@code null} so that multiple method calls can be safely chained. - */ - public static final ResolvableType NONE = new ResolvableType(null, null, null, 0); - - private static final ResolvableType[] EMPTY_TYPES_ARRAY = new ResolvableType[0]; - - private static final ConcurrentReferenceHashMap cache = - new ConcurrentReferenceHashMap(256); - - - /** - * The underlying Java type being managed (only ever {@code null} for {@link #NONE}). - */ - private final Type type; - - /** - * Optional provider for the type. - */ - private final TypeProvider typeProvider; - - /** - * The {@code VariableResolver} to use or {@code null} if no resolver is available. - */ - private final VariableResolver variableResolver; - - /** - * The component type for an array or {@code null} if the type should be deduced. - */ - private final ResolvableType componentType; - - /** - * Copy of the resolved value. - */ - private final Class resolved; - - private final Integer hash; - - private ResolvableType superType; - - private ResolvableType[] interfaces; - - private ResolvableType[] generics; - - - /** - * Private constructor used to create a new {@link ResolvableType} for cache key purposes, - * with no upfront resolution. - */ - private ResolvableType(Type type, TypeProvider typeProvider, VariableResolver variableResolver) { - this.type = type; - this.typeProvider = typeProvider; - this.variableResolver = variableResolver; - this.componentType = null; - this.resolved = null; - this.hash = calculateHashCode(); - } - - /** - * Private constructor used to create a new {@link ResolvableType} for cache value purposes, - * with upfront resolution and a pre-calculated hash. - * @since 4.2 - */ - private ResolvableType(Type type, TypeProvider typeProvider, VariableResolver variableResolver, Integer hash) { - this.type = type; - this.typeProvider = typeProvider; - this.variableResolver = variableResolver; - this.componentType = null; - this.resolved = resolveClass(); - this.hash = hash; - } - - /** - * Private constructor used to create a new {@link ResolvableType} for uncached purposes, - * with upfront resolution but lazily calculated hash. - */ - private ResolvableType( - Type type, TypeProvider typeProvider, VariableResolver variableResolver, ResolvableType componentType) { - - this.type = type; - this.typeProvider = typeProvider; - this.variableResolver = variableResolver; - this.componentType = componentType; - this.resolved = resolveClass(); - this.hash = null; - } - - /** - * Private constructor used to create a new {@link ResolvableType} on a {@link Class} basis. - * Avoids all {@code instanceof} checks in order to create a straight {@link Class} wrapper. - * @since 4.2 - */ - private ResolvableType(Class clazz) { - this.resolved = (clazz != null ? clazz : Object.class); - this.type = this.resolved; - this.typeProvider = null; - this.variableResolver = null; - this.componentType = null; - this.hash = null; - } - - - /** - * Return the underling Java {@link Type} being managed. With the exception of - * the {@link #NONE} constant, this method will never return {@code null}. - */ - public Type getType() { - return SerializableTypeWrapper.unwrap(this.type); - } - - /** - * Return the underlying Java {@link Class} being managed, if available; - * otherwise {@code null}. - */ - public Class getRawClass() { - if (this.type == this.resolved) { - return this.resolved; - } - Type rawType = this.type; - if (rawType instanceof ParameterizedType) { - rawType = ((ParameterizedType) rawType).getRawType(); - } - return (rawType instanceof Class ? (Class) rawType : null); - } - - /** - * Return the underlying source of the resolvable type. Will return a {@link Field}, - * {@link MethodParameter} or {@link Type} depending on how the {@link ResolvableType} - * was constructed. With the exception of the {@link #NONE} constant, this method will - * never return {@code null}. This method is primarily to provide access to additional - * type information or meta-data that alternative JVM languages may provide. - */ - public Object getSource() { - Object source = (this.typeProvider != null ? this.typeProvider.getSource() : null); - return (source != null ? source : this.type); - } - - /** - * Determine whether the given object is an instance of this {@code ResolvableType}. - * @param obj the object to check - * @since 4.2 - * @see #isAssignableFrom(Class) - */ - public boolean isInstance(Object obj) { - return (obj != null && isAssignableFrom(obj.getClass())); - } - - /** - * Determine whether this {@code ResolvableType} is assignable from the - * specified other type. - * @param other the type to be checked against (as a {@code Class}) - * @since 4.2 - * @see #isAssignableFrom(ResolvableType) - */ - public boolean isAssignableFrom(Class other) { - return isAssignableFrom(forClass(other), null); - } - - /** - * Determine whether this {@code ResolvableType} is assignable from the - * specified other type. - *

Attempts to follow the same rules as the Java compiler, considering - * whether both the {@link #resolve() resolved} {@code Class} is - * {@link Class#isAssignableFrom(Class) assignable from} the given type - * as well as whether all {@link #getGenerics() generics} are assignable. - * @param other the type to be checked against (as a {@code ResolvableType}) - * @return {@code true} if the specified other type can be assigned to this - * {@code ResolvableType}; {@code false} otherwise - */ - public boolean isAssignableFrom(ResolvableType other) { - return isAssignableFrom(other, null); - } - - private boolean isAssignableFrom(ResolvableType other, Map matchedBefore) { - Assert.notNull(other, "ResolvableType must not be null"); - - // If we cannot resolve types, we are not assignable - if (this == NONE || other == NONE) { - return false; - } - - // Deal with array by delegating to the component type - if (isArray()) { - return (other.isArray() && getComponentType().isAssignableFrom(other.getComponentType())); - } - - if (matchedBefore != null && matchedBefore.get(this.type) == other.type) { - return true; - } - - // Deal with wildcard bounds - WildcardBounds ourBounds = WildcardBounds.get(this); - WildcardBounds typeBounds = WildcardBounds.get(other); - - // In the form X is assignable to - if (typeBounds != null) { - return (ourBounds != null && ourBounds.isSameKind(typeBounds) && - ourBounds.isAssignableFrom(typeBounds.getBounds())); - } - - // In the form is assignable to X... - if (ourBounds != null) { - return ourBounds.isAssignableFrom(other); - } - - // Main assignability check about to follow - boolean exactMatch = (matchedBefore != null); // We're checking nested generic variables now... - boolean checkGenerics = true; - Class ourResolved = null; - if (this.type instanceof TypeVariable) { - TypeVariable variable = (TypeVariable) this.type; - // Try default variable resolution - if (this.variableResolver != null) { - ResolvableType resolved = this.variableResolver.resolveVariable(variable); - if (resolved != null) { - ourResolved = resolved.resolve(); - } - } - if (ourResolved == null) { - // Try variable resolution against target type - if (other.variableResolver != null) { - ResolvableType resolved = other.variableResolver.resolveVariable(variable); - if (resolved != null) { - ourResolved = resolved.resolve(); - checkGenerics = false; - } - } - } - if (ourResolved == null) { - // Unresolved type variable, potentially nested -> never insist on exact match - exactMatch = false; - } - } - if (ourResolved == null) { - ourResolved = resolve(Object.class); - } - Class otherResolved = other.resolve(Object.class); - - // We need an exact type match for generics - // List is not assignable from List - if (exactMatch ? !ourResolved.equals(otherResolved) : !ClassUtils.isAssignable(ourResolved, otherResolved)) { - return false; - } - - if (checkGenerics) { - // Recursively check each generic - ResolvableType[] ourGenerics = getGenerics(); - ResolvableType[] typeGenerics = other.as(ourResolved).getGenerics(); - if (ourGenerics.length != typeGenerics.length) { - return false; - } - if (matchedBefore == null) { - matchedBefore = new IdentityHashMap(1); - } - matchedBefore.put(this.type, other.type); - for (int i = 0; i < ourGenerics.length; i++) { - if (!ourGenerics[i].isAssignableFrom(typeGenerics[i], matchedBefore)) { - return false; - } - } - } - - return true; - } - - /** - * Return {@code true} if this type resolves to a Class that represents an array. - * @see #getComponentType() - */ - public boolean isArray() { - if (this == NONE) { - return false; - } - return ((this.type instanceof Class && ((Class) this.type).isArray()) || - this.type instanceof GenericArrayType || resolveType().isArray()); - } - - /** - * Return the ResolvableType representing the component type of the array or - * {@link #NONE} if this type does not represent an array. - * @see #isArray() - */ - public ResolvableType getComponentType() { - if (this == NONE) { - return NONE; - } - if (this.componentType != null) { - return this.componentType; - } - if (this.type instanceof Class) { - Class componentType = ((Class) this.type).getComponentType(); - return forType(componentType, this.variableResolver); - } - if (this.type instanceof GenericArrayType) { - return forType(((GenericArrayType) this.type).getGenericComponentType(), this.variableResolver); - } - return resolveType().getComponentType(); - } - - /** - * Convenience method to return this type as a resolvable {@link Collection} type. - * Returns {@link #NONE} if this type does not implement or extend - * {@link Collection}. - * @see #as(Class) - * @see #asMap() - */ - public ResolvableType asCollection() { - return as(Collection.class); - } - - /** - * Convenience method to return this type as a resolvable {@link Map} type. - * Returns {@link #NONE} if this type does not implement or extend - * {@link Map}. - * @see #as(Class) - * @see #asCollection() - */ - public ResolvableType asMap() { - return as(Map.class); - } - - /** - * Return this type as a {@link ResolvableType} of the specified class. Searches - * {@link #getSuperType() supertype} and {@link #getInterfaces() interface} - * hierarchies to find a match, returning {@link #NONE} if this type does not - * implement or extend the specified class. - * @param type the required type (typically narrowed) - * @return a {@link ResolvableType} representing this object as the specified - * type, or {@link #NONE} if not resolvable as that type - * @see #asCollection() - * @see #asMap() - * @see #getSuperType() - * @see #getInterfaces() - */ - public ResolvableType as(Class type) { - if (this == NONE) { - return NONE; - } - if (ObjectUtil.nullSafeEquals(resolve(), type)) { - return this; - } - for (ResolvableType interfaceType : getInterfaces()) { - ResolvableType interfaceAsType = interfaceType.as(type); - if (interfaceAsType != NONE) { - return interfaceAsType; - } - } - return getSuperType().as(type); - } - - /** - * Return a {@link ResolvableType} representing the direct supertype of this type. - * If no supertype is available this method returns {@link #NONE}. - * @see #getInterfaces() - */ - public ResolvableType getSuperType() { - Class resolved = resolve(); - if (resolved == null || resolved.getGenericSuperclass() == null) { - return NONE; - } - if (this.superType == null) { - this.superType = forType(SerializableTypeWrapper.forGenericSuperclass(resolved), asVariableResolver()); - } - return this.superType; - } - - /** - * Return a {@link ResolvableType} array representing the direct interfaces - * implemented by this type. If this type does not implement any interfaces an - * empty array is returned. - * @see #getSuperType() - */ - public ResolvableType[] getInterfaces() { - Class resolved = resolve(); - if (resolved == null || ObjectUtil.isEmpty(resolved.getGenericInterfaces())) { - return EMPTY_TYPES_ARRAY; - } - if (this.interfaces == null) { - this.interfaces = forTypes(SerializableTypeWrapper.forGenericInterfaces(resolved), asVariableResolver()); - } - return this.interfaces; - } - - /** - * Return {@code true} if this type contains generic parameters. - * @see #getGeneric(int...) - * @see #getGenerics() - */ - public boolean hasGenerics() { - return (getGenerics().length > 0); - } - - /** - * Return {@code true} if this type contains unresolvable generics only, - * that is, no substitute for any of its declared type variables. - */ - boolean isEntirelyUnresolvable() { - if (this == NONE) { - return false; - } - ResolvableType[] generics = getGenerics(); - for (ResolvableType generic : generics) { - if (!generic.isUnresolvableTypeVariable() && !generic.isWildcardWithoutBounds()) { - return false; - } - } - return true; - } - - /** - * Determine whether the underlying type has any unresolvable generics: - * either through an unresolvable type variable on the type itself - * or through implementing a generic interface in a raw fashion, - * i.e. without substituting that interface's type variables. - * The result will be {@code true} only in those two scenarios. - */ - public boolean hasUnresolvableGenerics() { - if (this == NONE) { - return false; - } - ResolvableType[] generics = getGenerics(); - for (ResolvableType generic : generics) { - if (generic.isUnresolvableTypeVariable() || generic.isWildcardWithoutBounds()) { - return true; - } - } - Class resolved = resolve(); - if (resolved != null) { - for (Type genericInterface : resolved.getGenericInterfaces()) { - if (genericInterface instanceof Class) { - if (forClass((Class) genericInterface).hasGenerics()) { - return true; - } - } - } - return getSuperType().hasUnresolvableGenerics(); - } - return false; - } - - /** - * Determine whether the underlying type is a type variable that - * cannot be resolved through the associated variable resolver. - */ - private boolean isUnresolvableTypeVariable() { - if (this.type instanceof TypeVariable) { - if (this.variableResolver == null) { - return true; - } - TypeVariable variable = (TypeVariable) this.type; - ResolvableType resolved = this.variableResolver.resolveVariable(variable); - if (resolved == null || resolved.isUnresolvableTypeVariable()) { - return true; - } - } - return false; - } - - /** - * Determine whether the underlying type represents a wildcard - * without specific bounds (i.e., equal to {@code ? extends Object}). - */ - private boolean isWildcardWithoutBounds() { - if (this.type instanceof WildcardType) { - WildcardType wt = (WildcardType) this.type; - if (wt.getLowerBounds().length == 0) { - Type[] upperBounds = wt.getUpperBounds(); - if (upperBounds.length == 0 || (upperBounds.length == 1 && Object.class == upperBounds[0])) { - return true; - } - } - } - return false; - } - - /** - * Return a {@link ResolvableType} for the specified nesting level. - * See {@link #getNested(int, Map)} for details. - * @param nestingLevel the nesting level - * @return the {@link ResolvableType} type, or {@code #NONE} - */ - public ResolvableType getNested(int nestingLevel) { - return getNested(nestingLevel, null); - } - - /** - * Return a {@link ResolvableType} for the specified nesting level. - *

The nesting level refers to the specific generic parameter that should be returned. - * A nesting level of 1 indicates this type; 2 indicates the first nested generic; - * 3 the second; and so on. For example, given {@code List>} level 1 refers - * to the {@code List}, level 2 the {@code Set}, and level 3 the {@code Integer}. - *

The {@code typeIndexesPerLevel} map can be used to reference a specific generic - * for the given level. For example, an index of 0 would refer to a {@code Map} key; - * whereas, 1 would refer to the value. If the map does not contain a value for a - * specific level the last generic will be used (e.g. a {@code Map} value). - *

Nesting levels may also apply to array types; for example given - * {@code String[]}, a nesting level of 2 refers to {@code String}. - *

If a type does not {@link #hasGenerics() contain} generics the - * {@link #getSuperType() supertype} hierarchy will be considered. - * @param nestingLevel the required nesting level, indexed from 1 for the - * current type, 2 for the first nested generic, 3 for the second and so on - * @param typeIndexesPerLevel a map containing the generic index for a given - * nesting level (may be {@code null}) - * @return a {@link ResolvableType} for the nested level, or {@link #NONE} - */ - public ResolvableType getNested(int nestingLevel, Map typeIndexesPerLevel) { - ResolvableType result = this; - for (int i = 2; i <= nestingLevel; i++) { - if (result.isArray()) { - result = result.getComponentType(); - } - else { - // Handle derived types - while (result != ResolvableType.NONE && !result.hasGenerics()) { - result = result.getSuperType(); - } - Integer index = (typeIndexesPerLevel != null ? typeIndexesPerLevel.get(i) : null); - index = (index == null ? result.getGenerics().length - 1 : index); - result = result.getGeneric(index); - } - } - return result; - } - - /** - * Return a {@link ResolvableType} representing the generic parameter for the - * given indexes. Indexes are zero based; for example given the type - * {@code Map>}, {@code getGeneric(0)} will access the - * {@code Integer}. Nested generics can be accessed by specifying multiple indexes; - * for example {@code getGeneric(1, 0)} will access the {@code String} from the - * nested {@code List}. For convenience, if no indexes are specified the first - * generic is returned. - *

If no generic is available at the specified indexes {@link #NONE} is returned. - * @param indexes the indexes that refer to the generic parameter - * (may be omitted to return the first generic) - * @return a {@link ResolvableType} for the specified generic, or {@link #NONE} - * @see #hasGenerics() - * @see #getGenerics() - * @see #resolveGeneric(int...) - * @see #resolveGenerics() - */ - public ResolvableType getGeneric(int... indexes) { - ResolvableType[] generics = getGenerics(); - if (indexes == null || indexes.length == 0) { - return (generics.length == 0 ? NONE : generics[0]); - } - ResolvableType generic = this; - for (int index : indexes) { - generics = generic.getGenerics(); - if (index < 0 || index >= generics.length) { - return NONE; - } - generic = generics[index]; - } - return generic; - } - - /** - * Return an array of {@link ResolvableType}s representing the generic parameters of - * this type. If no generics are available an empty array is returned. If you need to - * access a specific generic consider using the {@link #getGeneric(int...)} method as - * it allows access to nested generics and protects against - * {@code IndexOutOfBoundsExceptions}. - * @return an array of {@link ResolvableType}s representing the generic parameters - * (never {@code null}) - * @see #hasGenerics() - * @see #getGeneric(int...) - * @see #resolveGeneric(int...) - * @see #resolveGenerics() - */ - public ResolvableType[] getGenerics() { - if (this == NONE) { - return EMPTY_TYPES_ARRAY; - } - if (this.generics == null) { - if (this.type instanceof Class) { - Class typeClass = (Class) this.type; - this.generics = forTypes(SerializableTypeWrapper.forTypeParameters(typeClass), this.variableResolver); - } - else if (this.type instanceof ParameterizedType) { - Type[] actualTypeArguments = ((ParameterizedType) this.type).getActualTypeArguments(); - ResolvableType[] generics = new ResolvableType[actualTypeArguments.length]; - for (int i = 0; i < actualTypeArguments.length; i++) { - generics[i] = forType(actualTypeArguments[i], this.variableResolver); - } - this.generics = generics; - } - else { - this.generics = resolveType().getGenerics(); - } - } - return this.generics; - } - - /** - * Convenience method that will {@link #getGenerics() get} and - * {@link #resolve() resolve} generic parameters. - * @return an array of resolved generic parameters (the resulting array - * will never be {@code null}, but it may contain {@code null} elements}) - * @see #getGenerics() - * @see #resolve() - */ - public Class[] resolveGenerics() { - return resolveGenerics(null); - } - - /** - * Convenience method that will {@link #getGenerics() get} and {@link #resolve() - * resolve} generic parameters, using the specified {@code fallback} if any type - * cannot be resolved. - * @param fallback the fallback class to use if resolution fails - * @return an array of resolved generic parameters - * @see #getGenerics() - * @see #resolve() - */ - public Class[] resolveGenerics(Class fallback) { - ResolvableType[] generics = getGenerics(); - Class[] resolvedGenerics = new Class[generics.length]; - for (int i = 0; i < generics.length; i++) { - resolvedGenerics[i] = generics[i].resolve(fallback); - } - return resolvedGenerics; - } - - /** - * Convenience method that will {@link #getGeneric(int...) get} and - * {@link #resolve() resolve} a specific generic parameters. - * @param indexes the indexes that refer to the generic parameter - * (may be omitted to return the first generic) - * @return a resolved {@link Class} or {@code null} - * @see #getGeneric(int...) - * @see #resolve() - */ - public Class resolveGeneric(int... indexes) { - return getGeneric(indexes).resolve(); - } - - /** - * Resolve this type to a {@link java.lang.Class}, returning {@code null} - * if the type cannot be resolved. This method will consider bounds of - * {@link TypeVariable}s and {@link WildcardType}s if direct resolution fails; - * however, bounds of {@code Object.class} will be ignored. - * @return the resolved {@link Class}, or {@code null} if not resolvable - * @see #resolve(Class) - * @see #resolveGeneric(int...) - * @see #resolveGenerics() - */ - public Class resolve() { - return resolve(null); - } - - /** - * Resolve this type to a {@link java.lang.Class}, returning the specified - * {@code fallback} if the type cannot be resolved. This method will consider bounds - * of {@link TypeVariable}s and {@link WildcardType}s if direct resolution fails; - * however, bounds of {@code Object.class} will be ignored. - * @param fallback the fallback class to use if resolution fails - * @return the resolved {@link Class} or the {@code fallback} - * @see #resolve() - * @see #resolveGeneric(int...) - * @see #resolveGenerics() - */ - public Class resolve(Class fallback) { - return (this.resolved != null ? this.resolved : fallback); - } - - private Class resolveClass() { - if (this.type instanceof Class || this.type == null) { - return (Class) this.type; - } - if (this.type instanceof GenericArrayType) { - Class resolvedComponent = getComponentType().resolve(); - return (resolvedComponent != null ? Array.newInstance(resolvedComponent, 0).getClass() : null); - } - return resolveType().resolve(); - } - - /** - * Resolve this type by a single level, returning the resolved value or {@link #NONE}. - *

Note: The returned {@link ResolvableType} should only be used as an intermediary - * as it cannot be serialized. - */ - ResolvableType resolveType() { - if (this.type instanceof ParameterizedType) { - return forType(((ParameterizedType) this.type).getRawType(), this.variableResolver); - } - if (this.type instanceof WildcardType) { - Type resolved = resolveBounds(((WildcardType) this.type).getUpperBounds()); - if (resolved == null) { - resolved = resolveBounds(((WildcardType) this.type).getLowerBounds()); - } - return forType(resolved, this.variableResolver); - } - if (this.type instanceof TypeVariable) { - TypeVariable variable = (TypeVariable) this.type; - // Try default variable resolution - if (this.variableResolver != null) { - ResolvableType resolved = this.variableResolver.resolveVariable(variable); - if (resolved != null) { - return resolved; - } - } - // Fallback to bounds - return forType(resolveBounds(variable.getBounds()), this.variableResolver); - } - return NONE; - } - - private Type resolveBounds(Type[] bounds) { - if (ObjectUtil.isEmpty(bounds) || Object.class == bounds[0]) { - return null; - } - return bounds[0]; - } - - private ResolvableType resolveVariable(TypeVariable variable) { - if (this.type instanceof TypeVariable) { - return resolveType().resolveVariable(variable); - } - if (this.type instanceof ParameterizedType) { - ParameterizedType parameterizedType = (ParameterizedType) this.type; - TypeVariable[] variables = resolve().getTypeParameters(); - for (int i = 0; i < variables.length; i++) { - if (ObjectUtil.nullSafeEquals(variables[i].getName(), variable.getName())) { - Type actualType = parameterizedType.getActualTypeArguments()[i]; - return forType(actualType, this.variableResolver); - } - } - if (parameterizedType.getOwnerType() != null) { - return forType(parameterizedType.getOwnerType(), this.variableResolver).resolveVariable(variable); - } - } - if (this.variableResolver != null) { - return this.variableResolver.resolveVariable(variable); - } - return null; - } - - - @Override - public boolean equals(Object other) { - if (this == other) { - return true; - } - if (!(other instanceof ResolvableType)) { - return false; - } - - ResolvableType otherType = (ResolvableType) other; - if (!ObjectUtil.nullSafeEquals(this.type, otherType.type)) { - return false; - } - if (this.typeProvider != otherType.typeProvider && - (this.typeProvider == null || otherType.typeProvider == null || - !ObjectUtil.nullSafeEquals(this.typeProvider.getType(), otherType.typeProvider.getType()))) { - return false; - } - if (this.variableResolver != otherType.variableResolver && - (this.variableResolver == null || otherType.variableResolver == null || - !ObjectUtil.nullSafeEquals(this.variableResolver.getSource(), otherType.variableResolver.getSource()))) { - return false; - } - if (!ObjectUtil.nullSafeEquals(this.componentType, otherType.componentType)) { - return false; - } - return true; - } - - @Override - public int hashCode() { - return (this.hash != null ? this.hash : calculateHashCode()); - } - - private int calculateHashCode() { - int hashCode = ObjectUtil.nullSafeHashCode(this.type); - if (this.typeProvider != null) { - hashCode = 31 * hashCode + ObjectUtil.nullSafeHashCode(this.typeProvider.getType()); - } - if (this.variableResolver != null) { - hashCode = 31 * hashCode + ObjectUtil.nullSafeHashCode(this.variableResolver.getSource()); - } - if (this.componentType != null) { - hashCode = 31 * hashCode + ObjectUtil.nullSafeHashCode(this.componentType); - } - return hashCode; - } - - /** - * Adapts this {@link ResolvableType} to a {@link VariableResolver}. - */ - VariableResolver asVariableResolver() { - if (this == NONE) { - return null; - } - return new DefaultVariableResolver(); - } - - /** - * Custom serialization support for {@link #NONE}. - */ - private Object readResolve() { - return (this.type == null ? NONE : this); - } - - /** - * Return a String representation of this type in its fully resolved form - * (including any generic parameters). - */ - @Override - public String toString() { - if (isArray()) { - return getComponentType() + "[]"; - } - if (this.resolved == null) { - return "?"; - } - if (this.type instanceof TypeVariable) { - TypeVariable variable = (TypeVariable) this.type; - if (this.variableResolver == null || this.variableResolver.resolveVariable(variable) == null) { - // Don't bother with variable boundaries for toString()... - // Can cause infinite recursions in case of self-references - return "?"; - } - } - StringBuilder result = new StringBuilder(this.resolved.getName()); - if (hasGenerics()) { - result.append('<'); - result.append(StringUtil.arrayToDelimitedString(getGenerics(), ", ")); - result.append('>'); - } - return result.toString(); - } - - - // Factory methods - - /** - * Return a {@link ResolvableType} for the specified {@link Class}, - * using the full generic type information for assignability checks. - * For example: {@code ResolvableType.forClass(MyArrayList.class)}. - * @param clazz the class to introspect ({@code null} is semantically - * equivalent to {@code Object.class} for typical use cases here) - * @return a {@link ResolvableType} for the specified class - * @see #forClass(Class, Class) - * @see #forClassWithGenerics(Class, Class...) - */ - public static ResolvableType forClass(Class clazz) { - return new ResolvableType(clazz); - } - - /** - * Return a {@link ResolvableType} for the specified {@link Class}, - * doing assignability checks against the raw class only (analogous to - * {@link Class#isAssignableFrom}, which this serves as a wrapper for. - * For example: {@code ResolvableType.forRawClass(List.class)}. - * @param clazz the class to introspect ({@code null} is semantically - * equivalent to {@code Object.class} for typical use cases here) - * @return a {@link ResolvableType} for the specified class - * @since 4.2 - * @see #forClass(Class) - * @see #getRawClass() - */ - public static ResolvableType forRawClass(Class clazz) { - return new ResolvableType(clazz) { - @Override - public ResolvableType[] getGenerics() { - return EMPTY_TYPES_ARRAY; - } - @Override - public boolean isAssignableFrom(Class other) { - return ClassUtils.isAssignable(getRawClass(), other); - } - @Override - public boolean isAssignableFrom(ResolvableType other) { - Class otherClass = other.getRawClass(); - return (otherClass != null && ClassUtils.isAssignable(getRawClass(), otherClass)); - } - }; - } - - /** - * Return a {@link ResolvableType} for the specified base type - * (interface or base class) with a given implementation class. - * For example: {@code ResolvableType.forClass(List.class, MyArrayList.class)}. - * @param baseType the base type (must not be {@code null}) - * @param implementationClass the implementation class - * @return a {@link ResolvableType} for the specified base type backed by the - * given implementation class - * @see #forClass(Class) - * @see #forClassWithGenerics(Class, Class...) - */ - public static ResolvableType forClass(Class baseType, Class implementationClass) { - Assert.notNull(baseType, "Base type must not be null"); - ResolvableType asType = forType(implementationClass).as(baseType); - return (asType == NONE ? forType(baseType) : asType); - } - - /** - * Return a {@link ResolvableType} for the specified {@link Class} with pre-declared generics. - * @param clazz the class (or interface) to introspect - * @param generics the generics of the class - * @return a {@link ResolvableType} for the specific class and generics - * @see #forClassWithGenerics(Class, ResolvableType...) - */ - public static ResolvableType forClassWithGenerics(Class clazz, Class... generics) { - Assert.notNull(clazz, "Class must not be null"); - Assert.notNull(generics, "Generics array must not be null"); - ResolvableType[] resolvableGenerics = new ResolvableType[generics.length]; - for (int i = 0; i < generics.length; i++) { - resolvableGenerics[i] = forClass(generics[i]); - } - return forClassWithGenerics(clazz, resolvableGenerics); - } - - /** - * Return a {@link ResolvableType} for the specified {@link Class} with pre-declared generics. - * @param clazz the class (or interface) to introspect - * @param generics the generics of the class - * @return a {@link ResolvableType} for the specific class and generics - * @see #forClassWithGenerics(Class, Class...) - */ - public static ResolvableType forClassWithGenerics(Class clazz, ResolvableType... generics) { - Assert.notNull(clazz, "Class must not be null"); - Assert.notNull(generics, "Generics array must not be null"); - TypeVariable[] variables = clazz.getTypeParameters(); - Assert.isTrue(variables.length == generics.length, "Mismatched number of generics specified"); - - Type[] arguments = new Type[generics.length]; - for (int i = 0; i < generics.length; i++) { - ResolvableType generic = generics[i]; - Type argument = (generic != null ? generic.getType() : null); - arguments[i] = (argument != null ? argument : variables[i]); - } - - ParameterizedType syntheticType = new SyntheticParameterizedType(clazz, arguments); - return forType(syntheticType, new TypeVariablesVariableResolver(variables, generics)); - } - - /** - * Return a {@link ResolvableType} for the specified instance. The instance does not - * convey generic information but if it implements {@link ResolvableTypeProvider} a - * more precise {@link ResolvableType} can be used than the simple one based on - * the {@link #forClass(Class) Class instance}. - * @param instance the instance - * @return a {@link ResolvableType} for the specified instance - * @since 4.2 - * @see ResolvableTypeProvider - */ - public static ResolvableType forInstance(Object instance) { - Assert.notNull(instance, "Instance must not be null"); - if (instance instanceof ResolvableTypeProvider) { - ResolvableType type = ((ResolvableTypeProvider) instance).getResolvableType(); - if (type != null) { - return type; - } - } - return ResolvableType.forClass(instance.getClass()); - } - - /** - * Return a {@link ResolvableType} for the specified {@link Field}. - * @param field the source field - * @return a {@link ResolvableType} for the specified field - * @see #forField(Field, Class) - */ - public static ResolvableType forField(Field field) { - Assert.notNull(field, "Field must not be null"); - return forType(null, new FieldTypeProvider(field), null); - } - - /** - * Return a {@link ResolvableType} for the specified {@link Field} with a given - * implementation. - *

Use this variant when the class that declares the field includes generic - * parameter variables that are satisfied by the implementation class. - * @param field the source field - * @param implementationClass the implementation class - * @return a {@link ResolvableType} for the specified field - * @see #forField(Field) - */ - public static ResolvableType forField(Field field, Class implementationClass) { - Assert.notNull(field, "Field must not be null"); - ResolvableType owner = forType(implementationClass).as(field.getDeclaringClass()); - return forType(null, new FieldTypeProvider(field), owner.asVariableResolver()); - } - - /** - * Return a {@link ResolvableType} for the specified {@link Field} with a given - * implementation. - *

Use this variant when the class that declares the field includes generic - * parameter variables that are satisfied by the implementation type. - * @param field the source field - * @param implementationType the implementation type - * @return a {@link ResolvableType} for the specified field - * @see #forField(Field) - */ - public static ResolvableType forField(Field field, ResolvableType implementationType) { - Assert.notNull(field, "Field must not be null"); - ResolvableType owner = (implementationType != null ? implementationType : NONE); - owner = owner.as(field.getDeclaringClass()); - return forType(null, new FieldTypeProvider(field), owner.asVariableResolver()); - } - - /** - * Return a {@link ResolvableType} for the specified {@link Field} with the - * given nesting level. - * @param field the source field - * @param nestingLevel the nesting level (1 for the outer level; 2 for a nested - * generic type; etc) - * @see #forField(Field) - */ - public static ResolvableType forField(Field field, int nestingLevel) { - Assert.notNull(field, "Field must not be null"); - return forType(null, new FieldTypeProvider(field), null).getNested(nestingLevel); - } - - /** - * Return a {@link ResolvableType} for the specified {@link Field} with a given - * implementation and the given nesting level. - *

Use this variant when the class that declares the field includes generic - * parameter variables that are satisfied by the implementation class. - * @param field the source field - * @param nestingLevel the nesting level (1 for the outer level; 2 for a nested - * generic type; etc) - * @param implementationClass the implementation class - * @return a {@link ResolvableType} for the specified field - * @see #forField(Field) - */ - public static ResolvableType forField(Field field, int nestingLevel, Class implementationClass) { - Assert.notNull(field, "Field must not be null"); - ResolvableType owner = forType(implementationClass).as(field.getDeclaringClass()); - return forType(null, new FieldTypeProvider(field), owner.asVariableResolver()).getNested(nestingLevel); - } - - /** - * Return a {@link ResolvableType} for the specified {@link Constructor} parameter. - * @param constructor the source constructor (must not be {@code null}) - * @param parameterIndex the parameter index - * @return a {@link ResolvableType} for the specified constructor parameter - * @see #forConstructorParameter(Constructor, int, Class) - */ - public static ResolvableType forConstructorParameter(Constructor constructor, int parameterIndex) { - Assert.notNull(constructor, "Constructor must not be null"); - return forMethodParameter(new MethodParameter(constructor, parameterIndex)); - } - - /** - * Return a {@link ResolvableType} for the specified {@link Constructor} parameter - * with a given implementation. Use this variant when the class that declares the - * constructor includes generic parameter variables that are satisfied by the - * implementation class. - * @param constructor the source constructor (must not be {@code null}) - * @param parameterIndex the parameter index - * @param implementationClass the implementation class - * @return a {@link ResolvableType} for the specified constructor parameter - * @see #forConstructorParameter(Constructor, int) - */ - public static ResolvableType forConstructorParameter(Constructor constructor, int parameterIndex, - Class implementationClass) { - - Assert.notNull(constructor, "Constructor must not be null"); - MethodParameter methodParameter = new MethodParameter(constructor, parameterIndex); - methodParameter.setContainingClass(implementationClass); - return forMethodParameter(methodParameter); - } - - /** - * Return a {@link ResolvableType} for the specified {@link Method} return type. - * @param method the source for the method return type - * @return a {@link ResolvableType} for the specified method return - * @see #forMethodReturnType(Method, Class) - */ - public static ResolvableType forMethodReturnType(Method method) { - Assert.notNull(method, "Method must not be null"); - return forMethodParameter(new MethodParameter(method, -1)); - } - - /** - * Return a {@link ResolvableType} for the specified {@link Method} return type. - * Use this variant when the class that declares the method includes generic - * parameter variables that are satisfied by the implementation class. - * @param method the source for the method return type - * @param implementationClass the implementation class - * @return a {@link ResolvableType} for the specified method return - * @see #forMethodReturnType(Method) - */ - public static ResolvableType forMethodReturnType(Method method, Class implementationClass) { - Assert.notNull(method, "Method must not be null"); - MethodParameter methodParameter = new MethodParameter(method, -1); - methodParameter.setContainingClass(implementationClass); - return forMethodParameter(methodParameter); - } - - /** - * Return a {@link ResolvableType} for the specified {@link Method} parameter. - * @param method the source method (must not be {@code null}) - * @param parameterIndex the parameter index - * @return a {@link ResolvableType} for the specified method parameter - * @see #forMethodParameter(Method, int, Class) - * @see #forMethodParameter(MethodParameter) - */ - public static ResolvableType forMethodParameter(Method method, int parameterIndex) { - Assert.notNull(method, "Method must not be null"); - return forMethodParameter(new MethodParameter(method, parameterIndex)); - } - - /** - * Return a {@link ResolvableType} for the specified {@link Method} parameter with a - * given implementation. Use this variant when the class that declares the method - * includes generic parameter variables that are satisfied by the implementation class. - * @param method the source method (must not be {@code null}) - * @param parameterIndex the parameter index - * @param implementationClass the implementation class - * @return a {@link ResolvableType} for the specified method parameter - * @see #forMethodParameter(Method, int, Class) - * @see #forMethodParameter(MethodParameter) - */ - public static ResolvableType forMethodParameter(Method method, int parameterIndex, Class implementationClass) { - Assert.notNull(method, "Method must not be null"); - MethodParameter methodParameter = new MethodParameter(method, parameterIndex); - methodParameter.setContainingClass(implementationClass); - return forMethodParameter(methodParameter); - } - - /** - * Return a {@link ResolvableType} for the specified {@link MethodParameter}. - * @param methodParameter the source method parameter (must not be {@code null}) - * @return a {@link ResolvableType} for the specified method parameter - * @see #forMethodParameter(Method, int) - */ - public static ResolvableType forMethodParameter(MethodParameter methodParameter) { - return forMethodParameter(methodParameter, (Type) null); - } - - /** - * Return a {@link ResolvableType} for the specified {@link MethodParameter} with a - * given implementation type. Use this variant when the class that declares the method - * includes generic parameter variables that are satisfied by the implementation type. - * @param methodParameter the source method parameter (must not be {@code null}) - * @param implementationType the implementation type - * @return a {@link ResolvableType} for the specified method parameter - * @see #forMethodParameter(MethodParameter) - */ - public static ResolvableType forMethodParameter(MethodParameter methodParameter, ResolvableType implementationType) { - Assert.notNull(methodParameter, "MethodParameter must not be null"); - implementationType = (implementationType != null ? implementationType : - forType(methodParameter.getContainingClass())); - ResolvableType owner = implementationType.as(methodParameter.getDeclaringClass()); - return forType(null, new MethodParameterTypeProvider(methodParameter), owner.asVariableResolver()). - getNested(methodParameter.getNestingLevel(), methodParameter.typeIndexesPerLevel); - } - - /** - * Return a {@link ResolvableType} for the specified {@link MethodParameter}, - * overriding the target type to resolve with a specific given type. - * @param methodParameter the source method parameter (must not be {@code null}) - * @param targetType the type to resolve (a part of the method parameter's type) - * @return a {@link ResolvableType} for the specified method parameter - * @see #forMethodParameter(Method, int) - */ - public static ResolvableType forMethodParameter(MethodParameter methodParameter, Type targetType) { - Assert.notNull(methodParameter, "MethodParameter must not be null"); - ResolvableType owner = forType(methodParameter.getContainingClass()).as(methodParameter.getDeclaringClass()); - return forType(targetType, new MethodParameterTypeProvider(methodParameter), owner.asVariableResolver()). - getNested(methodParameter.getNestingLevel(), methodParameter.typeIndexesPerLevel); - } - - /** - * Resolve the top-level parameter type of the given {@code MethodParameter}. - * @param methodParameter the method parameter to resolve - * @since 4.1.9 - * @see MethodParameter#setParameterType - */ - static void resolveMethodParameter(MethodParameter methodParameter) { - Assert.notNull(methodParameter, "MethodParameter must not be null"); - ResolvableType owner = forType(methodParameter.getContainingClass()).as(methodParameter.getDeclaringClass()); - methodParameter.setParameterType( - forType(null, new MethodParameterTypeProvider(methodParameter), owner.asVariableResolver()).resolve()); - } - - /** - * Return a {@link ResolvableType} as a array of the specified {@code componentType}. - * @param componentType the component type - * @return a {@link ResolvableType} as an array of the specified component type - */ - public static ResolvableType forArrayComponent(ResolvableType componentType) { - Assert.notNull(componentType, "Component type must not be null"); - Class arrayClass = Array.newInstance(componentType.resolve(), 0).getClass(); - return new ResolvableType(arrayClass, null, null, componentType); - } - - private static ResolvableType[] forTypes(Type[] types, VariableResolver owner) { - ResolvableType[] result = new ResolvableType[types.length]; - for (int i = 0; i < types.length; i++) { - result[i] = forType(types[i], owner); - } - return result; - } - - /** - * Return a {@link ResolvableType} for the specified {@link Type}. - *

Note: The resulting {@link ResolvableType} instance may not be {@link Serializable}. - * @param type the source type (potentially {@code null}) - * @return a {@link ResolvableType} for the specified {@link Type} - * @see #forType(Type, ResolvableType) - */ - public static ResolvableType forType(Type type) { - return forType(type, null, null); - } - - /** - * Return a {@link ResolvableType} for the specified {@link Type} backed by the given - * owner type. - *

Note: The resulting {@link ResolvableType} instance may not be {@link Serializable}. - * @param type the source type or {@code null} - * @param owner the owner type used to resolve variables - * @return a {@link ResolvableType} for the specified {@link Type} and owner - * @see #forType(Type) - */ - public static ResolvableType forType(Type type, ResolvableType owner) { - VariableResolver variableResolver = null; - if (owner != null) { - variableResolver = owner.asVariableResolver(); - } - return forType(type, variableResolver); - } - - - /** - * Return a {@link ResolvableType} for the specified {@link ParameterizedTypeReference}. - *

Note: The resulting {@link ResolvableType} instance may not be {@link Serializable}. - * @param typeReference the reference to obtain the source type from - * @return a {@link ResolvableType} for the specified {@link ParameterizedTypeReference} - * @since 4.3.12 - * @see #forType(Type) - */ - public static ResolvableType forType(ParameterizedTypeReference typeReference) { - return forType(typeReference.getType(), null, null); - } - - /** - * Return a {@link ResolvableType} for the specified {@link Type} backed by a given - * {@link VariableResolver}. - * @param type the source type or {@code null} - * @param variableResolver the variable resolver or {@code null} - * @return a {@link ResolvableType} for the specified {@link Type} and {@link VariableResolver} - */ - static ResolvableType forType(Type type, VariableResolver variableResolver) { - return forType(type, null, variableResolver); - } - - /** - * Return a {@link ResolvableType} for the specified {@link Type} backed by a given - * {@link VariableResolver}. - * @param type the source type or {@code null} - * @param typeProvider the type provider or {@code null} - * @param variableResolver the variable resolver or {@code null} - * @return a {@link ResolvableType} for the specified {@link Type} and {@link VariableResolver} - */ - static ResolvableType forType(Type type, TypeProvider typeProvider, VariableResolver variableResolver) { - if (type == null && typeProvider != null) { - type = SerializableTypeWrapper.forTypeProvider(typeProvider); - } - if (type == null) { - return NONE; - } - - // For simple Class references, build the wrapper right away - - // no expensive resolution necessary, so not worth caching... - if (type instanceof Class) { - return new ResolvableType(type, typeProvider, variableResolver, (ResolvableType) null); - } - - // Purge empty entries on access since we don't have a clean-up thread or the like. - cache.purgeUnreferencedEntries(); - - // Check the cache - we may have a ResolvableType which has been resolved before... - ResolvableType key = new ResolvableType(type, typeProvider, variableResolver); - ResolvableType resolvableType = cache.get(key); - if (resolvableType == null) { - resolvableType = new ResolvableType(type, typeProvider, variableResolver, key.hash); - cache.put(resolvableType, resolvableType); - } - return resolvableType; - } - - /** - * Clear the internal {@code ResolvableType}/{@code SerializableTypeWrapper} cache. - * @since 4.2 - */ - public static void clearCache() { - cache.clear(); - SerializableTypeWrapper.cache.clear(); - } - - - /** - * Strategy interface used to resolve {@link TypeVariable}s. - */ - interface VariableResolver extends Serializable { - - /** - * Return the source of the resolver (used for hashCode and equals). - */ - Object getSource(); - - /** - * Resolve the specified variable. - * @param variable the variable to resolve - * @return the resolved variable, or {@code null} if not found - */ - ResolvableType resolveVariable(TypeVariable variable); - } - - - @SuppressWarnings("serial") - private class DefaultVariableResolver implements VariableResolver { - - @Override - public ResolvableType resolveVariable(TypeVariable variable) { - return ResolvableType.this.resolveVariable(variable); - } - - @Override - public Object getSource() { - return ResolvableType.this; - } - } - - - @SuppressWarnings("serial") - private static class TypeVariablesVariableResolver implements VariableResolver { - - private final TypeVariable[] variables; - - private final ResolvableType[] generics; - - public TypeVariablesVariableResolver(TypeVariable[] variables, ResolvableType[] generics) { - this.variables = variables; - this.generics = generics; - } - - @Override - public ResolvableType resolveVariable(TypeVariable variable) { - for (int i = 0; i < this.variables.length; i++) { - TypeVariable v1 = SerializableTypeWrapper.unwrap(this.variables[i]); - TypeVariable v2 = SerializableTypeWrapper.unwrap(variable); - if (ObjectUtil.nullSafeEquals(v1, v2)) { - return this.generics[i]; - } - } - return null; - } - - @Override - public Object getSource() { - return this.generics; - } - } - - - private static final class SyntheticParameterizedType implements ParameterizedType, Serializable { - - private final Type rawType; - - private final Type[] typeArguments; - - public SyntheticParameterizedType(Type rawType, Type[] typeArguments) { - this.rawType = rawType; - this.typeArguments = typeArguments; - } - - @Override // on Java 8 - public String getTypeName() { - StringBuilder result = new StringBuilder(this.rawType.getTypeName()); - if (this.typeArguments.length > 0) { - result.append('<'); - for (int i = 0; i < this.typeArguments.length; i++) { - if (i > 0) { - result.append(", "); - } - result.append(this.typeArguments[i].getTypeName()); - } - result.append('>'); - } - return result.toString(); - } - - @Override - public Type getOwnerType() { - return null; - } - - @Override - public Type getRawType() { - return this.rawType; - } - - @Override - public Type[] getActualTypeArguments() { - return this.typeArguments; - } - - @Override - public boolean equals(Object other) { - if (this == other) { - return true; - } - if (!(other instanceof ParameterizedType)) { - return false; - } - ParameterizedType otherType = (ParameterizedType) other; - return (otherType.getOwnerType() == null && this.rawType.equals(otherType.getRawType()) && - Arrays.equals(this.typeArguments, otherType.getActualTypeArguments())); - } - - @Override - public int hashCode() { - return (this.rawType.hashCode() * 31 + Arrays.hashCode(this.typeArguments)); - } - } - - - /** - * Internal helper to handle bounds from {@link WildcardType}s. - */ - private static class WildcardBounds { - - private final Kind kind; - - private final ResolvableType[] bounds; - - /** - * Internal constructor to create a new {@link WildcardBounds} instance. - * @param kind the kind of bounds - * @param bounds the bounds - * @see #get(ResolvableType) - */ - public WildcardBounds(Kind kind, ResolvableType[] bounds) { - this.kind = kind; - this.bounds = bounds; - } - - /** - * Return {@code true} if this bounds is the same kind as the specified bounds. - */ - public boolean isSameKind(WildcardBounds bounds) { - return this.kind == bounds.kind; - } - - /** - * Return {@code true} if this bounds is assignable to all the specified types. - * @param types the types to test against - * @return {@code true} if this bounds is assignable to all types - */ - public boolean isAssignableFrom(ResolvableType... types) { - for (ResolvableType bound : this.bounds) { - for (ResolvableType type : types) { - if (!isAssignable(bound, type)) { - return false; - } - } - } - return true; - } - - private boolean isAssignable(ResolvableType source, ResolvableType from) { - return (this.kind == Kind.UPPER ? source.isAssignableFrom(from) : from.isAssignableFrom(source)); - } - - /** - * Return the underlying bounds. - */ - public ResolvableType[] getBounds() { - return this.bounds; - } - - /** - * Get a {@link WildcardBounds} instance for the specified type, returning - * {@code null} if the specified type cannot be resolved to a {@link WildcardType}. - * @param type the source type - * @return a {@link WildcardBounds} instance or {@code null} - */ - public static WildcardBounds get(ResolvableType type) { - ResolvableType resolveToWildcard = type; - while (!(resolveToWildcard.getType() instanceof WildcardType)) { - if (resolveToWildcard == NONE) { - return null; - } - resolveToWildcard = resolveToWildcard.resolveType(); - } - WildcardType wildcardType = (WildcardType) resolveToWildcard.type; - Kind boundsType = (wildcardType.getLowerBounds().length > 0 ? Kind.LOWER : Kind.UPPER); - Type[] bounds = (boundsType == Kind.UPPER ? wildcardType.getUpperBounds() : wildcardType.getLowerBounds()); - ResolvableType[] resolvableBounds = new ResolvableType[bounds.length]; - for (int i = 0; i < bounds.length; i++) { - resolvableBounds[i] = ResolvableType.forType(bounds[i], type.variableResolver); - } - return new WildcardBounds(boundsType, resolvableBounds); - } - - /** - * The various kinds of bounds. - */ - enum Kind {UPPER, LOWER} - } - -} - diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/type/ResolvableTypeProvider.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/type/ResolvableTypeProvider.java deleted file mode 100644 index db566cf2..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/type/ResolvableTypeProvider.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.base.type; - -/** - * @author: aoshiguchen - * @date: 2022/9/25 - */ -public interface ResolvableTypeProvider { - - /** - * Return the {@link ResolvableType} describing this instance - * (or {@code null} if some sort of default should be applied instead). - */ - ResolvableType getResolvableType(); - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/type/SerializableTypeWrapper.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/type/SerializableTypeWrapper.java deleted file mode 100644 index dc67e08d..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/base/type/SerializableTypeWrapper.java +++ /dev/null @@ -1,399 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.base.type; - -import fun.asgc.neutrino.core.util.ConcurrentReferenceHashMap; -import fun.asgc.neutrino.core.util.ReflectUtil; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.Serializable; -import java.lang.reflect.*; - -/** - * @author: aoshiguchen - * @date: 2022/9/25 - */ -abstract class SerializableTypeWrapper { - - private static final Class[] SUPPORTED_SERIALIZABLE_TYPES = { - GenericArrayType.class, ParameterizedType.class, TypeVariable.class, WildcardType.class}; - - static final ConcurrentReferenceHashMap cache = new ConcurrentReferenceHashMap(256); - - - /** - * Return a {@link Serializable} variant of {@link Field#getGenericType()}. - */ - public static Type forField(Field field) { - return forTypeProvider(new FieldTypeProvider(field)); - } - - /** - * Return a {@link Serializable} variant of - * {@link MethodParameter#getGenericParameterType()}. - */ - public static Type forMethodParameter(MethodParameter methodParameter) { - return forTypeProvider(new MethodParameterTypeProvider(methodParameter)); - } - - /** - * Return a {@link Serializable} variant of {@link Class#getGenericSuperclass()}. - */ - @SuppressWarnings("serial") - public static Type forGenericSuperclass(final Class type) { - return forTypeProvider(new SimpleTypeProvider() { - @Override - public Type getType() { - return type.getGenericSuperclass(); - } - }); - } - - /** - * Return a {@link Serializable} variant of {@link Class#getGenericInterfaces()}. - */ - @SuppressWarnings("serial") - public static Type[] forGenericInterfaces(final Class type) { - Type[] result = new Type[type.getGenericInterfaces().length]; - for (int i = 0; i < result.length; i++) { - final int index = i; - result[i] = forTypeProvider(new SimpleTypeProvider() { - @Override - public Type getType() { - return type.getGenericInterfaces()[index]; - } - }); - } - return result; - } - - /** - * Return a {@link Serializable} variant of {@link Class#getTypeParameters()}. - */ - @SuppressWarnings("serial") - public static Type[] forTypeParameters(final Class type) { - Type[] result = new Type[type.getTypeParameters().length]; - for (int i = 0; i < result.length; i++) { - final int index = i; - result[i] = forTypeProvider(new SimpleTypeProvider() { - @Override - public Type getType() { - return type.getTypeParameters()[index]; - } - }); - } - return result; - } - - /** - * Unwrap the given type, effectively returning the original non-serializable type. - * @param type the type to unwrap - * @return the original non-serializable type - */ - @SuppressWarnings("unchecked") - public static T unwrap(T type) { - Type unwrapped = type; - while (unwrapped instanceof SerializableTypeProxy) { - unwrapped = ((SerializableTypeProxy) type).getTypeProvider().getType(); - } - return (T) unwrapped; - } - - /** - * Return a {@link Serializable} {@link Type} backed by a {@link TypeProvider} . - */ - static Type forTypeProvider(TypeProvider provider) { - Type providedType = provider.getType(); - if (providedType == null || providedType instanceof Serializable) { - // No serializable type wrapping necessary (e.g. for java.lang.Class) - return providedType; - } - - // Obtain a serializable type proxy for the given provider... - Type cached = cache.get(providedType); - if (cached != null) { - return cached; - } - for (Class type : SUPPORTED_SERIALIZABLE_TYPES) { - if (type.isInstance(providedType)) { - ClassLoader classLoader = provider.getClass().getClassLoader(); - Class[] interfaces = new Class[] {type, SerializableTypeProxy.class, Serializable.class}; - InvocationHandler handler = new TypeProxyInvocationHandler(provider); - cached = (Type) Proxy.newProxyInstance(classLoader, interfaces, handler); - cache.put(providedType, cached); - return cached; - } - } - throw new IllegalArgumentException("Unsupported Type class: " + providedType.getClass().getName()); - } - - - /** - * Additional interface implemented by the type proxy. - */ - interface SerializableTypeProxy { - - /** - * Return the underlying type provider. - */ - TypeProvider getTypeProvider(); - } - - - /** - * A {@link Serializable} interface providing access to a {@link Type}. - */ - interface TypeProvider extends Serializable { - - /** - * Return the (possibly non {@link Serializable}) {@link Type}. - */ - Type getType(); - - /** - * Return the source of the type or {@code null}. - */ - Object getSource(); - } - - - /** - * Base implementation of {@link TypeProvider} with a {@code null} source. - */ - @SuppressWarnings("serial") - private static abstract class SimpleTypeProvider implements TypeProvider { - - @Override - public Object getSource() { - return null; - } - } - - - /** - * {@link Serializable} {@link InvocationHandler} used by the proxied {@link Type}. - * Provides serialization support and enhances any methods that return {@code Type} - * or {@code Type[]}. - */ - @SuppressWarnings("serial") - private static class TypeProxyInvocationHandler implements InvocationHandler, Serializable { - - private final TypeProvider provider; - - public TypeProxyInvocationHandler(TypeProvider provider) { - this.provider = provider; - } - - @Override - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - if (method.getName().equals("equals")) { - Object other = args[0]; - // Unwrap proxies for speed - if (other instanceof Type) { - other = unwrap((Type) other); - } - return this.provider.getType().equals(other); - } - else if (method.getName().equals("hashCode")) { - return this.provider.getType().hashCode(); - } - else if (method.getName().equals("getTypeProvider")) { - return this.provider; - } - - if (Type.class == method.getReturnType() && args == null) { - return forTypeProvider(new MethodInvokeTypeProvider(this.provider, method, -1)); - } - else if (Type[].class == method.getReturnType() && args == null) { - Type[] result = new Type[((Type[]) method.invoke(this.provider.getType(), args)).length]; - for (int i = 0; i < result.length; i++) { - result[i] = forTypeProvider(new MethodInvokeTypeProvider(this.provider, method, i)); - } - return result; - } - - try { - return method.invoke(this.provider.getType(), args); - } - catch (InvocationTargetException ex) { - throw ex.getTargetException(); - } - } - } - - - /** - * {@link TypeProvider} for {@link Type}s obtained from a {@link Field}. - */ - @SuppressWarnings("serial") - static class FieldTypeProvider implements TypeProvider { - - private final String fieldName; - - private final Class declaringClass; - - private transient Field field; - - public FieldTypeProvider(Field field) { - this.fieldName = field.getName(); - this.declaringClass = field.getDeclaringClass(); - this.field = field; - } - - @Override - public Type getType() { - return this.field.getGenericType(); - } - - @Override - public Object getSource() { - return this.field; - } - - private void readObject(ObjectInputStream inputStream) throws IOException, ClassNotFoundException { - inputStream.defaultReadObject(); - try { - this.field = this.declaringClass.getDeclaredField(this.fieldName); - } - catch (Throwable ex) { - throw new IllegalStateException("Could not find original class structure", ex); - } - } - } - - - /** - * {@link TypeProvider} for {@link Type}s obtained from a {@link MethodParameter}. - */ - @SuppressWarnings("serial") - static class MethodParameterTypeProvider implements TypeProvider { - - private final String methodName; - - private final Class[] parameterTypes; - - private final Class declaringClass; - - private final int parameterIndex; - - private transient MethodParameter methodParameter; - - public MethodParameterTypeProvider(MethodParameter methodParameter) { - if (methodParameter.getMethod() != null) { - this.methodName = methodParameter.getMethod().getName(); - this.parameterTypes = methodParameter.getMethod().getParameterTypes(); - } - else { - this.methodName = null; - this.parameterTypes = methodParameter.getConstructor().getParameterTypes(); - } - this.declaringClass = methodParameter.getDeclaringClass(); - this.parameterIndex = methodParameter.getParameterIndex(); - this.methodParameter = methodParameter; - } - - - @Override - public Type getType() { - return this.methodParameter.getGenericParameterType(); - } - - @Override - public Object getSource() { - return this.methodParameter; - } - - private void readObject(ObjectInputStream inputStream) throws IOException, ClassNotFoundException { - inputStream.defaultReadObject(); - try { - if (this.methodName != null) { - this.methodParameter = new MethodParameter( - this.declaringClass.getDeclaredMethod(this.methodName, this.parameterTypes), this.parameterIndex); - } - else { - this.methodParameter = new MethodParameter( - this.declaringClass.getDeclaredConstructor(this.parameterTypes), this.parameterIndex); - } - } - catch (Throwable ex) { - throw new IllegalStateException("Could not find original class structure", ex); - } - } - } - - - /** - * {@link TypeProvider} for {@link Type}s obtained by invoking a no-arg method. - */ - @SuppressWarnings("serial") - static class MethodInvokeTypeProvider implements TypeProvider { - - private final TypeProvider provider; - - private final String methodName; - - private final Class declaringClass; - - private final int index; - - private transient Method method; - - private transient volatile Object result; - - public MethodInvokeTypeProvider(TypeProvider provider, Method method, int index) { - this.provider = provider; - this.methodName = method.getName(); - this.declaringClass = method.getDeclaringClass(); - this.index = index; - this.method = method; - } - - @Override - public Type getType() { - Object result = this.result; - if (result == null) { - // Lazy invocation of the target method on the provided type - result = ReflectUtil.invokeMethod(this.method, this.provider.getType()); - // Cache the result for further calls to getType() - this.result = result; - } - return (result instanceof Type[] ? ((Type[]) result)[this.index] : (Type) result); - } - - @Override - public Object getSource() { - return null; - } - - private void readObject(ObjectInputStream inputStream) throws IOException, ClassNotFoundException { - inputStream.defaultReadObject(); - this.method = ReflectUtil.findMethod(this.declaringClass, this.methodName); - if (this.method.getReturnType() != Type.class && this.method.getReturnType() != Type[].class) { - throw new IllegalStateException( - "Invalid return type on deserialized method - needs to be Type or Type[]: " + this.method); - } - } - } - -} - diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/bean/BeanIdentity.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/bean/BeanIdentity.java deleted file mode 100644 index e4dfb18e..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/bean/BeanIdentity.java +++ /dev/null @@ -1,97 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.bean; - -import fun.asgc.neutrino.core.base.Identity; -import fun.asgc.neutrino.core.util.Assert; - -/** - * 用于标识bean的身份 - * - * 此处用名称+类型作为bean的唯一标识 - * - * @author: aoshiguchen - * @date: 2022/7/1 - */ -public class BeanIdentity implements Identity { - /** - * 名称 - */ - private String name; - /** - * 类型 - */ - private Class type; - /** - * hashCode - */ - private int identityHashCode; - - public BeanIdentity(String name, Class type) { - Assert.notEmpty(name, "名称不能为空!"); - Assert.notNull(type, "类型不能为空!"); - this.name = name; - this.type = type; - this.identityHashCode = System.identityHashCode(type); - } - - /** - * 获取名称 - * @return - */ - public String getName() { - return this.name; - } - - /** - * 获取类型 - * @return - */ - public Class getType() { - return this.type; - } - - @Override - public boolean isOnly() { - return Boolean.TRUE; - } - - @Override - public boolean equals(Object obj) { - if (null == obj) { - return false; - } - if (obj == this) { - return true; - } - if (!(obj instanceof BeanIdentity)) { - return false; - } - BeanIdentity beanIdentity = (BeanIdentity)obj; - return this.name.equals(beanIdentity.getName()) && this.type.equals(beanIdentity.getType()); - } - - @Override - public int hashCode() { - return identityHashCode; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/bean/BeanInstantiationMode.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/bean/BeanInstantiationMode.java deleted file mode 100644 index 026c2404..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/bean/BeanInstantiationMode.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.bean; - -import lombok.AllArgsConstructor; -import lombok.Getter; - -/** - * Bean实例化的方式 - * @author: aoshiguchen - * @date: 2022/7/4 - */ -@Getter -@AllArgsConstructor -public enum BeanInstantiationMode { - // newInstance - DIRECT(1, "直接"), - METHOD(2, "方法"), - FACTORY(3, "工厂"); - private Integer mode; - private String desc; -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/bean/BeanMatchMode.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/bean/BeanMatchMode.java deleted file mode 100644 index fba32ba2..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/bean/BeanMatchMode.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.bean; - -import lombok.AllArgsConstructor; -import lombok.Getter; - -/** - * bean的匹配模式 - * @author: aoshiguchen - * @date: 2022/7/4 - */ -@Getter -@AllArgsConstructor -public enum BeanMatchMode { - ByType(1, "根据类型匹配"), - ByName(2, "根据名称匹配"), - ByTypeName(3, "根据类型+名称匹配"); - - private Integer mode; - private String desc; -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/bean/BeanRegistry.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/bean/BeanRegistry.java deleted file mode 100644 index 30728821..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/bean/BeanRegistry.java +++ /dev/null @@ -1,91 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.bean; - -import fun.asgc.neutrino.core.exception.BeanException; - -/** - * bean注册表 - * @author: aoshiguchen - * @date: 2022/7/1 - */ -public interface BeanRegistry { - - /** - * 注册bean - * @param obj - * @throws BeanException - */ - void registerBean(Object obj) throws BeanException; - - /** - * 注册bean - * @param obj - * @param name - * @throws BeanException - */ - void registerBean(Object obj, String name) throws BeanException; - - /** - * 注册bean - * @param type - * @throws BeanException - */ - void registerBean(Class type) throws BeanException; - - /** - * 注册bean - * @param type - * @param name - * @throws BeanException - */ - void registerBean(Class type, String name) throws BeanException; - - /** - * 判断是否包含此bean - * @param type - * @param name - * @return - */ - boolean hasBean(Class type, String name); - - /** - * 判断是否包含此bean - * @param type - * @return - */ - boolean hasBean(Class type); - - /** - * 查询bean容器中有多少个叫该名称的bean - * @param name - * @return - */ - int countBean(String name); - - /** - * 查询bean容器中有多少个该类型的bean - * @param type - * @return - */ - int countBean(Class type); -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/bean/BeanStatus.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/bean/BeanStatus.java deleted file mode 100644 index 5062f4b4..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/bean/BeanStatus.java +++ /dev/null @@ -1,55 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.bean; - -import lombok.AllArgsConstructor; -import lombok.Getter; - -import java.util.Map; -import java.util.function.Function; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -/** - * Bean的几种状态 - * @author: aoshiguchen - * @date: 2022/7/2 - */ -@Getter -@AllArgsConstructor -public enum BeanStatus { - REGISTER(1, "已注册"), - DEPENDENCY_CHECKING(2, "依赖关系检测完成"), - INSTANCE(3, "已实例化"), - INJECT(4, "已完成注入"), - INIT(5, "已初始化"), - RUNNING(6, "运行中"), - DESTROY(7, "已销毁"); - private static final Map cache = Stream.of(BeanStatus.values()).collect(Collectors.toMap(BeanStatus::getStatus, Function.identity())); - - private Integer status; - private String desc; - - public static BeanStatus of(Integer status) { - return cache.get(status); - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/bean/BeanWrapper.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/bean/BeanWrapper.java deleted file mode 100644 index 1163377f..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/bean/BeanWrapper.java +++ /dev/null @@ -1,162 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.bean; - -import fun.asgc.neutrino.core.annotation.*; -import fun.asgc.neutrino.core.context.ApplicationRunner; -import fun.asgc.neutrino.core.context.LifeCycle; -import fun.asgc.neutrino.core.util.ClassUtil; -import fun.asgc.neutrino.core.util.CollectionUtil; -import fun.asgc.neutrino.core.util.LockUtil; -import fun.asgc.neutrino.core.util.ReflectUtil; -import lombok.Data; -import lombok.experimental.Accessors; -import lombok.extern.slf4j.Slf4j; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.HashSet; -import java.util.Set; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -@Slf4j -@Accessors(chain = true) -@Data -public class BeanWrapper implements LifeCycle { - private String name; - private Class type; - private Object instance; - private Component component; - private int order; - private boolean isBoot; - private volatile boolean isInit; - private BeanStatus status; - private boolean isLazy; - private BeanIdentity beanIdentity; - private BeanWrapper factoryBean; - private BeanInstantiationMode instantiationMode; - private Method instantiationMethod; - private boolean isNonIntercept; - private Set innerDeanIdentitySet = new HashSet<>(); - - public boolean hasInstance() { - return null != instance; - } - - @Override - public void init() { - if (BeanStatus.INJECT != status) { - return; - } - this.setStatus(BeanStatus.INIT); - log.debug("Bean[type:{} name:{}]初始化...", getType().getName(), getName()); - isInit = true; - - Set methods = ReflectUtil.getMethods(type); - if (CollectionUtil.notEmpty(methods)) { - for (Method method : methods) { - if (method.isAnnotationPresent(Init.class) && method.getParameters().length == 0) { - try { - method.invoke(instance); - } catch (Exception e) { - log.error(String.format("Bean[type:%s name:%s]初始化方法执行异常 method:%s", type.getName(), name, method.getName()), e); - } - } - } - } - } - - @Override - public void destroy() { - if (BeanStatus.DESTROY == status) { - return; - } - this.setStatus(BeanStatus.DESTROY); - - Set methods = ReflectUtil.getMethods(type); - if (CollectionUtil.notEmpty(methods)) { - for (Method method : methods) { - if (method.isAnnotationPresent(Destroy.class) && method.getParameters().length == 0) { - try { - method.invoke(instance); - } catch (Exception e) { - log.error(String.format("Bean[type:%s name:%s]销毁方法执行异常 method:%s", type.getName(), name, method.getName()), e); - } - } - } - } - } - - public boolean isLazy() { - Lazy lazy = ClassUtil.getAnnotation(type, Lazy.class); - return null != lazy; - } - - private boolean isDependOn(Class target) { - if (null == target) { - return false; - } - Set fieldSet = ReflectUtil.getInheritChainDeclaredFieldSet(type); - if (CollectionUtil.isEmpty(fieldSet)) { - return false; - } - for (Field field : fieldSet) { - Autowired autowired = field.getAnnotation(Autowired.class); - if (null == autowired) { - continue; - } - if (field.getType() == target) { - return true; - } - } - return false; - } - - public void run(String[] args) throws Exception { - if (BeanStatus.INIT != status) { - return; - } - this.setStatus(BeanStatus.RUNNING); - if (this.instance instanceof ApplicationRunner) { - log.debug("Bean[type:{} name:{}]运行...", getType().getName(), getName()); - ((ApplicationRunner)this.instance).run(args); - } - } - - public BeanIdentity getIdentity() { - return LockUtil.doubleCheckProcessForNoException( - () -> null == beanIdentity, - this, - () -> beanIdentity = new BeanIdentity(this.name, this.type), - () -> beanIdentity - ); - } - - public Set getInnerDeanIdentitySet() { - return innerDeanIdentitySet; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/bean/FactoryBean.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/bean/FactoryBean.java deleted file mode 100644 index e11f60c2..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/bean/FactoryBean.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.bean; - -import fun.asgc.neutrino.core.exception.BeanException; - -/** - * 工厂Bean - * @author: aoshiguchen - * @date: 2022/7/4 - */ -public interface FactoryBean { - /** - * 获取bean实例 - * @return - * @throws BeanException - */ - T getInstance() throws BeanException; - - /** - * 获取Bean身份 - * @return - */ - BeanIdentity getBeanIdentity(); -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/bean/factory/AbstractBeanFactory.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/bean/factory/AbstractBeanFactory.java deleted file mode 100644 index 857b5676..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/bean/factory/AbstractBeanFactory.java +++ /dev/null @@ -1,599 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.bean.factory; - -import fun.asgc.neutrino.core.annotation.Subscribe; -import fun.asgc.neutrino.core.base.CustomThreadFactory; -import fun.asgc.neutrino.core.base.event.ApplicationEventReceiver; -import fun.asgc.neutrino.core.base.event.SimpleApplicationEventManager; -import fun.asgc.neutrino.core.bean.*; -import fun.asgc.neutrino.core.context.Environment; -import fun.asgc.neutrino.core.context.LifeCycle; -import fun.asgc.neutrino.core.context.LifeCycleManager; -import fun.asgc.neutrino.core.context.LifeCycleStatus; -import fun.asgc.neutrino.core.exception.BeanException; -import fun.asgc.neutrino.core.util.*; -import lombok.extern.slf4j.Slf4j; - -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -/** - * 抽象的bean工厂 - * @author: aoshiguchen - * @date: 2022/7/1 - */ -@Slf4j -public abstract class AbstractBeanFactory implements BeanFactory, BeanRegistry, LifeCycle { - /** - * 父工厂 - */ - protected AbstractBeanFactory parent; - /** - * bean缓存 - */ - protected Map beanCache; - /** - * 互斥锁 - */ - private Object mutex; - /** - * 名称 - */ - private String name; - /** - * 生命周期管理 - */ - private LifeCycleManager lifeCycleManager = LifeCycleManager.create(); - /** - * 环境参数 - */ - private static volatile Environment environment; - /** - * 调度器 - */ - private static final ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor(new CustomThreadFactory("BeanFactory")); - - public AbstractBeanFactory(String name) { - this(null, name); - } - - public AbstractBeanFactory(AbstractBeanFactory parent, String name) { - Assert.notNull(name, "工厂名称不能为空"); - this.parent = parent; - this.beanCache = new ConcurrentHashMap<>(256); - this.name = name; - if (null == parent) { - this.mutex = new Object(); - } else { - this.mutex = parent.getMutex(); - } - this.registerBean(this, this.name); - } - - @Override - public T getBean(String name, Object... args) throws BeanException { - Assert.notEmpty(name, "Bean名称不能为空!"); - T bean = (null == parent) ? null : parent.getBean(name, args); - return null != bean ? bean : doGetBean(name, args); - } - - - @Override - public T getBeanByName(Class type, String name, Object... args) { - Assert.notEmpty(name, "Bean名称不能为空!"); - T bean = (null == parent) ? null : parent.getBeanByName(type, name, args); - return null != bean ? bean : doGetBeanByName(type, name, args); - } - - @Override - public T getBean(Class type, Object... args) throws BeanException { - Assert.notNull(type, "Bean类型不能为空!"); - T bean = (null == parent) ? null : parent.getBean(type, args); - return null != bean ? bean : doGetBean(type, args); - } - - @Override - public T getBeanByTypeAndName(Class type, String name, Object... args) throws BeanException { - Assert.notEmpty(name, "Bean名称不能为空!"); - Assert.notNull(type, "Bean类型不能为空!"); - T bean = (null == parent) ? null : parent.getBeanByTypeAndName(type, name, args); - return null != bean ? bean : doGetBeanByTypeAndName(type, name, args); - } - - @Override - public T getBean(BeanIdentity identity, Object... args) throws BeanException { - Assert.notNull(identity, "Bean的身份标识不能为空!"); - return (T)getBeanByTypeAndName(identity.getType(), identity.getName(), args); - } - - @Override - public List getBeanList(Class type, Object... args) throws BeanException { - return CollectionUtil.addAll(() -> new LinkedList<>(), - null == parent ? null : parent.getBeanList(type, args), - doGetBeanList(type, args) - ); - } - - @Override - public List getBeanListByName(Class type, String name, Object... args) throws BeanException { - return CollectionUtil.addAll(() -> new LinkedList<>(), - null == parent ? null : parent.getBeanListByName(type, name, args), - doGetBeanListByName(type, name, args) - ); - } - - @Override - public boolean hasBean(Class type, String name) { - boolean res = (null != parent) ? parent.hasBean(type, name) : false; - return res || doHasBean(type, name); - } - - @Override - public boolean hasBean(Class type) { - return hasBean(type, ClassUtil.getBeanName(type)); - } - - @Override - public int countBean(String name) { - int count = (null != parent) ? parent.countBean(name) : 0; - return count + doCountBean(name); - } - - @Override - public int countBean(Class type) { - int count = (null != parent) ? parent.countBean(type) : 0; - return count + doCountBean(type); - } - - @Override - public void registerBean(Object obj) throws BeanException { - Assert.notNull(obj, "被注册的bean实例不能为空!"); - String name = TypeUtil.getDefaultVariableName(obj.getClass()); - registerBean(obj, name); - } - - /** - * 手动new出来的bean注册进来,视为已经初始化了 - * @param obj - * @param name - * @throws BeanException - */ - @Override - public void registerBean(Object obj, String name) throws BeanException { - Assert.notNull(obj, "被注册的bean实例不能为空!"); - Assert.notEmpty(name, "被注册的bean名称不能为空!"); - synchronized (mutex) { - if (hasBean(obj.getClass(), name)) { - throw new BeanException(String.format("Bean[type:%s name:%s] 已存在,不能重复注册!", obj.getClass().getName(), name)); - } - addBean(new BeanWrapper() - .setType(obj.getClass()) - .setName(name) - .setInstance(obj) - .setStatus(BeanStatus.INIT) - ); - } - } - - @Override - public void registerBean(Class type) throws BeanException { - registerBean(type, ClassUtil.getBeanName(type)); - } - - @Override - public void registerBean(Class type, String name) throws BeanException { - synchronized (mutex) { - if (hasBean(type, name)) { - throw new BeanException(String.format("Bean[type:%s name:%s] 已存在,不能重复注册!", type.getName(), name)); - } - addBean(type, name); - } - } - - private T doGetBean(String name, Object... args) throws BeanException { - List beanList = findBeanList(name); - if (CollectionUtil.isEmpty(beanList)) { - return null; - } else if (beanList.size() > 1) { - throw new BeanException(String.format("Bean[name:%s] 存在多个实例!", name)); - } - return getOrNew(beanList.get(0), args); - } - - private T doGetBeanByName(Class type, String name, Object... args) throws BeanException { - List beanList = findBeanList(type, name); - if (CollectionUtil.isEmpty(beanList)) { - return null; - } else if (beanList.size() > 1) { - throw new BeanException(String.format("Bean[name:%s] 存在多个实例!", name)); - } - return getOrNew(beanList.get(0), args); - } - - private T doGetBean(Class type, Object... args) throws BeanException { - List beanList = findBeanList(type); - if (CollectionUtil.isEmpty(beanList)) { - return null; - } else if (beanList.size() > 1) { - throw new BeanException(String.format("Bean[type:%s] 存在多个实例!", type)); - } - return getOrNew(beanList.get(0), args); - } - - private T doGetBeanByTypeAndName(Class type, String name, Object... args) throws BeanException { - BeanWrapper bean = findBean(type, name); - if (null == bean) { - return null; - } - if (null == bean) { - return null; - } - return getOrNew(bean, args); - } - - private List doGetBeanList(Class type, Object... args) throws BeanException { - List beanList = findBeanList(type); - if (CollectionUtil.isEmpty(beanList)) { - return null; - } - return getOrNew(beanList, args); - } - - private List doGetBeanListByName(Class type, String name, Object... args) throws BeanException { - List beanList = findBeanList(type, name); - if (CollectionUtil.isEmpty(beanList)) { - return null; - } - return getOrNew(beanList, args); - } - - private boolean doHasBean(Class type, String name) { - return beanCache.containsKey(new BeanIdentity(name, type)); - } - - private int doCountBean(String name) { - return beanCache.keySet().stream().filter(e -> e.getName().equals(name)).collect(Collectors.counting()).intValue(); - } - - private int doCountBean(Class type) { - return beanCache.keySet().stream().filter(e -> type.isAssignableFrom(e.getType())).collect(Collectors.counting()).intValue(); - } - - public Object getMutex() { - return mutex; - } - - /** - * 查找bean - * @param name - * @return - */ - private List findBeanList(String name) { - Assert.notNull(name, "bean的名称不能为空!"); - List beanList = new LinkedList<>(); - for (BeanIdentity identity : beanCache.keySet()) { - if (identity.getName().equals(name)) { - beanList.add(beanCache.get(identity)); - } - } - return beanList; - } - - /** - * 查找bean - * @param type - * @return - */ - private List findBeanList(Class type) { - Assert.notNull(type, "bean的类型不能为空!"); - List beanList = new LinkedList<>(); - for (BeanIdentity identity : beanCache.keySet()) { - if (type.isAssignableFrom(identity.getType())) { - beanList.add(beanCache.get(identity)); - } - } - return beanList; - } - - /** - * 查找bean - * @param type - * @return - */ - private List findBeanList(Class type, String name) { - Assert.notNull(type, "bean的类型不能为空!"); - List beanList = new LinkedList<>(); - for (BeanIdentity identity : beanCache.keySet()) { - if (type.isAssignableFrom(identity.getType()) && identity.getName().equals(name)) { - beanList.add(beanCache.get(identity)); - } - } - return beanList; - } - - /** - * 查找bean - * @param type - * @param name - * @return - */ - protected BeanWrapper findBean(Class type, String name) { - Assert.notNull(type, "bean的类型不能为空!"); - Assert.notNull(name, "bean的名称不能为空!"); - return beanCache.get(new BeanIdentity(name, type)); - } - - /** - * 新增一个bean - * @param bean - */ - protected void addBean(BeanWrapper bean) throws BeanException { - beanCache.put(new BeanIdentity(bean.getName(), bean.getType()), bean); - if (FactoryBean.class.isAssignableFrom(bean.getType())) { - dependencyCheck(bean); - newInstance(bean); - // 工厂bean - BeanIdentity identity = ((FactoryBean)bean.getInstance()).getBeanIdentity(); - if (beanCache.containsKey(identity)) { - throw new BeanException(String.format("Bean[type:%s name:%s] 定义与BeanFactory[type:%s name:%s]冲突!", identity.getType().getName(), identity.getName(), bean.getType().getName(), bean.getName())); - } - BeanWrapper targetBeanWrapper = addBean(identity.getType(), identity.getName()); - targetBeanWrapper.setFactoryBean(bean); - targetBeanWrapper.setInstantiationMode(BeanInstantiationMode.FACTORY); - } - } - - @Override - public void init() { - lifeCycleManager.init(() -> { - if (null != parent) { - parent.init(); - } - if (CollectionUtil.notEmpty(beanCache)) { - beanCache.values().stream().forEach(bean -> { - SimpleApplicationEventManager defaultApplicationEventManager = getEnvironment().getDefaultApplicationEventManager(); - if (null != defaultApplicationEventManager && ApplicationEventReceiver.class.isAssignableFrom(bean.getType())) { - boolean enable = true; - String topic = null; - Set tags = null; - Subscribe subscribe = bean.getType().getAnnotation(Subscribe.class); - if (null != subscribe) { - enable = subscribe.enable(); - topic = subscribe.topic(); - if (ArrayUtil.notEmpty(subscribe.tags())) { - tags = Stream.of(subscribe.tags()).collect(Collectors.toSet()); - } - } - if (enable) { - ApplicationEventReceiver receiver = (ApplicationEventReceiver) bean.getInstance(); - receiver.setTopic(topic); - receiver.setTags(tags); - defaultApplicationEventManager.registerReceiver(receiver); - } - } - - if (BeanStatus.INJECT == bean.getStatus()) { - bean.init(); - } - }); - } - log.info("bean工厂[{}]初始化.", getName()); - scheduledExecutor.scheduleWithFixedDelay(this::run, 0, 1, TimeUnit.SECONDS); - }); - } - - @Override - public void destroy() { - lifeCycleManager.destroy(() -> { - if (null != parent) { - parent.destroy(); - } - if (CollectionUtil.notEmpty(beanCache)) { - beanCache.values().stream().filter(b -> BeanStatus.DESTROY != b.getStatus()).forEach(bean -> bean.destroy()); - } - log.info("bean工厂[{}]销毁.", getName()); - }); - } - - /** - * 获取或创建实例 - * @param beanList - * @param - * @return - * @throws BeanException - */ - protected List getOrNew(List beanList, Object... args) throws BeanException { - if (CollectionUtil.isEmpty(beanList)) { - return null; - } - dependencyCheck(beanList); - newInstance(beanList, args); - inject(beanList); - beanList.forEach(beanWrapper -> beanWrapper.init()); - - for (BeanWrapper beanWrapper : beanList) { - if (beanWrapper.getStatus().getStatus() < BeanStatus.INIT.getStatus()) { - throw new BeanException(String.format("Bean[type:%s name:%s]实例化失败!", beanWrapper.getType().getName(), beanWrapper.getName())); - } - } - - return beanList.stream().filter(beanWrapper -> BeanStatus.DESTROY != beanWrapper.getStatus()).map(beanWrapper -> (T)beanWrapper.getInstance()).collect(Collectors.toList()); - } - - /** - * 获取名称 - * @return - */ - public String getName() { - return name; - } - - /** - * 获取生命周期状态 - * @return - */ - public LifeCycleStatus getLifeCycleStatus() { - return lifeCycleManager.getStatus(); - } - - /** - * 获取生命周期管理对象 - * @return - */ - public LifeCycleManager getLifeCycleManager() { - return lifeCycleManager; - } - - /** - * 新增一个bean - * @param type - * @param name - */ - protected abstract BeanWrapper addBean(Class type, String name); - - /** - * 获取或创建实例 - * @param bean - * @param - * @return - */ - protected T getOrNew(BeanWrapper bean, Object... args) throws BeanException { - try { - return (T)LockUtil.doubleCheckProcess( - () -> !(BeanStatus.INIT == bean.getStatus() || BeanStatus.RUNNING == bean.getStatus()), - bean, - () -> { - if (BeanStatus.REGISTER == bean.getStatus()) { - dependencyCheck(bean); - } - if (BeanStatus.DEPENDENCY_CHECKING == bean.getStatus()) { - newInstance(bean); - } - if (BeanStatus.INSTANCE == bean.getStatus()) { - inject(bean); - } - if (BeanStatus.INJECT == bean.getStatus()) { - bean.init(); - } - }, - () -> bean.getInstance() - ); - } catch (Exception e) { - throw new BeanException(String.format("Bean[type:%s name:%s] getOrNew bean实例异常!", bean.getType().getName(), bean.getName()), e); - } - } - - /** - * 依赖关系检测 - * @param beanList - * @return - * @throws BeanException - */ - protected void dependencyCheck(List beanList) throws BeanException { - for (BeanWrapper beanWrapper : beanList) { - dependencyCheck(beanWrapper); - } - } - - /** - * 实例化 - * @param beanList - * @return - * @throws BeanException - */ - protected void newInstance(List beanList, Object... args) throws BeanException { - for (BeanWrapper beanWrapper : beanList) { - newInstance(beanWrapper, args); - } - } - - /** - * 注入 - * @param beanList - * @return - * @throws BeanException - */ - protected void inject(List beanList) throws BeanException { - for (BeanWrapper beanWrapper : beanList) { - inject(beanWrapper); - } - } - - /** - * 依赖关系检测 - * @param bean - * @return - * @throws BeanException - */ - protected abstract void dependencyCheck(BeanWrapper bean) throws BeanException; - - /** - * 实例化 - * @param bean - * @param - * @return - * @throws BeanException - */ - protected abstract T newInstance(BeanWrapper bean, Object... args) throws BeanException; - - /** - * 注入 - * @param bean - * @return - * @throws BeanException - */ - protected abstract void inject(BeanWrapper bean) throws BeanException; - - /** - * 运行 - */ - private void run() { - beanCache.values().stream().filter(b -> b.getStatus().getStatus() < BeanStatus.RUNNING.getStatus()) - .sorted(Comparator.comparing(BeanWrapper::getOrder)).forEach(b -> { - try { - getOrNew(b); - b.run(getEnvironment().getMainArgs()); - } catch (Exception e) { - e.printStackTrace(); - } - }); - } - - /** - * 获取环境参数 - * @return - */ - private Environment getEnvironment() { - return LockUtil.doubleCheckProcessForNoException( - () -> null == environment, - this, - () -> environment = getBean(Environment.class), - () -> environment - ); - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/bean/factory/BeanFactory.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/bean/factory/BeanFactory.java deleted file mode 100644 index d4ffceeb..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/bean/factory/BeanFactory.java +++ /dev/null @@ -1,106 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.bean.factory; - -import fun.asgc.neutrino.core.bean.BeanIdentity; -import fun.asgc.neutrino.core.exception.BeanException; - -import java.util.List; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/1 - */ -public interface BeanFactory { - - /** - * 尝试根据名称获取bean - * @param name - * @param args - * @return - * @throws BeanException - */ - T getBean(String name, Object... args) throws BeanException; - - /** - * 尝试根据名称获取bean,此处的type不做强制限定,可以是bean的接口或超类型 - * @param type - * @param name - * @param args - * @param - * @return - */ - T getBeanByName(Class type, String name, Object... args); - - /** - * 尝试根据类型获取bean - * @param type - * @param args - * @param - * @return - * @throws BeanException - */ - T getBean(Class type, Object... args) throws BeanException; - - /** - * 尝试根据Bean身份标识获取bean - * @param identity - * @param args - * @param - * @return - * @throws BeanException - */ - T getBean(BeanIdentity identity, Object... args) throws BeanException; - - /** - * 根据类型+名称获取bean - * @param type - * @param name - * @param args - * @param - * @return - * @throws BeanException - */ - T getBeanByTypeAndName(Class type, String name, Object... args) throws BeanException; - - /** - * 尝试根据类型获取bean - * @param type - * @param args - * @param - * @return - * @throws BeanException - */ - List getBeanList(Class type, Object... args) throws BeanException; - - /** - * 尝试根据名称获取bean,此处的type不做强制限定,可以是bean的接口或超类型 - * @param type - * @param name - * @param args - * @param - * @return - * @throws BeanException - */ - List getBeanListByName(Class type, String name, Object... args) throws BeanException; -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/bean/factory/BeanFactoryAware.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/bean/factory/BeanFactoryAware.java deleted file mode 100644 index 032461be..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/bean/factory/BeanFactoryAware.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.bean.factory; - -/** - * 用于标识需要beanFactory的组件 - * @author: aoshiguchen - * @date: 2022/7/6 - */ -public interface BeanFactoryAware { - - /** - * 设置bean工厂 - * @param beanFactory - */ - void setBeanFactory(BeanFactory beanFactory); -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/bean/factory/SimpleBeanFactory.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/bean/factory/SimpleBeanFactory.java deleted file mode 100644 index 8d241285..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/bean/factory/SimpleBeanFactory.java +++ /dev/null @@ -1,419 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.bean.factory; - -import com.google.common.collect.Lists; -import fun.asgc.neutrino.core.annotation.*; -import fun.asgc.neutrino.core.aop.Aop; -import fun.asgc.neutrino.core.aop.interceptor.ExceptionHandler; -import fun.asgc.neutrino.core.aop.interceptor.Filter; -import fun.asgc.neutrino.core.aop.interceptor.Interceptor; -import fun.asgc.neutrino.core.aop.interceptor.ResultAdvice; -import fun.asgc.neutrino.core.base.event.ApplicationEventReceiver; -import fun.asgc.neutrino.core.bean.*; -import fun.asgc.neutrino.core.exception.BeanException; -import fun.asgc.neutrino.core.context.ApplicationRunner; -import fun.asgc.neutrino.core.util.*; -import lombok.extern.slf4j.Slf4j; - -import javax.annotation.processing.Filer; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - -/** - * - * @author: 一个简单的bean工厂实现 - * @date: 2022/7/2 - */ -@Slf4j -public class SimpleBeanFactory extends AbstractBeanFactory { - - /** - * 类集合 - */ - private Set> classes = new HashSet<>(); - - public SimpleBeanFactory(String name) { - super(name); - } - - public SimpleBeanFactory(AbstractBeanFactory parent, String name) { - super(parent, name); - } - - @Override - protected BeanWrapper addBean(Class type, String name) { - log.debug("addBean[type:{} name:{}]", type.getName(), name); - BeanWrapper beanWrapper = new BeanWrapper() - .setType(type) - .setName(name) - .setLazy(Boolean.FALSE) - .setOrder(Integer.MAX_VALUE) - .setStatus(BeanStatus.REGISTER) - .setInstantiationMode(BeanInstantiationMode.DIRECT) - .setNonIntercept(false); - Lazy lazy = ClassUtil.getAnnotation(type, Lazy.class); - if (null != lazy) { - beanWrapper.setLazy(lazy.value()); - } - Order order = ClassUtil.getAnnotation(type, Order.class); - if (null != order) { - beanWrapper.setOrder(order.value()); - } - // 默认不拦截 - if (ApplicationRunner.class.isAssignableFrom(type) || - type.isAnnotationPresent(Configuration.class) || - Interceptor.class.isAssignableFrom(type) || - Filer.class.isAssignableFrom(type) || - ExceptionHandler.class.isAssignableFrom(type) || - ResultAdvice.class.isAssignableFrom(type) || - BeanFactoryAware.class.isAssignableFrom(type) - ) { - beanWrapper.setNonIntercept(true); - } - NonIntercept nonIntercept = ClassUtil.getAnnotation(type, NonIntercept.class); - if (null != nonIntercept) { - beanWrapper.setNonIntercept(nonIntercept.value()); - } - - addBean(beanWrapper); - registerBeanForMethod(beanWrapper, type); - return beanWrapper; - } - - /** - * 根据method注册bean - * @param factoryBean - * @param type - */ - private void registerBeanForMethod(BeanWrapper factoryBean, Class type) { - Set methods = ReflectUtil.getMethods(type); - if (CollectionUtil.isEmpty(methods)) { - return; - } - for (Method method : methods) { - Bean bean = method.getAnnotation(Bean.class); - if (null == bean) { - continue; - } - String beanName = bean.value(); - if (StringUtil.isEmpty(beanName)) { - beanName = method.getName(); - } - Class beanType = method.getReturnType(); - if (method.getParameters().length > 0) { - if (!(method.getParameters().length == 1 && method.getParameters()[0].isAnnotationPresent(Autowired.class))) { - throw new BeanException(String.format("Bean[type:%s name:%s] 注册失败,Class:%s method:%s 方法仅支持最多带一个参数,且参数必须带`Autowired`注解!", beanType.getName(), beanName, type.getName(), method.getName())); - } - } - BeanWrapper beanWrapper = addBean(beanType, beanName); - beanWrapper.setFactoryBean(factoryBean); - beanWrapper.setInstantiationMode(BeanInstantiationMode.METHOD); - beanWrapper.setInstantiationMethod(method); - beanWrapper.setNonIntercept(false); - - Lazy lazy = method.getAnnotation(Lazy.class); - if (null != lazy) { - beanWrapper.setLazy(lazy.value()); - } - Order order = method.getAnnotation(Order.class); - if (null != order) { - beanWrapper.setOrder(order.value()); - } - } - } - - @Override - protected void dependencyCheck(BeanWrapper bean) throws BeanException { - try { - LockUtil.doubleCheckProcess( - () -> BeanStatus.REGISTER == bean.getStatus(), - bean, - () -> { - // TODO - bean.setStatus(BeanStatus.DEPENDENCY_CHECKING); - } - ); - } catch (Exception e) { - throw new BeanException(String.format("Bean[type:%s name:%s] 依赖检测异常!", bean.getType().getName(), bean.getName())); - } - } - - @Override - protected T newInstance(BeanWrapper bean, Object... args) throws BeanException { - try { - return LockUtil.doubleCheckProcess( - () -> BeanStatus.DEPENDENCY_CHECKING == bean.getStatus(), - bean, - () -> { - if (BeanInstantiationMode.DIRECT == bean.getInstantiationMode()) { - // 直接实例化 - if (ClassUtil.isInterface(bean.getType())) { - Class implementationType = findOneImplementationAndReturn(bean.getType()); - // 如果是一个接口,且有唯一实现类,则采用该实现类的实例作为bean。否则直接代理该接口 - if (null == implementationType) { - bean.setInstance(Aop.get(bean.getType())); - } else { - if (ClassUtil.hasNoArgsConstructor(implementationType)) { - if (bean.isNonIntercept()) { - bean.setInstance(implementationType.newInstance()); - } else { - bean.setInstance(Aop.get(implementationType, bean.getType())); - } - } else { - // TODO 暂不支持有参构造器 - throw new BeanException(String.format("Bean[type:%s name:%s] 没有无参构造器,实例化失败!", bean.getType().getName(), bean.getName())); - } - } - } else if(bean.getType().isAnnotationPresent(Configuration.class)) { - if (CollectionUtil.isEmpty(ReflectUtil.getDeclaredFields(bean.getType()))) { - if (bean.isNonIntercept()) { - bean.setInstance(bean.getType().newInstance()); - } else { - bean.setInstance(Aop.get(bean.getType())); - } - } else { - bean.setInstance(ConfigUtil.getYmlConfig(bean.getType())); - } - } else { - if (ClassUtil.hasNoArgsConstructor(bean.getType())) { - if (bean.isNonIntercept()) { - bean.setInstance(bean.getType().newInstance()); - } else { - bean.setInstance(Aop.get(bean.getType())); - } - } else { - // TODO 暂不支持有参构造器 - throw new BeanException(String.format("Bean[type:%s name:%s] 没有无参构造器,实例化失败!", bean.getType().getName(), bean.getName())); - } - } - } else if (BeanInstantiationMode.METHOD == bean.getInstantiationMode()) { - // 通过bean方法实例化 - BeanWrapper factoryBean = bean.getFactoryBean(); - factoryBean.getInnerDeanIdentitySet().add(bean.getIdentity()); - if (!factoryBean.hasInstance()) { - newInstance(factoryBean); - } - // 工厂bean,实例化方法执行前,工厂bean需要完成注入。但此时如果存在循环引用,这个注入只能完成一部分。实例化完成后,继续注入 - if (factoryBean.getStatus() == BeanStatus.INSTANCE) { - inject(factoryBean); - } - if (bean.getInstantiationMethod().getParameters().length == 0) { - bean.setInstance(bean.getInstantiationMethod().invoke(factoryBean.getInstance())); - // 实例化完成后继续注入 - if (null != bean.getInstance()) { - bean.setStatus(BeanStatus.INSTANCE); - } - inject(factoryBean); - } else { - // 暂时只处理一个参数的情况 - Autowired autowired = bean.getInstantiationMethod().getParameters()[0].getAnnotation(Autowired.class); - String beanName = autowired.value(); - Class beanType = bean.getInstantiationMethod().getParameters()[0].getType(); - Object arg = null; - if (BeanMatchMode.ByName == autowired.matchMode()) { - arg = getBean(beanName); - } else if(BeanMatchMode.ByType == autowired.matchMode()) { - arg = getBean(beanType); - } else { - arg = getBeanByTypeAndName(beanType, beanName); - } - bean.setInstance(bean.getInstantiationMethod().invoke(factoryBean.getInstance(), arg)); - // 实例化完成后继续注入 - if (null != bean.getInstance()) { - bean.setStatus(BeanStatus.INSTANCE); - } - inject(factoryBean); - } - - } else if (BeanInstantiationMode.FACTORY == bean.getInstantiationMode()) { - // 通过FactoryBean实例化 - BeanWrapper factoryBean = bean.getFactoryBean(); - if (!factoryBean.hasInstance()) { - newInstance(factoryBean); - } - bean.setInstance(((FactoryBean)factoryBean.getInstance()).getInstance()); - } - - if (null != bean.getInstance()) { - bean.setStatus(BeanStatus.INSTANCE); - } - }, - () -> (T)bean.getInstance() - ); - } catch (BeanException e) { - throw e; - }catch (Exception e) { - throw new BeanException(String.format("Bean[type:%s name:%s] 实例化异常", bean.getType().getName(), bean.getName()), e); - } - } - - @Override - protected void inject(BeanWrapper bean) throws BeanException { - try { - LockUtil.doubleCheckProcess( - () -> BeanStatus.INSTANCE == bean.getStatus(), - bean, - () -> { - Set fieldSet = ReflectUtil.getInheritChainDeclaredFieldSet(bean.getType()); - if (CollectionUtil.isEmpty(fieldSet)) { - bean.setStatus(BeanStatus.INJECT); - return; - } - boolean flag = true; - for (Field field : fieldSet) { - Autowired autowired = field.getAnnotation(Autowired.class); - if (null == autowired) { - continue; - } - // 已完成注入,无需重复注入 - field.setAccessible(true); - Object oldObj = field.get(bean.getInstance()); - if (null != oldObj) { - continue; - } - - String beanName = autowired.value(); - if (StringUtil.isEmpty(beanName)) { - beanName = field.getName(); - } - Class parameterType = autowired.parameterTypes().length == 0 ? Object.class : autowired.parameterTypes()[0]; - - // 临时解决自引用导致堆栈溢出的问题 - BeanIdentity innerBeanIdentity = new BeanIdentity(beanName, field.getType()); - if (bean.getInnerDeanIdentitySet().contains(innerBeanIdentity)) { - BeanWrapper beanWrapper = findBean(field.getType(), beanName); - if (null == beanWrapper || !beanWrapper.hasInstance()) { - flag = false; - continue; - } - } - - BeanMatchMode matchMode = autowired.matchMode(); - Object obj = null; - if (matchMode == BeanMatchMode.ByType) { - if (TypeUtil.isListable(field.getType())) { - List list = getBeanList(parameterType); - obj = TypeUtil.listTo(list, field.getType()); - } else { - obj = getBean(field.getType()); - } - } else if(matchMode == BeanMatchMode.ByName) { - if (TypeUtil.isListable(field.getType())) { - List list = getBeanListByName(parameterType, beanName); - obj = TypeUtil.listTo(list, field.getType()); - } else { - obj = getBeanByName(field.getType(), beanName); - } - } else if (matchMode == BeanMatchMode.ByTypeName) { - obj = getBeanByTypeAndName(field.getType(), beanName); - if (TypeUtil.isListable(field.getType())) { - obj = TypeUtil.listTo(Lists.newArrayList(obj), field.getType()); - } - } - if (null == obj) { - throw new BeanException(String.format("Bean[type:%s name:%s field:%s] 注入异常", bean.getType().getName(), bean.getName(), field.getName())); - } - - ReflectUtil.setFieldValue(field, bean.getInstance(), obj); - } - if (flag) { - bean.setStatus(BeanStatus.INJECT); - } - } - ); - } catch (BeanException e){ - throw e; - }catch (Exception e) { - throw new BeanException(String.format("Bean[type:%s name:%s] 注入异常", bean.getType().getName(), bean.getName()), e); - } - } - - @Override - public void init() { - List beanWrapperList = beanCache.values().stream() - .filter(b -> b.getStatus().getStatus() < BeanStatus.INIT.getStatus()) - .filter(b -> ApplicationRunner.class.isAssignableFrom(b.getType()) || !b.isLazy() || b.getOrder() <= 0) - .collect(Collectors.toList()); - if (CollectionUtil.notEmpty(beanWrapperList)) { - getOrNew(beanWrapperList); - } - super.init(); - } - - public void register(Set> classes) { - if (CollectionUtil.isEmpty(classes)) { - return; - } - this.classes.addAll(classes); - classes.stream() - .filter(item -> ClassUtil.isAnnotateWith(item, Component.class) - || Interceptor.class.isAssignableFrom(item) - || Filter.class.isAssignableFrom(item) - || ExceptionHandler.class.isAssignableFrom(item) - || ResultAdvice.class.isAssignableFrom(item) - || ApplicationEventReceiver.class.isAssignableFrom(item) - ) - .forEach(clazz -> { - String beanName = TypeUtil.getDefaultVariableName(clazz); - Component component = ClassUtil.getAnnotation(clazz, Component.class); - if (null != component && StringUtil.notEmpty(component.value())) { - beanName = component.value(); - } - registerBean(clazz, beanName); - }); - } - - /** - * 查找指定接口的唯一实现类,若存在一个则返回 - * @param clazz - * @return - */ - private Class findOneImplementationAndReturn(Class clazz) { - if (!ClassUtil.isInterface(clazz) || CollectionUtil.isEmpty(this.classes)) { - return null; - } - Set> cls = classes.stream().filter(c -> clazz.isAssignableFrom(c) - && !ClassUtil.isInterface(c) && !ClassUtil.isAbstract(c) && !ClassUtil.isStatic(c) && ClassUtil.isPublic(c) - ).collect(Collectors.toSet()); - if (cls.size() == 1) { - return cls.iterator().next(); - } - return null; - } - - /** - * BeanWrapper集合 - * @return - */ - public List beanWrapperList() { - return FunctionUtil.mergeList( - () -> null == parent ? null : - parent instanceof SimpleBeanFactory ? ((SimpleBeanFactory)parent).beanWrapperList() : null, - () -> beanCache.values().stream().collect(Collectors.toList()) - ); - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/cache/Cache.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/cache/Cache.java deleted file mode 100644 index 6383d543..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/cache/Cache.java +++ /dev/null @@ -1,97 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.cache; - -import java.util.Collection; -import java.util.Set; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -public interface Cache { - - /** - * 设置缓存 - * @param k - * @param v - */ - void set(K k, V v); - - /** - * 获取缓存 - * @param k - * @return - */ - V get(K k); - - /** - * 判断缓存是否存在 - * @param k - * @return - */ - boolean containsKey(K k); - - /** - * 判断缓存值是否存在 - * @param v - * @return - */ - boolean containsValue(V v); - - /** - * key集合 - * @return - */ - Set keySet(); - - /** - * 值集合 - * @return - */ - Collection values(); - - /** - * 是否为空 - * @return - */ - boolean isEmpty(); - - /** - * 清空缓存 - */ - void clear(); - - /** - * 缓存大小 - * @return - */ - int size(); - - /** - * 如果有且只有一个缓存,则返回该缓存值,否则返回空 - * @return - */ - V isOnePeek(); -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/cache/CacheGroup.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/cache/CacheGroup.java deleted file mode 100644 index 1cdbb22c..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/cache/CacheGroup.java +++ /dev/null @@ -1,84 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.cache; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -public interface CacheGroup { - - /** - * 获取缓存 - * @param group - * @return - */ - Cache getCache(String group); - - /** - * 设置缓存 - * @param group - * @param cache - */ - void setCache(String group, Cache cache); - - /** - * 判断缓存是否存在 - * @param group - * @return - */ - boolean containsCache(String group); - - /** - * 设置缓存值 - * @param group - * @param k - * @param v - */ - void set(String group, K k, V v); - - /** - * 获取缓存值 - * @param group - * @param k - * @return - */ - V get(String group, K k); - - /** - * 判断缓存值是否存在 - * @param group - * @param k - * @return - */ - boolean containsKey(String group, K k); - - /** - * 是否为空 - * @param group - * @return - */ - boolean isEmpty(String group); - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/cache/LocalCache.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/cache/LocalCache.java deleted file mode 100644 index 0f951888..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/cache/LocalCache.java +++ /dev/null @@ -1,274 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.cache; - - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.alibaba.fastjson.TypeReference; -import com.alibaba.fastjson.parser.ParserConfig; -import com.alibaba.fastjson.util.TypeUtils; -import fun.asgc.neutrino.core.util.FileUtil; -import org.apache.commons.lang3.StringUtils; - -import java.lang.reflect.Type; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.sql.Timestamp; -import java.util.*; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -public class LocalCache implements Cache, Preservable { - - private JSONObject cache; - private String path; - - public LocalCache(String path) { - this.cache = new JSONObject(); - this.path = path; - FileUtil.makeDirs(path); - this.load(); - } - - @Override - public void set(String k, Object v) { - cache.put(k, v); - this.save(); - } - - @Override - public Object get(String k) { - return cache.getJSONObject(k); - } - - @Override - public boolean containsKey(String k) { - return cache.containsKey(k); - } - - @Override - public boolean containsValue(Object v) { - return cache.containsValue(v); - } - - @Override - public Set keySet() { - return cache.keySet(); - } - - @Override - public boolean isEmpty() { - return cache.isEmpty(); - } - - @Override - public void clear() { - cache.clear(); - save(); - } - - @Override - public int size() { - return cache.size(); - } - - @Override - public Object isOnePeek() { - if (size() != 1) { - return null; - } - return cache.values().stream().findFirst().get(); - } - - @Override - public Collection values() { - return cache.values(); - } - - @Override - public synchronized void save() { - FileUtil.write(path, JSONObject.toJSONString(cache)); - } - - @Override - public synchronized void load() { - String content = FileUtil.readContentAsString(path); - if (StringUtils.isNotEmpty(content)) { - cache = JSONObject.parseObject(content); - } - } - - public JSONObject getJSONObject(String key) { - Object value = this.cache.get(key); - if (value instanceof JSONObject) { - return (JSONObject)value; - } else if (value instanceof Map) { - return new JSONObject((Map)value); - } else { - return value instanceof String ? JSON.parseObject((String)value) : (JSONObject)JSON.toJSON(value); - } - } - - public JSONArray getJSONArray(String key) { - Object value = this.cache.get(key); - if (value instanceof JSONArray) { - return (JSONArray)value; - } else if (value instanceof List) { - return new JSONArray((List)value); - } else { - return value instanceof String ? (JSONArray)JSON.parse((String)value) : (JSONArray)JSON.toJSON(value); - } - } - - public T getObject(String key, Class clazz) { - Object obj = this.cache.get(key); - return TypeUtils.castToJavaBean(obj, clazz); - } - - public T getObject(String key, Type type) { - Object obj = this.cache.get(key); - return TypeUtils.cast(obj, type, ParserConfig.getGlobalInstance()); - } - - public T getObject(String key, TypeReference typeReference) { - Object obj = this.cache.get(key); - return typeReference == null ? (T)obj : TypeUtils.cast(obj, typeReference.getType(), ParserConfig.getGlobalInstance()); - } - - public Boolean getBoolean(String key) { - Object value = this.get(key); - return value == null ? null : TypeUtils.castToBoolean(value); - } - - public byte[] getBytes(String key) { - Object value = this.get(key); - return value == null ? null : TypeUtils.castToBytes(value); - } - - public boolean getBooleanValue(String key) { - Object value = this.get(key); - Boolean booleanVal = TypeUtils.castToBoolean(value); - return booleanVal == null ? false : booleanVal; - } - - public Byte getByte(String key) { - Object value = this.get(key); - return TypeUtils.castToByte(value); - } - - public byte getByteValue(String key) { - Object value = this.get(key); - Byte byteVal = TypeUtils.castToByte(value); - return byteVal == null ? 0 : byteVal; - } - - public Short getShort(String key) { - Object value = this.get(key); - return TypeUtils.castToShort(value); - } - - public short getShortValue(String key) { - Object value = this.get(key); - Short shortVal = TypeUtils.castToShort(value); - return shortVal == null ? 0 : shortVal; - } - - public Integer getInteger(String key) { - Object value = this.get(key); - return TypeUtils.castToInt(value); - } - - public int getIntValue(String key) { - Object value = this.get(key); - Integer intVal = TypeUtils.castToInt(value); - return intVal == null ? 0 : intVal; - } - - public Long getLong(String key) { - Object value = this.get(key); - return TypeUtils.castToLong(value); - } - - public long getLongValue(String key) { - Object value = this.get(key); - Long longVal = TypeUtils.castToLong(value); - return longVal == null ? 0L : longVal; - } - - public Float getFloat(String key) { - Object value = this.get(key); - return TypeUtils.castToFloat(value); - } - - public float getFloatValue(String key) { - Object value = this.get(key); - Float floatValue = TypeUtils.castToFloat(value); - return floatValue == null ? 0.0F : floatValue; - } - - public Double getDouble(String key) { - Object value = this.get(key); - return TypeUtils.castToDouble(value); - } - - public double getDoubleValue(String key) { - Object value = this.get(key); - Double doubleValue = TypeUtils.castToDouble(value); - return doubleValue == null ? 0.0D : doubleValue; - } - - public BigDecimal getBigDecimal(String key) { - Object value = this.get(key); - return TypeUtils.castToBigDecimal(value); - } - - public BigInteger getBigInteger(String key) { - Object value = this.get(key); - return TypeUtils.castToBigInteger(value); - } - - public String getString(String key) { - Object value = this.get(key); - return value == null ? null : value.toString(); - } - - public Date getDate(String key) { - Object value = this.get(key); - return TypeUtils.castToDate(value); - } - - public java.sql.Date getSqlDate(String key) { - Object value = this.get(key); - return (java.sql.Date) TypeUtils.castToSqlDate(value); - } - - public Timestamp getTimestamp(String key) { - Object value = this.get(key); - return (Timestamp) TypeUtils.castToTimestamp(value); - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/cache/MemoryCache.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/cache/MemoryCache.java deleted file mode 100644 index 593a8901..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/cache/MemoryCache.java +++ /dev/null @@ -1,88 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.cache; - -import java.util.*; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -public class MemoryCache implements Cache { - - private Map cache = Collections.synchronizedMap(new HashMap<>()); - - @Override - public void set(K k, V v) { - cache.put(k, v); - } - - @Override - public V get(K k) {IdentityHashMap a = new IdentityHashMap(); - return (V)cache.get(k); - } - - @Override - public boolean containsKey(K k) { - return cache.containsKey(k); - } - - @Override - public boolean containsValue(V v) { - return cache.containsValue(v); - } - - @Override - public Set keySet() { - return cache.keySet(); - } - - @Override - public Collection values() { - return cache.values(); - } - - @Override - public boolean isEmpty() { - return cache.isEmpty(); - } - - @Override - public void clear() { - cache.clear(); - } - - @Override - public int size() { - return cache.size(); - } - - @Override - public V isOnePeek() { - if (size() != 1) { - return null; - } - return cache.values().stream().findFirst().get(); - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/cache/MemoryCacheGroup.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/cache/MemoryCacheGroup.java deleted file mode 100644 index 088742eb..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/cache/MemoryCacheGroup.java +++ /dev/null @@ -1,81 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.cache; - -import fun.asgc.neutrino.core.util.LockUtil; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -public class MemoryCacheGroup implements CacheGroup { - - /** - * 缓存 - */ - private final Cache> cacheGroup = new MemoryCache<>(); - - @Override - public Cache getCache(String group) { - return cacheGroup.get(group); - } - - @Override - public void setCache(String group, Cache cache) { - cacheGroup.set(group, cache); - } - - @Override - public boolean containsCache(String group) { - return cacheGroup.containsKey(group); - } - - @Override - public void set(String group, K k, V v) { - try { - LockUtil.doubleCheckProcess(() -> !cacheGroup.containsKey(group), - group, - () -> cacheGroup.set(group, new MemoryCache<>()) - ); - cacheGroup.get(group).set(k, v); - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Override - public V get(String group, K k) { - return (cacheGroup.containsKey(group) && cacheGroup.get(group).containsKey(k)) ? cacheGroup.get(group).get(k) : null; - } - - @Override - public boolean containsKey(String group, K k) { - return cacheGroup.containsKey(group) && cacheGroup.get(group).containsKey(k); - } - - @Override - public boolean isEmpty(String group) { - return !cacheGroup.containsKey(group) || cacheGroup.get(group).isEmpty(); - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/cache/Preservable.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/cache/Preservable.java deleted file mode 100644 index 42dcf8b2..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/cache/Preservable.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.cache; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -public interface Preservable { - - /** - * 保存到磁盘 - */ - void save(); - - /** - * 从磁盘加载 - */ - void load(); - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/config/AbstractConfigurationParser.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/config/AbstractConfigurationParser.java deleted file mode 100644 index e04de74e..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/config/AbstractConfigurationParser.java +++ /dev/null @@ -1,172 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.config; - -import fun.asgc.neutrino.core.annotation.Configuration; -import fun.asgc.neutrino.core.annotation.Value; -import fun.asgc.neutrino.core.constant.MetaDataConstant; -import fun.asgc.neutrino.core.exception.ConfigurationParserException; -import fun.asgc.neutrino.core.util.*; -import org.apache.commons.lang3.StringUtils; - -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.lang.reflect.Field; -import java.util.Map; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -public abstract class AbstractConfigurationParser implements ConfigurationParser { - private static Pattern pattern = Pattern.compile("\\$\\{[\\s\\p{Zs}]*(.*):(.*)[\\s\\p{Zs}]*\\}"); - - @Override - public T parse(InputStream in, Class clazz) throws ConfigurationParserException { - return parse(in, clazz, null); - } - - public T parse(InputStream in, Class clazz, Object obj) throws ConfigurationParserException { - Map config = parse2Map(in); - return parse(config, clazz, obj); - } - - @Override - public T parse(Class clazz) throws ConfigurationParserException { - return parse(clazz, null); - } - - public T parse(Class clazz, Object obj) throws ConfigurationParserException { - String fileName = defaultFileName(); - Configuration configuration = clazz.getAnnotation(Configuration.class); - if (null != configuration && StringUtils.isNotEmpty(configuration.file())) { - fileName = configuration.file(); - } - - try { - InputStream in = FileUtil.getInputStream(MetaDataConstant.CLASSPATH_RESOURCE_IDENTIFIER.concat("/").concat(fileName)); - return parse(in, clazz, obj); - } catch (FileNotFoundException e) { - throw new ConfigurationParserException(String.format("配置文件[%s]不存在", fileName)); - } - } - - @Override - public void parse(Object obj) throws ConfigurationParserException { - Assert.notNull(obj, "对象不能为空"); - parse(obj.getClass(), obj); - } - - @Override - public T parse(Map config, Class clazz) throws ConfigurationParserException { - return parse(config, clazz, null); - } - - public T parse(Map config, Class clazz, Object obj) throws ConfigurationParserException { - return parseProxy(config, clazz, obj); - } - - private T parseProxy(Map config, Class clazz, Object obj) throws ConfigurationParserException { - T instance = null; - try { - instance = (null != obj) ? (T)obj : (T)clazz.newInstance(); - } catch (InstantiationException e) { - throw new ConfigurationParserException(String.format("无法实例化类:%s", clazz.getName())); - } catch (IllegalAccessException e) { - throw new ConfigurationParserException(String.format("没有权限访问类:%s", clazz.getName())); - } - - String prefix = ""; - Configuration configuration = clazz.getAnnotation(Configuration.class); - if (null != configuration) { - prefix = configuration.prefix(); - } - - if (StringUtils.isNotEmpty(prefix)) { - String[] prefixNodes = prefix.split("\\."); - for (String prefixNode : prefixNodes) { - if (config.containsKey(prefixNode) && config.get(prefixNode) instanceof Map) { - config = (Map) config.get(prefixNode); - if (CollectionUtil.isEmpty(config)) { - return instance; - } - } else { - return instance; - } - } - } - - Set fields = ReflectUtil.getInheritChainDeclaredFieldSet(clazz); - if (CollectionUtil.isEmpty(fields)) { - return instance; - } - for (Field field : fields) { - String key = field.getName(); - Value value = field.getAnnotation(Value.class); - Object defaultValue = null; - if (null != value && StringUtil.notEmpty(value.value())) { - Matcher m = pattern.matcher(value.value()); - if (m.find()) { - key = m.group(1); - defaultValue = m.group(2); - } else { - key = value.value(); - } - } - Object fieldValue = config.get(key); - if (null == fieldValue) { - fieldValue = defaultValue; - } - boolean success = ReflectUtil.setFieldValue(field, instance, fieldValue); - if (!success) { - try { - Object o = parseProxy((Map)config.get(key), field.getType(), null); - if (null != o) { - ReflectUtil.setFieldValue(field, instance, o); - } - } catch (Exception e) { - // ignore - } - } - } - - return instance; - } - - /** - * 解析配置为map - * @param in - * @return - */ - protected abstract Map parse2Map(InputStream in) throws ConfigurationParserException; - - /** - * 默认的文件名 - * @return - */ - protected abstract String defaultFileName(); -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/config/ConfigurationParser.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/config/ConfigurationParser.java deleted file mode 100644 index 2adc672e..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/config/ConfigurationParser.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.config; - -import fun.asgc.neutrino.core.exception.ConfigurationParserException; - -import java.io.InputStream; -import java.util.Map; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -public interface ConfigurationParser { - - /** - * 解析 - * @param in - * @param clazz - * @param - * @return - */ - T parse(InputStream in, Class clazz) throws ConfigurationParserException; - - /** - * 解析 - * @param clazz - * @param - * @return - */ - T parse(Class clazz) throws ConfigurationParserException; - - /** - * 解析 - * @param obj - * @throws ConfigurationParserException - */ - void parse(Object obj) throws ConfigurationParserException; - - /** - * 解析 - * @param config - * @param clazz - * @param - * @return - * @throws ConfigurationParserException - */ - T parse(Map config, Class clazz) throws ConfigurationParserException; -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/config/impl/YmlConfigurationParser.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/config/impl/YmlConfigurationParser.java deleted file mode 100644 index f30a634b..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/config/impl/YmlConfigurationParser.java +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.config.impl; - -import fun.asgc.neutrino.core.config.AbstractConfigurationParser; -import fun.asgc.neutrino.core.constant.MetaDataConstant; -import fun.asgc.neutrino.core.exception.ConfigurationParserException; -import org.yaml.snakeyaml.Yaml; - -import java.io.InputStream; -import java.util.Map; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -public class YmlConfigurationParser extends AbstractConfigurationParser { - - @Override - public Map parse2Map(InputStream in) throws ConfigurationParserException { - try { - return new Yaml().load(in); - } catch (Exception e) { - throw new ConfigurationParserException("yml配置解析异常!"); - } - } - - @Override - protected String defaultFileName() { - return MetaDataConstant.DEFAULT_YML_CONFIG_FILE_NAME; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/constant/AppLifeCycleStatusEnum.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/constant/AppLifeCycleStatusEnum.java deleted file mode 100644 index cae4d241..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/constant/AppLifeCycleStatusEnum.java +++ /dev/null @@ -1,60 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.constant; - -import lombok.AllArgsConstructor; -import lombok.Getter; - -import java.util.Map; -import java.util.function.Function; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -/** - * 应用生命周期状态枚举 - * @author: aoshiguchen - * @date: 2022/10/10 - */ -@AllArgsConstructor -@Getter -public enum AppLifeCycleStatusEnum { - // 应用已创建 - APP_CREATE(100, "已创建"), - // 应用已初始化 - APP_INIT(200, "配置初始化"), - // 容器已初始化 - CONTAINER_INIT(300, "容器初始化"), - // 应用已启动完成 - APP_STARTUP(400, "应用启动"), - // 应用准备销毁 - APP_PRE_DESTROY(500, "应用准备销毁"), - // 应用已销毁 - APP_DESTROY(600, "应用已销毁"); - - private Integer status; - private String desc; - private static Map CACHE = Stream.of(AppLifeCycleStatusEnum.values()).collect(Collectors.toMap(AppLifeCycleStatusEnum::getStatus, Function.identity())); - - public static AppLifeCycleStatusEnum of(Integer status) { - return CACHE.get(status); - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/constant/FileTypeEnum.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/constant/FileTypeEnum.java deleted file mode 100644 index e54530b4..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/constant/FileTypeEnum.java +++ /dev/null @@ -1,33 +0,0 @@ -package fun.asgc.neutrino.core.constant; - -import com.google.common.collect.Sets; -import lombok.AllArgsConstructor; -import lombok.Getter; - -import java.util.Map; -import java.util.Set; -import java.util.function.Function; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -/** - * @author: aoshiguchen - * @date: 2023/3/6 - */ -@AllArgsConstructor -@Getter -public enum FileTypeEnum { - YML(1, "yml", Sets.newHashSet(".yml", ".yaml")), - PROPERTIES(2, "properties", Sets.newHashSet(".properties")), - JSON(3, "json", Sets.newHashSet(".json")), - ; - - private Integer type; - private String desc; - private Set suffixSet; - private static final Map typeMap = Stream.of(FileTypeEnum.values()).collect(Collectors.toMap(FileTypeEnum::getType, Function.identity())); - - public static FileTypeEnum ofType(Integer type) { - return typeMap.get(type); - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/constant/MetaDataConstant.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/constant/MetaDataConstant.java deleted file mode 100644 index 2fe351cb..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/constant/MetaDataConstant.java +++ /dev/null @@ -1,124 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.constant; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -public interface MetaDataConstant { - - String DEFAULT_BANNER = "\n _____ _____ _____ _____ _____ _____ _____ _______ \n" + - " /\\ \\ /\\ \\ /\\ \\ /\\ \\ /\\ \\ /\\ \\ /\\ \\ /::\\ \\ \n" + - " /::\\____\\ /::\\ \\ /::\\____\\ /::\\ \\ /::\\ \\ /::\\ \\ /::\\____\\ /::::\\ \\ \n" + - " /::::| | /::::\\ \\ /:::/ / \\:::\\ \\ /::::\\ \\ \\:::\\ \\ /::::| | /::::::\\ \\ \n" + - " /:::::| | /::::::\\ \\ /:::/ / \\:::\\ \\ /::::::\\ \\ \\:::\\ \\ /:::::| | /::::::::\\ \\ \n" + - " /::::::| | /:::/\\:::\\ \\ /:::/ / \\:::\\ \\ /:::/\\:::\\ \\ \\:::\\ \\ /::::::| | /:::/~~\\:::\\ \\ \n" + - " /:::/|::| | /:::/__\\:::\\ \\ /:::/ / \\:::\\ \\ /:::/__\\:::\\ \\ \\:::\\ \\ /:::/|::| | /:::/ \\:::\\ \\ \n" + - " /:::/ |::| | /::::\\ \\:::\\ \\ /:::/ / /::::\\ \\ /::::\\ \\:::\\ \\ /::::\\ \\ /:::/ |::| | /:::/ / \\:::\\ \\ \n" + - " /:::/ |::| | _____ /::::::\\ \\:::\\ \\ /:::/ / _____ /::::::\\ \\ /::::::\\ \\:::\\ \\ ____ /::::::\\ \\ /:::/ |::| | _____ /:::/____/ \\:::\\____\\ \n" + - " /:::/ |::| |/\\ \\ /:::/\\:::\\ \\:::\\ \\ /:::/____/ /\\ \\ /:::/\\:::\\ \\ /:::/\\:::\\ \\:::\\____\\ /\\ \\ /:::/\\:::\\ \\ /:::/ |::| |/\\ \\ |:::| | |:::| |\n" + - "/:: / |::| /::\\____\\/:::/__\\:::\\ \\:::\\____\\|:::| / /::\\____\\ /:::/ \\:::\\____\\/:::/ \\:::\\ \\:::| |/::\\ \\/:::/ \\:::\\____\\/:: / |::| /::\\____\\|:::|____| |:::| |\n" + - "\\::/ /|::| /:::/ /\\:::\\ \\:::\\ \\::/ /|:::|____\\ /:::/ / /:::/ \\::/ /\\::/ |::::\\ /:::|____|\\:::\\ /:::/ \\::/ /\\::/ /|::| /:::/ / \\:::\\ \\ /:::/ / \n" + - " \\/____/ |::| /:::/ / \\:::\\ \\:::\\ \\/____/ \\:::\\ \\ /:::/ / /:::/ / \\/____/ \\/____|:::::\\/:::/ / \\:::\\/:::/ / \\/____/ \\/____/ |::| /:::/ / \\:::\\ \\ /:::/ / \n" + - " |::|/:::/ / \\:::\\ \\:::\\ \\ \\:::\\ \\ /:::/ / /:::/ / |:::::::::/ / \\::::::/ / |::|/:::/ / \\:::\\ /:::/ / \n" + - " |::::::/ / \\:::\\ \\:::\\____\\ \\:::\\ /:::/ / /:::/ / |::|\\::::/ / \\::::/____/ |::::::/ / \\:::\\__/:::/ / \n" + - " |:::::/ / \\:::\\ \\::/ / \\:::\\__/:::/ / \\::/ / |::| \\::/____/ \\:::\\ \\ |:::::/ / \\::::::::/ / \n" + - " |::::/ / \\:::\\ \\/____/ \\::::::::/ / \\/____/ |::| ~| \\:::\\ \\ |::::/ / \\::::::/ / \n" + - " /:::/ / \\:::\\ \\ \\::::::/ / |::| | \\:::\\ \\ /:::/ / \\::::/ / \n" + - " /:::/ / \\:::\\____\\ \\::::/ / \\::| | \\:::\\____\\ /:::/ / \\::/____/ \n" + - " \\::/ / \\::/ / \\::/____/ \\:| | \\::/ / \\::/ / ~~ \n" + - " \\/____/ \\/____/ ~~ \\|___| \\/____/ \\/____/ \n" + - " "; - - /** - * classpath标识符 - */ - String CLASSPATH_IDENTIFIER = "classpath"; - - /** - * classpath资源标识 - */ - String CLASSPATH_RESOURCE_IDENTIFIER = CLASSPATH_IDENTIFIER + ":"; - - /** - * 默认的yml配置文件名 - */ - String DEFAULT_YML_CONFIG_FILE_NAME = "application.yml"; - - /** - * 应用banner路径 - */ - String APP_BANNER_FILE_PATH = CLASSPATH_RESOURCE_IDENTIFIER.concat("/banner.txt"); - - /** - * 默认的http页面路径 - */ - String DEFAULT_HTTP_PAGE_PATH = CLASSPATH_RESOURCE_IDENTIFIER.concat("/webapp/"); - /** - * 服务版本 - */ - String SERVER_VS = "Neutrino-1.0"; - /** - * app生命周期主题 - */ - String TOPIC_APP_LIFE_CYCLE = "TP_APP_LIFE_CYCLE"; - /** - * 环境变量key - */ - String ENVIRONMENT_VARIABLE_KEY = "NEUTRINO_PROXY"; - - interface Config { - String NEUTRINO_APPLICATION_NAME = "neutrino.application.name"; - String NEUTRINO_HTTP_ENABLE = "neutrino.http.enable"; - String NEUTRINO_HTTP_PORT = "neutrino.http.port"; - String NEUTRINO_HTTP_CONTEXT_PATH = "neutrino.http.context-path"; - String NEUTRINO_HTTP_MAX_CONTENT_LENGTH_DESC = "neutrino.http.max-content-length-desc"; - String NEUTRINO_HTTP_STATIC_RESOURCE_LOCATIONS = "neutrino.http.static-resource.locations"; - String NEUTRINO_PROXY_PROTOCOL_MAX_FRAME_LENGTH = "neutrino.proxy.protocol.max-frame-length"; - String NEUTRINO_PROXY_PROTOCOL_LENGTH_FIELD_OFFSET = "neutrino.proxy.protocol.length-field-offset"; - String NEUTRINO_PROXY_PROTOCOL_LENGTH_FIELD_LENGTH = "neutrino.proxy.protocol.length-field-length"; - String NEUTRINO_PROXY_PROTOCOL_INITIAL_BYTES_TO_STRIP = "neutrino.proxy.protocol.initial-bytes-to-strip"; - String NEUTRINO_PROXY_PROTOCOL_LENGTH_ADJUSTMENT = "neutrino.proxy.protocol.length-adjustment"; - String NEUTRINO_PROXY_PROTOCOL_READ_IDLE_TIME = "neutrino.proxy.protocol.read-idle-time"; - String NEUTRINO_PROXY_PROTOCOL_WRITE_IDLE_TIME = "neutrino.proxy.protocol.write-idle-time"; - String NEUTRINO_PROXY_PROTOCOL_ALL_IDLE_TIME_SECONDS = "neutrino.proxy.protocol.all-idle-time-seconds"; - String NEUTRINO_PROXY_SERVER_PORT = "neutrino.proxy.server.port"; - String NEUTRINO_PROXY_SERVER_SSL_PORT = "neutrino.proxy.server.ssl-port"; - String NEUTRINO_PROXY_SERVER_KEY_STORE_PASSWORD = "neutrino.proxy.server.key-store-password"; - String NEUTRINO_PROXY_SERVER_KEY_MANAGER_PASSWORD = "neutrino.proxy.server.key-manager-password"; - String NEUTRINO_PROXY_SERVER_JKS_PATH = "neutrino.proxy.server.jks-path"; - String NEUTRINO_PROXY_CLIENT_KEY_STORE_PASSWORD = "neutrino.proxy.client.key-store-password"; - String NEUTRINO_PROXY_CLIENT_JKS_PATH = "neutrino.proxy.client.jks-path"; - String NEUTRINO_PROXY_CLIENT_SERVER_IP = "neutrino.proxy.client.server-ip"; - String NEUTRINO_PROXY_CLIENT_SERVER_PORT = "neutrino.proxy.client.server-port"; - String NEUTRINO_PROXY_CLIENT_SSL_ENABLE = "neutrino.proxy.client.ssl-enable"; - String NEUTRINO_PROXY_CLIENT_OBTAIN_LICENSE_INTERVAL = "neutrino.proxy.client.obtain-license-interval"; - String NEUTRINO_DATA_DB_TYPE = "neutrino.data.db.type"; - String NEUTRINO_DATA_DB_URL = "neutrino.data.db.url"; - String NEUTRINO_DATA_DB_DRIVER_CLASS = "neutrino.data.db.driver-class"; - String NEUTRINO_DATA_DB_USERNAME = "neutrino.data.db.username"; - String NEUTRINO_DATA_DB_PASSWORD = "neutrino.data.db.password"; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/context/ApplicationConfig.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/context/ApplicationConfig.java deleted file mode 100644 index a55e5ff8..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/context/ApplicationConfig.java +++ /dev/null @@ -1,69 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.context; - -import fun.asgc.neutrino.core.annotation.Configuration; -import fun.asgc.neutrino.core.annotation.Value; -import lombok.Data; - -import java.util.Set; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -@Data -@Configuration(prefix = "neutrino") -public class ApplicationConfig { - private Application application; - private Http http; - - @Data - public static class Application { - /** - * 应用名称 - */ - private String name; - } - - @Data - public static class Http { - private Boolean enable; - @Value("${port:8080}") - private Integer port; - @Value("context-path") - private String contextPath; - @Value("${max-content-length-desc:64KB}") - private String maxContentLengthDesc; - @Value("max-content-length") - private Long maxContentLength; - @Value("static-resource") - private StaticResource staticResource; - } - - @Data - public static class StaticResource{ - private Set locations; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/context/ApplicationContext.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/context/ApplicationContext.java deleted file mode 100644 index fa0c57bc..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/context/ApplicationContext.java +++ /dev/null @@ -1,168 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.context; - -import fun.asgc.neutrino.core.annotation.PreLoad; -import fun.asgc.neutrino.core.base.GlobalConfig; -import fun.asgc.neutrino.core.bean.factory.BeanFactoryAware; -import fun.asgc.neutrino.core.bean.factory.SimpleBeanFactory; -import fun.asgc.neutrino.core.util.*; -import lombok.Data; -import lombok.experimental.Accessors; -import lombok.extern.slf4j.Slf4j; - -import java.io.IOException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.HashSet; -import java.util.List; -import java.util.Optional; -import java.util.Set; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -@Accessors(chain = true) -@Data -@Slf4j -public class ApplicationContext implements LifeCycle { - - /** - * 应用环境 - */ - private Environment environment; - /** - * 根Bean工厂 - */ - private SimpleBeanFactory rootBeanFactory; - /** - * bean工厂 - */ - private SimpleBeanFactory applicationBeanFactory; - /** - * 生命周期管理者 - */ - private LifeCycleManager lifeCycleManager = LifeCycleManager.create(); - private Set> classes = new HashSet<>(); - - public ApplicationContext(Environment environment) { - this.environment = environment; - } - - @Override - public synchronized void init() { - this.lifeCycleManager.init(() -> { - try { - GlobalConfig.setIsContainerStartup(true); - this.classes = ClassUtil.scan(environment.getScanBasePackages()); - this.rootBeanFactory = new SimpleBeanFactory("rootBeanFactory"); - this.applicationBeanFactory = new SimpleBeanFactory(rootBeanFactory, "applicationBeanFactory"); - this.rootBeanFactory.registerBean(environment); - this.rootBeanFactory.registerBean(this); - this.rootBeanFactory.registerBean(environment.getConfig()); - preLoad(); - register(); - List beanFactoryAwareList = this.applicationBeanFactory.getBeanList(BeanFactoryAware.class); - if (CollectionUtil.notEmpty(beanFactoryAwareList)) { - beanFactoryAwareList.forEach(beanFactoryAware -> beanFactoryAware.setBeanFactory(applicationBeanFactory)); - } - this.applicationBeanFactory.init(); - } catch (Exception e) { - log.error("应用上下文初始化异常!", e); - System.exit(-1); - } - - log.info("应用上下文初始化完成"); - }); - } - - @Override - public void destroy() { - this.lifeCycleManager.destroy(() -> { - this.applicationBeanFactory.destroy(); - log.info("应用上下文销毁"); - }); - } - - /** - * 预加载 - * @throws Exception - */ - private void preLoad() throws Exception { - for (Class c : this.classes) { - if (!c.isAnnotationPresent(PreLoad.class)) { - continue; - } - Set methodSet = ReflectUtil.getDeclaredMethods(c); - if (CollectionUtil.isEmpty(methodSet)) { - continue; - } - PreLoad preLoad = c.getAnnotation(PreLoad.class); - String name = preLoad.value(); - if (StringUtil.isEmpty(name)) { - continue; - } - Optional methodOptional = methodSet.stream().filter(m -> m.getName().equals(name) && Modifier.isStatic(m.getModifiers()) - && (m.getParameterCount() == 0 || m.getParameterCount() == 1)) - .findFirst(); - if (!methodOptional.isPresent()) { - continue; - } - Method method = methodOptional.get(); - Object o = c.newInstance(); - log.debug("PreLoad execute {}#{}", c.getName(), method.getName()); - if (method.getParameterCount() == 0) { - method.invoke(o); - } else if (method.getParameterCount() == 1){ - if (String[].class.isAssignableFrom(method.getParameters()[0].getType())) { - method.invoke(o, new Object[]{this.environment.getMainArgs()}); - } else if (Environment.class.isAssignableFrom(method.getParameters()[0].getType())){ - method.invoke(o, this.environment); - } else { - log.error("PreLoad execute failed. init method args nonsupport!"); - } - } else { - log.error("PreLoad execute failed. init method args nonsupport!"); - } - } - } - - /** - * bean注册 - * 所有的拦截器默认都是bean组件,没带Component注解时,默认是延迟加载的 - */ - private void register() throws IOException, ClassNotFoundException { - classes.add(BeanManager.class); - classes.add(ExtensionServiceLoader.class); - applicationBeanFactory.register(classes); - } - - /** - * 应用上下文启动 - */ - public void run() { - init(); - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/context/ApplicationRunner.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/context/ApplicationRunner.java deleted file mode 100644 index dcd56d82..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/context/ApplicationRunner.java +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.context; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -public interface ApplicationRunner { - - void run(String[] args) throws Exception; -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/context/Environment.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/context/Environment.java deleted file mode 100644 index 7e810ce6..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/context/Environment.java +++ /dev/null @@ -1,235 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.context; - -import fun.asgc.neutrino.core.base.NvMap; -import fun.asgc.neutrino.core.base.NvMaps; -import fun.asgc.neutrino.core.base.event.SimpleApplicationEventManager; -import fun.asgc.neutrino.core.constant.MetaDataConstant; -import fun.asgc.neutrino.core.util.ArrayUtil; -import fun.asgc.neutrino.core.util.LockUtil; -import fun.asgc.neutrino.core.util.StringUtil; -import fun.asgc.neutrino.core.util.SystemUtil; -import lombok.Data; -import lombok.experimental.Accessors; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static fun.asgc.neutrino.core.constant.MetaDataConstant.Config.*; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -@Accessors(chain = true) -@Data -public class Environment { - /** - * 启动类 - */ - private Class mainClass; - /** - * 启动参数 - */ - private String[] mainArgs; - /** - * 包扫描路径 - */ - private List scanBasePackages; - /** - * 横幅 - */ - private String banner; - /** - * 应用配置 - */ - private ApplicationConfig config; - /** - * 启用job - */ - private boolean enableJob; - /** - * 运行上下文 - */ - private SystemUtil.RunContext runContext; - /** - * 默认的应用事件管理器 - */ - private SimpleApplicationEventManager defaultApplicationEventManager; - /** - * 全局配置 - */ - private NvMap nvMap; - - public NvMap getNvMap() { - return nvMap; - } - - public void loadNvMap(String envKey) throws Exception { - // 创建NvMaps实例 - NvMaps nvMaps = NvMaps.of(); - - // 阶段1:设置内部默认值、别名 - nvMaps.setAlias(NEUTRINO_APPLICATION_NAME, "app.name"); - nvMaps.setKv(NEUTRINO_APPLICATION_NAME, "neutrino-app"); - - nvMaps.setAlias(NEUTRINO_HTTP_ENABLE, "http.enable"); - nvMaps.setKv(NEUTRINO_HTTP_ENABLE, true); - nvMaps.setAlias(NEUTRINO_HTTP_PORT, "http.port"); - nvMaps.setKv(NEUTRINO_HTTP_PORT, 8080); - nvMaps.setAlias(NEUTRINO_HTTP_CONTEXT_PATH, "http.context-path"); - nvMaps.setKv(NEUTRINO_HTTP_CONTEXT_PATH, "/"); - nvMaps.setAlias(NEUTRINO_HTTP_MAX_CONTENT_LENGTH_DESC, "http.max-content-length-desc"); - nvMaps.setKv(NEUTRINO_HTTP_MAX_CONTENT_LENGTH_DESC, "/"); - nvMaps.setAlias(NEUTRINO_HTTP_STATIC_RESOURCE_LOCATIONS, "http.static-resource"); - - nvMaps.setAlias(NEUTRINO_PROXY_PROTOCOL_MAX_FRAME_LENGTH, "protocol.max-frame-length"); - nvMaps.setAlias(NEUTRINO_PROXY_PROTOCOL_LENGTH_FIELD_OFFSET, "protocol.length-field-offset"); - nvMaps.setAlias(NEUTRINO_PROXY_PROTOCOL_LENGTH_FIELD_LENGTH, "protocol.length-field-length"); - nvMaps.setAlias(NEUTRINO_PROXY_PROTOCOL_INITIAL_BYTES_TO_STRIP, "protocol.initial-bytes-to-strip"); - nvMaps.setAlias(NEUTRINO_PROXY_PROTOCOL_LENGTH_ADJUSTMENT, "protocol.length-adjustment"); - nvMaps.setAlias(NEUTRINO_PROXY_PROTOCOL_READ_IDLE_TIME, "protocol.read-idle-time"); - nvMaps.setAlias(NEUTRINO_PROXY_PROTOCOL_WRITE_IDLE_TIME, "protocol.write-idle-time"); - nvMaps.setAlias(NEUTRINO_PROXY_PROTOCOL_ALL_IDLE_TIME_SECONDS, "protocol.all-idle-time-seconds"); - - nvMaps.setAlias(NEUTRINO_PROXY_SERVER_PORT, "proxy.port"); - nvMaps.setAlias(NEUTRINO_PROXY_SERVER_SSL_PORT, "proxy.ssl-port"); - nvMaps.setAlias(NEUTRINO_PROXY_SERVER_KEY_STORE_PASSWORD, "proxy.key-store-password"); - nvMaps.setAlias(NEUTRINO_PROXY_SERVER_KEY_MANAGER_PASSWORD, "proxy.key-manager-password"); - nvMaps.setAlias(NEUTRINO_PROXY_SERVER_JKS_PATH, "proxy.jks-path"); - - nvMaps.setAlias(NEUTRINO_PROXY_CLIENT_KEY_STORE_PASSWORD, "proxy.key-store-password"); - nvMaps.setAlias(NEUTRINO_PROXY_CLIENT_JKS_PATH, "proxy.jks-path"); - nvMaps.setAlias(NEUTRINO_PROXY_CLIENT_SERVER_IP, "proxy.server-ip"); - nvMaps.setAlias(NEUTRINO_PROXY_CLIENT_SERVER_PORT, "proxy.server-port"); - nvMaps.setAlias(NEUTRINO_PROXY_CLIENT_SSL_ENABLE, "proxy.ssl-enable"); - nvMaps.setAlias(NEUTRINO_PROXY_CLIENT_OBTAIN_LICENSE_INTERVAL, "proxy.obtain-license-interval"); - - nvMaps.setAlias(NEUTRINO_DATA_DB_TYPE, "db.type"); - nvMaps.setAlias(NEUTRINO_DATA_DB_URL, "db.url"); - nvMaps.setAlias(NEUTRINO_DATA_DB_DRIVER_CLASS, "db.driver-class"); - nvMaps.setAlias(NEUTRINO_DATA_DB_USERNAME, "db.username"); - nvMaps.setAlias(NEUTRINO_DATA_DB_PASSWORD, "db.password"); - - nvMaps.stageDone(); - - // 阶段2:内部配置文件 - nvMaps.loadFile(MetaDataConstant.CLASSPATH_RESOURCE_IDENTIFIER.concat("/application.yml")); - nvMaps.stageDone(); - - // 阶段3:环境变量 - if (!StringUtil.isEmpty(envKey)) { - nvMaps.loadEnvironmentVariable(envKey); - nvMaps.stageDone(); - } - - // 结算4:外部配置文件 - nvMaps.loadFile("./.application.properties"); - nvMaps.stageDone(); - - // 阶段5:启动参数 - nvMaps.loadMainArgs(this.mainArgs); - nvMaps.stageDone(); - - // 获取NvMap实例 - this.nvMap = nvMaps.getNvMap(); - } - - /** - * 参数map - */ - @Deprecated - private Map mainArgsMap = null; - - @Deprecated - private Map getMainArgsMap() { - return LockUtil.doubleCheckProcessForNoException( - () -> null == mainArgsMap, - this, - () -> { - Map map = new HashMap<>(); - if (ArrayUtil.notEmpty(mainArgs)) { - for (String param : mainArgs) { - if (!StringUtil.isEmpty(param)) { - int index = param.indexOf("="); - if (index > 0 && index < param.length() - 1) { - String key = param.substring(0, index); - String val = param.substring(index + 1); - map.put(key, val); - } - } - } - } - mainArgsMap = map; - }, - () -> mainArgsMap - ); - } - - @Deprecated - private String getMainArgs(String key) { - return getMainArgsMap().get(key); - } - - @Deprecated - public Integer getMainArgsForInteger(String key, Integer defaultValue) { - String val = getMainArgs(key); - Integer res = null; - try { - if (!StringUtil.isEmpty(val)) { - res = Integer.valueOf(val); - } - } catch (Exception e) { - // ignore - } - return (null != res) ? res : defaultValue; - } - - @Deprecated - public Boolean getMainArgsForBoolean(String key, Boolean defaultValue) { - String val = getMainArgs(key); - Boolean res = null; - try { - if (!StringUtil.isEmpty(val)) { - res = Boolean.valueOf(val); - } - } catch (Exception e) { - // ignore - } - return (null != res) ? res : defaultValue; - } - - @Deprecated - public String getMainArgsForString(String key, String defaultValue) { - String res = getMainArgs(key); - return !StringUtil.isEmpty(res) ? res : defaultValue; - } - - @Deprecated - public String getMainArgsForString(String key) { - return getMainArgsForString(key, null); - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/context/ExtensionServiceLoader.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/context/ExtensionServiceLoader.java deleted file mode 100644 index 58f2929c..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/context/ExtensionServiceLoader.java +++ /dev/null @@ -1,62 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.context; - -import fun.asgc.neutrino.core.annotation.Autowired; -import fun.asgc.neutrino.core.annotation.Component; -import fun.asgc.neutrino.core.annotation.NonIntercept; -import fun.asgc.neutrino.core.bean.factory.SimpleBeanFactory; -import fun.asgc.neutrino.core.web.context.WebApplicationContext; -import fun.asgc.neutrino.core.web.context.WebContextHolder; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/9 - */ -@NonIntercept -@Component -public class ExtensionServiceLoader implements ApplicationRunner { - @Autowired - private ApplicationConfig applicationConfig; - @Autowired - private SimpleBeanFactory applicationBeanFactory; - @Autowired - private Environment environment; - - @Override - public void run(String[] args) { - startHttpServer(); - } - - private void startHttpServer() { - if (null == applicationConfig) { - return; - } - ApplicationConfig.Http http = applicationConfig.getHttp(); - if (null == http || null == http.getEnable() || !http.getEnable()) { - return; - } - applicationBeanFactory.registerBean(WebContextHolder.class); - applicationBeanFactory.registerBean(WebApplicationContext.class); - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/context/LifeCycle.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/context/LifeCycle.java deleted file mode 100644 index fc03464a..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/context/LifeCycle.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.context; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -public interface LifeCycle { - - /** - * 初始化 - */ - void init(); - - /** - * 销毁 - */ - void destroy(); -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/context/LifeCycleManager.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/context/LifeCycleManager.java deleted file mode 100644 index e04b55b5..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/context/LifeCycleManager.java +++ /dev/null @@ -1,76 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.context; - -import fun.asgc.neutrino.core.base.CodeBlock; -import fun.asgc.neutrino.core.util.FunctionUtil; - -/** - * - * @author: 生命周期管理 - * @date: 2022/7/2 - */ -public class LifeCycleManager { - /** - * 生命周期状态 - */ - private LifeCycleStatus status; - - private LifeCycleManager() { - this.status = LifeCycleStatus.CREATE; - } - - public synchronized void init(CodeBlock codeBlock) { - if (this.status == LifeCycleStatus.CREATE) { - FunctionUtil.ignoreException(() -> { - codeBlock.execute(); - this.status = LifeCycleStatus.INIT; - }); - } - } - - public synchronized void run(CodeBlock codeBlock) { - if (this.status == LifeCycleStatus.INIT) { - FunctionUtil.ignoreException(() -> { - codeBlock.execute(); - this.status = LifeCycleStatus.RUN; - }); - } - } - - public synchronized void destroy(CodeBlock codeBlock) { - if (this.status != LifeCycleStatus.DESTROY) { - FunctionUtil.ignoreException(() -> { - codeBlock.execute(); - this.status = LifeCycleStatus.DESTROY; - }); - } - } - - public static LifeCycleManager create() { - return new LifeCycleManager(); - } - - public LifeCycleStatus getStatus() { - return status; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/context/LifeCycleStatus.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/context/LifeCycleStatus.java deleted file mode 100644 index 64ef71be..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/context/LifeCycleStatus.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.context; - -import lombok.AllArgsConstructor; -import lombok.Getter; - -/** - * - * @author: 生命周期状态 - * @date: 2022/7/2 - */ -@Getter -@AllArgsConstructor -public enum LifeCycleStatus { - CREATE(1, "已创建"), - INIT(2, "已初始化"), - RUN(3, "运行"), - DESTROY(4, "已销毁"); - - private Integer status; - private String desc; -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/context/NeutrinoLauncher.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/context/NeutrinoLauncher.java deleted file mode 100644 index 5452600b..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/context/NeutrinoLauncher.java +++ /dev/null @@ -1,170 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.context; - -import com.google.common.collect.Lists; -import fun.asgc.neutrino.core.annotation.EnableJob; -import fun.asgc.neutrino.core.annotation.NeutrinoApplication; -import fun.asgc.neutrino.core.base.event.SimpleApplicationEventManager; -import fun.asgc.neutrino.core.constant.AppLifeCycleStatusEnum; -import fun.asgc.neutrino.core.constant.MetaDataConstant; -import fun.asgc.neutrino.core.util.*; -import lombok.extern.slf4j.Slf4j; - -import java.lang.management.ManagementFactory; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -@Slf4j -public class NeutrinoLauncher { - private Environment environment; - - public static SystemUtil.RunContext run(final Class clazz, final String[] args) { - Assert.notNull(clazz, "启动类不能为空!"); - return new NeutrinoLauncher(clazz, args).launch(); - } - - public static void runSync(final Class clazz, final String[] args) { - run(clazz, args).sync(); - } - - private NeutrinoLauncher(Class clazz, String[] args) { - this.environment = new Environment() - .setMainClass(clazz) - .setMainArgs(args) - .setDefaultApplicationEventManager(new SimpleApplicationEventManager(this)) - ; - } - - private SystemUtil.RunContext launch() { - // 已创建 - publishAppLifeCycleEvent(AppLifeCycleStatusEnum.APP_CREATE); - - StopWatch stopWatch = new StopWatch(); - stopWatch.start(); - environmentInit(); - - // 应用已初始化 - publishAppLifeCycleEvent(AppLifeCycleStatusEnum.APP_INIT); - - ApplicationContext context = new ApplicationContext(environment); - SystemUtil.RunContext runContext = SystemUtil.waitProcessDestroy(() -> { - // 应用准备销毁 - publishAppLifeCycleEvent(AppLifeCycleStatusEnum.APP_PRE_DESTROY); - context.destroy(); - log.info("Application already stop."); - // 应用已销毁 - publishAppLifeCycleEvent(AppLifeCycleStatusEnum.APP_DESTROY); - }); - environment.setRunContext(runContext); - - context.run(); - - // 容器已初始化 - publishAppLifeCycleEvent(AppLifeCycleStatusEnum.CONTAINER_INIT); - - stopWatch.stop(); - printLog(environment, stopWatch); - - // 应用已启动完成 - publishAppLifeCycleEvent(AppLifeCycleStatusEnum.APP_STARTUP); - - return runContext; - } - - /** - * 环境初始化 - */ - private void environmentInit() { - environment.setScanBasePackages(Lists.newArrayList(TypeUtil.getPackageName(environment.getMainClass()))); - - bannerProcess(environment); - - NeutrinoApplication neutrinoApplication = environment.getMainClass().getAnnotation(NeutrinoApplication.class); - if (null != neutrinoApplication) { - String[] scanBasePackages = neutrinoApplication.scanBasePackages(); - if (ArrayUtil.notEmpty(scanBasePackages)) { - environment.setScanBasePackages(Lists.newArrayList(scanBasePackages)); - } - } - log.info("scanBasePackages: {}", environment.getScanBasePackages()); - EnableJob enableJob = environment.getMainClass().getAnnotation(EnableJob.class); - if (null != enableJob && enableJob.value()) { - environment.setEnableJob(Boolean.TRUE); - } - - // 加载应用配置 - environment.setConfig(ConfigUtil.getYmlConfig(ApplicationConfig.class)); - try { - environment.loadNvMap(neutrinoApplication.environmentVariableKey()); - log.info("load ApplicationConfig finished."); - } catch (Exception e) { - log.error("load ApplicationConfig err.", e); - } - - } - - /** - * 打印启动日志 - * @param environment - * @param stopWatch - */ - private void printLog(Environment environment, StopWatch stopWatch) { - StringBuffer sb = new StringBuffer(); - sb.append("Started "); - sb.append(environment.getMainClass().getName()); - sb.append(" in "); - sb.append(stopWatch.getTotalTimeSeconds()); - - try { - double uptime = (double) ManagementFactory.getRuntimeMXBean().getUptime() / 1000.0D; - sb.append(" seconds (JVM running for " + uptime + ")"); - } catch (Throwable var5) { - } - log.info(sb.toString()); - } - - /** - * banner处理 - * @param environment - */ - private void bannerProcess(Environment environment) { - environment.setBanner(MetaDataConstant.DEFAULT_BANNER); - String banner = FileUtil.readContentAsString(MetaDataConstant.APP_BANNER_FILE_PATH); - if (StringUtil.notEmpty(banner)) { - environment.setBanner(banner); - } - log.info(environment.getBanner()); - } - - /** - * 发布应用生命周期事件 - * @param appLifeCycleStatusEnum 应用生命周期事件 - */ - private void publishAppLifeCycleEvent(AppLifeCycleStatusEnum appLifeCycleStatusEnum) { - this.environment.getDefaultApplicationEventManager().publish(MetaDataConstant.TOPIC_APP_LIFE_CYCLE, appLifeCycleStatusEnum); - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/annotation/Column.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/annotation/Column.java deleted file mode 100644 index 41a27ee5..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/annotation/Column.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.annotation; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/27 - */ -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.FIELD) -public @interface Column { - String value(); -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/annotation/Delete.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/annotation/Delete.java deleted file mode 100644 index d3eed038..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/annotation/Delete.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.annotation; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/28 - */ -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.METHOD) -public @interface Delete { - String value(); -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/annotation/Id.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/annotation/Id.java deleted file mode 100644 index 093e4e64..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/annotation/Id.java +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.annotation; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Id - * 在持久化模型中标注单一主键 - * @author: aoshiguchen - * @date: 2022/6/27 - */ -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.FIELD) -public @interface Id { - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/annotation/Insert.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/annotation/Insert.java deleted file mode 100644 index 3ba3101c..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/annotation/Insert.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.annotation; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/28 - */ -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.METHOD) -public @interface Insert { - String value(); -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/annotation/NotColumn.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/annotation/NotColumn.java deleted file mode 100644 index a80c2593..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/annotation/NotColumn.java +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.annotation; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * - * 在持久化模型中标注不需要持久化的字段 - * @author: aoshiguchen - * @date: 2022/6/27 - */ -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.FIELD) -public @interface NotColumn { - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/annotation/PrimaryKey.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/annotation/PrimaryKey.java deleted file mode 100644 index ffcebffb..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/annotation/PrimaryKey.java +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.annotation; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * PrimaryKey - * 在持久化模型中标注主键(可标注一个或多个) - * @author: aoshiguchen - * @date: 2022/6/27 - */ -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.FIELD) -public @interface PrimaryKey { - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/annotation/ResultType.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/annotation/ResultType.java deleted file mode 100644 index a49c775b..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/annotation/ResultType.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.annotation; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * @author: aoshiguchen - * @date: 2022/6/28 - */ -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.METHOD) -public @interface ResultType { - Class value(); -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/annotation/Select.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/annotation/Select.java deleted file mode 100644 index bda96130..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/annotation/Select.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.annotation; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/28 - */ -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.METHOD) -public @interface Select { - String value(); -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/annotation/Table.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/annotation/Table.java deleted file mode 100644 index 18420878..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/annotation/Table.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.annotation; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * @author: aoshiguchen - * @date: 2022/6/27 - */ -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.TYPE) -public @interface Table { - String value(); -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/annotation/Update.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/annotation/Update.java deleted file mode 100644 index 86648c79..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/annotation/Update.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.annotation; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/28 - */ -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.METHOD) -public @interface Update { - String value(); -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/CrispDbKit.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/CrispDbKit.java deleted file mode 100644 index b189ea9c..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/CrispDbKit.java +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.crisp; - -/** - * 清爽的数据库工具 - * @author: aoshiguchen - * @date: 2022/11/3 - */ -public class CrispDbKit { - private static final JdbcManager manager = new JdbcManager(); - - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/DbConfig.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/DbConfig.java deleted file mode 100644 index 9ee65ced..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/DbConfig.java +++ /dev/null @@ -1,87 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.crisp; - -import fun.asgc.neutrino.core.db.crisp.ds.DefaultDataSourceProvider; -import fun.asgc.neutrino.core.db.crisp.ds.IDataSourceProvider; - -import javax.sql.DataSource; - -/** - * @author: aoshiguchen - * @date: 2022/11/3 - */ -public class DbConfig { - /** - * 数据库名称 - */ - private String name; - /** - * 数据源提供者 - */ - private IDataSourceProvider dataSourceProvider; - /** - * 是否显示sql - */ - private Boolean showSql; - /** - * 是否开启调试模式 - */ - private Boolean debugMode; - /** - * 上下文 - */ - private DbContext context; - /** - * 数据库执行器 - */ - private DbExecutor dbExecutor; - - public DbConfig(String name, IDataSourceProvider dataSourceProvider) { - this.name = name; - this.dataSourceProvider = dataSourceProvider; - this.showSql = Boolean.FALSE; - this.debugMode = Boolean.FALSE; - this.context = new DbContext(this); - this.dbExecutor = new DbExecutor(this); - } - - public DbConfig(String name, DataSource dataSource) { - this(name, new DefaultDataSourceProvider(dataSource)); - } - - public DbConfig(IDataSourceProvider dataSourceProvider) { - this("unknown", dataSourceProvider); - } - - public DbConfig(DataSource dataSource) { - this(new DefaultDataSourceProvider(dataSource)); - } - - /** - * 获取数据库操作实例 - * @return 数据库操作实例 - */ - public DbExecutor getDbExecutor() { - return dbExecutor; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/DbContext.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/DbContext.java deleted file mode 100644 index 78f9ef4b..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/DbContext.java +++ /dev/null @@ -1,43 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.crisp; - -import fun.asgc.neutrino.core.db.crisp.session.SqlSessionFactory; - -import java.sql.Connection; - -/** - * @author: aoshiguchen - * @date: 2022/11/3 - */ -public class DbContext { - private DbConfig dbConfig; - private final ThreadLocal connectionHolder = new ThreadLocal<>(); - - public DbContext(DbConfig dbConfig) { - this.dbConfig = dbConfig; - } - public SqlSessionFactory getSqlSessionFactory() { - // TODO - return null; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/DbExecutor.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/DbExecutor.java deleted file mode 100644 index 8851b75a..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/DbExecutor.java +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.crisp; - -import fun.asgc.neutrino.core.db.crisp.base.DbUpdateResult; -import fun.asgc.neutrino.core.db.crisp.ds.IDataSourceProvider; - -import javax.sql.DataSource; -import java.util.List; - -/** - * @author: aoshiguchen - * @date: 2022/11/3 - */ -class DbExecutor implements DbOperator { - /** - * 配置 - */ - private DbConfig config; - - - public DbExecutor(DbConfig config) { - this.config = config; - } - - public DbExecutor(IDataSourceProvider dataSourceProvider) { - this(new DbConfig(dataSourceProvider)); - } - - public DbExecutor(String name, IDataSourceProvider dataSourceProvider) { - this(new DbConfig(name, dataSourceProvider)); - } - - public DbExecutor(DataSource dataSource) { - this(new DbConfig(dataSource)); - } - - public DbExecutor(String name, DataSource dataSource) { - this(new DbConfig(name, dataSource)); - } - - @Override - public List queryList(Class resultType, String sql, Object... params) { - return null; - } - - @Override - public T query(Class resultType, String sql, Object... params) { - return null; - } - - @Override - public DbUpdateResult update(String sql, Object... params) { - return null; - } - - @Override - public DbUpdateResult insert(String sql, Object... params) { - return null; - } - - @Override - public DbUpdateResult delete(String sql, Object... params) { - return null; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/DbOperator.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/DbOperator.java deleted file mode 100644 index 1e114cf7..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/DbOperator.java +++ /dev/null @@ -1,76 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.crisp; - -import fun.asgc.neutrino.core.db.crisp.base.DbUpdateResult; - -import java.util.List; - -/** - * @author: aoshiguchen - * @date: 2022/11/3 - */ -public interface DbOperator { - /** - * 查询数据列表 - * @param resultType 结果类型 - * @param sql sql - * @param params 参数列表 - * @return 查询结果列表 - * @param - */ - List queryList(Class resultType, String sql, Object... params); - - /** - * 查询单条记录 - * @param resultType 结果类型 - * @param sql sql - * @param params 参数列表 - * @return 查询结果 - * @param - */ - T query(Class resultType, String sql, Object... params); - - /** - * 更新 - * @param sql sql - * @param params 参数列表 - * @return 更新结果 - */ - DbUpdateResult update(String sql, Object... params); - - /** - * 新增 - * @param sql sql - * @param params 参数列表 - * @return 新增结果 - */ - DbUpdateResult insert(String sql, Object... params); - - /** - * 删除 - * @param sql sql - * @param params 参数列表 - * @return 删除结果 - */ - DbUpdateResult delete(String sql, Object... params); -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/JdbcException.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/JdbcException.java deleted file mode 100644 index 664e9b98..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/JdbcException.java +++ /dev/null @@ -1,18 +0,0 @@ -package fun.asgc.neutrino.core.db.crisp; - -import fun.asgc.neutrino.core.exception.InternalException; - -/** - * @author: aoshiguchen - * @date: 2022/11/7 - */ -public class JdbcException extends InternalException { - - public JdbcException(String message) { - super(message); - } - - public JdbcException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/JdbcManager.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/JdbcManager.java deleted file mode 100644 index c29cb768..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/JdbcManager.java +++ /dev/null @@ -1,100 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.crisp; - -import java.util.HashMap; -import java.util.Map; - -/** - * @author: aoshiguchen - * @date: 2022/11/4 - */ -public class JdbcManager { - /** - * 数据源缓存 - */ - private Map dbConfigMap = new HashMap<>(); - /** - * 默认数据库的key - */ - private final String DEFAULT_KEY = "default"; - - /** - * 设置默认数据库配置 - * @param config 数据库配置 - */ - public void setConfig(DbConfig config) { - setConfig(DEFAULT_KEY, config); - } - - /** - * 设置数据库配置 - * @param key 键 - * @param config 数据库配置 - */ - public void setConfig(String key, DbConfig config) { - dbConfigMap.put(key, config); - } - - /** - * 根据名称获取数据库配置 - * @param key 键 - * @return 数据库配置 - */ - public DbConfig getConfig(String key) { - return dbConfigMap.get(key); - } - - /** - * 获取默认数据库配置 - * @return 数据库配置 - */ - public DbConfig getConfig() { - return getConfig(DEFAULT_KEY); - } - - /** - * 获取默认数据库操作实例 - * @return - */ - private DbExecutor getDbExecutor(String key) { - DbConfig dbConfig = getConfig(key); - return null == dbConfig ? null : dbConfig.getDbExecutor(); - } - - /** - * 切换数据源 - * @param name 数据源名称 - * @return 数据库操作实例 - */ - public DbExecutor use(String name) { - return getDbExecutor(name); - } - - /** - * 切换为默认数据源 - * @return 默认数据库操作实例 - */ - public DbExecutor useDefault() { - return getDbExecutor(DEFAULT_KEY); - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/base/BatchResult.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/base/BatchResult.java deleted file mode 100644 index 982b3198..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/base/BatchResult.java +++ /dev/null @@ -1,80 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.crisp.base; - -import java.util.ArrayList; -import java.util.List; - -/** - * @author: aoshiguchen - * @date: 2022/11/4 - */ -public class BatchResult { - - private final MappedStatement mappedStatement; - private final String sql; - private final List parameterObjects; - - private int[] updateCounts; - - public BatchResult(MappedStatement mappedStatement, String sql) { - super(); - this.mappedStatement = mappedStatement; - this.sql = sql; - this.parameterObjects = new ArrayList<>(); - } - - public BatchResult(MappedStatement mappedStatement, String sql, Object parameterObject) { - this(mappedStatement, sql); - addParameterObject(parameterObject); - } - - public MappedStatement getMappedStatement() { - return mappedStatement; - } - - public String getSql() { - return sql; - } - - @Deprecated - public Object getParameterObject() { - return parameterObjects.get(0); - } - - public List getParameterObjects() { - return parameterObjects; - } - - public int[] getUpdateCounts() { - return updateCounts; - } - - public void setUpdateCounts(int[] updateCounts) { - this.updateCounts = updateCounts; - } - - public void addParameterObject(Object parameterObject) { - this.parameterObjects.add(parameterObject); - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/base/DbUpdateResult.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/base/DbUpdateResult.java deleted file mode 100644 index 91e7a423..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/base/DbUpdateResult.java +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.crisp.base; - -/** - * @author: aoshiguchen - * @date: 2022/11/3 - */ -public class DbUpdateResult { - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/base/MappedStatement.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/base/MappedStatement.java deleted file mode 100644 index c2459d9b..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/base/MappedStatement.java +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.crisp.base; - -/** - * @author: aoshiguchen - * @date: 2022/11/4 - */ -public class MappedStatement { - // TODO -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/base/RowBounds.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/base/RowBounds.java deleted file mode 100644 index 461c1e79..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/base/RowBounds.java +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.crisp.base; - -/** - * @author: aoshiguchen - * @date: 2022/11/4 - */ -public class RowBounds { - - public static final int NO_ROW_OFFSET = 0; - public static final int NO_ROW_LIMIT = Integer.MAX_VALUE; - public static final RowBounds DEFAULT = new RowBounds(); - - private final int offset; - private final int limit; - - public RowBounds() { - this.offset = NO_ROW_OFFSET; - this.limit = NO_ROW_LIMIT; - } - - public RowBounds(int offset, int limit) { - this.offset = offset; - this.limit = limit; - } - - public int getOffset() { - return offset; - } - - public int getLimit() { - return limit; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/base/SqlExecutorType.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/base/SqlExecutorType.java deleted file mode 100644 index 802e513a..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/base/SqlExecutorType.java +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.crisp.base; - -/** - * @author: aoshiguchen - * @date: 2022/11/4 - */ -public enum SqlExecutorType { - SIMPLE, REUSE, BATCH -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/ds/DefaultDataSourceProvider.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/ds/DefaultDataSourceProvider.java deleted file mode 100644 index 4d49288c..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/ds/DefaultDataSourceProvider.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.crisp.ds; - -import javax.sql.DataSource; - -/** - * @author: aoshiguchen - * @date: 2022/11/3 - */ -public class DefaultDataSourceProvider implements IDataSourceProvider { - /** - * 数据源 - */ - private DataSource dataSource; - - public DefaultDataSourceProvider(DataSource dataSource) { - this.dataSource = dataSource; - } - - @Override - public DataSource getDataSource() { - return dataSource; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/ds/IDataSourceProvider.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/ds/IDataSourceProvider.java deleted file mode 100644 index fa748d58..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/ds/IDataSourceProvider.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.crisp.ds; - -import javax.sql.DataSource; - -/** - * 数据源提供商 - * @author: aoshiguchen - * @date: 2022/11/3 - */ -public interface IDataSourceProvider { - /** - * 获取数据源 - * @return - */ - DataSource getDataSource(); -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/session/DefaultSqlSessionFactory.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/session/DefaultSqlSessionFactory.java deleted file mode 100644 index fa613d44..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/session/DefaultSqlSessionFactory.java +++ /dev/null @@ -1,95 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.crisp.session; - -import fun.asgc.neutrino.core.db.crisp.DbConfig; -import fun.asgc.neutrino.core.db.crisp.base.SqlExecutorType; -import fun.asgc.neutrino.core.db.crisp.tx.TransactionIsolationLevel; - -import java.sql.Connection; - -/** - * @author: aoshiguchen - * @date: 2022/11/4 - */ -public class DefaultSqlSessionFactory implements SqlSessionFactory { - - private final DbConfig config; - - public DefaultSqlSessionFactory(DbConfig config) { - this.config = config; - } - - @Override - public SqlSession openSession() { - // TODO - return null; - } - - @Override - public SqlSession openSession(boolean autoCommit) { - // TODO - return null; - } - - @Override - public SqlSession openSession(Connection connection) { - // TODO - return null; - } - - @Override - public SqlSession openSession(TransactionIsolationLevel level) { - // TODO - return null; - } - - @Override - public SqlSession openSession(SqlExecutorType execType) { - // TODO - return null; - } - - @Override - public SqlSession openSession(SqlExecutorType execType, boolean autoCommit) { - // TODO - return null; - } - - @Override - public SqlSession openSession(SqlExecutorType execType, TransactionIsolationLevel level) { - // TODO - return null; - } - - @Override - public SqlSession openSession(SqlExecutorType execType, Connection connection) { - // TODO - return null; - } - - @Override - public DbConfig getDbConfig() { - // TODO - return null; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/session/ResultContext.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/session/ResultContext.java deleted file mode 100644 index 4448e05d..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/session/ResultContext.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.crisp.session; - -/** - * @author: aoshiguchen - * @date: 2022/11/23 - */ -public interface ResultContext { - T getResultObject(); - - int getResultCount(); - - boolean isStopped(); - - void stop(); -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/session/ResultHandler.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/session/ResultHandler.java deleted file mode 100644 index 027c9108..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/session/ResultHandler.java +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.crisp.session; - -/** - * @author: aoshiguchen - * @date: 2022/11/23 - */ -public interface ResultHandler { - void handleResult(ResultContext resultContext); -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/session/SqlSession.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/session/SqlSession.java deleted file mode 100644 index 6633f51c..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/session/SqlSession.java +++ /dev/null @@ -1,264 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.crisp.session; - -import fun.asgc.neutrino.core.db.crisp.DbConfig; -import fun.asgc.neutrino.core.db.crisp.base.BatchResult; -import fun.asgc.neutrino.core.db.crisp.base.RowBounds; - -import java.io.Closeable; -import java.sql.Connection; -import java.util.List; -import java.util.Map; - -/** - * @author: aoshiguchen - * @date: 2022/11/4 - */ -public interface SqlSession extends Closeable { - - /** - * Retrieve a single row mapped from the statement key. - * @param the returned object type - * @param statement - * @return Mapped object - */ - T selectOne(String statement); - - /** - * Retrieve a single row mapped from the statement key and parameter. - * @param the returned object type - * @param statement Unique identifier matching the statement to use. - * @param parameter A parameter object to pass to the statement. - * @return Mapped object - */ - T selectOne(String statement, Object parameter); - - /** - * Retrieve a list of mapped objects from the statement key and parameter. - * @param the returned list element type - * @param statement Unique identifier matching the statement to use. - * @return List of mapped object - */ - List selectList(String statement); - - /** - * Retrieve a list of mapped objects from the statement key and parameter. - * @param the returned list element type - * @param statement Unique identifier matching the statement to use. - * @param parameter A parameter object to pass to the statement. - * @return List of mapped object - */ - List selectList(String statement, Object parameter); - - /** - * Retrieve a list of mapped objects from the statement key and parameter, - * within the specified row bounds. - * @param the returned list element type - * @param statement Unique identifier matching the statement to use. - * @param parameter A parameter object to pass to the statement. - * @param rowBounds Bounds to limit object retrieval - * @return List of mapped object - */ - List selectList(String statement, Object parameter, RowBounds rowBounds); - - /** - * The selectMap is a special case in that it is designed to convert a list - * of results into a Map based on one of the properties in the resulting - * objects. - * Eg. Return a of Map[Integer,Author] for selectMap("selectAuthors","id") - * @param the returned Map keys type - * @param the returned Map values type - * @param statement Unique identifier matching the statement to use. - * @param mapKey The property to use as key for each value in the list. - * @return Map containing key pair data. - */ - Map selectMap(String statement, String mapKey); - - /** - * The selectMap is a special case in that it is designed to convert a list - * of results into a Map based on one of the properties in the resulting - * objects. - * @param the returned Map keys type - * @param the returned Map values type - * @param statement Unique identifier matching the statement to use. - * @param parameter A parameter object to pass to the statement. - * @param mapKey The property to use as key for each value in the list. - * @return Map containing key pair data. - */ - Map selectMap(String statement, Object parameter, String mapKey); - - /** - * The selectMap is a special case in that it is designed to convert a list - * of results into a Map based on one of the properties in the resulting - * objects. - * @param the returned Map keys type - * @param the returned Map values type - * @param statement Unique identifier matching the statement to use. - * @param parameter A parameter object to pass to the statement. - * @param mapKey The property to use as key for each value in the list. - * @param rowBounds Bounds to limit object retrieval - * @return Map containing key pair data. - */ - Map selectMap(String statement, Object parameter, String mapKey, RowBounds rowBounds); - - /** - * Retrieve a single row mapped from the statement key and parameter - * using a {@code ResultHandler}. - * - * @param statement Unique identifier matching the statement to use. - * @param parameter A parameter object to pass to the statement. - * @param handler ResultHandler that will handle each retrieved row - */ - default void select(String statement, Object parameter, ResultHandler handler) { - - } - - /** - * Retrieve a single row mapped from the statement - * using a {@code ResultHandler}. - * @param statement Unique identifier matching the statement to use. - * @param handler ResultHandler that will handle each retrieved row - */ - void select(String statement, ResultHandler handler); - - /** - * Retrieve a single row mapped from the statement key and parameter - * using a {@code ResultHandler} and {@code RowBounds}. - * @param statement Unique identifier matching the statement to use. - * @param rowBounds RowBound instance to limit the query results - * @param handler ResultHandler that will handle each retrieved row - */ - void select(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler); - - /** - * Execute an insert statement. - * @param statement Unique identifier matching the statement to execute. - * @return int The number of rows affected by the insert. - */ - int insert(String statement); - - /** - * Execute an insert statement with the given parameter object. Any generated - * autoincrement values or selectKey entries will modify the given parameter - * object properties. Only the number of rows affected will be returned. - * @param statement Unique identifier matching the statement to execute. - * @param parameter A parameter object to pass to the statement. - * @return int The number of rows affected by the insert. - */ - int insert(String statement, Object parameter); - - /** - * Execute an update statement. The number of rows affected will be returned. - * @param statement Unique identifier matching the statement to execute. - * @return int The number of rows affected by the update. - */ - int update(String statement); - - /** - * Execute an update statement. The number of rows affected will be returned. - * @param statement Unique identifier matching the statement to execute. - * @param parameter A parameter object to pass to the statement. - * @return int The number of rows affected by the update. - */ - int update(String statement, Object parameter); - - /** - * Execute a delete statement. The number of rows affected will be returned. - * @param statement Unique identifier matching the statement to execute. - * @return int The number of rows affected by the delete. - */ - int delete(String statement); - - /** - * Execute a delete statement. The number of rows affected will be returned. - * @param statement Unique identifier matching the statement to execute. - * @param parameter A parameter object to pass to the statement. - * @return int The number of rows affected by the delete. - */ - int delete(String statement, Object parameter); - - /** - * Flushes batch statements and commits database connection. - * Note that database connection will not be committed if no updates/deletes/inserts were called. - * To force the commit call {@link SqlSession#commit(boolean)} - */ - void commit(); - - /** - * Flushes batch statements and commits database connection. - * @param force forces connection commit - */ - void commit(boolean force); - - /** - * Discards pending batch statements and rolls database connection back. - * Note that database connection will not be rolled back if no updates/deletes/inserts were called. - * To force the rollback call {@link SqlSession#rollback(boolean)} - */ - void rollback(); - - /** - * Discards pending batch statements and rolls database connection back. - * Note that database connection will not be rolled back if no updates/deletes/inserts were called. - * @param force forces connection rollback - */ - void rollback(boolean force); - - /** - * Flushes batch statements. - * @return BatchResult list of updated records - * @since 3.0.6 - */ - List flushStatements(); - - /** - * Closes the session. - */ - @Override - void close(); - - /** - * Clears local session cache. - */ - void clearCache(); - - /** - * Retrieves current configuration. - * @return DbConfig - */ - DbConfig getDbConfig(); - - /** - * Retrieves a mapper. - * @param the mapper type - * @param type Mapper interface class - * @return a mapper bound to this SqlSession - */ - T getMapper(Class type); - - /** - * Retrieves inner database connection. - * @return Connection - */ - Connection getConnection(); -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/session/SqlSessionFactory.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/session/SqlSessionFactory.java deleted file mode 100644 index ebd82cc0..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/session/SqlSessionFactory.java +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.crisp.session; - -import fun.asgc.neutrino.core.db.crisp.DbConfig; -import fun.asgc.neutrino.core.db.crisp.base.SqlExecutorType; -import fun.asgc.neutrino.core.db.crisp.tx.TransactionIsolationLevel; - -import java.sql.Connection; - -/** - * @author: aoshiguchen - * @date: 2022/11/4 - */ -public interface SqlSessionFactory { - - SqlSession openSession(); - - SqlSession openSession(boolean autoCommit); - - SqlSession openSession(Connection connection); - - SqlSession openSession(TransactionIsolationLevel level); - - SqlSession openSession(SqlExecutorType execType); - - SqlSession openSession(SqlExecutorType execType, boolean autoCommit); - - SqlSession openSession(SqlExecutorType execType, TransactionIsolationLevel level); - - SqlSession openSession(SqlExecutorType execType, Connection connection); - - DbConfig getDbConfig(); -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/session/SqlSessionFactoryBuilder.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/session/SqlSessionFactoryBuilder.java deleted file mode 100644 index ff77cc3f..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/session/SqlSessionFactoryBuilder.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.crisp.session; - -import fun.asgc.neutrino.core.db.crisp.DbConfig; - -/** - * @author: aoshiguchen - * @date: 2022/11/7 - */ -public class SqlSessionFactoryBuilder { - public SqlSessionFactory build(DbConfig config) { - return new DefaultSqlSessionFactory(config); - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/tx/JdbcTransaction.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/tx/JdbcTransaction.java deleted file mode 100644 index 9e971f94..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/tx/JdbcTransaction.java +++ /dev/null @@ -1,123 +0,0 @@ -package fun.asgc.neutrino.core.db.crisp.tx; - -import lombok.extern.slf4j.Slf4j; - -import javax.sql.DataSource; -import java.sql.Connection; -import java.sql.SQLException; - -/** - * @author: aoshiguchen - * @date: 2022/11/7 - */ -@Slf4j -public class JdbcTransaction implements Transaction { - - protected Connection connection; - protected DataSource dataSource; - protected TransactionIsolationLevel level; - protected boolean autoCommit; - - public JdbcTransaction(DataSource ds, TransactionIsolationLevel desiredLevel, boolean desiredAutoCommit) { - dataSource = ds; - level = desiredLevel; - autoCommit = desiredAutoCommit; - } - - public JdbcTransaction(Connection connection) { - this.connection = connection; - } - - @Override - public Connection getConnection() throws SQLException { - if (connection == null) { - openConnection(); - } - return connection; - } - - @Override - public void commit() throws SQLException { - if (connection != null && !connection.getAutoCommit()) { - if (log.isDebugEnabled()) { - log.debug("Committing JDBC Connection [" + connection + "]"); - } - connection.commit(); - } - } - - @Override - public void rollback() throws SQLException { - if (connection != null && !connection.getAutoCommit()) { - if (log.isDebugEnabled()) { - log.debug("Rolling back JDBC Connection [" + connection + "]"); - } - connection.rollback(); - } - } - - @Override - public void close() throws SQLException { - if (connection != null) { - resetAutoCommit(); - if (log.isDebugEnabled()) { - log.debug("Closing JDBC Connection [" + connection + "]"); - } - connection.close(); - } - } - - @Override - public Integer getTimeout() throws SQLException { - return null; - } - - protected void openConnection() throws SQLException { - if (log.isDebugEnabled()) { - log.debug("Opening JDBC Connection"); - } - connection = dataSource.getConnection(); - if (level != null) { - connection.setTransactionIsolation(level.getLevel()); - } - setDesiredAutoCommit(autoCommit); - } - - protected void setDesiredAutoCommit(boolean desiredAutoCommit) { - try { - if (connection.getAutoCommit() != desiredAutoCommit) { - if (log.isDebugEnabled()) { - log.debug("Setting autocommit to " + desiredAutoCommit + " on JDBC Connection [" + connection + "]"); - } - connection.setAutoCommit(desiredAutoCommit); - } - } catch (SQLException e) { - // Only a very poorly implemented driver would fail here, - // and there's not much we can do about that. - throw new TransactionException("Error configuring AutoCommit. " - + "Your driver may not support getAutoCommit() or setAutoCommit(). " - + "Requested setting: " + desiredAutoCommit + ". Cause: " + e, e); - } - } - - protected void resetAutoCommit() { - try { - if (!connection.getAutoCommit()) { - // MyBatis does not call commit/rollback on a connection if just selects were performed. - // Some databases start transactions with select statements - // and they mandate a commit/rollback before closing the connection. - // A workaround is setting the autocommit to true before closing the connection. - // Sybase throws an exception here. - if (log.isDebugEnabled()) { - log.debug("Resetting autocommit to true on JDBC Connection [" + connection + "]"); - } - connection.setAutoCommit(true); - } - } catch (SQLException e) { - if (log.isDebugEnabled()) { - log.debug("Error resetting autocommit to true " - + "before closing the connection. Cause: " + e); - } - } - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/tx/Transaction.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/tx/Transaction.java deleted file mode 100644 index 65baaf8e..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/tx/Transaction.java +++ /dev/null @@ -1,63 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.crisp.tx; - -import java.sql.Connection; -import java.sql.SQLException; - -/** - * @author: aoshiguchen - * @date: 2022/11/7 - */ -public interface Transaction { - - /** - * Retrieve inner database connection. - * @return DataBase connection - * @throws SQLException - */ - Connection getConnection() throws SQLException; - - /** - * Commit inner database connection. - * @throws SQLException - */ - void commit() throws SQLException; - - /** - * Rollback inner database connection. - * @throws SQLException - */ - void rollback() throws SQLException; - - /** - * Close inner database connection. - * @throws SQLException - */ - void close() throws SQLException; - - /** - * Get transaction timeout if set. - * @throws SQLException - */ - Integer getTimeout() throws SQLException; -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/tx/TransactionException.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/tx/TransactionException.java deleted file mode 100644 index 853fc704..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/tx/TransactionException.java +++ /dev/null @@ -1,19 +0,0 @@ -package fun.asgc.neutrino.core.db.crisp.tx; - -import fun.asgc.neutrino.core.db.crisp.JdbcException; - -/** - * @author: aoshiguchen - * @date: 2022/11/7 - */ -public class TransactionException extends JdbcException { - - public TransactionException(String message) { - super(message); - } - - public TransactionException(String message, Throwable cause) { - super(message, cause); - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/tx/TransactionIsolationLevel.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/tx/TransactionIsolationLevel.java deleted file mode 100644 index 78afa711..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/crisp/tx/TransactionIsolationLevel.java +++ /dev/null @@ -1,43 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.crisp.tx; - -import lombok.AllArgsConstructor; -import lombok.Getter; - -import java.sql.Connection; - -/** - * @author: aoshiguchen - * @date: 2022/11/4 - */ -@Getter -@AllArgsConstructor -public enum TransactionIsolationLevel { - NONE(Connection.TRANSACTION_NONE), - READ_COMMITTED(Connection.TRANSACTION_READ_COMMITTED), - READ_UNCOMMITTED(Connection.TRANSACTION_READ_UNCOMMITTED), - REPEATABLE_READ(Connection.TRANSACTION_REPEATABLE_READ), - SERIALIZABLE(Connection.TRANSACTION_SERIALIZABLE); - - private final int level; -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/dao/DBType.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/dao/DBType.java deleted file mode 100644 index 48877a54..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/dao/DBType.java +++ /dev/null @@ -1,58 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.dao; - -import lombok.AllArgsConstructor; -import lombok.Getter; - -import java.util.Map; -import java.util.function.Function; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/28 - */ -@Getter -@AllArgsConstructor -public enum DBType { - MYSQL(1, "mysql"), - SQL_SERVER(2, "sqserver"), - ORACLE(3, "oracle"), - SQL_LITE(4, "sqllite"), - MONGO(5, "mongodb"); - private static final Map typeMap = Stream.of(DBType.values()).collect(Collectors.toMap(DBType::getType, Function.identity())); - private static final Map nameMap = Stream.of(DBType.values()).collect(Collectors.toMap(DBType::getName, Function.identity())); - - private Integer type; - private String name; - - public static DBType byType(Integer type) { - return typeMap.get(type); - } - - public static DBType byName(String name) { - return nameMap.get(name); - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/dao/Dao.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/dao/Dao.java deleted file mode 100644 index f48e55d7..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/dao/Dao.java +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.dao; - -import java.io.Serializable; -import java.sql.SQLException; -import java.util.List; - -/** - * @author: aoshiguchen - * @date: 2022/6/28 - */ -public interface Dao { - - //==============================================新增===================== - - /** - * 新增单条记录 - * @param po - * @return - */ - T add(T po) throws SQLException; - - //==============================================修改===================== - - /** - * 更新单条记录 - * @param po - * @return - */ - int updateById(T po); - - /** - * 更新单条记录 - * @param po - * @param field - * @return - */ - int updateById(T po, String ...field); - - //==============================================删除===================== - - /** - * 根据id删除 - * @param id - * @return - */ - int deleteById(Serializable id); - - int delete(T po, String ...field); - - int delete(); - - //==============================================查询===================== - Long count() throws SQLException; - Long count(T po, String ...field) throws SQLException; - - T findOneById(Serializable id) throws SQLException; - T findOne(T po, String ...field) throws SQLException; - List find() throws SQLException; - List find(T po, String ...field) throws SQLException; - - List findPage(int beginNo, int pageSize); - List findPage(T po,int beginNo, int pageSize, String ...field); -} - diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/dao/DaoFactory.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/dao/DaoFactory.java deleted file mode 100644 index 9a9adb06..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/dao/DaoFactory.java +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.dao; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/28 - */ -public class DaoFactory { - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/dao/DefaultDaoImpl.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/dao/DefaultDaoImpl.java deleted file mode 100644 index d77bc405..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/dao/DefaultDaoImpl.java +++ /dev/null @@ -1,233 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.dao; - -import com.google.common.collect.Sets; -import fun.asgc.neutrino.core.cache.Cache; -import fun.asgc.neutrino.core.db.annotation.Id; -import fun.asgc.neutrino.core.db.template.DataSourceHolder; -import fun.asgc.neutrino.core.db.template.DbCache; -import fun.asgc.neutrino.core.db.template.JdbcTemplate; -import fun.asgc.neutrino.core.db.template.SqlAndParams; -import fun.asgc.neutrino.core.util.Assert; -import fun.asgc.neutrino.core.util.CollectionUtil; -import fun.asgc.neutrino.core.util.ReflectUtil; - -import javax.sql.DataSource; -import java.io.Serializable; -import java.lang.reflect.Field; -import java.sql.SQLException; -import java.util.*; - -/** - * TODO 暂时先实现一部分,需要放下来思考更好的方式 - * @author: aoshiguchen - * @date: 2022/6/28 - */ -public class DefaultDaoImpl implements Dao { - - /** - * 数据源持有者 - */ - private DataSourceHolder dataSourceHolder; - /** - * jdbc操作工具 - */ - private JdbcTemplate jdbcTemplate; - /** - * 实体类 - */ - private Class entryClass; - /** - * sql方言 - */ - private SqlDialect sqlDialect; - /** - * id字段 - */ - private Field idField; - /** - * id列名 - */ - private String idColumnName; - - public DefaultDaoImpl(DataSource dataSource, DBType dbType, Class entryClass) { - this(new DataSourceHolder(dataSource, dbType), entryClass); - } - - public DefaultDaoImpl(DataSourceHolder dataSourceHolder, Class entryClass) { - Assert.notNull(dataSourceHolder, "数据源持有者不能为空!"); - Assert.notNull(dataSourceHolder.getDbType(), "数据库类型不能为空!"); - Assert.notNull(entryClass, "实体类不能为空!"); - - this.dataSourceHolder = dataSourceHolder; - this.jdbcTemplate = new JdbcTemplate(this.dataSourceHolder); - this.entryClass = entryClass; - this.sqlDialect = SqlDialectFactory.getSqlDialect(this.dataSourceHolder.getDbType()); - this.idField = getIdField(this.entryClass); - Assert.notNull(idField, "实体类必须存在主键"); - this.idColumnName = DbCache.getColumnNameByField(idField); - } - - @Override - public T add(T po) throws SQLException { - SqlAndParams sqlAndParams = this.sqlDialect.add(po); - jdbcTemplate.update(sqlAndParams.getSql()); - Serializable idValue = getIdValue(po); - if (null != idValue) { - return findOneById(idValue); - } - return null; - } - - @Override - public int delete(T po, String... field) { - return 0; - } - - @Override - public int delete() { - return 0; - } - - @Override - public Long count() throws SQLException { - SqlAndParams sqlAndParams = this.sqlDialect.count(entryClass, null); - return jdbcTemplate.queryForLong(sqlAndParams.getSql(), sqlAndParams.getParamArray()); - } - - @Override - public Long count(T po, String... field) throws SQLException { - Set filter = Sets.newHashSet(field); - Cache fieldCache = DbCache.getFieldCache(entryClass); - SqlAndParams sqlAndParams = this.sqlDialect.count(entryClass, new LinkedHashMap(){ - { - for (Field item : fieldCache.keySet()) { - if (!filter.isEmpty() && !filter.contains(item.getName())) { - continue; - } - this.put(fieldCache.get(item), ReflectUtil.getFieldValue(item, po)); - } - } - }); - return jdbcTemplate.queryForLong(sqlAndParams.getSql(), sqlAndParams.getParamArray()); - } - - @Override - public T findOneById(Serializable id) throws SQLException { - SqlAndParams sqlAndParams = this.sqlDialect.find(entryClass, new LinkedHashMap(){ - { - this.put(idColumnName, id); - } - }); - return jdbcTemplate.query(entryClass, sqlAndParams); - } - - @Override - public T findOne(T po, String... field) throws SQLException { - Set filter = Sets.newHashSet(field); - Cache fieldCache = DbCache.getFieldCache(entryClass); - SqlAndParams sqlAndParams = this.sqlDialect.find(entryClass, new LinkedHashMap(){ - { - for (Field item : fieldCache.keySet()) { - if (!filter.isEmpty() && !filter.contains(item.getName())) { - continue; - } - this.put(fieldCache.get(item), ReflectUtil.getFieldValue(item, po)); - } - } - }); - return jdbcTemplate.query(entryClass, sqlAndParams); - } - - @Override - public List find() throws SQLException { - SqlAndParams sqlAndParams = this.sqlDialect.find(entryClass, null); - return jdbcTemplate.queryForList(entryClass, sqlAndParams); - } - - @Override - public List find(T po, String... field) throws SQLException { - Set filter = Sets.newHashSet(field); - Cache fieldCache = DbCache.getFieldCache(entryClass); - SqlAndParams sqlAndParams = this.sqlDialect.find(entryClass, new LinkedHashMap(){ - { - for (Field item : fieldCache.keySet()) { - if (!filter.isEmpty() && !filter.contains(item.getName())) { - continue; - } - this.put(fieldCache.get(item), ReflectUtil.getFieldValue(item, po)); - } - } - }); - return jdbcTemplate.queryForList(entryClass, sqlAndParams); - } - - @Override - public List findPage(int beginNo, int pageSize) { - return null; - } - - @Override - public int updateById(T po) { - return 0; - } - - @Override - public int updateById(T po, String... field) { - return 0; - } - - @Override - public int deleteById(Serializable id) { - return 0; - } - - @Override - public List findPage(T po, int beginNo, int pageSize, String... field) { - return null; - } - - private V getIdValue(Object obj) { - if (null == obj) { - return null; - } - return (V)ReflectUtil.getFieldValue(idField, obj); - } - - private static Field getIdField(Class clazz) { - List fieldList = DbCache.getFieldList(clazz); - if (CollectionUtil.isEmpty(fieldList)) { - return null; - } - Field res = null; - for (Field field : fieldList) { - if (field.isAnnotationPresent(Id.class)) { - return field; - } - if (field.getName().equals("id")) { - res = field; - } - } - return res; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/dao/SqlDialect.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/dao/SqlDialect.java deleted file mode 100644 index ccff894a..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/dao/SqlDialect.java +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.dao; - -import fun.asgc.neutrino.core.db.template.SqlAndParams; - -import java.util.LinkedHashMap; - -/** - * sql方言,用于屏蔽各种不同的数据库的sql差异 - * @author: aoshiguchen - * @date: 2022/6/27 - */ -public interface SqlDialect { - /** - * 新增单条记录 - * @param obj - * @return - */ - SqlAndParams add(Object obj); - - /** - * 查询单条记录 - * @return - */ - SqlAndParams find(Class clazz, LinkedHashMap params); - - /** - * 查询数据条数 - * @param clazz - * @param params - * @return - */ - SqlAndParams count(Class clazz, LinkedHashMap params); -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/dao/SqlDialectFactory.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/dao/SqlDialectFactory.java deleted file mode 100644 index 269f0215..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/dao/SqlDialectFactory.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.dao; - -import fun.asgc.neutrino.core.util.Assert; - -/** - * sql方言工厂 TODO 暂时只支持mysql - * @author: aoshiguchen - * @date: 2022/6/28 - */ -public class SqlDialectFactory { - private static final SqlDialect mysql = new SqlDialectForMysql(); - - public static SqlDialect getSqlDialect(DBType dbType) { - Assert.notNull(dbType, "数据库类型不能为空!"); - switch (dbType) { - case MYSQL: return mysql; - default: { - throw new RuntimeException("不支持的数据库类型!"); - } - } - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/dao/SqlDialectForMysql.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/dao/SqlDialectForMysql.java deleted file mode 100644 index 639365cd..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/dao/SqlDialectForMysql.java +++ /dev/null @@ -1,245 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.dao; - -import fun.asgc.neutrino.core.cache.Cache; -import fun.asgc.neutrino.core.db.template.DbCache; -import fun.asgc.neutrino.core.db.template.SqlAndParams; -import fun.asgc.neutrino.core.util.*; - -import java.lang.reflect.Field; -import java.util.*; -import java.util.stream.Collectors; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/28 - */ -public class SqlDialectForMysql implements SqlDialect { - private static final String TEMPLATE_FIND = "select * from `${tableName}` ${where}"; - private static final String TEMPLATE_COUNT = "select count(*) from `${tableName}` ${where}"; - private static final String TEMPLATE_LIMIT = "limit ${offset},${size}"; - private static final String TEMPLATE_INSERT = "insert into `${tableName}`(${columns}) values ${values}"; - private static final String TEMPLATE_UPDATE = "update `${tableName}` ${set} ${where}`"; - private static final String TEMPLATE_DELETE = "delete from `${tableName}` ${where}"; - - @Override - public SqlAndParams add(Object obj) { - LinkedHashMap params = getParams(obj); - Set filterColumns = params.keySet(); - String sql = templateProcess(TEMPLATE_INSERT, new HashMap(){ - { - this.put("tableName", getTableName(obj)); - this.put("columns", buildSqlColumns(filterColumns)); - this.put("values", getSqlValue(filterColumns, params)); - } - }); - return new SqlAndParams(sql); - } - - @Override - public SqlAndParams find(Class clazz, LinkedHashMap params) { - String sql = templateProcess(TEMPLATE_FIND, new HashMap(){ - { - this.put("tableName", getTableName(clazz)); - this.put("where", buildSqlWhere(null, params)); - } - }); - return new SqlAndParams(sql, params); - } - - @Override - public SqlAndParams count(Class clazz, LinkedHashMap params) { - String sql = templateProcess(TEMPLATE_COUNT, new HashMap(){ - { - this.put("tableName", getTableName(clazz)); - this.put("where", buildSqlWhere(null, params)); - } - }); - return new SqlAndParams(sql, params); - } - - /** - * 获取表名 - * @param obj - * @return - */ - private static String getTableName(Object obj) { - Assert.notNull(obj, "对象不能为空!"); - return DbCache.toTableName(obj.getClass()); - } - - /** - * 获取表名 - * @param clazz - * @return - */ - private static String getTableName(Class clazz) { - Assert.notNull(clazz, "类不能为空!"); - return DbCache.toTableName(clazz); - } - - /** - * 获取参数 - * @param obj - * @return - */ - private static LinkedHashMap getParams(Object obj) { - return getParams(obj, null); - } - - /** - * 获取参数 - * @param obj - * @return - */ - private static LinkedHashMap getParams(Object obj, Set excludeFieldName) { - Assert.notNull(obj, "对象不能为空!"); - Cache cache = DbCache.getFieldCache(obj.getClass()); - LinkedHashMap params = new LinkedHashMap<>(); - if (null == cache || cache.isEmpty()) { - return params; - } - Set tmp = new HashSet<>(); - for (Field field : cache.keySet()) { - String column = cache.get(field); - if (tmp.contains(column)) { - continue; - } - if (CollectionUtil.notEmpty(excludeFieldName) && excludeFieldName.contains(field.getName())) { - continue; - } - tmp.add(column); - Object value = ReflectUtil.getFieldValue(field, obj); - params.put(column, value); - } - return params; - } - - /** - * 拼接where条件 - * @param filterColumns - * @return - */ - private static String buildSqlWhere(Set filterColumns, LinkedHashMap params) { - List sql = new ArrayList<>(); - if (CollectionUtil.isEmpty(params)) { - return ""; - } - for (String column : params.keySet()) { - if (null != filterColumns && !filterColumns.contains(column)) { - continue; - } - Object value = params.get(column); - if (null == value) { - sql.add(String.format("`%s` is null", column)); - } else { - sql.add(String.format("`%s` = :%s", column, column)); - } - } - if (sql.isEmpty()) { - return ""; - } - return "where " + sql.stream().collect(Collectors.joining(" and ")); - } - - /** - * 拼接sql设置值的部分 - * @param filterColumns - * @param params - * @return - */ - private static String buildSqlSet(Set filterColumns, LinkedHashMap params) { - List sql = new ArrayList<>(); - if (CollectionUtil.isEmpty(filterColumns)) { - return ""; - } - for (String column : filterColumns) { - Object value = params.get(column); - if (null == value) { - sql.add(String.format("`%s` = null")); - } else { - sql.add(String.format("%s = :%s", column, column)); - } - } - if (sql.isEmpty()) { - return ""; - } - return "set " + sql.stream().collect(Collectors.joining(",")); - } - - /** - * 拼接字段 - * @param filterColumns - * @return - */ - private static String buildSqlColumns(Set filterColumns) { - return filterColumns.stream().map(s -> String.format("`%s`", s)).collect(Collectors.joining(",")); - } - - /** - * 值处理 - * @param value - * @return - */ - private static String sqlValueProcess(Object value) { - if (null == value) { - return "null"; - } else if (value instanceof Date) { - return String.format("'%s'", DateUtil.format((Date)value, "yyyy-MM-dd HH:mm:ss")); - } - String res = String.valueOf(value).replaceAll("'", "\\\\\\\\'"); - - return "'" + res + "'"; - } - - /** - * 获取values后面的sql语句 - * @param filterColumns - * @param params - * @return - */ - private static String getSqlValue(Set filterColumns, LinkedHashMap params) { - List list = new ArrayList<>(); - for (String column : filterColumns) { - list.add(sqlValueProcess(params.get(column))); - } - return "(" + list.stream().collect(Collectors.joining(",")) + ")"; - } - - /** - * sql模板处理 - * @param template - * @param params - * @return - */ - private static String templateProcess(String template, Map params) { - if (StringUtil.isEmpty(template) || CollectionUtil.isEmpty(params)) { - return template; - } - for (String key : params.keySet()) { - template = template.replaceAll(String.format("\\$\\{%s\\}", key), params.get(key)); - } - return template; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/mapper/SqlMapper.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/mapper/SqlMapper.java deleted file mode 100644 index c3552724..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/mapper/SqlMapper.java +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.mapper; - -import fun.asgc.neutrino.core.aop.Intercept; - -/** - * @author: aoshiguchen - * @date: 2022/6/28 - */ -@Intercept(SqlMapperInterceptor.class) -public interface SqlMapper { - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/mapper/SqlMapperInterceptor.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/mapper/SqlMapperInterceptor.java deleted file mode 100644 index 75aa296d..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/mapper/SqlMapperInterceptor.java +++ /dev/null @@ -1,135 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.mapper; - -import fun.asgc.neutrino.core.annotation.Component; -import fun.asgc.neutrino.core.annotation.NonIntercept; -import fun.asgc.neutrino.core.annotation.Param; -import fun.asgc.neutrino.core.aop.Invocation; -import fun.asgc.neutrino.core.aop.interceptor.Interceptor; -import fun.asgc.neutrino.core.db.page.PageInfo; -import fun.asgc.neutrino.core.db.template.JdbcTemplate; -import fun.asgc.neutrino.core.util.*; - -import java.lang.reflect.Parameter; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * sqlmapper拦截器 - * @author: aoshiguchen - * @date: 2022/6/28 - */ -@NonIntercept -@Component -public class SqlMapperInterceptor implements Interceptor { - @Override - public void intercept(Invocation inv) throws Exception { - JdbcTemplate jdbcTemplate = BeanManager.getBean(JdbcTemplate.class); - Assert.notNull(jdbcTemplate, "JdbcTemplate未注入,调用失败!"); - SqlParser sqlParser = SqlParser.getInstance(inv.getTargetMethod()); - if (null == sqlParser) { - return; - } - - String sql = sqlParser.getSql(); - Class resultType = sqlParser.getResultType(); - Class resultComponentType = sqlParser.getResultComponentType(); - Object res = null; - if (sqlParser.isSelect()) { - if (sqlParser.isReturnCollection()) { - Object params = getParams(inv); - if (null == params || params.getClass().isArray()) { - res = jdbcTemplate.queryForList(resultComponentType, sql, inv.getArgs()); - } else { - res = jdbcTemplate.queryForListByMap(resultComponentType, sql, (Map)params); - } - } else { - if (PageInfo.class.isAssignableFrom(inv.getTargetMethod().getParameters()[0].getType())) { - // 分页查询 TODO 此处暂时临时处理,假设后面的参数是一个DO对象 - PageInfo pageInfo = (PageInfo) inv.getArgs()[0]; - int offset = (pageInfo.getCurrent() - 1) * pageInfo.getSize(); - long total = jdbcTemplate.queryForLongByModel(String.format("select count(1) from (%s) T", sql), inv.getArgs()[1]); - List resultList = jdbcTemplate.queryForListByModel(resultComponentType, String.format("%s limit %s,%s", sql, offset, pageInfo.getSize()), inv.getArgs()[1]); - pageInfo.setTotal(total); - pageInfo.setRecords(resultList); - } else { - Object params = getParams(inv); - if (null == params || params.getClass().isArray()) { - res = jdbcTemplate.query(resultType, sql, inv.getArgs()); - } else { - res = jdbcTemplate.queryByMap(resultType, sql, (Map)params); - } - } - } - } else if (sqlParser.isInsert() || sqlParser.isDelete() || sqlParser.isUpdate()) { - int argsCount = ArrayUtil.isEmpty(inv.getArgs()) ? 0 : inv.getArgs().length; - if (argsCount == 1 && inv.getArgs()[0] instanceof Map) { - res = jdbcTemplate.updateByMap(sql, (Map)inv.getArgs()[0]); - // 临时解决只有一个参数,且参数类型不是实体类型时,参数未起作用的情况 - } else if (argsCount == 1 && !TypeUtil.isNormalBasicType(inv.getArgs()[0].getClass()) && !(inv.getArgs()[0] instanceof Date)) { - res = jdbcTemplate.updateByModel(sql, inv.getArgs()[0]); - } else { - Object params = getParams(inv); - if (null == params) { - res = jdbcTemplate.update(sql); - } else if (params.getClass().isArray()){ - res = jdbcTemplate.update(sql, (Object[])params); - } else if (params instanceof Map) { - res = jdbcTemplate.updateByMap(sql, (Map)params); - } - } - } - inv.setReturnValue(TypeUtil.conversion(res, resultType)); - } - - /** - * 获取请求参数 - * @param inv - * @return - */ - private Object getParams(Invocation inv) { - if (inv.getTargetMethod().getParameterCount() == 0) { - return null; - } - if (!inv.getTargetMethod().getParameters()[0].isAnnotationPresent(Param.class)) { - return inv.getArgs(); - } - Map params = new HashMap<>(); - for (int i = 0; i < inv.getTargetMethod().getParameterCount(); i++) { - Parameter parameter = inv.getTargetMethod().getParameters()[i]; - Param param = parameter.getAnnotation(Param.class); - if (null == param) { - continue; - } - String key = param.value(); - Object val = inv.getArgs()[i]; - if (!StringUtil.isEmpty(key)) { - params.put(key, val); - } - - } - return params; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/mapper/SqlOperatorType.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/mapper/SqlOperatorType.java deleted file mode 100644 index 35b0ef57..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/mapper/SqlOperatorType.java +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.mapper; - -/** - * sql操作类型 - * @author: aoshiguchen - * @date: 2022/8/3 - */ -public enum SqlOperatorType { - SELECT,DELETE,UPDATE,INSERT -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/mapper/SqlParser.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/mapper/SqlParser.java deleted file mode 100644 index 72f49390..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/mapper/SqlParser.java +++ /dev/null @@ -1,216 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.mapper; - -import fun.asgc.neutrino.core.base.GlobalConfig; -import fun.asgc.neutrino.core.cache.Cache; -import fun.asgc.neutrino.core.cache.MemoryCache; -import fun.asgc.neutrino.core.constant.MetaDataConstant; -import fun.asgc.neutrino.core.db.annotation.*; -import fun.asgc.neutrino.core.util.CollectionUtil; -import fun.asgc.neutrino.core.util.FileUtil; -import fun.asgc.neutrino.core.util.LockUtil; -import fun.asgc.neutrino.core.util.StringUtil; -import lombok.Data; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.dom4j.Document; -import org.dom4j.Element; -import org.dom4j.io.SAXReader; - -import java.io.StringReader; -import java.lang.reflect.Method; -import java.util.Collection; -import java.util.Optional; - -/** - * sql解析器 - * @author: aoshiguchen - * @date: 2022/8/3 - */ -@Data -@Slf4j -public class SqlParser { - /** - * sqlParser实例缓存 - */ - private static final Cache sqlParserCache = new MemoryCache<>(); - /** - * 目标执行方法 - */ - private Method targetMethod; - /** - * 操作类型 - */ - private SqlOperatorType operatorType; - /** - * 结果类型 - */ - private Class resultType; - /** - * 返回结果组成类型(集合类型的子类型) - */ - private Class resultComponentType; - /** - * 目标方法签名 - */ - private String targetMethodSign; - /** - * 返回数据是否是集合类型 - */ - private boolean isReturnCollection; - /** - * sql语句 - */ - private String sql; - - private SqlParser(Method targetMethod) { - this.targetMethod = targetMethod; - this.resultType = targetMethod.getReturnType(); - this.targetMethodSign = String.format("%s#%s", targetMethod.getDeclaringClass().getName(), targetMethod.getName()); - this.initByAnnotation(); - this.initByXml(); - if (StringUtil.isEmpty(sql)) { - throw new RuntimeException(String.format("%s sql不能为空!", targetMethodSign)); - } - } - - /** - * 根据注解进行初始化 - */ - private void initByAnnotation() { - if (!StringUtil.isEmpty(this.sql)) { - return; - } - ResultType resultType = targetMethod.getAnnotation(ResultType.class); - Class resultClass = (null == resultType) ? null : resultType.value(); - this.resultComponentType = resultClass; - - if (targetMethod.isAnnotationPresent(Select.class)) { - // 查询 - this.operatorType = SqlOperatorType.SELECT; - Select select = targetMethod.getAnnotation(Select.class); - this.sql = select.value(); - if (StringUtil.isEmpty(sql)) { - throw new RuntimeException(String.format("%s sql不能为空!", targetMethodSign)); - } - this.isReturnCollection = Collection.class.isAssignableFrom(targetMethod.getReturnType()); - if (isReturnCollection && null == resultClass) { - throw new RuntimeException(String.format("%s 请指名实体类型!", targetMethodSign)); - } - } else if (targetMethod.isAnnotationPresent(Insert.class)) { - // 新增 - this.operatorType = SqlOperatorType.INSERT; - Insert insert = targetMethod.getAnnotation(Insert.class); - this.sql = insert.value(); - if (StringUtil.isEmpty(sql)) { - throw new RuntimeException(String.format("%s sql不能为空!", targetMethodSign)); - } - } else if (targetMethod.isAnnotationPresent(Delete.class)) { - // 删除 - this.operatorType = SqlOperatorType.DELETE; - Delete delete = targetMethod.getAnnotation(Delete.class); - this.sql = delete.value(); - if (StringUtil.isEmpty(sql)) { - throw new RuntimeException(String.format("%s sql不能为空!", targetMethodSign)); - } - } else if (targetMethod.isAnnotationPresent(Update.class)) { - // 更新 - this.operatorType = SqlOperatorType.UPDATE; - Update update = targetMethod.getAnnotation(Update.class); - this.sql = update.value(); - if (StringUtil.isEmpty(sql)) { - throw new RuntimeException(String.format("%s sql不能为空!", targetMethodSign)); - } - } - } - - /** - * 根据xml文件进行初始化 - */ - private void initByXml() { -// if (!StringUtil.isEmpty(this.sql)) { -// return; -// } - String xmlPath = String.format("%s/%s.xml", GlobalConfig.getMapperXmlFileBasePath(), this.targetMethod.getDeclaringClass().getSimpleName()); - String xmlStr = FileUtil.readContentAsString(xmlPath); - if (StringUtil.isEmpty(xmlStr)) { - return; - } - try { - SAXReader saxReader = new SAXReader(); - Document document = saxReader.read(new StringReader(xmlStr)); - Element rootElement = document.getRootElement(); - if (CollectionUtil.isEmpty(rootElement.elements())) { - return; - } - Optional optionalElement = rootElement.elements().stream().filter(e -> e.attributeValue("id").equals(targetMethod.getName())).findFirst(); - if (!optionalElement.isPresent()) { - return; - } - Element element = optionalElement.get(); - this.sql = element.getText().replaceAll("\n", "").replaceAll( " ", " "); - if (element.getName().equals("select")) { - this.operatorType = SqlOperatorType.SELECT; - } else if (element.getName().equals("update")) { - this.operatorType = SqlOperatorType.UPDATE; - } else if (element.getName().equals("delete")) { - this.operatorType = SqlOperatorType.DELETE; - } else if (element.getName().equals("insert")) { - this.operatorType = SqlOperatorType.INSERT; - } - if (!StringUtil.isEmpty(element.attributeValue("resultType"))) { - this.resultComponentType = Class.forName(element.attributeValue("resultType")); - } - if (StringUtil.isEmpty(sql)) { - throw new RuntimeException(String.format("%s sql不能为空!", targetMethodSign)); - } - } catch (Exception e) { - throw new RuntimeException(String.format("Mapper文件[%s]异常! %s", xmlPath, e.getMessage())); - } - } - - public static SqlParser getInstance(Method targetMethod) throws Exception { - return LockUtil.doubleCheckProcess( - () -> !sqlParserCache.containsKey(targetMethod), - targetMethod, - () -> sqlParserCache.set(targetMethod, new SqlParser(targetMethod)), - () -> sqlParserCache.get(targetMethod) - ); - } - - public boolean isSelect() { - return this.operatorType == SqlOperatorType.SELECT; - } - - public boolean isUpdate() { - return this.operatorType == SqlOperatorType.UPDATE; - } - - public boolean isDelete() { - return this.operatorType == SqlOperatorType.DELETE; - } - - public boolean isInsert() { - return this.operatorType == SqlOperatorType.INSERT; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/page/PageInfo.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/page/PageInfo.java deleted file mode 100644 index 7cfb80bf..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/page/PageInfo.java +++ /dev/null @@ -1,123 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.page; - -import lombok.Data; - -import java.io.Serializable; -import java.util.Collections; -import java.util.List; - -/** - * - * @author: aoshiguchen - * @date: 2022/8/6 - */ -@Data -public class PageInfo implements Serializable { - private static final long serialVersionUID = 8545996863226528797L; - private List records; - private Long total; - private Integer size; - private Integer current; - - public PageInfo() { - this.records = Collections.emptyList(); - this.total = 0L; - this.size = 10; - this.current = 1; - } - - public PageInfo(Integer current, Integer size) { - this(current, size, 0L); - } - - public PageInfo(Integer current, Integer size, Long total) { - this.records = Collections.emptyList(); - this.total = 0L; - this.size = 10; - this.current = 1; - if ((long)current > 1L) { - this.current = current; - } - - this.size = size; - this.total = total; - } - - public Long getPages() { - if ((long)this.getSize() == 0L) { - return 0L; - } else { - Long pages = this.getTotal() / (long)this.getSize(); - if (this.getTotal() % (long)this.getSize() != 0L) { - pages = pages + 1L; - } - - return pages; - } - } - - public Long getTotal() { - return this.total; - } - - public Integer getSize() { - return this.size; - } - - public boolean hasPrevious() { - return (long)this.current > 1L; - } - - public boolean hasNext() { - return (long)this.current < this.getPages(); - } - - public List getRecords() { - return this.records; - } - - public PageInfo setRecords(List records) { - this.records = records; - return this; - } - - public PageInfo setTotal(Long total) { - this.total = total; - return this; - } - - public PageInfo setSize(Integer size) { - this.size = size; - return this; - } - - public Integer getCurrent() { - return this.current; - } - - public PageInfo setCurrent(Integer current) { - this.current = current; - return this; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/page/PageQuery.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/page/PageQuery.java deleted file mode 100644 index c00288bc..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/page/PageQuery.java +++ /dev/null @@ -1,43 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.page; - -import lombok.Data; - -import java.io.Serializable; - -/** - * - * @author: aoshiguchen - * @date: 2022/8/6 - */ -@Data -public class PageQuery implements Serializable { - /** - * 当前页 - */ - private int current = 1; - /** - * 分页大小 - */ - private int size = 10; -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/template/DataSourceHolder.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/template/DataSourceHolder.java deleted file mode 100644 index dbcc95a9..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/template/DataSourceHolder.java +++ /dev/null @@ -1,86 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.template; - -import fun.asgc.neutrino.core.db.dao.DBType; - -import javax.sql.DataSource; -import java.sql.Connection; -import java.sql.SQLException; - -/** - * 数据源持有者 - * @author: aoshiguchen - * @date: 2022/6/28 - */ -public class DataSourceHolder { - /** - * 数据源 - */ - private DataSource dataSource; - /** - * 是否保持连接 - * 默认执行完SQL操作就归还连接 - * 在开启事务的情况下,事务操作完毕才能归还 - */ - private ThreadLocal keepConnectionCache = new ThreadLocal<>(); - /** - * 数据库类型 - */ - private DBType dbType; - - public DataSourceHolder(DataSource dataSource) { - this.dataSource = dataSource; - } - - public DataSourceHolder(DataSource dataSource, DBType dbType) { - this.dataSource = dataSource; - this.dbType = dbType; - } - - public Connection getConnection() throws SQLException { - return this.dataSource.getConnection(); - } - - public void close(Connection conn) throws SQLException { - conn.close(); - } - - public void tryClose(Connection conn) throws SQLException { - Boolean keepConnection = keepConnectionCache.get(); - if (null == keepConnection || !keepConnection) { - conn.close(); - } - } - - public void setKeepConnection(Boolean keepConnection) { - this.keepConnectionCache.set(keepConnection); - } - - public DBType getDbType() { - return dbType; - } - - public void setDbType(DBType dbType) { - this.dbType = dbType; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/template/DbCache.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/template/DbCache.java deleted file mode 100644 index 14d5f09f..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/template/DbCache.java +++ /dev/null @@ -1,281 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.template; - -import com.google.common.collect.Lists; -import fun.asgc.neutrino.core.cache.Cache; -import fun.asgc.neutrino.core.cache.MemoryCache; -import fun.asgc.neutrino.core.cache.MemoryCacheGroup; -import fun.asgc.neutrino.core.db.annotation.Column; -import fun.asgc.neutrino.core.db.annotation.NotColumn; -import fun.asgc.neutrino.core.db.annotation.Table; -import fun.asgc.neutrino.core.util.*; - -import java.lang.reflect.Field; -import java.util.List; -import java.util.Set; - -/** - * 数据库相关缓存 - * @author: aoshiguchen - * @date: 2022/6/27 - */ -public class DbCache { - /** - * 名称映射缓存组 - */ - private static final MemoryCacheGroup nameMappingCache = new MemoryCacheGroup<>(); - private static final String GROUP_COLUMN_NAME_TO = "GROUP_COLUMN_NAME_TO"; - private static final String GROUP_COLUMN_NAME_FROM = "GROUP_COLUMN_NAME_FROM"; - private static final String GROUP_TABLE_NAME_TO = "GROUP_TABLE_NAME_TO"; - private static final String GROUP_TABLE_NAME_FROM = "GROUP_TABLE_NAME_FROM"; - private static final Cache, Cache> fieldToColumnCache = new MemoryCache<>(); - private static final Object fieldToColumnCacheLock = new Object(); - private static final Cache,String> classTableNameCache = new MemoryCache<>(); - - /** - * 转换为列名 - * @param s - * @return - */ - public static String toColumnName(String s) { - try { - return LockUtil.doubleCheckProcess( - () -> !nameMappingCache.containsKey(GROUP_COLUMN_NAME_TO, s), - GROUP_COLUMN_NAME_TO, - () -> nameMappingCache.set(GROUP_COLUMN_NAME_TO, s, DefaultColumnNameConvert.getInstance().to(s)), - () -> nameMappingCache.get(GROUP_COLUMN_NAME_TO, s) - ); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - /** - * 转换为字段名 - * @param s - * @return - */ - public static String fromColumnName(String s) { - try { - return LockUtil.doubleCheckProcess( - () -> !nameMappingCache.containsKey(GROUP_COLUMN_NAME_FROM, s), - GROUP_COLUMN_NAME_FROM, - () -> nameMappingCache.set(GROUP_COLUMN_NAME_FROM, s, DefaultColumnNameConvert.getInstance().from(s)), - () -> nameMappingCache.get(GROUP_COLUMN_NAME_FROM, s) - ); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - /** - * 转换为表名 - * @param s - * @return - */ - public static String toTableName(String s) { - try { - return LockUtil.doubleCheckProcess( - () -> !nameMappingCache.containsKey(GROUP_TABLE_NAME_TO, s), - GROUP_TABLE_NAME_TO, - () -> nameMappingCache.set(GROUP_TABLE_NAME_TO, s, DefaultTableNameConvert.getInstance().to(s)), - () -> nameMappingCache.get(GROUP_TABLE_NAME_TO, s) - ); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - /** - * 转换为表名 - * @param clazz - * @return - */ - public static String toTableName(Class clazz) { - try { - return LockUtil.doubleCheckProcess(() -> !classTableNameCache.containsKey(clazz), - clazz, - () -> { - Table table = clazz.getAnnotation(Table.class); - String tableName; - if (null != table && StringUtil.notEmpty(table.value())) { - tableName = table.value(); - } else { - tableName = toTableName(TypeUtil.getSimpleName(clazz)); - } - classTableNameCache.set(clazz, tableName); - }, - () -> classTableNameCache.get(clazz) - ); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - /** - * 转换为实体名 - * @param s - * @return - */ - public static String fromTableName(String s) { - try { - return LockUtil.doubleCheckProcess( - () -> !nameMappingCache.containsKey(GROUP_TABLE_NAME_FROM, s), - GROUP_TABLE_NAME_FROM, - () -> nameMappingCache.set(GROUP_TABLE_NAME_FROM, s, DefaultTableNameConvert.getInstance().from(s)), - () -> nameMappingCache.get(GROUP_TABLE_NAME_FROM, s) - ); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - /** - * 根据类+列名获取字段 - * @param clazz - * @param column - * @return - */ - public static List getField(Class clazz, String column) { - try { - return LockUtil.doubleCheckProcess( - () -> !fieldToColumnCache.containsKey(clazz), - fieldToColumnCacheLock, - () -> initFieldCache(clazz), - () -> { - List list = Lists.newArrayList(); - Cache cache = fieldToColumnCache.get(clazz); - if (null == cache || cache.isEmpty()) { - return list; - } - for (Field field : cache.keySet()) { - if (cache.get(field).equals(column)) { - list.add(field); - } - } - - return list; - } - ); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - /** - * 根据类名获取列名列表 - * @param clazz - * @return - */ - public static List getFieldList(Class clazz) { - try { - return LockUtil.doubleCheckProcess( - () -> !fieldToColumnCache.containsKey(clazz), - fieldToColumnCacheLock, - () -> initFieldCache(clazz), - () -> { - List list = Lists.newArrayList(); - Cache cache = fieldToColumnCache.get(clazz); - if (null == cache || cache.isEmpty()) { - return list; - } - list.addAll(cache.keySet()); - return list; - } - ); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - /** - * 根据类获取字段缓存 - * @param clazz - * @return - */ - public static Cache getFieldCache(Class clazz) { - try { - return LockUtil.doubleCheckProcess( - () -> !fieldToColumnCache.containsKey(clazz), - clazz, - () -> initFieldCache(clazz), - () -> fieldToColumnCache.get(clazz) - ); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - public static String getColumnNameByField(Field field) { - try { - return LockUtil.doubleCheckProcess( - () -> !fieldToColumnCache.containsKey(field.getDeclaringClass()), - fieldToColumnCacheLock, - () -> initFieldCache(field.getDeclaringClass()), - () -> { - if (!fieldToColumnCache.containsKey(field.getDeclaringClass()) || !fieldToColumnCache.get(field.getDeclaringClass()).containsKey(field)) { - return null; - } - return fieldToColumnCache.get(field.getDeclaringClass()).get(field); - } - ); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - /** - * 初始化字段缓存 - * @param clazz - */ - private static void initFieldCache(Class clazz) { - Set fieldSet = ReflectUtil.getDeclaredFields(clazz); - if (CollectionUtil.isEmpty(fieldSet)) { - return; - } - Cache cache = new MemoryCache<>(); - fieldSet.forEach(field -> { - if (field.isAnnotationPresent(NotColumn.class)) { - return; - } - Column column = field.getAnnotation(Column.class); - if (null != column && StringUtil.notEmpty(column.value())) { - cache.set(field, column.value()); - } else { - cache.set(field, toColumnName(field.getName())); - } - - }); - - fieldToColumnCache.set(clazz, cache); - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/template/DefaultColumnNameConvert.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/template/DefaultColumnNameConvert.java deleted file mode 100644 index 4a7cb70f..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/template/DefaultColumnNameConvert.java +++ /dev/null @@ -1,89 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.template; - -import fun.asgc.neutrino.core.base.Convert; -import fun.asgc.neutrino.core.util.StringUtil; - -/** - * 默认的列名转换器转换器 - * 代码 -> DB - * @author: aoshiguchen - * @date: 2022/6/27 - */ -public class DefaultColumnNameConvert implements Convert { - private static final DefaultColumnNameConvert instance = new DefaultColumnNameConvert(); - private static final char SEPARATOR = '_'; - - private DefaultColumnNameConvert() { - - } - - public static DefaultColumnNameConvert getInstance() { - return instance; - } - - @Override - public String from(String target) { - if (StringUtil.isEmpty(target)) { - return ""; - } - boolean flag = false; - StringBuilder sb = new StringBuilder(target.length()); - for (char c : target.toCharArray()) { - if (SEPARATOR == c) { - flag = true; - } else { - if (flag) { - sb.append(Character.toUpperCase(c)); - flag = false; - } else { - sb.append(c); - } - } - } - return sb.toString(); - } - - @Override - public String to(String source) { - if (StringUtil.isEmpty(source)) { - return ""; - } - boolean flag = true; - StringBuilder sb = new StringBuilder(source.length()); - for (char c : source.toCharArray()) { - if (flag) { - sb.append(Character.toLowerCase(c)); - flag = false; - } else { - if (Character.isUpperCase(c)) { - sb.append(SEPARATOR); - sb.append(Character.toLowerCase(c)); - } else { - sb.append(c); - } - } - } - return sb.toString(); - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/template/DefaultTableNameConvert.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/template/DefaultTableNameConvert.java deleted file mode 100644 index 026592dd..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/template/DefaultTableNameConvert.java +++ /dev/null @@ -1,88 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.template; - -import fun.asgc.neutrino.core.base.Convert; -import fun.asgc.neutrino.core.util.StringUtil; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/27 - */ -public class DefaultTableNameConvert implements Convert { - private static final DefaultTableNameConvert instance = new DefaultTableNameConvert(); - private static final char SEPARATOR = '_'; - - private DefaultTableNameConvert() { - - } - - public static DefaultTableNameConvert getInstance() { - return instance; - } - - @Override - public String from(String target) { - if (StringUtil.isEmpty(target)) { - return ""; - } - boolean flag = true; - StringBuilder sb = new StringBuilder(target.length()); - for (char c : target.toCharArray()) { - if (SEPARATOR == c) { - flag = true; - } else { - if (flag) { - sb.append(Character.toUpperCase(c)); - flag = false; - } else { - sb.append(c); - } - } - } - return sb.toString(); - } - - @Override - public String to(String source) { - if (StringUtil.isEmpty(source)) { - return ""; - } - boolean flag = true; - StringBuilder sb = new StringBuilder(source.length()); - for (char c : source.toCharArray()) { - if (flag) { - sb.append(Character.toLowerCase(c)); - flag = false; - } else { - if (Character.isUpperCase(c)) { - sb.append(SEPARATOR); - sb.append(Character.toLowerCase(c)); - } else { - sb.append(c); - } - } - } - return sb.toString(); - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/template/JdbcCallback.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/template/JdbcCallback.java deleted file mode 100644 index 341687eb..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/template/JdbcCallback.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.template; - -import java.sql.SQLException; - -/** - * @author: aoshiguchen - * @date: 2022/6/27 - */ -public interface JdbcCallback { - - /** - * 执行 - * @return - */ - T execute() throws SQLException; - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/template/JdbcOperations.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/template/JdbcOperations.java deleted file mode 100644 index 4fe86a20..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/template/JdbcOperations.java +++ /dev/null @@ -1,293 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.template; - -import fun.asgc.neutrino.core.db.annotation.Id; -import fun.asgc.neutrino.core.util.CollectionUtil; -import fun.asgc.neutrino.core.util.ReflectUtil; -import fun.asgc.neutrino.core.util.TypeUtil; - -import java.lang.reflect.Field; -import java.sql.*; -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/27 - */ -public class JdbcOperations { - private static final JdbcOperations instance = new JdbcOperations(); - - private static final Map, Field> generateIdFieldMap = new ConcurrentHashMap<>(); - - private JdbcOperations() { - - } - - public static JdbcOperations getInstance() { - return instance; - } - - /** - * 通用执行方法 - * @param callback - * @param - * @return - */ - public T execute(JdbcCallback callback) throws SQLException { - return callback.execute(); - } - - /** - * 执行更新操作 - * @param conn - * @param sql - * @param params - * @return - */ - public int executeUpdate(final Connection conn , final String sql, final Object[] params) throws SQLException { - return this.execute(new PreparedStatementJdbcCallback(){ - @Override - public Integer execute(PreparedStatement ps) throws SQLException { - return ps.executeUpdate(); - } - @Override - public Object[] getParams() { - return params; - } - @Override - public String getSql() { - return sql; - } - @Override - public Connection getConnection(){ - return conn; - } - }); - } - - /** - * 执行更新操作 - * 临时兼容返设主键问题 - * @param conn - * @param sql - * @param params - * @return - */ - public int executeUpdateByModel(final Connection conn , final String sql, final Object model, final Object[] params) throws SQLException { - return this.execute(new PreparedStatementJdbcCallback(){ - @Override - public Integer execute(PreparedStatement ps) throws SQLException { - Integer res = ps.executeUpdate(); - if (null != model) { - ResultSet resultSet = ps.getGeneratedKeys(); - if (resultSet.next()) { - Field field = getGenerateIdField(model.getClass()); - if (null != field) { - ReflectUtil.setFieldValue(field, model, resultSet.getInt(1)); - } - } - } - return res; - } - @Override - public Object[] getParams() { - return params; - } - @Override - public String getSql() { - return sql; - } - @Override - public Connection getConnection(){ - return conn; - } - }); - } - - /** - * 执行单条查询操作 - * @param conn - * @param clazz - * @param sql - * @param params - * @param - * @return - */ - public T executeQuery(final Connection conn,final Class clazz,final String sql,final Object[] params) throws SQLException { - return this.execute(new PreparedStatementJdbcCallback() { - - @Override - public T execute(PreparedStatement ps) { - T obj = null; - - try{ - ResultSet resultSet = ps.executeQuery(); - if(resultSet.next()){ - if(TypeUtil.isNormalBasicType(clazz)){ - Object value = resultSet.getObject(1); - obj = TypeUtil.conversion(value, clazz); - }else if(TypeUtil.isMap(clazz)){ - Map map = new HashMap(); - obj = (T)map; - - ResultSetMetaData rsmd = resultSet.getMetaData(); - int columnCount = rsmd.getColumnCount(); - for(int i = 1;i <= columnCount;i++){ - String name = rsmd.getColumnName(i); - Object value = resultSet.getObject(i); - map.put(DbCache.fromColumnName(name), value); - } - }else{ - obj = clazz.newInstance(); - ResultSetMetaData rsmd = resultSet.getMetaData(); - int columnCount = rsmd.getColumnCount(); - for(int i = 1;i <= columnCount;i++){ - String name = rsmd.getColumnName(i); - Object value = resultSet.getObject(i); - List fieldList = DbCache.getField(clazz, name); - ReflectUtil.setFieldValue(fieldList, obj, value); - } - } - } - }catch(Exception e){ - throw new RuntimeException(e); - } - return obj; - } - @Override - public Connection getConnection() { - return conn; - } - @Override - public Object[] getParams() { - return params; - } - @Override - public String getSql() { - return sql; - } - }); - } - - /** - * 执行多条查询操作 - * @param conn - * @param clazz - * @param sql - * @param params - * @param - * @return - */ - public List executeQueryForList(final Connection conn, final Class clazz, final String sql, final Object[] params) throws SQLException { - return this.execute(new PreparedStatementJdbcCallback>() { - @Override - public List execute(PreparedStatement ps) { - List res = new ArrayList(); - try{ - ResultSet resultSet = ps.executeQuery(); - ResultSetMetaData rsmd = resultSet.getMetaData(); - int columnCount = rsmd.getColumnCount(); - - while(resultSet.next()){ - T obj = null; - - if(TypeUtil.isNormalBasicType(clazz)){ - Object value = resultSet.getObject(1); - obj = TypeUtil.conversion(value, clazz); - }else if(TypeUtil.isMap(clazz)){ - Map map = new HashMap(); - obj = (T)map; - - for(int i = 1;i <= columnCount;i++){ - String name = rsmd.getColumnName(i); - Object value = resultSet.getObject(i); - map.put(DbCache.fromColumnName(name), value); - } - }else{ - obj = clazz.newInstance(); - - for(int i = 1;i <= columnCount;i++){ - String name = rsmd.getColumnName(i); - Object value = resultSet.getObject(i); - List fieldList = DbCache.getField(clazz, name); - ReflectUtil.setFieldValue(fieldList, obj, value); - } - } - - res.add(obj); - } - - }catch(Exception e){ - throw new RuntimeException(e); - } - - return res; - } - - @Override - public Connection getConnection() { - - return conn; - } - - @Override - public Object[] getParams() { - - return params; - } - - @Override - public String getSql() { - - return sql; - } - - }); - } - - /** - * 获取自动生成ID字段 - * @param clazz - * @return - */ - private static Field getGenerateIdField(Class clazz) { - if (null == clazz) { - return null; - } - if (generateIdFieldMap.containsKey(clazz)) { - return generateIdFieldMap.get(clazz); - } - Set fields = ReflectUtil.getDeclaredFields(clazz); - if (CollectionUtil.isEmpty(fields)) { - return null; - } - Field field = fields.stream().filter(f -> f.isAnnotationPresent(Id.class)).findFirst().orElse(null); - if (null != field) { - return field; - } - field = fields.stream().filter(f -> f.getName().equals("id")).findFirst().orElse(null); - return field; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/template/JdbcTemplate.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/template/JdbcTemplate.java deleted file mode 100644 index 5bab3bf9..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/template/JdbcTemplate.java +++ /dev/null @@ -1,452 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.template; - -import javax.sql.DataSource; -import java.sql.Connection; -import java.sql.SQLException; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/27 - */ -public class JdbcTemplate { - /** - * 数据源持有者 - */ - private DataSourceHolder dataSourceHolder; - /** - * jdbc操作 - */ - private JdbcOperations jdbcOperations; - - public JdbcTemplate(DataSource dataSource) { - this(new DataSourceHolder(dataSource)); - } - - public JdbcTemplate(DataSourceHolder dataSourceHolder) { - this.dataSourceHolder = dataSourceHolder; - this.jdbcOperations = JdbcOperations.getInstance(); - } - - public int update(String sql, Object ...params) throws SQLException { - int res = -1; - Connection conn = null; - - try { - conn = dataSourceHolder.getConnection(); - res = jdbcOperations.executeUpdate(conn,sql, params); - } finally { - try { - dataSourceHolder.tryClose(conn); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - return res; - } - - /** - * TODO 临时用来兼容insert之后需要返设主键的问题 - * @param sql - * @param params - * @return - * @throws SQLException - */ - public int updateByModel(String sql, Object model, Object ...params) throws SQLException { - int res = -1; - Connection conn = null; - - try { - conn = dataSourceHolder.getConnection(); - res = jdbcOperations.executeUpdateByModel(conn,sql, model, params); - } finally { - try { - dataSourceHolder.tryClose(conn); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - return res; - } - - public int update(SqlAndParams sqlAndParams) throws SQLException { - return update(sqlAndParams.getSql(), sqlAndParams.getParamArray()); - } - - public int updateByMap(String sql, Map params) throws SQLException { - return update(new SqlAndParams(sql, params)); - } - - public int updateByModel(String sql, Object model) throws SQLException { - SqlAndParams sqlAndParams = new SqlAndParams(sql, model); - return updateByModel(sqlAndParams.getSql(), model, sqlAndParams.getParamArray()); - } - - public T query(Class clazz, String sql, Object ...params) throws SQLException { - T res = null; - Connection conn = null; - try { - conn = dataSourceHolder.getConnection(); - res = jdbcOperations.executeQuery(conn, clazz,sql, params); - } finally { - try { - dataSourceHolder.tryClose(conn); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - return res; - } - - public T query(Class clazz, SqlAndParams sqlAndParams) throws SQLException { - return query(clazz, sqlAndParams.getSql(), sqlAndParams.getParamArray()); - } - - public T queryByMap(Class clazz, String sql, Map params) throws SQLException { - return query(clazz, new SqlAndParams(sql, params)); - } - - public T queryByModel(Class clazz, String sql, Object model) throws SQLException { - return query(clazz, new SqlAndParams(sql, model)); - } - - public byte queryForByteByMap(String sql, Map params) throws SQLException { - SqlAndParams sqlAndParams = new SqlAndParams(sql, params); - return queryForByte(sqlAndParams.getSql(), sqlAndParams.getParamArray()); - } - - public byte queryForByteByModel(String sql, Object model) throws SQLException { - SqlAndParams sqlAndParams = new SqlAndParams(sql, model); - return queryForByte(sqlAndParams.getSql(), sqlAndParams.getParamArray()); - } - - public byte queryForByte(String sql, Object ...params) throws SQLException { - return query(byte.class, sql, params); - } - - public short queryForShortByMap(String sql, Map params) throws SQLException { - SqlAndParams sqlAndParams = new SqlAndParams(sql, params); - return queryForShort(sqlAndParams.getSql(), sqlAndParams.getParamArray()); - } - - public short queryForShortByModel(String sql, Object model) throws SQLException { - SqlAndParams sqlAndParams = new SqlAndParams(sql, model); - return queryForShort(sqlAndParams.getSql(), sqlAndParams.getParamArray()); - } - - public short queryForShort(String sql, Object ...params) throws SQLException { - return query(short.class, sql, params); - } - - public int queryForIntByMap(String sql, Map params) throws SQLException { - SqlAndParams sqlAndParams = new SqlAndParams(sql, params); - return queryForInt(sqlAndParams.getSql(), sqlAndParams.getParamArray()); - } - - public int queryForIntByModel(String sql, Object model) throws SQLException { - SqlAndParams sqlAndParams = new SqlAndParams(sql, model); - return queryForInt(sqlAndParams.getSql(), sqlAndParams.getParamArray()); - } - - public int queryForInt(String sql, Object ...params) throws SQLException { - return query(int.class, sql, params); - } - - public Long queryForLongByMap(String sql, Map params) throws SQLException { - SqlAndParams sqlAndParams = new SqlAndParams(sql, params); - return queryForLong(sqlAndParams.getSql(), sqlAndParams.getParamArray()); - } - - public Long queryForLongByModel(String sql, Object model) throws SQLException { - SqlAndParams sqlAndParams = new SqlAndParams(sql, model); - return queryForLong(sqlAndParams.getSql(), sqlAndParams.getParamArray()); - } - - public Long queryForLong(String sql,Object ...params) throws SQLException { - return query(long.class, sql, params); - } - - public float queryForFloatByMap(String sql, Map params) throws SQLException { - SqlAndParams sqlAndParams = new SqlAndParams(sql, params); - return queryForFloat(sqlAndParams.getSql(), sqlAndParams.getParamArray()); - } - - public float queryForFloatByModel(String sql, Object model) throws SQLException { - SqlAndParams sqlAndParams = new SqlAndParams(sql, model); - return queryForFloat(sqlAndParams.getSql(), sqlAndParams.getParamArray()); - } - - public float queryForFloat(String sql,Object ...params) throws SQLException { - return query(float.class, sql, params); - } - - public double queryForDoubleByMap(String sql, Map params) throws SQLException { - SqlAndParams sqlAndParams = new SqlAndParams(sql, params); - return queryForDouble(sqlAndParams.getSql(), sqlAndParams.getParamArray()); - } - - public double queryForDoubleByModel(String sql, Object model) throws SQLException { - SqlAndParams sqlAndParams = new SqlAndParams(sql, model); - return queryForDouble(sqlAndParams.getSql(), sqlAndParams.getParamArray()); - } - - public double queryForDouble(String sql, Object ...params) throws SQLException { - return query(double.class, sql, params); - } - - public char queryForCharByMap(String sql, Map params) throws SQLException { - SqlAndParams sqlAndParams = new SqlAndParams(sql, params); - return queryForChar(sqlAndParams.getSql(), sqlAndParams.getParamArray()); - } - - public char queryForCharByModel(String sql, Object model) throws SQLException { - SqlAndParams sqlAndParams = new SqlAndParams(sql, model); - return queryForChar(sqlAndParams.getSql(), sqlAndParams.getParamArray()); - } - - public char queryForChar(String sql, Object ...params) throws SQLException { - return query(char.class, sql, params); - } - - public boolean queryForBooleanByMap(String sql, Map params) throws SQLException { - SqlAndParams sqlAndParams = new SqlAndParams(sql, params); - return queryForBoolean(sqlAndParams.getSql(), sqlAndParams.getParamArray()); - } - - public boolean queryForBooleanByModel(String sql, Object model) throws SQLException { - SqlAndParams sqlAndParams = new SqlAndParams(sql, model); - return queryForBoolean(sqlAndParams.getSql(), sqlAndParams.getParamArray()); - } - - public boolean queryForBoolean(String sql, Object ...params) throws SQLException { - return query(boolean.class, sql, params); - } - - public String queryForStringByMap(String sql, Map params) throws SQLException { - SqlAndParams sqlAndParams = new SqlAndParams(sql, params); - return queryForString(sqlAndParams.getSql(), sqlAndParams.getParamArray()); - } - - public String queryForStringByModel(String sql, Object model) throws SQLException { - SqlAndParams sqlAndParams = new SqlAndParams(sql, model); - return queryForString(sql, sqlAndParams.getParamArray()); - } - - public String queryForString(String sql, Object ...params) throws SQLException { - return query(String.class, sql, params); - } - - public Map queryForMapByMap(String sql, Map params) throws SQLException { - SqlAndParams sqlAndParams = new SqlAndParams(sql, params); - return queryForMap(sql, sqlAndParams.getParamArray()); - } - - public Map queryForMapByModel(String sql, Object model) throws SQLException { - SqlAndParams sqlAndParams = new SqlAndParams(sql, model); - return queryForMap(sql, sqlAndParams.getParamArray()); - } - - public Map queryForMap(String sql, Object ...params) throws SQLException { - return (Map)query(HashMap.class, sql, params); - } - - public List queryForList(Class clazz, String sql, Object ...params) throws SQLException { - List res = null; - Connection conn = null; - - try { - conn = dataSourceHolder.getConnection(); - res = jdbcOperations.executeQueryForList(conn, clazz, sql, params); - } finally { - try { - dataSourceHolder.tryClose(conn); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - return res; - } - - public List queryForList(Class clazz, SqlAndParams sqlAndParams) throws SQLException { - return queryForList(clazz, sqlAndParams.getSql(), sqlAndParams.getParamArray()); - } - - public List queryForListByMap(Class clazz, String sql, Map params) throws SQLException { - SqlAndParams sqlAndParams = new SqlAndParams(sql, params); - return queryForList(clazz, sqlAndParams.getSql(), sqlAndParams.getParamArray()); - } - - public List queryForListByModel(Class clazz, String sql, Object model) throws SQLException { - SqlAndParams sqlAndParams = new SqlAndParams(sql, model); - return queryForList(clazz, sqlAndParams.getSql(), sqlAndParams.getParamArray()); - } - - public List queryForListByteByMap(String sql, Map params) throws SQLException { - SqlAndParams sqlAndParams = new SqlAndParams(sql, params); - return queryForListByte(sqlAndParams.getSql(), sqlAndParams.getParamArray()); - } - - public List queryForListByteByModel(String sql, Object model) throws SQLException { - SqlAndParams sqlAndParams = new SqlAndParams(sql, model); - return queryForListByte(sqlAndParams.getSql(), sqlAndParams.getParamArray()); - } - - public List queryForListByte(String sql,Object ...params) throws SQLException { - return queryForList(byte.class, sql,params); - } - - public List queryForListShortByMap(String sql, Map params) throws SQLException { - SqlAndParams sqlAndParams = new SqlAndParams(sql, params); - return queryForListShort(sqlAndParams.getSql(), sqlAndParams.getParamArray()); - } - - public List queryForListShortByModel(String sql, Object model) throws SQLException { - SqlAndParams sqlAndParams = new SqlAndParams(sql, model); - return queryForListShort(sqlAndParams.getSql(), sqlAndParams.getParamArray()); - } - - public List queryForListShort(String sql, Object ...params) throws SQLException { - return queryForList(short.class, sql, params); - } - - public List queryForListIntByMap(String sql, Map params) throws SQLException { - SqlAndParams sqlAndParams = new SqlAndParams(sql, params); - return queryForListInt(sqlAndParams.getSql(), sqlAndParams.getParamArray()); - } - - public List queryForListIntByModel(String sql, Object model) throws SQLException { - SqlAndParams sqlAndParams = new SqlAndParams(sql, model); - return queryForListInt(sqlAndParams.getSql(), sqlAndParams.getParamArray()); - } - - public List queryForListInt(String sql, Object ...params) throws SQLException { - return queryForList(int.class, sql, params); - } - - public List queryForListLongByMap(String sql, Map params) throws SQLException { - SqlAndParams sqlAndParams = new SqlAndParams(sql, params); - return queryForListLong(sqlAndParams.getSql(), sqlAndParams.getParamArray()); - } - - public List queryForListLongByModel(String sql, Object model) throws SQLException { - SqlAndParams sqlAndParams = new SqlAndParams(sql, model); - return queryForListLong(sqlAndParams.getSql(), sqlAndParams.getParamArray()); - } - - public List queryForListLong(String sql,Object ...params) throws SQLException { - return queryForList(long.class, sql, params); - } - - public List queryForListFloatByMap(String sql, Map params) throws SQLException { - SqlAndParams sqlAndParams = new SqlAndParams(sql, params); - return queryForListFloat(sqlAndParams.getSql(), sqlAndParams.getParamArray()); - } - - public List queryForListFloatByModel(String sql, Object model) throws SQLException { - SqlAndParams sqlAndParams = new SqlAndParams(sql, model); - return queryForListFloat(sqlAndParams.getSql(), sqlAndParams.getParamArray()); - } - - public List queryForListFloat(String sql, Object ...params) throws SQLException { - return queryForList(float.class, sql, params); - } - - public List queryForListDoubleByMap(String sql ,Map params) throws SQLException { - SqlAndParams sqlAndParams = new SqlAndParams(sql, params); - return queryForListDouble(sqlAndParams.getSql(), sqlAndParams.getParamArray()); - } - - public List queryForListDoubleByModel(String sql, Object model) throws SQLException { - SqlAndParams sqlAndParams = new SqlAndParams(sql, model); - return queryForListDouble(sqlAndParams.getSql(), sqlAndParams.getParamArray()); - } - - public List queryForListDouble(String sql, Object ...params) throws SQLException { - return queryForList(double.class, sql, params); - } - - public List queryForListCharByMap(String sql, Map params) throws SQLException { - SqlAndParams sqlAndParams = new SqlAndParams(sql, params); - return queryForListChar(sqlAndParams.getSql(), sqlAndParams.getParamArray()); - } - - public List queryForListCharByModel(String sql, Object model) throws SQLException { - SqlAndParams sqlAndParams = new SqlAndParams(sql, model); - return queryForListChar(sqlAndParams.getSql(), sqlAndParams.getParamArray()); - } - - public List queryForListChar(String sql, Object ...params) throws SQLException { - return queryForList(char.class, sql, params); - } - - public List queryForListBooleanByMap(String sql, Map params) throws SQLException { - SqlAndParams sqlAndParams = new SqlAndParams(sql, params); - return queryForListBoolean(sqlAndParams.getSql(), sqlAndParams.getParamArray()); - } - - public List queryForListBooleanByModel(String sql, Object model) throws SQLException { - SqlAndParams sqlAndParams = new SqlAndParams(sql, model); - return queryForListBoolean(sqlAndParams.getSql(), sqlAndParams.getParamArray()); - } - - public List queryForListBoolean(String sql, Object ...params) throws SQLException { - return queryForList(boolean.class, sql, params); - } - - public List queryForListStringByMap(String sql, Map params) throws SQLException { - SqlAndParams sqlAndParams = new SqlAndParams(sql, params); - return queryForListString(sqlAndParams.getSql(), sqlAndParams.getParamArray()); - } - - public List queryForListStringByModel(String sql, Object model) throws SQLException { - SqlAndParams sqlAndParams = new SqlAndParams(sql, model); - return queryForListString(sqlAndParams.getSql(), sqlAndParams.getParamArray()); - } - - public List queryForListString(String sql, Object ...params) throws SQLException { - return queryForList(String.class, sql, params); - } - - public List queryForListMap(String sql, Object ...params) throws SQLException { - return queryForList(Map.class, sql, params); - } - - public List queryForListMapByMap(String sql, Map params) throws SQLException { - SqlAndParams sqlAndParams = new SqlAndParams(sql, params); - return queryForListMap(sqlAndParams.getSql(), sqlAndParams.getParamArray()); - } - - public List queryForListMapByModel(String sql, Object model) throws SQLException { - SqlAndParams sqlAndParams = new SqlAndParams(sql, model); - return queryForListMap(sqlAndParams.getSql(), sqlAndParams.getParamArray()); - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/template/PreparedStatementJdbcCallback.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/template/PreparedStatementJdbcCallback.java deleted file mode 100644 index de13689d..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/template/PreparedStatementJdbcCallback.java +++ /dev/null @@ -1,95 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - *

- * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - *

- * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - *

- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.template; - -import fun.asgc.neutrino.core.util.ArrayUtil; -import lombok.extern.slf4j.Slf4j; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.sql.Statement; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/27 - */ -@Slf4j -public abstract class PreparedStatementJdbcCallback implements JdbcCallback { - - @Override - public T execute() throws SQLException { - PreparedStatement pstm = null; - Object[] params = this.getParams(); - Connection conn = getConnection(); - - T res = null; - - log.debug("sql:" + this.getSql()); - StringBuffer sb = new StringBuffer(); - if (ArrayUtil.notEmpty(params)) { - for (Object o : params) { - sb.append(o).append(","); - } - - if (sb.length() > 0 && sb.charAt(sb.length() - 1) == ',') { - sb.deleteCharAt(sb.length() - 1); - } - } - log.debug("params:" + sb.toString()); - pstm = conn.prepareStatement(this.getSql(), Statement.RETURN_GENERATED_KEYS); - if (ArrayUtil.notEmpty(params)) { - for (int i = 0; i < params.length; i++) { - pstm.setObject(i + 1, params[i]); - } - } - res = this.execute(pstm); - - return res; - } - - /** - * 获取参数 - * @return - */ - abstract Object[] getParams(); - - /** - * 获取sql语句 - * @return - */ - abstract String getSql(); - - /** - * 执行 - * @param ps - * @return - */ - abstract T execute(PreparedStatement ps) throws SQLException; - - /** - * 获取数据库连接 - * @return - */ - abstract Connection getConnection(); -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/template/SqlAndParams.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/template/SqlAndParams.java deleted file mode 100644 index 2688b51e..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/template/SqlAndParams.java +++ /dev/null @@ -1,146 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.template; - -import fun.asgc.neutrino.core.base.Orderly; -import fun.asgc.neutrino.core.util.ArrayUtil; -import fun.asgc.neutrino.core.util.ReflectUtil; - -import java.lang.reflect.Field; -import java.util.*; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -/** - * sql语句+sql参数的封装,用于支持以下3种用法 - * 1、jdbcTemplate.query(User.class,"select * from user where id = ?",1); - * 2、dbcTemplate.query(User.class,"select * from user where id = :id", new HashMap(){ - * { - * this.put("id","1"); - * } - * }); - * 3、dbcTemplate.query(User.class,"select * from user where id = :id", new User().setId("1")); - * @author: aoshiguchen - * @date: 2022/6/27 - */ -public class SqlAndParams { - private String sql; - private Object[] paramArray; - private Map paramMap; - private Object paramObject; - - public SqlAndParams(String sql, Object[] paramArray) { - this.sql = sql; - this.paramArray = paramArray; - } - - public SqlAndParams(String sql) { - this.sql = sql; - } - - public SqlAndParams(String sql,Map paramMap) { - this.sql = sql; - this.paramMap = paramMap; - this.initParams(); - } - - public SqlAndParams(String sql,Object paramObject) { - this.sql = sql; - this.paramObject = paramObject; - - this.initParamMap(); - this.initParams(); - } - - private void initParamMap(){ - if (null == paramObject) { - return; - } - if (null == paramMap) { - paramMap = new HashMap<>(); - } - for(Field field : ReflectUtil.getDeclaredFields(paramObject.getClass())){ - paramMap.put(field.getName(), ReflectUtil.getFieldValue(field, paramObject)); - } - } - - private void initParams() { - if (null == paramMap) { - paramMap = new HashMap<>(); - } - String originSql = sql; - List orderlyList = new ArrayList<>(); - for(String key : paramMap.keySet()){ - int index = originSql.indexOf(":" + key); - if(-1 != index){ - List currentList = new ArrayList<>(); - - // 解决数组、集合参数问题 - int count = 1; - Object tmp = paramMap.get(key); - if (null != tmp) { - if (tmp.getClass().isArray()) { - count = ((Object[])tmp).length; - currentList.addAll(Stream.of((Object[])tmp).map(e -> new Orderly(e, index)).collect(Collectors.toList())); - } else if (Collection.class.isAssignableFrom(tmp.getClass())) { - count = ((Collection)tmp).size(); - Object[] arr = ((Collection)tmp).toArray(); - paramMap.put(key, arr); - currentList.addAll((List)((Collection)tmp).stream().map(e -> new Orderly(e, index)).collect(Collectors.toList())); - } - } - List s = new ArrayList<>(); - for (int i = 0; i < count; i++) { - s.add("?"); - } - sql = sql.replaceFirst(":" + key, s.stream().collect(Collectors.joining(","))); - - if (currentList.isEmpty()) { - currentList.add(new Orderly(paramMap.get(key), index)); - } - - orderlyList.addAll(currentList); -// orderlyList.add(new Orderly(paramMap.get(key), index)); - } - } - - this.paramArray = orderlyList.stream().sorted().map(Orderly::getData).collect(Collectors.toList()).toArray(); - } - - public Object[] getParamArray(){ - return paramArray; - } - - public String getSql(){ - return sql; - } - - @Override - public String toString() { - return "SqlAndParams{" + - "sql='" + sql + '\'' + - ", paramArray=" + Arrays.toString(paramArray) + - ", paramMap=" + paramMap + - ", paramObject=" + paramObject + - '}'; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/exception/BeanException.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/exception/BeanException.java deleted file mode 100644 index 1f266bb4..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/exception/BeanException.java +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.exception; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/1 - */ -public class BeanException extends InternalException { - - public BeanException(String message) { - super(message); - } - - public BeanException(String message, Throwable cause) { - super(message, cause); - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/exception/ConfigurationParserException.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/exception/ConfigurationParserException.java deleted file mode 100644 index aa3bfefa..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/exception/ConfigurationParserException.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.exception; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -public class ConfigurationParserException extends InternalException { - - public ConfigurationParserException(String message) { - super(message); - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/exception/InternalException.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/exception/InternalException.java deleted file mode 100644 index 8e3b2d23..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/exception/InternalException.java +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.exception; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -public class InternalException extends RuntimeException { - - public InternalException(String message) { - super(message); - } - - public InternalException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/quartz/DefaultJobSource.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/quartz/DefaultJobSource.java deleted file mode 100644 index 6c4ad85b..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/quartz/DefaultJobSource.java +++ /dev/null @@ -1,63 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.quartz; - -import com.google.common.collect.Lists; -import fun.asgc.neutrino.core.quartz.annotation.JobHandler; -import fun.asgc.neutrino.core.util.BeanManager; -import fun.asgc.neutrino.core.util.CollectionUtil; -import fun.asgc.neutrino.core.util.StringUtil; - -import java.util.List; - -/** - * - * @author: aoshiguchen - * @date: 2022/9/4 - */ -public class DefaultJobSource implements IJobSource { - - @Override - public List sourceList() { - List jobHandlerList = BeanManager.getBeanListBySuperClass(IJobHandler.class); - if (CollectionUtil.isEmpty(jobHandlerList)) { - return Lists.newArrayList(); - } - List jobInfoList = Lists.newArrayList(); - for (IJobHandler jobHandler : jobHandlerList) { - JobHandler handler = jobHandler.getClass().getAnnotation(JobHandler.class); - if (null == handler || StringUtil.isEmpty(handler.name()) || StringUtil.isEmpty(handler.cron())) { - continue; - } - jobInfoList.add(new JobInfo() - .setId(handler.name()) - .setName(handler.name()) - .setDesc(handler.desc()) - .setCron(handler.cron()) - .setParam(handler.param()) - .setEnable(true) - ); - } - return jobInfoList; - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/quartz/IJobCallback.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/quartz/IJobCallback.java deleted file mode 100644 index 402badd1..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/quartz/IJobCallback.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.quartz; - -/** - * - * @author: aoshiguchen - * @date: 2022/9/4 - */ -public interface IJobCallback { - - /** - * 执行日志 - * @param jobInfo - * @param param - * @param throwable - */ - void executeLog(JobInfo jobInfo, String param, Throwable throwable); -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/quartz/IJobExecutor.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/quartz/IJobExecutor.java deleted file mode 100644 index cc4aff31..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/quartz/IJobExecutor.java +++ /dev/null @@ -1,55 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.quartz; - -/** - * - * @author: aoshiguchen - * @date: 2022/9/4 - */ -public interface IJobExecutor { - - /** - * 初始化 - * @throws JobException - */ - void init() throws JobException; - - /** - * 新增job - * @param jobInfo - */ - void add(JobInfo jobInfo); - - /** - * 删除job - * @param jobName - */ - void remove(String jobName); - - /** - * 触发 - * @param jobName - * @param param - */ - void trigger(String jobName, String param); -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/quartz/IJobHandler.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/quartz/IJobHandler.java deleted file mode 100644 index d0f62cae..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/quartz/IJobHandler.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.quartz; - -/** - * @author: aoshiguchen - * @date: 2022/9/4 - */ -public interface IJobHandler { - - /** - * job执行 - * @param param - * @throws Exception - */ - void execute(String param) throws Exception; - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/quartz/IJobSource.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/quartz/IJobSource.java deleted file mode 100644 index e399fb44..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/quartz/IJobSource.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.quartz; - -import java.util.List; - -/** - * - * @author: aoshiguchen - * @date: 2022/9/4 - */ -public interface IJobSource { - - /** - * 获取所有job列表 - * @return - */ - List sourceList(); -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/quartz/JobBean.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/quartz/JobBean.java deleted file mode 100644 index 9f47cedd..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/quartz/JobBean.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.quartz; - -import fun.asgc.neutrino.core.util.BeanManager; -import lombok.extern.slf4j.Slf4j; -import org.quartz.Job; -import org.quartz.JobExecutionContext; -import org.quartz.JobExecutionException; - -/** - * - * @author: aoshiguchen - * @date: 2022/9/4 - */ -@Slf4j -public class JobBean implements Job { - - @Override - public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { - JobExecutor jobExecutor = BeanManager.getBean(JobExecutor.class); - if (null != jobExecutor) { - jobExecutor.execute(jobExecutionContext); - } - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/quartz/JobException.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/quartz/JobException.java deleted file mode 100644 index b61e12d4..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/quartz/JobException.java +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Copyright (C) 2018-2022 Zeyi information technology (Shanghai) Co., Ltd. - *

- * All right reserved. - *

- * This software is the confidential and proprietary - * information of Zeyi Company of China. - * ("Confidential Information"). You shall not disclose - * such Confidential Information and shall use it only - * in accordance with the terms of the contract agreement - * you entered into with Zeyi inc. - */ -package fun.asgc.neutrino.core.quartz; - -import fun.asgc.neutrino.core.exception.InternalException; - -/** - * - * @author: wen.y - * @date: 2022/9/4 - */ -public class JobException extends InternalException { - - public JobException(String message) { - super(message); - } - - public JobException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/quartz/JobExecutor.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/quartz/JobExecutor.java deleted file mode 100644 index a50f2ab0..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/quartz/JobExecutor.java +++ /dev/null @@ -1,209 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.quartz; - -import com.google.common.collect.Sets; -import fun.asgc.neutrino.core.annotation.Autowired; -import fun.asgc.neutrino.core.base.CustomThreadFactory; -import fun.asgc.neutrino.core.context.ApplicationRunner; -import fun.asgc.neutrino.core.context.Environment; -import fun.asgc.neutrino.core.quartz.annotation.JobHandler; -import fun.asgc.neutrino.core.util.BeanManager; -import fun.asgc.neutrino.core.util.CollectionUtil; -import fun.asgc.neutrino.core.util.StringUtil; -import lombok.extern.slf4j.Slf4j; -import org.quartz.*; -import org.quartz.impl.StdSchedulerFactory; - -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -/** - * Job执行器 - * @author: aoshiguchen - * @date: 2022/9/4 - */ -@Slf4j -public class JobExecutor implements ApplicationRunner, IJobExecutor { - @Autowired - private Environment environment; - private IJobSource jobSource; - private ThreadPoolExecutor threadPoolExecutor; - private Map jobInfoMap = new ConcurrentHashMap<>(); - private SchedulerFactory schedulerFactory; - private Scheduler scheduler; - private Map jobHandlerMap = new ConcurrentHashMap<>(); - private Set runJobSet = Sets.newHashSet(); - private IJobCallback jobCallback; - private Map triggerKeyMap = new ConcurrentHashMap<>(); - - @Override - public void run(String[] args) throws JobException { - if (!environment.isEnableJob() || null == jobSource) { - return; - } - if (null == threadPoolExecutor) { - threadPoolExecutor = new ThreadPoolExecutor(5, 20, 10L, TimeUnit.SECONDS, - new LinkedBlockingQueue<>(), new CustomThreadFactory("DefaultJobPool")); - } - - List jobHandlerList = BeanManager.getBeanListBySuperClass(IJobHandler.class); - if (!CollectionUtil.isEmpty(jobHandlerList)) { - for (IJobHandler item : jobHandlerList) { - JobHandler jobHandler = item.getClass().getAnnotation(JobHandler.class); - if (null == jobHandler) { - continue; - } - jobHandlerMap.put(jobHandler.name(), item); - } - } - - try { - this.schedulerFactory = new StdSchedulerFactory(); - this.scheduler = schedulerFactory.getScheduler(); - this.init(); - } catch (Exception e){ - throw new JobException("job初始化异常"); - } - } - - public void setJobSource(IJobSource jobSource) { - this.jobSource = jobSource; - } - - public void setThreadPoolExecutor(ThreadPoolExecutor threadPoolExecutor) { - this.threadPoolExecutor = threadPoolExecutor; - } - - public void setJobCallback(IJobCallback jobCallback) { - this.jobCallback = jobCallback; - } - - @Override - public void init() throws JobException { - List jobInfoList = jobSource.sourceList(); - if (CollectionUtil.isEmpty(jobInfoList)) { - return; - } - - for (JobInfo jobInfo : jobInfoList) { - add(jobInfo); - } - log.info("Job初始化完成."); - } - - @Override - public void add(JobInfo jobInfo) throws JobException { - if (null == jobInfo || StringUtil.isEmpty(jobInfo.getId()) || StringUtil.isEmpty(jobInfo.getName()) || - StringUtil.isEmpty(jobInfo.getCron())) { - return; - } - synchronized (jobInfo.getId()) { - runJobSet.add(jobInfo.getName()); - jobInfoMap.put(jobInfo.getId(), jobInfo); - - TriggerKey triggerKey = TriggerKey.triggerKey(jobInfo.getId()); - triggerKeyMap.put(jobInfo.getId(), triggerKey); - JobKey jobKey = new JobKey(jobInfo.getName()); - - CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(jobInfo.getCron()).withMisfireHandlingInstructionDoNothing(); - CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(triggerKey).withSchedule(cronScheduleBuilder).build(); - JobDetail jobDetail = JobBuilder.newJob(JobBean.class).withIdentity(jobKey).build(); - - try { - if (jobInfo.isEnable()) { - scheduler.scheduleJob(jobDetail, cronTrigger); - scheduler.start(); - } - } catch (Exception e) { - throw new RuntimeException(String.format("新增job[name=%s]异常", jobInfo.getName())); - } - } - } - - @Override - public void remove(String jobId) { - JobInfo jobInfo = jobInfoMap.get(jobId); - if (null == jobInfo) { - return; - } - synchronized (jobId) { - runJobSet.remove(jobInfo.getName()); - unscheduleJob(jobId); - } - } - - @Override - public void trigger(String jobId, String param) { - doExecute(jobId, param); - } - - public void execute(JobExecutionContext context) throws JobExecutionException { - if (null == context || null == context.getTrigger()) { - return; - } - String jobId = context.getTrigger().getKey().getName(); - JobInfo jobInfo = jobInfoMap.get(jobId); - if (null == jobInfo) { - unscheduleJob(jobId); - return; - } - doExecute(jobId, jobInfo.getParam()); - } - - private void unscheduleJob(String jobId) { - TriggerKey triggerKey = triggerKeyMap.get(jobId); - if (null != triggerKey) { - try { - scheduler.unscheduleJob(triggerKey); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - private void doExecute(String jobId, String param) { - JobInfo jobInfo = jobInfoMap.get(jobId); - if (null == jobInfo) { - return; - } - IJobHandler jobHandler =jobHandlerMap.get(jobInfo.getName()); - if (null == jobHandler) { - return; - } - threadPoolExecutor.submit(() -> { - try { - jobHandler.execute(param); - if (null != jobCallback) { - jobCallback.executeLog(jobInfo, param, null); - } - } catch (Throwable e) { - jobCallback.executeLog(jobInfo, param, e); - } - }); - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/quartz/JobInfo.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/quartz/JobInfo.java deleted file mode 100644 index c7055f0a..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/quartz/JobInfo.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.quartz; - -import lombok.Data; -import lombok.experimental.Accessors; - -import java.util.Map; - -/** - * - * @author: aoshiguchen - * @date: 2022/9/4 - */ -@Accessors(chain = true) -@Data -public class JobInfo { - private String id; - private String name; - private String desc; - private String cron; - private String param; - private boolean enable; - private Map extension; -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/quartz/annotation/JobHandler.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/quartz/annotation/JobHandler.java deleted file mode 100644 index 87f83ffc..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/quartz/annotation/JobHandler.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.quartz.annotation; - -import java.lang.annotation.*; - -/** - * - * @author: aoshiguchen - * @date: 2022/9/4 - */ -@Target({ElementType.TYPE}) -@Retention(RetentionPolicy.RUNTIME) -public @interface JobHandler { - String name(); - String desc() default ""; - String cron(); - String param() default ""; -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/AbstractMatcherGroup.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/AbstractMatcherGroup.java deleted file mode 100644 index e1c60fc1..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/AbstractMatcherGroup.java +++ /dev/null @@ -1,77 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.type; - -import java.util.ArrayList; -import java.util.List; - -/** - * 抽象的匹配器组 - * @author: aoshiguchen - * @date: 2022/6/29 - */ -public abstract class AbstractMatcherGroup implements TypeMatcherGroup { - /** - * 最小距离 - */ - protected int distanceMin; - - /** - * 最大距离 - */ - protected int distanceMax; - - /** - * 匹配器列表 - */ - private List matchers; - - public AbstractMatcherGroup(int distanceMin, int distanceMax) { - this.distanceMin = distanceMin; - this.distanceMax = distanceMax; - this.matchers = new ArrayList<>(); - this.init(); - } - - protected abstract void init(); - - @Override - public List matchers() { - return matchers; - } - - public synchronized void add(TypeMatcher matcher) { - if (null != matcher) { - this.matchers.add(matcher); - } - } - - @Override - public int getDistanceMin() { - return distanceMin; - } - - @Override - public int getDistanceMax() { - return distanceMax; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/DefaultTypeMatcherGroup.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/DefaultTypeMatcherGroup.java deleted file mode 100644 index 01fc5d38..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/DefaultTypeMatcherGroup.java +++ /dev/null @@ -1,133 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.type; - -import fun.asgc.neutrino.core.util.TypeUtil; - -/** - * 默认的类型匹配器组 - * @author: aoshiguchen - * @date: 2022/7/1 - */ -public class DefaultTypeMatcherGroup extends AbstractMatcherGroup { - - public DefaultTypeMatcherGroup(int distanceMin, int distanceMax) { - super(distanceMin, distanceMax); - } - - @Override - protected void init() { - // 空匹配 - add(new TypeMatcher() { - @Override - public TypeMatchInfo match(Class clazz, Class targetClass) { - TypeMatchInfo matchInfo = new TypeMatchInfo(clazz, targetClass, this); - if (null == clazz) { - matchInfo.setTypeDistance(TypeMatchLevel.NULL.getDistanceMin()); - matchInfo.setTypeConverter((value, type) -> TypeUtil.getDefaultValue(type)); - } - return matchInfo; - } - }); - // 完美匹配 - add(new TypeMatcher() { - @Override - public TypeMatchInfo match(Class clazz, Class targetClass) { - TypeMatchInfo matchInfo = new TypeMatchInfo(clazz, targetClass, this); - if (clazz == targetClass) { - matchInfo.setTypeDistance(TypeMatchLevel.PERFECT.getDistanceMin()); - matchInfo.setTypeConverter((value, type) -> value); - } - return matchInfo; - } - }); - // 装箱匹配 - add(new TypeMatcher() { - @Override - public TypeMatchInfo match(Class clazz, Class targetClass) { - TypeMatchInfo matchInfo = new TypeMatchInfo(clazz, targetClass, this); - if (TypeUtil.isStrictBasicType(clazz) && TypeUtil.getWrapType(clazz) == targetClass) { - matchInfo.setTypeDistance(TypeMatchLevel.PACKING.getDistanceMin()); - matchInfo.setTypeConverter((value, type) -> value); - } - return matchInfo; - } - }); - // 拆箱匹配 - add(new TypeMatcher() { - @Override - public TypeMatchInfo match(Class clazz, Class targetClass) { - TypeMatchInfo matchInfo = new TypeMatchInfo(clazz, targetClass, this); - if (TypeUtil.isStrictBasicType(targetClass) && TypeUtil.getWrapType(targetClass) == clazz) { - matchInfo.setTypeDistance(TypeMatchLevel.UNPACKING.getDistanceMin()); - matchInfo.setTypeConverter((value, type) -> value); - } - return matchInfo; - } - }); - // 类型提升匹配 - add(new TypeMatcher() { - @Override - public TypeMatchInfo match(Class clazz, Class targetClass) { - TypeMatchInfo matchInfo = new TypeMatchInfo(clazz, targetClass, this); - int index1 = TypeUtil.basicTypeList.indexOf(clazz); - int index2 = TypeUtil.basicTypeList.indexOf(targetClass); - if (index2 > index1 && index1 >= 0) { - matchInfo.setTypeDistance(TypeMatchLevel.ASCENSION.getDistanceMin() + (index2 - index1)); - matchInfo.setTypeConverter((value, type) -> { - if (value == type || TypeUtil.getWrapType(value.getClass()) == type) { - return value; - } - if (TypeUtil.isInteger(clazz) && TypeUtil.isLong(targetClass)) { - return Long.valueOf(String.valueOf(value)); - } - if (TypeUtil.isBoolean(value.getClass())) { - return ((boolean)value) ? 1 : 0; - } - if (TypeUtil.isBoolean(type)) { - return TypeUtil.isChar(value.getClass()) ? ((char)value == 0 ? false : true) : - (((Number)value).intValue() == 0 ? false : true); - } - if (TypeUtil.isChar(type)) { - return (char)(int)value; - } - return value; - }); - } - return matchInfo; - } - }); - // 超类匹配 - add(new TypeMatcher() { - @Override - public TypeMatchInfo match(Class clazz, Class targetClass) { - TypeMatchInfo matchInfo = new TypeMatchInfo(clazz, targetClass, this); - if (targetClass.isAssignableFrom(clazz)) { - int level = TypeUtil.getInheritLevel(targetClass, clazz); - matchInfo.setTypeDistance(TypeMatchLevel.SUPER.getDistanceMin() + level); - matchInfo.setTypeConverter((value, type) -> value); - } - return matchInfo; - } - }); - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/TypeConverter.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/TypeConverter.java deleted file mode 100644 index 06c55dc9..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/TypeConverter.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.type; - -/** - * 类型转换器 - * @author: aoshiguchen - * @date: 2022/6/17 - */ -@FunctionalInterface -public interface TypeConverter { - /** - * 类型转换 - * @param value - * @param targetType - * @return - */ - Object convert(Object value, Class targetType); -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/TypeMatchInfo.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/TypeMatchInfo.java deleted file mode 100644 index 91b7f9c0..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/TypeMatchInfo.java +++ /dev/null @@ -1,77 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.type; - -import lombok.Data; -import lombok.experimental.Accessors; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -@Accessors(chain = true) -@Data -public class TypeMatchInfo { - - /** - * 目标类型类型 - */ - private Class targetType; - - /** - * 值类型 - */ - private Class valueType; - - /** - * 类型距离 - */ - private int typeDistance; - - /** - * 类型匹配器 - */ - private TypeMatcher typeMatcher; - - /** - * 类型转换器 - */ - private TypeConverter typeConverter; - - public TypeMatchInfo(Class valueType, Class targetType, TypeMatcher typeMatcher) { - this.valueType = valueType; - this.targetType = targetType; - this.typeMatcher = typeMatcher; - this.typeDistance = TypeMatchLevel.NOT.getDistanceMin(); - } - - public boolean isNotMatch() { - return !isMatched(); - } - - public boolean isMatched() { - TypeMatchLevel matchLevel = TypeMatchLevel.byTypeDistance(this.typeDistance); - return matchLevel != null && matchLevel != TypeMatchLevel.NOT && typeConverter != null; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/TypeMatchLevel.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/TypeMatchLevel.java deleted file mode 100644 index 1f383ed2..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/TypeMatchLevel.java +++ /dev/null @@ -1,89 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.type; - -import lombok.AllArgsConstructor; -import lombok.Getter; - -import java.util.Map; -import java.util.function.Function; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -/** - * 类型匹配等级 - * @author: aoshiguchen - * @date: 2022/6/17 - */ -@Getter -@AllArgsConstructor -public enum TypeMatchLevel { - // 当且仅当匹配类为空(即匹配对象为null没有类型)时 - NULL(0, 0, 0, "空匹配"), - // 当且仅当匹配类与目标类完全相等 - PERFECT(1, 1, 1, "完美匹配"), - // 当且仅当匹配类为严格基本数据类型,且目标类为对应的包装类型 - PACKING(2, 100, 100, "装箱匹配"), - // 当且仅当目标类为严格基本数据类型,且匹配类为对应的包装类型 - UNPACKING(3, 200,200,"拆箱匹配"), - // 当且仅当匹配类和目标类均为一般基本数据类型(非严格),且目标类型的范围更加宽泛时 - ASCENSION(4, 1000, 2000, "类型提升匹配"), - // 超类匹配,当且仅当目标类是匹配类的超类时 - SUPER(5, 1000000, 2000000, "超类匹配"), - // 内置的扩展匹配 - EXTENSION(6, 10000000, 50000000, "扩展匹配"), - // 自定义匹配 - CUSTOM(7, 100000000, 500000000, "自定义匹配"), - // 不匹配 - NOT(8, Integer.MAX_VALUE, Integer.MAX_VALUE, "不匹配"); - private static Map levelMap = Stream.of(TypeMatchLevel.values()).collect(Collectors.toMap(TypeMatchLevel::getLevel, Function.identity())); - - /** - * 匹配级别 - */ - private int level; - /** - * 类型距离最小值 - */ - private int distanceMin; - /** - * 类型距离最大值 - */ - private int distanceMax; - /** - * 描述 - */ - private String desc; - - public static TypeMatchLevel byLevel(int level) { - return levelMap.get(level); - } - - public static TypeMatchLevel byTypeDistance(int typeDistance) { - for (TypeMatchLevel item : values()) { - if (typeDistance >= item.getDistanceMin() && typeDistance <= item.getDistanceMax()) { - return item; - } - } - return null; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/TypeMatcher.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/TypeMatcher.java deleted file mode 100644 index 3d82ea95..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/TypeMatcher.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.type; - -/** - * 值类型匹配器 - * - * @author: aoshiguchen - * @date: 2022/6/17 - */ -@FunctionalInterface -public interface TypeMatcher { - - /** - * 匹配 - * @param clazz - * @param targetClass - * @return - */ - TypeMatchInfo match(Class clazz, Class targetClass); - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/TypeMatcherGroup.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/TypeMatcherGroup.java deleted file mode 100644 index d48285a8..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/TypeMatcherGroup.java +++ /dev/null @@ -1,49 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.type; - -import java.util.List; - -/** - * 匹配器组 - * @author: aoshiguchen - * @date: 2022/6/29 - */ -public interface TypeMatcherGroup { - /** - * 匹配器列表 - * @return - */ - List matchers(); - - /** - * 获取最小距离 - * @return - */ - int getDistanceMin(); - - /** - * 获取最大距离 - * @return - */ - int getDistanceMax(); -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/TypeMatchers.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/TypeMatchers.java deleted file mode 100644 index d675e335..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/TypeMatchers.java +++ /dev/null @@ -1,217 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.type; - -import fun.asgc.neutrino.core.type.extension.*; -import fun.asgc.neutrino.core.util.Assert; -import fun.asgc.neutrino.core.util.CollectionUtil; -import fun.asgc.neutrino.core.util.TypeUtil; - -import java.util.*; -import java.util.stream.Collectors; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/17 - */ -public class TypeMatchers { - /** - * 默认的基本匹配器列表 - */ - private static List defaultTypeMatcherList = new ArrayList<>(); - /** - * 默认内置扩展的匹配器列表 - */ - private static List extensionMatcherList = new ArrayList<>(); - /** - * 内置扩展匹配器组列表 - */ - private static List extensionMatcherGroupList = new ArrayList<>(); - /** - * 用户自定义的匹配器列表 - */ - private List customTypeMatcherList = new ArrayList<>(); - /** - * 是否启用内置扩展匹配器 - */ - private volatile boolean enableExtensionMatcher = true; - - static { - init(); - } - - /** - * 注册内置扩展匹配器组 - * @param typeMatcherGroup - */ - private static synchronized void registerExtensionTypeMatcher(TypeMatcherGroup typeMatcherGroup) { - if (null == typeMatcherGroup || CollectionUtil.isEmpty(typeMatcherGroup.matchers())) { - return; - } - // 内置扩展匹配器距离区间检测 - if (typeMatcherGroup.getDistanceMin() < TypeMatchLevel.EXTENSION.getDistanceMin() || - typeMatcherGroup.getDistanceMax() > TypeMatchLevel.EXTENSION.getDistanceMax() || - typeMatcherGroup.getDistanceMax() < typeMatcherGroup.getDistanceMin()) { - throw new RuntimeException(String.format("内置扩展匹配器:[%s] 距离区间定义有误!", typeMatcherGroup.getClass().getSimpleName())); - } - for (TypeMatcherGroup group : extensionMatcherGroupList) { - // 距离区间不能重叠 - if (!(typeMatcherGroup.getDistanceMin() > group.getDistanceMax() || typeMatcherGroup.getDistanceMax() < group.getDistanceMin())) { - throw new RuntimeException(String.format("内置扩展匹配器:[%s]与[%s] 距离区间定义有重叠!", typeMatcherGroup.getClass().getSimpleName(), group.getClass().getSimpleName())); - } - } - extensionMatcherGroupList.add(typeMatcherGroup); - } - - /** - * 注册默认的类型匹配器组 - * @param typeMatcherGroup - */ - private static synchronized void registerDefaultTypeMatcher(TypeMatcherGroup typeMatcherGroup) { - if (null == typeMatcherGroup || CollectionUtil.isEmpty(typeMatcherGroup.matchers())) { - return; - } - // 自定义匹配器距离区间检测 - if (typeMatcherGroup.getDistanceMin() < TypeMatchLevel.NULL.getDistanceMin() || - typeMatcherGroup.getDistanceMax() > TypeMatchLevel.SUPER.getDistanceMax() || - typeMatcherGroup.getDistanceMax() < typeMatcherGroup.getDistanceMin()) { - throw new RuntimeException(String.format("默认匹配器组器:[%s] 距离区间定义有误!", typeMatcherGroup.getClass().getSimpleName())); - } - defaultTypeMatcherList.addAll(typeMatcherGroup.matchers()); - } - - /** - * 注册自定义类型匹配器具 - * @param typeMatcher - */ - public synchronized void registerCustomTypeMatcher(TypeMatcher typeMatcher) { - Assert.notNull(typeMatcher, "匹配器不能为空!"); - customTypeMatcherList.add(typeMatcher); - } - - /** - * 注册自定义匹配器组 - * @param typeMatcherGroup - */ - public synchronized void registerCustomTypeMatcher(TypeMatcherGroup typeMatcherGroup) { - if (null == typeMatcherGroup || CollectionUtil.isEmpty(typeMatcherGroup.matchers())) { - return; - } - // 自定义匹配器距离区间检测 - if (typeMatcherGroup.getDistanceMin() < TypeMatchLevel.CUSTOM.getDistanceMin() || - typeMatcherGroup.getDistanceMax() > TypeMatchLevel.CUSTOM.getDistanceMax() || - typeMatcherGroup.getDistanceMax() < typeMatcherGroup.getDistanceMin()) { - throw new RuntimeException(String.format("自定义扩展匹配器:[%s] 距离区间定义有误!", typeMatcherGroup.getClass().getSimpleName())); - } - customTypeMatcherList.addAll(typeMatcherGroup.matchers()); - } - - /** - * 匹配 - * @param clazz - * @param targetClass - * @return - */ - public TypeMatchInfo match(Class clazz, Class targetClass) { - // 先匹配自定义的 - for (TypeMatcher matcher : customTypeMatcherList) { - TypeMatchInfo typeMatchInfo = matcher.match(clazz, targetClass); - if (typeMatchInfo.isMatched()) { - return typeMatchInfo; - } - } - // 再匹配内置默认的 - for (TypeMatcher matcher : defaultTypeMatcherList) { - TypeMatchInfo typeMatchInfo = matcher.match(clazz, targetClass); - if (typeMatchInfo.isMatched()) { - return typeMatchInfo; - } - } - if (enableExtensionMatcher) { - // 再匹配内置扩展的 - for (TypeMatcher matcher : extensionMatcherList) { - TypeMatchInfo typeMatchInfo = matcher.match(clazz, targetClass); - if (typeMatchInfo.isMatched()) { - return typeMatchInfo; - } - } - } - return null; - } - - public boolean isEnableExtensionMatcher() { - return enableExtensionMatcher; - } - - public void setEnableExtensionMatcher(boolean enableExtensionMatcher) { - this.enableExtensionMatcher = enableExtensionMatcher; - } - - /** - * 类型转换 - * @param value - * @param targetType - * @return - */ - public Object conversion(Object value, Class targetType) { - Assert.notNull(targetType, "目标类型不能为空!"); - TypeMatchInfo typeMatchInfo = match(value == null ? null : value.getClass(), targetType); - if (null == typeMatchInfo || typeMatchInfo.isNotMatch()) { - return null; - } - return typeMatchInfo.getTypeConverter().convert(value, targetType); - } - - /** - * 初始化 - */ - private static void init() { - // 注册默认的类型匹配器组 - registerDefaultTypeMatcher(new DefaultTypeMatcherGroup(TypeMatchLevel.NULL.getDistanceMin(), TypeMatchLevel.SUPER.getDistanceMax())); - - // 注册内置扩展匹配 - int extensionMatcherGroupSize = 100000; - int extensionMatcherGroupDistance = TypeMatchLevel.EXTENSION.getDistanceMin(); - - registerExtensionTypeMatcher(new StringMatcherGroup(extensionMatcherGroupDistance + extensionMatcherGroupSize * 0, - extensionMatcherGroupDistance + extensionMatcherGroupSize * 1 - 1)); - registerExtensionTypeMatcher(new BooleanMatcherGroup(extensionMatcherGroupDistance + extensionMatcherGroupSize * 1, - extensionMatcherGroupDistance + extensionMatcherGroupSize * 2 - 1)); - registerExtensionTypeMatcher(new NumberMatcherGroup(extensionMatcherGroupDistance + extensionMatcherGroupSize * 2, - extensionMatcherGroupDistance + extensionMatcherGroupSize * 3 - 1)); - registerExtensionTypeMatcher(new DateMatcherGroup(extensionMatcherGroupDistance + extensionMatcherGroupSize * 3, - extensionMatcherGroupDistance + extensionMatcherGroupSize * 4 - 1)); - registerExtensionTypeMatcher(new ListMatcherGroup(extensionMatcherGroupDistance + extensionMatcherGroupSize * 4, - extensionMatcherGroupDistance + extensionMatcherGroupSize * 5 - 1)); - registerExtensionTypeMatcher(new SetMatcherGroup(extensionMatcherGroupDistance + extensionMatcherGroupSize * 5, - extensionMatcherGroupDistance + extensionMatcherGroupSize * 6 - 1)); - registerExtensionTypeMatcher(new MapMatcherGroup(extensionMatcherGroupDistance + extensionMatcherGroupSize * 6, - extensionMatcherGroupDistance + extensionMatcherGroupSize * 7 - 1)); - registerExtensionTypeMatcher(new ArrayMatcherGroup(extensionMatcherGroupDistance + extensionMatcherGroupSize * 7, - extensionMatcherGroupDistance + extensionMatcherGroupSize * 8 - 1)); - - // 按照距离区间排序 - extensionMatcherList = extensionMatcherGroupList.stream().sorted(Comparator.comparing(TypeMatcherGroup::getDistanceMin)) - .map(TypeMatcherGroup::matchers).flatMap(List::stream).collect(Collectors.toList()); - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/extension/ArrayMatcherGroup.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/extension/ArrayMatcherGroup.java deleted file mode 100644 index 3b8bfef7..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/extension/ArrayMatcherGroup.java +++ /dev/null @@ -1,71 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.type.extension; - -import fun.asgc.neutrino.core.type.AbstractMatcherGroup; -import fun.asgc.neutrino.core.type.TypeMatchInfo; -import fun.asgc.neutrino.core.type.TypeMatcher; - -import java.util.List; -import java.util.Set; - -/** - * 数组匹配器组 - * @author: aoshiguchen - * @date: 2022/6/29 - */ -public class ArrayMatcherGroup extends AbstractMatcherGroup { - - public ArrayMatcherGroup(int distanceMin, int distanceMax) { - super(distanceMin, distanceMax); - } - - @Override - public void init() { - // List -> Object[] - add(new TypeMatcher() { - @Override - public TypeMatchInfo match(Class clazz, Class targetClass) { - TypeMatchInfo matchInfo = new TypeMatchInfo(clazz, targetClass, this); - if (List.class.isAssignableFrom(clazz) && targetClass.isArray()) { - matchInfo.setTypeDistance(getDistanceMin()); - matchInfo.setTypeConverter((value, targetType) -> ((List)value).toArray()); - } - return matchInfo; - } - }); - - // Set -> Object[] - add(new TypeMatcher() { - @Override - public TypeMatchInfo match(Class clazz, Class targetClass) { - TypeMatchInfo matchInfo = new TypeMatchInfo(clazz, targetClass, this); - if (Set.class.isAssignableFrom(clazz) && targetClass.isArray()) { - matchInfo.setTypeDistance(getDistanceMin() + 1); - matchInfo.setTypeConverter((value, targetType) -> ((Set)value).toArray()); - } - return matchInfo; - } - }); - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/extension/BooleanMatcherGroup.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/extension/BooleanMatcherGroup.java deleted file mode 100644 index 0c61fc75..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/extension/BooleanMatcherGroup.java +++ /dev/null @@ -1,55 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.type.extension; - -import fun.asgc.neutrino.core.type.AbstractMatcherGroup; -import fun.asgc.neutrino.core.type.TypeMatchInfo; -import fun.asgc.neutrino.core.type.TypeMatcher; -import fun.asgc.neutrino.core.util.TypeUtil; - -/** - * 布尔值匹配器组 - * @author: aoshiguchen - * @date: 2022/6/29 - */ -public class BooleanMatcherGroup extends AbstractMatcherGroup { - - public BooleanMatcherGroup(int distanceMin, int distanceMax) { - super(distanceMin, distanceMax); - } - - @Override - public void init() { - add(new TypeMatcher() { - @Override - public TypeMatchInfo match(Class clazz, Class targetClass) { - TypeMatchInfo matchInfo = new TypeMatchInfo(clazz, targetClass, this); - if (TypeUtil.isString(clazz) && TypeUtil.isBoolean(targetClass)) { - matchInfo.setTypeDistance(getDistanceMin()); - matchInfo.setTypeConverter(((value, targetType) -> ((String)value).toLowerCase().equals("true"))); - } - return matchInfo; - } - }); - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/extension/DateMatcherGroup.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/extension/DateMatcherGroup.java deleted file mode 100644 index 2b7cc69a..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/extension/DateMatcherGroup.java +++ /dev/null @@ -1,84 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.type.extension; - - -import fun.asgc.neutrino.core.type.AbstractMatcherGroup; -import fun.asgc.neutrino.core.type.TypeMatchInfo; -import fun.asgc.neutrino.core.type.TypeMatcher; -import fun.asgc.neutrino.core.util.TypeUtil; - -import java.time.Instant; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.util.Date; - -/** - * 日期匹配器组 - * @author: aoshiguchen - * @date: 2022/6/29 - */ -public class DateMatcherGroup extends AbstractMatcherGroup { - - public DateMatcherGroup(int distanceMin, int distanceMax) { - super(distanceMin, distanceMax); - } - - @Override - public void init() { - // Long -> Date - add(new TypeMatcher() { - @Override - public TypeMatchInfo match(Class clazz, Class targetClass) { - TypeMatchInfo matchInfo = new TypeMatchInfo(clazz, targetClass, this); - if (TypeUtil.isLong(clazz) && TypeUtil.isDate(targetClass)) { - matchInfo.setTypeDistance(getDistanceMin()); - matchInfo.setTypeConverter(((value, targetType) -> { - if (targetClass == java.util.Date.class) { - return new java.util.Date((long)value); - } else { - return new java.sql.Date((long)value); - } - })); - } - return matchInfo; - } - }); - // LocalDateTime -> Date - add(new TypeMatcher() { - @Override - public TypeMatchInfo match(Class clazz, Class targetClass) { - TypeMatchInfo matchInfo = new TypeMatchInfo(clazz, targetClass, this); - if (LocalDateTime.class.isAssignableFrom(clazz) && TypeUtil.isDate(targetClass)) { - matchInfo.setTypeDistance(getDistanceMin() + 1); - matchInfo.setTypeConverter(((value, targetType) -> { - ZoneId zone = ZoneId.systemDefault(); - Instant instant = ((LocalDateTime)value).atZone(zone).toInstant(); - return Date.from(instant); - })); - } - return matchInfo; - } - }); - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/extension/ListMatcherGroup.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/extension/ListMatcherGroup.java deleted file mode 100644 index dc0e274d..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/extension/ListMatcherGroup.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.type.extension; - - -import fun.asgc.neutrino.core.type.AbstractMatcherGroup; -import fun.asgc.neutrino.core.type.TypeMatchInfo; -import fun.asgc.neutrino.core.type.TypeMatcher; - -import java.util.List; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -/** - * list匹配器组 - * @author: aoshiguchen - * @date: 2022/6/29 - */ -public class ListMatcherGroup extends AbstractMatcherGroup { - - public ListMatcherGroup(int distanceMin, int distanceMax) { - super(distanceMin, distanceMax); - } - - @Override - public void init() { - add(new TypeMatcher() { - @Override - public TypeMatchInfo match(Class clazz, Class targetClass) { - TypeMatchInfo matchInfo = new TypeMatchInfo(clazz, targetClass, this); - if (List.class == targetClass && clazz.isArray()) { - matchInfo.setTypeDistance(getDistanceMin()); - matchInfo.setTypeConverter(((value, targetType) -> Stream.of((Object[])value).collect(Collectors.toList()))); - } - return matchInfo; - } - }); - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/extension/MapMatcherGroup.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/extension/MapMatcherGroup.java deleted file mode 100644 index caade037..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/extension/MapMatcherGroup.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.type.extension; - -import fun.asgc.neutrino.core.type.AbstractMatcherGroup; - -/** - * Map匹配器组 - * @author: aoshiguchen - * @date: 2022/6/29 - */ -public class MapMatcherGroup extends AbstractMatcherGroup { - - public MapMatcherGroup(int distanceMin, int distanceMax) { - super(distanceMin, distanceMax); - } - - @Override - public void init() { - - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/extension/NumberMatcherGroup.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/extension/NumberMatcherGroup.java deleted file mode 100644 index 71537011..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/extension/NumberMatcherGroup.java +++ /dev/null @@ -1,182 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.type.extension; - -import fun.asgc.neutrino.core.type.AbstractMatcherGroup; -import fun.asgc.neutrino.core.type.TypeMatchInfo; -import fun.asgc.neutrino.core.type.TypeMatcher; -import fun.asgc.neutrino.core.util.TypeUtil; - -/** - * 字符串匹配器组 - * @author: aoshiguchen - * @date: 2022/6/29 - */ -public class NumberMatcherGroup extends AbstractMatcherGroup { - - public NumberMatcherGroup(int distanceMin, int distanceMax) { - super(distanceMin, distanceMax); - } - - @Override - public void init() { - // String -> Byte - add(new TypeMatcher() { - @Override - public TypeMatchInfo match(Class clazz, Class targetClass) { - TypeMatchInfo matchInfo = new TypeMatchInfo(clazz, targetClass, this); - if (TypeUtil.isString(clazz) && TypeUtil.isByte(targetClass)) { - matchInfo.setTypeDistance(getDistanceMin()); - matchInfo.setTypeConverter((value, targetType) -> { - try { - return Byte.valueOf((String)value); - } catch (Exception e) { - // ignore - } - return 0; - }); - } - return matchInfo; - } - }); - // String -> Short - add(new TypeMatcher() { - @Override - public TypeMatchInfo match(Class clazz, Class targetClass) { - TypeMatchInfo matchInfo = new TypeMatchInfo(clazz, targetClass, this); - if (TypeUtil.isString(clazz) && TypeUtil.isShort(targetClass)) { - matchInfo.setTypeDistance(getDistanceMin() + 1); - matchInfo.setTypeConverter((value, targetType) -> { - try { - return Short.valueOf((String)value); - } catch (Exception e) { - // ignore - } - return 0; - }); - } - return matchInfo; - } - }); - // String -> Integer - add(new TypeMatcher() { - @Override - public TypeMatchInfo match(Class clazz, Class targetClass) { - TypeMatchInfo matchInfo = new TypeMatchInfo(clazz, targetClass, this); - if (TypeUtil.isString(clazz) && TypeUtil.isInteger(targetClass)) { - matchInfo.setTypeDistance(getDistanceMin() + 2); - matchInfo.setTypeConverter((value, targetType) -> { - try { - return Integer.valueOf((String)value); - } catch (Exception e) { - // ignore - } - return 0; - }); - } - return matchInfo; - } - }); - // String -> Long - add(new TypeMatcher() { - @Override - public TypeMatchInfo match(Class clazz, Class targetClass) { - TypeMatchInfo matchInfo = new TypeMatchInfo(clazz, targetClass, this); - if (TypeUtil.isString(clazz) && TypeUtil.isLong(targetClass)) { - matchInfo.setTypeDistance(getDistanceMin() + 3); - matchInfo.setTypeConverter((value, targetType) -> { - try { - return Long.valueOf((String)value); - } catch (Exception e) { - // ignore - } - return 0; - }); - } - return matchInfo; - } - }); - // String -> Float - add(new TypeMatcher() { - @Override - public TypeMatchInfo match(Class clazz, Class targetClass) { - TypeMatchInfo matchInfo = new TypeMatchInfo(clazz, targetClass, this); - if (TypeUtil.isString(clazz) && TypeUtil.isFloat(targetClass)) { - matchInfo.setTypeDistance(getDistanceMin() + 4); - matchInfo.setTypeConverter((value, targetType) -> { - try { - return Float.valueOf((String)value); - } catch (Exception e) { - // ignore - } - return 0; - }); - } - return matchInfo; - } - }); - // String -> Double - add(new TypeMatcher() { - @Override - public TypeMatchInfo match(Class clazz, Class targetClass) { - TypeMatchInfo matchInfo = new TypeMatchInfo(clazz, targetClass, this); - if (TypeUtil.isString(clazz) && TypeUtil.isDouble(targetClass)) { - matchInfo.setTypeDistance(getDistanceMin() + 5); - matchInfo.setTypeConverter((value, targetType) -> { - try { - return Double.valueOf((String)value); - } catch (Exception e) { - // ignore - } - return 0; - }); - } - return matchInfo; - } - }); - // date -> Long - add(new TypeMatcher() { - @Override - public TypeMatchInfo match(Class clazz, Class targetClass) { - TypeMatchInfo matchInfo = new TypeMatchInfo(clazz, targetClass, this); - if (TypeUtil.isLong(targetClass) && TypeUtil.isDate(clazz)) { - matchInfo.setTypeDistance(getDistanceMin() + 6); - matchInfo.setTypeConverter(((value, targetType) -> ((java.util.Date)value).getTime())); - } - return matchInfo; - } - }); - // Long - > int - add(new TypeMatcher() { - @Override - public TypeMatchInfo match(Class clazz, Class targetClass) { - TypeMatchInfo matchInfo = new TypeMatchInfo(clazz, targetClass, this); - if (TypeUtil.isInteger(targetClass) && TypeUtil.isLong(clazz)) { - matchInfo.setTypeDistance(getDistanceMin() + 7); - matchInfo.setTypeConverter(((value, targetType) -> ((Long)value).intValue())); - } - return matchInfo; - } - }); - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/extension/SetMatcherGroup.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/extension/SetMatcherGroup.java deleted file mode 100644 index e4c2a715..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/extension/SetMatcherGroup.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.type.extension; - -import fun.asgc.neutrino.core.type.AbstractMatcherGroup; -import fun.asgc.neutrino.core.type.TypeMatchInfo; -import fun.asgc.neutrino.core.type.TypeMatcher; - -import java.util.Collection; -import java.util.Set; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -/** - * set匹配器组 - * @author: aoshiguchen - * @date: 2022/6/29 - */ -public class SetMatcherGroup extends AbstractMatcherGroup { - - public SetMatcherGroup(int distanceMin, int distanceMax) { - super(distanceMin, distanceMax); - } - - @Override - public void init() { - add(new TypeMatcher() { - @Override - public TypeMatchInfo match(Class clazz, Class targetClass) { - TypeMatchInfo matchInfo = new TypeMatchInfo(clazz, targetClass, this); - if (Set.class == targetClass && clazz.isArray()) { - matchInfo.setTypeDistance(getDistanceMin()); - matchInfo.setTypeConverter(((value, targetType) -> Stream.of((Object[])value).collect(Collectors.toSet()))); - } - return matchInfo; - } - }); - add(new TypeMatcher() { - @Override - public TypeMatchInfo match(Class clazz, Class targetClass) { - TypeMatchInfo matchInfo = new TypeMatchInfo(clazz, targetClass, this); - if (Set.class == targetClass && Collection.class.isAssignableFrom(clazz)) { - matchInfo.setTypeDistance(getDistanceMin() + 1); - matchInfo.setTypeConverter(((value, targetType) -> ((Collection)value).stream().collect(Collectors.toSet()))); - } - return matchInfo; - } - }); - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/extension/StringMatcherGroup.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/extension/StringMatcherGroup.java deleted file mode 100644 index 3da9c327..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/extension/StringMatcherGroup.java +++ /dev/null @@ -1,68 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.type.extension; - -import fun.asgc.neutrino.core.type.AbstractMatcherGroup; -import fun.asgc.neutrino.core.type.TypeMatchInfo; -import fun.asgc.neutrino.core.type.TypeMatcher; -import fun.asgc.neutrino.core.util.TypeUtil; - -/** - * 字符串匹配器组 - * @author: aoshiguchen - * @date: 2022/6/29 - */ -public class StringMatcherGroup extends AbstractMatcherGroup { - - public StringMatcherGroup(int distanceMin, int distanceMax) { - super(distanceMin, distanceMax); - } - - @Override - public void init() { - // 基本类型 -> String - add(new TypeMatcher() { - @Override - public TypeMatchInfo match(Class clazz, Class targetClass) { - TypeMatchInfo matchInfo = new TypeMatchInfo(clazz, targetClass, this); - if (TypeUtil.isNormalBasicType(clazz) && TypeUtil.isString(targetClass)) { - matchInfo.setTypeDistance(getDistanceMin()); - matchInfo.setTypeConverter(((value, targetType) -> String.valueOf(value))); - } - return matchInfo; - } - }); - // String -> char - add(new TypeMatcher() { - @Override - public TypeMatchInfo match(Class clazz, Class targetClass) { - TypeMatchInfo matchInfo = new TypeMatchInfo(clazz, targetClass, this); - if (TypeUtil.isChar(targetClass) && TypeUtil.isString(clazz)) { - matchInfo.setTypeDistance(getDistanceMin() + 1); - matchInfo.setTypeConverter(((value, targetType) -> ((String)value).charAt(0))); - } - return matchInfo; - } - }); - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/ArrayUtil.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/ArrayUtil.java deleted file mode 100644 index 2bea83aa..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/ArrayUtil.java +++ /dev/null @@ -1,49 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.util; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -public class ArrayUtil { - - /** - * 判断数组是否为空 - * @param arr - * @return - */ - public static boolean isEmpty(Object[] arr) { - return null == arr || arr.length == 0; - } - - /** - * 判断数组是否非空 - * @param arr - * @return - */ - public static boolean notEmpty(Object[] arr) { - return !isEmpty(arr); - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/Assert.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/Assert.java deleted file mode 100644 index 50c61468..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/Assert.java +++ /dev/null @@ -1,418 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.util; - -import org.apache.commons.lang3.ObjectUtils; - -import java.util.Collection; -import java.util.Map; -import java.util.function.Supplier; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -public abstract class Assert { - - /** - * - * @param expression - * @param message - */ - public static void state(boolean expression, String message) { - if (!expression) { - throw new IllegalStateException(message); - } - } - - /** - * - * @param expression - * @param messageSupplier - */ - public static void state(boolean expression, Supplier messageSupplier) { - if (!expression) { - throw new IllegalStateException(nullSafeGet(messageSupplier)); - } - } - - /** - * - * @param expression - * @param message - */ - public static void isTrue(boolean expression, String message) { - if (!expression) { - throw new IllegalArgumentException(message); - } - } - - /** - * - * @param expression - * @param messageSupplier - */ - public static void isTrue(boolean expression, Supplier messageSupplier) { - if (!expression) { - throw new IllegalArgumentException(nullSafeGet(messageSupplier)); - } - } - - /** - * - * @param object - * @param message - */ - public static void isNull(Object object, String message) { - if (object != null) { - throw new IllegalArgumentException(message); - } - } - - /** - * - * @param object - * @param messageSupplier - */ - public static void isNull(Object object, Supplier messageSupplier) { - if (object != null) { - throw new IllegalArgumentException(nullSafeGet(messageSupplier)); - } - } - - /** - * - * @param object - * @param message - */ - public static void notNull(Object object, String message) { - if (object == null) { - throw new IllegalArgumentException(message); - } - } - - /** - * - * @param object - * @param messageSupplier - */ - public static void notNull(Object object, Supplier messageSupplier) { - if (object == null) { - throw new IllegalArgumentException(nullSafeGet(messageSupplier)); - } - } - - /** - * - * @param text - * @param message - */ - public static void hasLength(String text, String message) { - if (!StringUtil.hasLength(text)) { - throw new IllegalArgumentException(message); - } - } - - /** - * - * @param text - * @param messageSupplier - */ - public static void hasLength(String text, Supplier messageSupplier) { - if (!StringUtil.hasLength(text)) { - throw new IllegalArgumentException(nullSafeGet(messageSupplier)); - } - } - - /** - * - * @param text - * @param message - */ - public static void hasText(String text, String message) { - if (!StringUtil.hasText(text)) { - throw new IllegalArgumentException(message); - } - } - - /** - * - * @param text - * @param messageSupplier - */ - public static void hasText(String text, Supplier messageSupplier) { - if (!StringUtil.hasText(text)) { - throw new IllegalArgumentException(nullSafeGet(messageSupplier)); - } - } - - /** - * - * @param textToSearch - * @param substring - * @param message - */ - public static void doesNotContain(String textToSearch, String substring, String message) { - if (StringUtil.hasLength(textToSearch) && StringUtil.hasLength(substring) && - textToSearch.contains(substring)) { - throw new IllegalArgumentException(message); - } - } - - /** - * - * @param textToSearch - * @param substring - * @param messageSupplier - */ - public static void doesNotContain(String textToSearch, String substring, Supplier messageSupplier) { - if (StringUtil.hasLength(textToSearch) && StringUtil.hasLength(substring) && - textToSearch.contains(substring)) { - throw new IllegalArgumentException(nullSafeGet(messageSupplier)); - } - } - - /** - * - * @param array - * @param message - */ - public static void notEmpty(Object[] array, String message) { - if (ObjectUtils.isEmpty(array)) { - throw new IllegalArgumentException(message); - } - } - - public static void notEmpty(String s, String message) { - if (StringUtil.isEmpty(s)) { - throw new IllegalArgumentException(message); - } - } - - /** - * - * @param array - * @param messageSupplier - */ - public static void notEmpty(Object[] array, Supplier messageSupplier) { - if (ObjectUtils.isEmpty(array)) { - throw new IllegalArgumentException(nullSafeGet(messageSupplier)); - } - } - - /** - * - * @param array - * @param message - */ - public static void noNullElements(Object[] array, String message) { - if (array != null) { - for (Object element : array) { - if (element == null) { - throw new IllegalArgumentException(message); - } - } - } - } - - /** - * - * @param array - * @param messageSupplier - */ - public static void noNullElements(Object[] array, Supplier messageSupplier) { - if (array != null) { - for (Object element : array) { - if (element == null) { - throw new IllegalArgumentException(nullSafeGet(messageSupplier)); - } - } - } - } - - /** - * - * @param collection - * @param message - */ - public static void notEmpty(Collection collection, String message) { - if (CollectionUtil.isEmpty(collection)) { - throw new IllegalArgumentException(message); - } - } - - /** - * - * @param collection - * @param messageSupplier - */ - public static void notEmpty(Collection collection, Supplier messageSupplier) { - if (CollectionUtil.isEmpty(collection)) { - throw new IllegalArgumentException(nullSafeGet(messageSupplier)); - } - } - - /** - * - * @param map - * @param message - */ - public static void notEmpty(Map map, String message) { - if (CollectionUtil.isEmpty(map)) { - throw new IllegalArgumentException(message); - } - } - - /** - * - * @param map - * @param messageSupplier - */ - public static void notEmpty(Map map, Supplier messageSupplier) { - if (CollectionUtil.isEmpty(map)) { - throw new IllegalArgumentException(nullSafeGet(messageSupplier)); - } - } - - /** - * - * @param type - * @param obj - * @param message - */ - public static void isInstanceOf(Class type, Object obj, String message) { - notNull(type, "Type to check against must not be null"); - if (!type.isInstance(obj)) { - instanceCheckFailed(type, obj, message); - } - } - - /** - * - * @param type - * @param obj - * @param messageSupplier - */ - public static void isInstanceOf(Class type, Object obj, Supplier messageSupplier) { - notNull(type, "Type to check against must not be null"); - if (!type.isInstance(obj)) { - instanceCheckFailed(type, obj, nullSafeGet(messageSupplier)); - } - } - - /** - * - * @param type - * @param obj - */ - public static void isInstanceOf(Class type, Object obj) { - isInstanceOf(type, obj, ""); - } - - /** - * - * @param superType - * @param subType - * @param message - */ - public static void isAssignable(Class superType, Class subType, String message) { - notNull(superType, "Super type to check against must not be null"); - if (subType == null || !superType.isAssignableFrom(subType)) { - assignableCheckFailed(superType, subType, message); - } - } - - /** - * - * @param superType - * @param subType - * @param messageSupplier - */ - public static void isAssignable(Class superType, Class subType, Supplier messageSupplier) { - notNull(superType, "Super type to check against must not be null"); - if (subType == null || !superType.isAssignableFrom(subType)) { - assignableCheckFailed(superType, subType, nullSafeGet(messageSupplier)); - } - } - - /** - * - * @param superType - * @param subType - */ - public static void isAssignable(Class superType, Class subType) { - isAssignable(superType, subType, ""); - } - - - private static void instanceCheckFailed(Class type, Object obj, String msg) { - String className = (obj != null ? obj.getClass().getName() : "null"); - String result = ""; - boolean defaultMessage = true; - if (StringUtil.hasLength(msg)) { - if (endsWithSeparator(msg)) { - result = msg + " "; - } - else { - result = messageWithTypeName(msg, className); - defaultMessage = false; - } - } - if (defaultMessage) { - result = result + ("Object of class [" + className + "] must be an instance of " + type); - } - throw new IllegalArgumentException(result); - } - - private static void assignableCheckFailed(Class superType, Class subType, String msg) { - String result = ""; - boolean defaultMessage = true; - if (StringUtil.hasLength(msg)) { - if (endsWithSeparator(msg)) { - result = msg + " "; - } - else { - result = messageWithTypeName(msg, subType); - defaultMessage = false; - } - } - if (defaultMessage) { - result = result + (subType + " is not assignable to " + superType); - } - throw new IllegalArgumentException(result); - } - - private static boolean endsWithSeparator(String msg) { - return (msg.endsWith(":") || msg.endsWith(";") || msg.endsWith(",") || msg.endsWith(".")); - } - - private static String messageWithTypeName(String msg, Object typeName) { - return msg + (msg.endsWith(" ") ? "" : ": ") + typeName; - } - - private static String nullSafeGet(Supplier messageSupplier) { - return (messageSupplier != null ? messageSupplier.get() : null); - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/BeanManager.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/BeanManager.java deleted file mode 100644 index 7032490e..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/BeanManager.java +++ /dev/null @@ -1,90 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.util; - -import fun.asgc.neutrino.core.annotation.Component; -import fun.asgc.neutrino.core.bean.factory.BeanFactory; -import fun.asgc.neutrino.core.bean.factory.BeanFactoryAware; -import fun.asgc.neutrino.core.bean.BeanIdentity; -import fun.asgc.neutrino.core.exception.BeanException; -import lombok.extern.slf4j.Slf4j; - -import java.util.List; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -@Slf4j -@Component -public class BeanManager implements BeanFactoryAware { - private static volatile BeanFactory beanFactory; - - @Override - public void setBeanFactory(BeanFactory beanFactory) { - BeanManager.beanFactory = beanFactory; - } - - public static Object getBean(String name) { - if (null == beanFactory) { - throw new RuntimeException("BeanFactory尚未初始化"); - } - return beanFactory.getBean(name); - } - - public static T getBean(Class clazz) { - if (null == beanFactory) { - throw new RuntimeException("BeanFactory尚未初始化"); - } - return beanFactory.getBean(clazz); - } - - /** - * 尝试根据Bean身份标识获取bean - * @param identity - * @param - * @return - * @throws BeanException - */ - public static T getBean(BeanIdentity identity) { - if (null == beanFactory) { - throw new RuntimeException("BeanFactory尚未初始化"); - } - return beanFactory.getBean(identity); - } - - /** - * 根据超类获取bean集合 - * @param superClass - * @param - * @return - */ - public static List getBeanListBySuperClass(Class superClass) { - if (null == beanFactory) { - throw new RuntimeException("BeanFactory尚未初始化"); - } - return beanFactory.getBeanList(superClass); - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/ClassUtil.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/ClassUtil.java deleted file mode 100644 index 948d8f55..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/ClassUtil.java +++ /dev/null @@ -1,322 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.util; - -import fun.asgc.neutrino.core.annotation.Component; -import fun.asgc.neutrino.core.aop.support.Async; -import fun.asgc.neutrino.core.aop.support.Singleton; -import fun.asgc.neutrino.core.cache.Cache; -import fun.asgc.neutrino.core.cache.MemoryCache; -import lombok.extern.slf4j.Slf4j; - -import java.io.File; -import java.io.FileFilter; -import java.io.IOException; -import java.lang.annotation.Annotation; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.net.JarURLConnection; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.*; -import java.util.jar.JarEntry; -import java.util.jar.JarFile; -import java.util.stream.Stream; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -@Slf4j -public class ClassUtil { - - private static Cache>> classesCache = new MemoryCache<>(); - private static Cache>> componentsCache = new MemoryCache<>(); - - /** - * 类扫描 - * @param packageName - * @return - */ - public static Set> scanComponents(String packageName) throws IOException, ClassNotFoundException { - if (StringUtil.isEmpty(packageName)) { - return null; - } - if (componentsCache.containsKey(packageName)) { - componentsCache.get(packageName); - } - - Set> result = new HashSet<>(); - Set> classes = scan(packageName); - for (Class clazz : classes) { - if (isAnnotateWith(clazz, Component.class)) { - if (!(clazz.isAnnotation() || clazz.isEnum())) { - log.debug("scan component {}", clazz.getName()); - result.add(clazz); - } - } - } - componentsCache.set(packageName, result); - return result; - } - - /** - * 类扫描 - * @param packages - * @return - */ - public static Set> scanComponents(Collection packages) throws IOException, ClassNotFoundException { - if (CollectionUtil.isEmpty(packages)) { - return null; - } - Set> classes = new HashSet<>(); - for (String packageName : packages) { - Set> tmp = scanComponents(packageName); - if (CollectionUtil.notEmpty(tmp)) { - classes.addAll(tmp); - } - } - return classes; - } - - public static Set> scan(List packageNames) throws IOException, ClassNotFoundException{ - Set> result = new HashSet<>(); - if (null != packageNames && packageNames.size() > 0) { - for (String packageName : packageNames) { - Set> tmp = scan(packageName); - if (null != tmp) { - result.addAll(tmp); - } - - } - } - return result; - } - - /** - * 类扫描 - * @param packageName - * @return - */ - public static Set> scan(String packageName) throws IOException, ClassNotFoundException { - if (StringUtil.isEmpty(packageName)) { - return null; - } - if (classesCache.containsKey(packageName)) { - return classesCache.get(packageName); - } - log.info("开始进行类扫描,扫描包:{}", packageName); - Set> classes = new HashSet<>(); - Enumeration resources = Thread.currentThread().getContextClassLoader().getResources(""); - while (resources.hasMoreElements()) { - classes.addAll(scan(packageName, resources.nextElement())); - } - if (SystemUtil.isStartupFromJar()) { - classes.addAll(scan(packageName, new URL("jar:file:" + SystemUtil.getCurrentJarFilePath() + "!/"))); - } - log.info("扫描完毕,包:{}下一共有:{}个类", packageName, classes.size()); - classesCache.set(packageName, classes); - return classes; - } - - public static Set> scan(String packageName, URL url) throws IOException, ClassNotFoundException { - Set> result = new HashSet<>(); - if (null == url) { - return result; - } - String packagePath = packageName.replace(".", "/"); - URLClassLoader urlClassLoader = new URLClassLoader(new URL[]{url}, Thread.currentThread().getContextClassLoader()); - log.info(url.toString()); - String protocol = url.getProtocol(); - if ("jar".equals(protocol)) { - JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection(); - JarFile jarFile = jarURLConnection.getJarFile(); - Enumeration entries = jarFile.entries(); - while (entries.hasMoreElements()) { - JarEntry jarEntry = entries.nextElement(); - String name = jarEntry.getName(); - int index = name.indexOf(packagePath); - if (index != -1 && name.endsWith(".class")) { - String replace = name.substring(index, name.length() - 6).replace("/", "."); - Class clazz = urlClassLoader.loadClass(replace); - log.debug("scan class {}", clazz.getName()); - result.add(clazz); - } - } - } else if ("file".endsWith(protocol)) { - String path = url.getPath(); - String targetPath = path + "/" + packagePath; - addClasses(targetPath, result, packageName); - } - return result; - } - - private static void addClasses(String path, Set> classes, String packageName) throws ClassNotFoundException { - File[] files = new File(path).listFiles(new FileFilter() { - @Override - public boolean accept(File file) { - return (file.isFile() && file.getName().endsWith(".class")) || file.isDirectory(); - } - }); - if (ArrayUtil.isEmpty(files)) { - return; - } - - for (File file : files) { - String fileName = file.getName(); - if (file.isFile()) { - String className = fileName.substring(0, fileName.lastIndexOf(".")); - String fullClassName = packageName + "." + className; - Class clazz = Thread.currentThread().getContextClassLoader().loadClass(fullClassName); - log.debug("scan class {}", clazz.getName()); - classes.add(clazz); - } else { - String subPackagePath = path + "/" + fileName; - String subPackageName = packageName + "." + fileName; - addClasses(subPackagePath, classes, subPackageName); - } - } - } - - public static boolean isAnnotateWith(Class clazz, Class targetAnnotation) { - Annotation[] annotations = clazz.getAnnotations(); - for (Annotation annotation : annotations) { - Class aClass = annotation.annotationType(); - if (aClass.equals(targetAnnotation)) { - return true; - } - if (aClass.isAnnotationPresent(targetAnnotation)) { - return true; - } - } - return false; - } - - public static T getAnnotation(Class clazz, Class annotationType) { - T annotation = clazz.getAnnotation(annotationType); - if (null == annotation) { - Annotation[] annotations = clazz.getAnnotations(); - for (Annotation item : annotations) { - Class aClass = item.annotationType(); - if (aClass.isAnnotationPresent(annotationType)) { - return aClass.getAnnotation(annotationType); - } - } - } - return annotation; - } - - public static T getAnnotation(Method method, Class annotationType) { - T annotation = method.getAnnotation(annotationType); - if (null == annotation) { - Annotation[] annotations = method.getAnnotations(); - for (Annotation item : annotations) { - Class aClass = item.annotationType(); - if (aClass.isAnnotationPresent(annotationType)) { - return aClass.getAnnotation(annotationType); - } - } - } - return annotation; - } - - public static boolean isAnnotationPresent(Method method, Class annotationType) { - Annotation annotation = method.getAnnotation(annotationType); - if (null != annotation) { - return true; - } - if (null == annotation) { - Annotation[] annotations = method.getAnnotations(); - for (Annotation item : annotations) { - Class aClass = item.annotationType(); - if (aClass.isAnnotationPresent(annotationType)) { - return true; - } - } - } - return false; - } - - public static Singleton getSingletonAnnotation(Method method) { - Singleton singleton = getAnnotation(method, Singleton.class); - if (null != singleton) { - return singleton; - } - return getAnnotation(method.getDeclaringClass(), Singleton.class); - } - - public static Async getAsyncAnnotation(Method method) { - Async async = getAnnotation(method, Async.class); - if (null != async) { - return async; - } - return getAnnotation(method.getDeclaringClass(), Async.class); - } - - public static boolean isPublic(Class clazz) { - return Modifier.isPublic(clazz.getModifiers()); - } - - public static boolean isPrivate(Class clazz) { - return Modifier.isPrivate(clazz.getModifiers()); - } - - public static boolean isProtected(Class clazz) { - return Modifier.isProtected(clazz.getModifiers()); - } - - public static boolean isFinal(Class clazz) { - return Modifier.isFinal(clazz.getModifiers()); - } - - public static boolean isAbstract(Class clazz) { - return Modifier.isAbstract(clazz.getModifiers()); - } - - public static boolean isStatic(Class clazz) { - return Modifier.isStatic(clazz.getModifiers()); - } - - public static boolean isInterface(Class clazz) { - return clazz.isInterface(); - } - - public static boolean hasNoArgsConstructor(Class clazz) { - return Stream.of(clazz.getConstructors()).filter(c -> c.getParameterCount() == 0).count() > 0; - } - - /** - * 获取bean名称 - * @param type - * @return - */ - public static String getBeanName(Class type) { - String name = TypeUtil.getDefaultVariableName(type); - Component component = ClassUtil.getAnnotation(type, Component.class); - if (null != component && StringUtil.notEmpty(component.value())) { - name = component.value(); - } - return name; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/CollectionUtil.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/CollectionUtil.java deleted file mode 100644 index 6b78d142..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/CollectionUtil.java +++ /dev/null @@ -1,364 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.util; - -import org.apache.commons.lang3.ObjectUtils; - -import java.util.*; -import java.util.function.Supplier; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -public class CollectionUtil { - - /** - * - * @param collection - * @return - */ - public static boolean isEmpty(Collection collection) { - return (collection == null || collection.isEmpty()); - } - - /** - * - * @param map - * @return - */ - public static boolean isEmpty(Map map) { - return (map == null || map.isEmpty()); - } - - /** - * - * @param collection - * @return - */ - public static boolean notEmpty(Collection collection) { - return !isEmpty(collection); - } - - public static boolean notEmpty(Map map) { - return !isEmpty(map); - } - - - /** - * - * @param source - * @return - */ - @SuppressWarnings("rawtypes") - public static List arrayToList(Object source) { - return Arrays.asList(ObjectUtil.toObjectArray(source)); - } - - /** - * - * @param array - * @param collection - * @param - */ - @SuppressWarnings("unchecked") - public static void mergeArrayIntoCollection(Object array, Collection collection) { - Object[] arr = ObjectUtil.toObjectArray(array); - for (Object elem : arr) { - collection.add((E) elem); - } - } - - /** - * - * @param props - * @param map - * @param - * @param - */ - @SuppressWarnings("unchecked") - public static void mergePropertiesIntoMap(Properties props, Map map) { - if (props != null) { - for (Enumeration en = props.propertyNames(); en.hasMoreElements();) { - String key = (String) en.nextElement(); - Object value = props.get(key); - if (value == null) { - // Allow for defaults fallback or potentially overridden accessor... - value = props.getProperty(key); - } - map.put((K) key, (V) value); - } - } - } - - /** - * - * @param iterator - * @param element - * @return - */ - public static boolean contains(Iterator iterator, Object element) { - if (iterator != null) { - while (iterator.hasNext()) { - Object candidate = iterator.next(); - if (ObjectUtil.nullSafeEquals(candidate, element)) { - return true; - } - } - } - return false; - } - - /** - * - * @param enumeration - * @param element - * @return - */ - public static boolean contains(Enumeration enumeration, Object element) { - if (enumeration != null) { - while (enumeration.hasMoreElements()) { - Object candidate = enumeration.nextElement(); - if (ObjectUtil.nullSafeEquals(candidate, element)) { - return true; - } - } - } - return false; - } - - /** - * - * @param collection - * @param element - * @return - */ - public static boolean containsInstance(Collection collection, Object element) { - if (collection != null) { - for (Object candidate : collection) { - if (candidate == element) { - return true; - } - } - } - return false; - } - - /** - * - * @param source - * @param candidates - * @return - */ - public static boolean containsAny(Collection source, Collection candidates) { - if (isEmpty(source) || isEmpty(candidates)) { - return false; - } - for (Object candidate : candidates) { - if (source.contains(candidate)) { - return true; - } - } - return false; - } - - /** - * - * @param source - * @param candidates - * @param - * @return - */ - @SuppressWarnings("unchecked") - public static E findFirstMatch(Collection source, Collection candidates) { - if (isEmpty(source) || isEmpty(candidates)) { - return null; - } - for (Object candidate : candidates) { - if (source.contains(candidate)) { - return (E) candidate; - } - } - return null; - } - - /** - * - * @param collection - * @param type - * @param - * @return - */ - @SuppressWarnings("unchecked") - public static T findValueOfType(Collection collection, Class type) { - if (isEmpty(collection)) { - return null; - } - T value = null; - for (Object element : collection) { - if (type == null || type.isInstance(element)) { - if (value != null) { - // More than one value found... no clear single value. - return null; - } - value = (T) element; - } - } - return value; - } - - /** - * - * @param collection - * @param types - * @return - */ - public static Object findValueOfType(Collection collection, Class[] types) { - if (isEmpty(collection) || ObjectUtils.isEmpty(types)) { - return null; - } - for (Class type : types) { - Object value = findValueOfType(collection, type); - if (value != null) { - return value; - } - } - return null; - } - - /** - * - * @param collection - * @return - */ - public static boolean hasUniqueObject(Collection collection) { - if (isEmpty(collection)) { - return false; - } - boolean hasCandidate = false; - Object candidate = null; - for (Object elem : collection) { - if (!hasCandidate) { - hasCandidate = true; - candidate = elem; - } - else if (candidate != elem) { - return false; - } - } - return true; - } - - /** - * - * @param collection - * @return - */ - public static Class findCommonElementType(Collection collection) { - if (isEmpty(collection)) { - return null; - } - Class candidate = null; - for (Object val : collection) { - if (val != null) { - if (candidate == null) { - candidate = val.getClass(); - } - else if (candidate != val.getClass()) { - return null; - } - } - } - return candidate; - } - - /** - * - * @param set - * @param - * @return - */ - public static T lastElement(Set set) { - if (isEmpty(set)) { - return null; - } - if (set instanceof SortedSet) { - return ((SortedSet) set).last(); - } - - // Full iteration necessary... - Iterator it = set.iterator(); - T last = null; - while (it.hasNext()) { - last = it.next(); - } - return last; - } - - /** - * - * @param list - * @param - * @return - */ - public static T lastElement(List list) { - if (isEmpty(list)) { - return null; - } - return list.get(list.size() - 1); - } - - /** - * - * @param enumeration - * @param array - * @param - * @param - * @return - */ - public static A[] toArray(Enumeration enumeration, A[] array) { - ArrayList elements = new ArrayList<>(); - while (enumeration.hasMoreElements()) { - elements.add(enumeration.nextElement()); - } - return elements.toArray(array); - } - - /** - * 将另一个集合的内容添加到指定集合中 - * @param supplier - * @param list - */ - public static List addAll(Supplier> supplier, List ...list) { - List res = supplier.get(); - if (ArrayUtil.notEmpty(list)) { - for (List l : list) { - if (null != l && CollectionUtil.notEmpty(l)) { - res.addAll(l); - } - } - } - return res; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/ConcurrentReferenceHashMap.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/ConcurrentReferenceHashMap.java deleted file mode 100644 index fc14aa9d..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/ConcurrentReferenceHashMap.java +++ /dev/null @@ -1,1017 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.util; - -import java.lang.ref.ReferenceQueue; -import java.lang.ref.SoftReference; -import java.lang.ref.WeakReference; -import java.lang.reflect.Array; -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.locks.ReentrantLock; - -/** - * @author: aoshiguchen - * @date: 2022/9/24 - */ -public class ConcurrentReferenceHashMap extends AbstractMap implements ConcurrentMap { - - private static final int DEFAULT_INITIAL_CAPACITY = 16; - - private static final float DEFAULT_LOAD_FACTOR = 0.75f; - - private static final int DEFAULT_CONCURRENCY_LEVEL = 16; - - private static final ReferenceType DEFAULT_REFERENCE_TYPE = ReferenceType.SOFT; - - private static final int MAXIMUM_CONCURRENCY_LEVEL = 1 << 16; - - private static final int MAXIMUM_SEGMENT_SIZE = 1 << 30; - - - /** - * Array of segments indexed using the high order bits from the hash. - */ - private final Segment[] segments; - - /** - * When the average number of references per table exceeds this value resize will be attempted. - */ - private final float loadFactor; - - /** - * The reference type: SOFT or WEAK. - */ - private final ReferenceType referenceType; - - /** - * The shift value used to calculate the size of the segments array and an index from the hash. - */ - private final int shift; - - /** - * Late binding entry set. - */ - private volatile Set> entrySet; - - - /** - * Create a new {@code ConcurrentReferenceHashMap} instance. - */ - public ConcurrentReferenceHashMap() { - this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL, DEFAULT_REFERENCE_TYPE); - } - - /** - * Create a new {@code ConcurrentReferenceHashMap} instance. - * @param initialCapacity the initial capacity of the map - */ - public ConcurrentReferenceHashMap(int initialCapacity) { - this(initialCapacity, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL, DEFAULT_REFERENCE_TYPE); - } - - /** - * Create a new {@code ConcurrentReferenceHashMap} instance. - * @param initialCapacity the initial capacity of the map - * @param loadFactor the load factor. When the average number of references per table - * exceeds this value resize will be attempted - */ - public ConcurrentReferenceHashMap(int initialCapacity, float loadFactor) { - this(initialCapacity, loadFactor, DEFAULT_CONCURRENCY_LEVEL, DEFAULT_REFERENCE_TYPE); - } - - /** - * Create a new {@code ConcurrentReferenceHashMap} instance. - * @param initialCapacity the initial capacity of the map - * @param concurrencyLevel the expected number of threads that will concurrently - * write to the map - */ - public ConcurrentReferenceHashMap(int initialCapacity, int concurrencyLevel) { - this(initialCapacity, DEFAULT_LOAD_FACTOR, concurrencyLevel, DEFAULT_REFERENCE_TYPE); - } - - /** - * Create a new {@code ConcurrentReferenceHashMap} instance. - * @param initialCapacity the initial capacity of the map - * @param referenceType the reference type used for entries (soft or weak) - */ - public ConcurrentReferenceHashMap(int initialCapacity, ReferenceType referenceType) { - this(initialCapacity, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL, referenceType); - } - - /** - * Create a new {@code ConcurrentReferenceHashMap} instance. - * @param initialCapacity the initial capacity of the map - * @param loadFactor the load factor. When the average number of references per - * table exceeds this value, resize will be attempted. - * @param concurrencyLevel the expected number of threads that will concurrently - * write to the map - */ - public ConcurrentReferenceHashMap(int initialCapacity, float loadFactor, int concurrencyLevel) { - this(initialCapacity, loadFactor, concurrencyLevel, DEFAULT_REFERENCE_TYPE); - } - - /** - * Create a new {@code ConcurrentReferenceHashMap} instance. - * @param initialCapacity the initial capacity of the map - * @param loadFactor the load factor. When the average number of references per - * table exceeds this value, resize will be attempted. - * @param concurrencyLevel the expected number of threads that will concurrently - * write to the map - * @param referenceType the reference type used for entries (soft or weak) - */ - @SuppressWarnings("unchecked") - public ConcurrentReferenceHashMap( - int initialCapacity, float loadFactor, int concurrencyLevel, ReferenceType referenceType) { - - Assert.isTrue(initialCapacity >= 0, "Initial capacity must not be negative"); - Assert.isTrue(loadFactor > 0f, "Load factor must be positive"); - Assert.isTrue(concurrencyLevel > 0, "Concurrency level must be positive"); - Assert.notNull(referenceType, "Reference type must not be null"); - this.loadFactor = loadFactor; - this.shift = calculateShift(concurrencyLevel, MAXIMUM_CONCURRENCY_LEVEL); - int size = 1 << this.shift; - this.referenceType = referenceType; - int roundedUpSegmentCapacity = (int) ((initialCapacity + size - 1L) / size); - this.segments = (Segment[]) Array.newInstance(Segment.class, size); - for (int i = 0; i < this.segments.length; i++) { - this.segments[i] = new Segment(roundedUpSegmentCapacity); - } - } - - - protected final float getLoadFactor() { - return this.loadFactor; - } - - protected final int getSegmentsSize() { - return this.segments.length; - } - - protected final Segment getSegment(int index) { - return this.segments[index]; - } - - /** - * Factory method that returns the {@link ReferenceManager}. - * This method will be called once for each {@link Segment}. - * @return a new reference manager - */ - protected ReferenceManager createReferenceManager() { - return new ReferenceManager(); - } - - /** - * Get the hash for a given object, apply an additional hash function to reduce - * collisions. This implementation uses the same Wang/Jenkins algorithm as - * {@link ConcurrentHashMap}. Subclasses can override to provide alternative hashing. - * @param o the object to hash (may be null) - * @return the resulting hash code - */ - protected int getHash(Object o) { - int hash = (o != null ? o.hashCode() : 0); - hash += (hash << 15) ^ 0xffffcd7d; - hash ^= (hash >>> 10); - hash += (hash << 3); - hash ^= (hash >>> 6); - hash += (hash << 2) + (hash << 14); - hash ^= (hash >>> 16); - return hash; - } - - @Override - public V get(Object key) { - Entry entry = getEntryIfAvailable(key); - return (entry != null ? entry.getValue() : null); - } - - @Override - public V getOrDefault(Object key, V defaultValue) { - Entry entry = getEntryIfAvailable(key); - return (entry != null ? entry.getValue() : defaultValue); - } - - @Override - public boolean containsKey(Object key) { - Entry entry = getEntryIfAvailable(key); - return (entry != null && ObjectUtil.nullSafeEquals(entry.getKey(), key)); - } - - private Entry getEntryIfAvailable(Object key) { - Reference ref = getReference(key, Restructure.WHEN_NECESSARY); - return (ref != null ? ref.get() : null); - } - - /** - * Return a {@link Reference} to the {@link Entry} for the specified {@code key}, - * or {@code null} if not found. - * @param key the key (can be {@code null}) - * @param restructure types of restructure allowed during this call - * @return the reference, or {@code null} if not found - */ - protected final Reference getReference(Object key, Restructure restructure) { - int hash = getHash(key); - return getSegmentForHash(hash).getReference(key, hash, restructure); - } - - @Override - public V put(K key, V value) { - return put(key, value, true); - } - - @Override - public V putIfAbsent(K key, V value) { - return put(key, value, false); - } - - private V put(final K key, final V value, final boolean overwriteExisting) { - return doTask(key, new Task(TaskOption.RESTRUCTURE_BEFORE, TaskOption.RESIZE) { - @Override - protected V execute(Reference ref, Entry entry, Entries entries) { - if (entry != null) { - V oldValue = entry.getValue(); - if (overwriteExisting) { - entry.setValue(value); - } - return oldValue; - } - entries.add(value); - return null; - } - }); - } - - @Override - public V remove(Object key) { - return doTask(key, new Task(TaskOption.RESTRUCTURE_AFTER, TaskOption.SKIP_IF_EMPTY) { - @Override - protected V execute(Reference ref, Entry entry) { - if (entry != null) { - ref.release(); - return entry.value; - } - return null; - } - }); - } - - @Override - public boolean remove(Object key, final Object value) { - return doTask(key, new Task(TaskOption.RESTRUCTURE_AFTER, TaskOption.SKIP_IF_EMPTY) { - @Override - protected Boolean execute(Reference ref, Entry entry) { - if (entry != null && ObjectUtil.nullSafeEquals(entry.getValue(), value)) { - ref.release(); - return true; - } - return false; - } - }); - } - - @Override - public boolean replace(K key, final V oldValue, final V newValue) { - return doTask(key, new Task(TaskOption.RESTRUCTURE_BEFORE, TaskOption.SKIP_IF_EMPTY) { - @Override - protected Boolean execute(Reference ref, Entry entry) { - if (entry != null && ObjectUtil.nullSafeEquals(entry.getValue(), oldValue)) { - entry.setValue(newValue); - return true; - } - return false; - } - }); - } - - @Override - public V replace(K key, final V value) { - return doTask(key, new Task(TaskOption.RESTRUCTURE_BEFORE, TaskOption.SKIP_IF_EMPTY) { - @Override - protected V execute(Reference ref, Entry entry) { - if (entry != null) { - V oldValue = entry.getValue(); - entry.setValue(value); - return oldValue; - } - return null; - } - }); - } - - @Override - public void clear() { - for (Segment segment : this.segments) { - segment.clear(); - } - } - - /** - * Remove any entries that have been garbage collected and are no longer referenced. - * Under normal circumstances garbage collected entries are automatically purged as - * items are added or removed from the Map. This method can be used to force a purge, - * and is useful when the Map is read frequently but updated less often. - */ - public void purgeUnreferencedEntries() { - for (Segment segment : this.segments) { - segment.restructureIfNecessary(false); - } - } - - - @Override - public int size() { - int size = 0; - for (Segment segment : this.segments) { - size += segment.getCount(); - } - return size; - } - - @Override - public boolean isEmpty() { - for (Segment segment : this.segments) { - if (segment.getCount() > 0) { - return false; - } - } - return true; - } - - @Override - public Set> entrySet() { - Set> entrySet = this.entrySet; - if (entrySet == null) { - entrySet = new EntrySet(); - this.entrySet = entrySet; - } - return entrySet; - } - - private T doTask(Object key, Task task) { - int hash = getHash(key); - return getSegmentForHash(hash).doTask(hash, key, task); - } - - private Segment getSegmentForHash(int hash) { - return this.segments[(hash >>> (32 - this.shift)) & (this.segments.length - 1)]; - } - - /** - * Calculate a shift value that can be used to create a power-of-two value between - * the specified maximum and minimum values. - * @param minimumValue the minimum value - * @param maximumValue the maximum value - * @return the calculated shift (use {@code 1 << shift} to obtain a value) - */ - protected static int calculateShift(int minimumValue, int maximumValue) { - int shift = 0; - int value = 1; - while (value < minimumValue && value < maximumValue) { - value <<= 1; - shift++; - } - return shift; - } - - - /** - * Various reference types supported by this map. - */ - public enum ReferenceType { - - /** Use {@link SoftReference}s */ - SOFT, - - /** Use {@link WeakReference}s */ - WEAK - } - - - /** - * A single segment used to divide the map to allow better concurrent performance. - */ - @SuppressWarnings("serial") - protected final class Segment extends ReentrantLock { - - private final ReferenceManager referenceManager; - - private final int initialSize; - - /** - * Array of references indexed using the low order bits from the hash. - * This property should only be set along with {@code resizeThreshold}. - */ - private volatile Reference[] references; - - /** - * The total number of references contained in this segment. This includes chained - * references and references that have been garbage collected but not purged. - */ - private volatile int count = 0; - - /** - * The threshold when resizing of the references should occur. When {@code count} - * exceeds this value references will be resized. - */ - private int resizeThreshold; - - public Segment(int initialCapacity) { - this.referenceManager = createReferenceManager(); - this.initialSize = 1 << calculateShift(initialCapacity, MAXIMUM_SEGMENT_SIZE); - setReferences(createReferenceArray(this.initialSize)); - } - - public Reference getReference(Object key, int hash, Restructure restructure) { - if (restructure == Restructure.WHEN_NECESSARY) { - restructureIfNecessary(false); - } - if (this.count == 0) { - return null; - } - // Use a local copy to protect against other threads writing - Reference[] references = this.references; - int index = getIndex(hash, references); - Reference head = references[index]; - return findInChain(head, key, hash); - } - - /** - * Apply an update operation to this segment. - * The segment will be locked during the update. - * @param hash the hash of the key - * @param key the key - * @param task the update operation - * @return the result of the operation - */ - public T doTask(final int hash, final Object key, final Task task) { - boolean resize = task.hasOption(TaskOption.RESIZE); - if (task.hasOption(TaskOption.RESTRUCTURE_BEFORE)) { - restructureIfNecessary(resize); - } - if (task.hasOption(TaskOption.SKIP_IF_EMPTY) && this.count == 0) { - return task.execute(null, null, null); - } - lock(); - try { - final int index = getIndex(hash, this.references); - final Reference head = this.references[index]; - Reference ref = findInChain(head, key, hash); - Entry entry = (ref != null ? ref.get() : null); - Entries entries = new Entries() { - @Override - public void add(V value) { - @SuppressWarnings("unchecked") - Entry newEntry = new Entry((K) key, value); - Reference newReference = Segment.this.referenceManager.createReference(newEntry, hash, head); - Segment.this.references[index] = newReference; - Segment.this.count++; - } - }; - return task.execute(ref, entry, entries); - } - finally { - unlock(); - if (task.hasOption(TaskOption.RESTRUCTURE_AFTER)) { - restructureIfNecessary(resize); - } - } - } - - /** - * Clear all items from this segment. - */ - public void clear() { - if (this.count == 0) { - return; - } - lock(); - try { - setReferences(createReferenceArray(this.initialSize)); - this.count = 0; - } - finally { - unlock(); - } - } - - /** - * Restructure the underlying data structure when it becomes necessary. This - * method can increase the size of the references table as well as purge any - * references that have been garbage collected. - * @param allowResize if resizing is permitted - */ - protected final void restructureIfNecessary(boolean allowResize) { - boolean needsResize = (this.count > 0 && this.count >= this.resizeThreshold); - Reference ref = this.referenceManager.pollForPurge(); - if (ref != null || (needsResize && allowResize)) { - lock(); - try { - int countAfterRestructure = this.count; - Set> toPurge = Collections.emptySet(); - if (ref != null) { - toPurge = new HashSet>(); - while (ref != null) { - toPurge.add(ref); - ref = this.referenceManager.pollForPurge(); - } - } - countAfterRestructure -= toPurge.size(); - - // Recalculate taking into account count inside lock and items that - // will be purged - needsResize = (countAfterRestructure > 0 && countAfterRestructure >= this.resizeThreshold); - boolean resizing = false; - int restructureSize = this.references.length; - if (allowResize && needsResize && restructureSize < MAXIMUM_SEGMENT_SIZE) { - restructureSize <<= 1; - resizing = true; - } - - // Either create a new table or reuse the existing one - Reference[] restructured = - (resizing ? createReferenceArray(restructureSize) : this.references); - - // Restructure - for (int i = 0; i < this.references.length; i++) { - ref = this.references[i]; - if (!resizing) { - restructured[i] = null; - } - while (ref != null) { - if (!toPurge.contains(ref) && (ref.get() != null)) { - int index = getIndex(ref.getHash(), restructured); - restructured[index] = this.referenceManager.createReference( - ref.get(), ref.getHash(), restructured[index]); - } - ref = ref.getNext(); - } - } - - // Replace volatile members - if (resizing) { - setReferences(restructured); - } - this.count = Math.max(countAfterRestructure, 0); - } - finally { - unlock(); - } - } - } - - private Reference findInChain(Reference ref, Object key, int hash) { - Reference currRef = ref; - while (currRef != null) { - if (currRef.getHash() == hash) { - Entry entry = currRef.get(); - if (entry != null) { - K entryKey = entry.getKey(); - if (ObjectUtil.nullSafeEquals(entryKey, key)) { - return currRef; - } - } - } - currRef = currRef.getNext(); - } - return null; - } - - @SuppressWarnings({"rawtypes", "unchecked"}) - private Reference[] createReferenceArray(int size) { - return new Reference[size]; - } - - private int getIndex(int hash, Reference[] references) { - return (hash & (references.length - 1)); - } - - /** - * Replace the references with a new value, recalculating the resizeThreshold. - * @param references the new references - */ - private void setReferences(Reference[] references) { - this.references = references; - this.resizeThreshold = (int) (references.length * getLoadFactor()); - } - - /** - * Return the size of the current references array. - */ - public final int getSize() { - return this.references.length; - } - - /** - * Return the total number of references in this segment. - */ - public final int getCount() { - return this.count; - } - } - - - /** - * A reference to an {@link Entry} contained in the map. Implementations are usually - * wrappers around specific Java reference implementations (e.g., {@link SoftReference}). - */ - protected interface Reference { - - /** - * Return the referenced entry, or {@code null} if the entry is no longer available. - */ - Entry get(); - - /** - * Return the hash for the reference. - */ - int getHash(); - - /** - * Return the next reference in the chain, or {@code null} if none. - */ - Reference getNext(); - - /** - * Release this entry and ensure that it will be returned from - * {@code ReferenceManager#pollForPurge()}. - */ - void release(); - } - - - /** - * A single map entry. - */ - protected static final class Entry implements Map.Entry { - - private final K key; - - private volatile V value; - - public Entry(K key, V value) { - this.key = key; - this.value = value; - } - - @Override - public K getKey() { - return this.key; - } - - @Override - public V getValue() { - return this.value; - } - - @Override - public V setValue(V value) { - V previous = this.value; - this.value = value; - return previous; - } - - @Override - public String toString() { - return (this.key + "=" + this.value); - } - - @Override - @SuppressWarnings("rawtypes") - public final boolean equals(Object other) { - if (this == other) { - return true; - } - if (!(other instanceof Map.Entry)) { - return false; - } - Map.Entry otherEntry = (Map.Entry) other; - return (ObjectUtil.nullSafeEquals(getKey(), otherEntry.getKey()) && - ObjectUtil.nullSafeEquals(getValue(), otherEntry.getValue())); - } - - @Override - public final int hashCode() { - return (ObjectUtil.nullSafeHashCode(this.key) ^ ObjectUtil.nullSafeHashCode(this.value)); - } - } - - - /** - * A task that can be {@link Segment#doTask run} against a {@link Segment}. - */ - private abstract class Task { - - private final EnumSet options; - - public Task(TaskOption... options) { - this.options = (options.length == 0 ? EnumSet.noneOf(TaskOption.class) : EnumSet.of(options[0], options)); - } - - public boolean hasOption(TaskOption option) { - return this.options.contains(option); - } - - /** - * Execute the task. - * @param ref the found reference (or {@code null}) - * @param entry the found entry (or {@code null}) - * @param entries access to the underlying entries - * @return the result of the task - * @see #execute(Reference, Entry) - */ - protected T execute(Reference ref, Entry entry, Entries entries) { - return execute(ref, entry); - } - - /** - * Convenience method that can be used for tasks that do not need access to {@link Entries}. - * @param ref the found reference (or {@code null}) - * @param entry the found entry (or {@code null}) - * @return the result of the task - * @see #execute(Reference, Entry, Entries) - */ - protected T execute(Reference ref, Entry entry) { - return null; - } - } - - - /** - * Various options supported by a {@code Task}. - */ - private enum TaskOption { - - RESTRUCTURE_BEFORE, RESTRUCTURE_AFTER, SKIP_IF_EMPTY, RESIZE - } - - - /** - * Allows a task access to {@link Segment} entries. - */ - private abstract class Entries { - - /** - * Add a new entry with the specified value. - * @param value the value to add - */ - public abstract void add(V value); - } - - - /** - * Internal entry-set implementation. - */ - private class EntrySet extends AbstractSet> { - - @Override - public Iterator> iterator() { - return new EntryIterator(); - } - - @Override - public boolean contains(Object o) { - if (o instanceof Map.Entry) { - Map.Entry entry = (Map.Entry) o; - Reference ref = ConcurrentReferenceHashMap.this.getReference(entry.getKey(), Restructure.NEVER); - Entry otherEntry = (ref != null ? ref.get() : null); - if (otherEntry != null) { - return ObjectUtil.nullSafeEquals(otherEntry.getValue(), otherEntry.getValue()); - } - } - return false; - } - - @Override - public boolean remove(Object o) { - if (o instanceof Map.Entry) { - Map.Entry entry = (Map.Entry) o; - return ConcurrentReferenceHashMap.this.remove(entry.getKey(), entry.getValue()); - } - return false; - } - - @Override - public int size() { - return ConcurrentReferenceHashMap.this.size(); - } - - @Override - public void clear() { - ConcurrentReferenceHashMap.this.clear(); - } - } - - - /** - * Internal entry iterator implementation. - */ - private class EntryIterator implements Iterator> { - - private int segmentIndex; - - private int referenceIndex; - - private Reference[] references; - - private Reference reference; - - private Entry next; - - private Entry last; - - public EntryIterator() { - moveToNextSegment(); - } - - @Override - public boolean hasNext() { - getNextIfNecessary(); - return (this.next != null); - } - - @Override - public Entry next() { - getNextIfNecessary(); - if (this.next == null) { - throw new NoSuchElementException(); - } - this.last = this.next; - this.next = null; - return this.last; - } - - private void getNextIfNecessary() { - while (this.next == null) { - moveToNextReference(); - if (this.reference == null) { - return; - } - this.next = this.reference.get(); - } - } - - private void moveToNextReference() { - if (this.reference != null) { - this.reference = this.reference.getNext(); - } - while (this.reference == null && this.references != null) { - if (this.referenceIndex >= this.references.length) { - moveToNextSegment(); - this.referenceIndex = 0; - } - else { - this.reference = this.references[this.referenceIndex]; - this.referenceIndex++; - } - } - } - - private void moveToNextSegment() { - this.reference = null; - this.references = null; - if (this.segmentIndex < ConcurrentReferenceHashMap.this.segments.length) { - this.references = ConcurrentReferenceHashMap.this.segments[this.segmentIndex].references; - this.segmentIndex++; - } - } - - @Override - public void remove() { - Assert.state(this.last != null, "No element to remove"); - ConcurrentReferenceHashMap.this.remove(this.last.getKey()); - } - } - - - /** - * The types of restructuring that can be performed. - */ - protected enum Restructure { - - WHEN_NECESSARY, NEVER - } - - - /** - * Strategy class used to manage {@link Reference}s. This class can be overridden if - * alternative reference types need to be supported. - */ - protected class ReferenceManager { - - private final ReferenceQueue> queue = new ReferenceQueue>(); - - /** - * Factory method used to create a new {@link Reference}. - * @param entry the entry contained in the reference - * @param hash the hash - * @param next the next reference in the chain, or {@code null} if none - * @return a new {@link Reference} - */ - public Reference createReference(Entry entry, int hash, Reference next) { - if (ConcurrentReferenceHashMap.this.referenceType == ReferenceType.WEAK) { - return new WeakEntryReference(entry, hash, next, this.queue); - } - return new SoftEntryReference(entry, hash, next, this.queue); - } - - /** - * Return any reference that has been garbage collected and can be purged from the - * underlying structure or {@code null} if no references need purging. This - * method must be thread safe and ideally should not block when returning - * {@code null}. References should be returned once and only once. - * @return a reference to purge or {@code null} - */ - @SuppressWarnings("unchecked") - public Reference pollForPurge() { - return (Reference) this.queue.poll(); - } - } - - - /** - * Internal {@link Reference} implementation for {@link SoftReference}s. - */ - private static final class SoftEntryReference extends SoftReference> implements Reference { - - private final int hash; - - private final Reference nextReference; - - public SoftEntryReference(Entry entry, int hash, Reference next, ReferenceQueue> queue) { - super(entry, queue); - this.hash = hash; - this.nextReference = next; - } - - @Override - public int getHash() { - return this.hash; - } - - @Override - public Reference getNext() { - return this.nextReference; - } - - @Override - public void release() { - enqueue(); - clear(); - } - } - - - /** - * Internal {@link Reference} implementation for {@link WeakReference}s. - */ - private static final class WeakEntryReference extends WeakReference> implements Reference { - - private final int hash; - - private final Reference nextReference; - - public WeakEntryReference(Entry entry, int hash, Reference next, ReferenceQueue> queue) { - super(entry, queue); - this.hash = hash; - this.nextReference = next; - } - - @Override - public int getHash() { - return this.hash; - } - - @Override - public Reference getNext() { - return this.nextReference; - } - - @Override - public void release() { - enqueue(); - clear(); - } - } - -} - diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/ConfigUtil.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/ConfigUtil.java deleted file mode 100644 index 62a45770..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/ConfigUtil.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.util; - -import fun.asgc.neutrino.core.config.ConfigurationParser; -import fun.asgc.neutrino.core.config.impl.YmlConfigurationParser; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -public class ConfigUtil { - - private static final ConfigurationParser ymlParser = new YmlConfigurationParser(); - - public static T getYmlConfig(Class clazz) { - return ymlParser.parse(clazz); - } - - public static T getYmlConfig(Object obj) { - ymlParser.parse(obj); - return (T)obj; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/DateUtil.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/DateUtil.java deleted file mode 100644 index af093be2..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/DateUtil.java +++ /dev/null @@ -1,380 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.util; - -import fun.asgc.neutrino.core.cache.Cache; -import fun.asgc.neutrino.core.cache.MemoryCache; -import org.apache.commons.lang3.StringUtils; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.*; -import java.util.function.Consumer; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/28 - */ -public class DateUtil { - public static final long SECOND_LONG = 1000L; - public static final long MINUTE_LONG = 60 * SECOND_LONG; - public static final long HOUR_LONG = 60 * MINUTE_LONG; - - private static final Cache sdfCache = new MemoryCache<>(); - private static SimpleDateFormat getSimpleDateFormat(String format) { - try { - return LockUtil.doubleCheckProcess( - () -> !sdfCache.containsKey(format), - format, - () -> sdfCache.set(format, new SimpleDateFormat(format)), - () -> sdfCache.get(format) - ); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - /** - * 解析日期 - * - * @param date 日期类 - * @param pattern 日期格式 - * @return 返回日期 - */ - public static Date parseStr(String date, String pattern) { - if (date == null || pattern == null) { - return null; - } - SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); - Date parse = null; - try { - parse = simpleDateFormat.parse(date); - } catch (ParseException e) { - throw new RuntimeException(e); - } - return parse; - } - - - /** - * @param date 时间。若为空,则返回空串 - * @param pattern 时间格式化 - * @return 格式化后的时间字符串. - */ - public static String format(Date date, String pattern) { - if (date == null) { - return ""; - } - return new SimpleDateFormat(pattern).format(date); - } - - /** - * @param date 日期 - * @param pattern 格式 - * @return 日期类型 - */ - public static Date parse(String date, String pattern) { - try { - return new SimpleDateFormat(pattern).parse(date); - } catch (ParseException e) { - throw new RuntimeException(e); - } - } - - /** - * 是否在指定时间段之间 - * - * @param judgeTime 比较时间 - * @param beginTime 开始时间 - * @param endTime 结束时间 - * @param flag 0-[beginTime<=judgeTime<=endTime] - * 1-[beginTime - * - * @param date 日期 - * @param month 月 - * @return 日期 - */ - public static Date getMonthDay(Date date, int month) { - Calendar cal = Calendar.getInstance(); - if (date != null) { - cal.setTime(date); - } - cal.add(Calendar.MONTH, month); - return cal.getTime(); - } - - /** - * 获取该日期当月第一天 - * - * @param date 日期 - * @return 结果日期 - */ - public static Date getMonthBegin(Date date) { - Calendar calendar = Calendar.getInstance(); - calendar.setTime(getDayBegin(date)); - calendar.set(Calendar.DAY_OF_MONTH, 1); - return calendar.getTime(); - } - - /** - * 获取该日期当月最后一天 - * - * @param date 日期 - * @return 结果日期 - */ - public static Date getMonthEnd(Date date) { - Calendar calendar = Calendar.getInstance(); - calendar.setTime(getDayBegin(date)); - calendar.add(Calendar.MONTH, 1); - calendar.set(Calendar.DAY_OF_MONTH, 1); - calendar.add(Calendar.MILLISECOND, -1); - return calendar.getTime(); - } - - /** - * 计算当期时间相差的日期 - * - * @param date 设置时间 - * @param field 日历字段.
eg:Calendar.MONTH,Calendar.DAY_OF_MONTH,
Calendar.HOUR_OF_DAY等. - * @param amount 相差的数值 - * @return 计算后的日志 - */ - public static Date addDate(Date date, int field, int amount) { - Calendar c = Calendar.getInstance(); - if (date != null) { - c.setTime(date); - } - c.add(field, amount); - return c.getTime(); - } - - /** - * 计算当期时间相差的日期 - * - * @param field 日历字段.
eg:Calendar.MONTH,Calendar.DAY_OF_MONTH,
Calendar.HOUR_OF_DAY等. - * @param amount 相差的数值 - * @return 计算后的日志 - */ - public static Date addDate(int field, int amount) { - return addDate(null, field, amount); - } - - /** - * 设置Calendar的小时、分钟、秒、毫秒 - * - * @param calendar 日历 - * @param hour 小时 - * @param minute 分钟 - * @param second 秒 - * @param milliSecond 毫秒 - * @return 结果日期 - */ - public static void setCalender(Calendar calendar, int hour, int minute, int second, int milliSecond) { - calendar.set(Calendar.HOUR_OF_DAY, hour); - calendar.set(Calendar.MINUTE, minute); - calendar.set(Calendar.SECOND, second); - calendar.set(Calendar.MILLISECOND, milliSecond); - } - - /** - * 获取某个时间段内的每天时间日期 - * - * @param beginDate 开始日期 - * @param endDate 结束日期 - * @return 返回结果 - */ - public static List getBetweenTimes(String beginDate, String endDate) { - if (StringUtils.isEmpty(beginDate) || StringUtils.isEmpty(endDate)) { - return Collections.emptyList(); - } - - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); - Date dBegin = null; - Date dEnd = null; - try { - dBegin = sdf.parse(beginDate); - dEnd = sdf.parse(endDate); - } catch (ParseException e) { - e.printStackTrace(); - } - - if (StringUtils.isEmpty(beginDate) || StringUtils.isEmpty(endDate)) { - return Collections.emptyList(); - } - - return findDates(dBegin, dEnd); - } - - /** - * @param dBegin 开始时间 - * @param dEnd 结束时间 - * @return 结果集 - */ - public static List findDates(Date dBegin, Date dEnd) { - List lDate = new ArrayList<>(); - SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd"); - lDate.add(sd.format(dBegin)); - Calendar calBegin = Calendar.getInstance(); - // 使用给定的 Date 设置此 Calendar 的时间 - calBegin.setTime(dBegin); - Calendar calEnd = Calendar.getInstance(); - // 使用给定的 Date 设置此 Calendar 的时间 - calEnd.setTime(dEnd); - // 测试此日期是否在指定日期之后 - while (dEnd.after(calBegin.getTime())) { - // 根据日历的规则,为给定的日历字段添加或减去指定的时间量 - calBegin.add(Calendar.DAY_OF_MONTH, 1); - lDate.add(sd.format(calBegin.getTime())); - } - return lDate; - } - - /** - * 取得日期所在年的下一年同一天
- * 注:若参数date为空,则取得第当前年所对应的下一年 - * - * @param date - * @return - */ - public static Date getNextYearDay(Date date) { - Calendar cal = Calendar.getInstance(); - if (date != null) { - cal.setTime(date); - } - cal.add(Calendar.YEAR, 1); - return cal.getTime(); - } - - - /** - * 获取指定天开始时间 - * - * @param date 日期 - * @return 获得该日期的开始 - */ - public static Date getDayBegin(Date date) { - Calendar calendar = Calendar.getInstance(); - calendar.setTime(date); - setCalender(calendar, 0, 0, 0, 0); - return calendar.getTime(); - } - - /** - * 获取指定小时开始时间 - * @param date 日期 - * @return 指定小时开始时间 - */ - public static Date getHourBegin(Date date) { - Calendar calendar = Calendar.getInstance(); - calendar.setTime(date); - setCalender(calendar, calendar.get(Calendar.HOUR), 0, 0, 0); - return calendar.getTime(); - } - - /** - * 获取指定小时结束时间 - * @param date 日期 - * @return 指定小时结束时间 - */ - public static Date getHourEnd(Date date) { - Calendar calendar = Calendar.getInstance(); - calendar.setTime(date); - setCalender(calendar, calendar.get(Calendar.HOUR), 59, 59, 999); - return calendar.getTime(); - } - - /** - * 获取当天开始时间 - * - * @return 获得该日期的开始 - */ - public static Date getDayBegin() { - return getDayBegin(new Date()); - } - - /** - * 获取指定天结束时间 - * - * @param date 日期 - * @return 获得该日期的结束 - */ - public static Date getDayEnd(Date date) { - Calendar calendar = Calendar.getInstance(); - calendar.setTime(date); - setCalender(calendar, 23, 59, 59, 999); - return calendar.getTime(); - } - - /** - * 获取指定天结束时间 - * - * @param date 日期 - * @return 获得该日期的结束 - */ - public static Date getDayEnd2(Date date) { - Calendar calendar = Calendar.getInstance(); - calendar.setTime(date); - setCalender(calendar, 23, 59, 59, 000); - return calendar.getTime(); - } - - /** - * 日期遍历接口 - * @param startDate 开始日期 yyyy-MM-dd - * @param endDate 结束日期 yyyy-MM-dd - * @param consumer 执行器回调 - */ - public static void dayForEach(String startDate, String endDate, Consumer consumer) { - if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate) || null == consumer) { - return; - } - Date current = parse(startDate, "yyyy-MM-dd"); - Date end = parse(endDate, "yyyy-MM-dd"); - while (!current.after(end)) { - consumer.accept(format(current, "yyyy-MM-dd")); - current = addDate(current, Calendar.DATE, 1); - } - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/FileUtil.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/FileUtil.java deleted file mode 100644 index 205d31f9..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/FileUtil.java +++ /dev/null @@ -1,244 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.util; - -import fun.asgc.neutrino.core.constant.MetaDataConstant; -import fun.asgc.neutrino.core.exception.InternalException; -import org.apache.commons.io.FileDeleteStrategy; -import org.apache.commons.lang3.StringUtils; - -import java.io.*; -import java.util.Enumeration; -import java.util.List; -import java.util.jar.JarEntry; -import java.util.jar.JarFile; -import java.util.stream.Collectors; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -public class FileUtil { - - /** - * 根据文件路径获取输入流 - * @param path - * @return - */ - public static InputStream getInputStream(String path) throws FileNotFoundException { - if (StringUtils.isEmpty(path)) { - throw new NullPointerException("path 不能为空!"); - } - if (path.startsWith(MetaDataConstant.CLASSPATH_RESOURCE_IDENTIFIER)) { - String subPath = path.substring(MetaDataConstant.CLASSPATH_RESOURCE_IDENTIFIER.length()); - return FileUtil.class.getResourceAsStream(subPath); - } - return new FileInputStream(path); - } - - /** - * 根据文件路径获取输出流 - * @param path - * @return - */ - public static OutputStream getOutputStream(String path) throws FileNotFoundException { - if (StringUtils.isEmpty(path)) { - throw new NullPointerException("path 不能为空!"); - } - if (path.startsWith(MetaDataConstant.CLASSPATH_RESOURCE_IDENTIFIER)) { - throw new InternalException("不支持路径以'" + MetaDataConstant.CLASSPATH_IDENTIFIER + "'开头"); - } - return new FileOutputStream(path); - } - - /** - * 读取文件内容 - * @param path - * @return - * @throws IOException - */ - public static String readContentAsString(String path) { - try (BufferedReader br = new BufferedReader(new InputStreamReader(getInputStream(path)))){ - return br.lines().collect(Collectors.joining("\n")); - } catch (Exception e) { - return null; - } - } - - /** - * 读取文件内容 - * @param in - * @return - * @throws IOException - */ - public static String readContentAsString(InputStream in) { - try (BufferedReader br = new BufferedReader(new InputStreamReader(in))){ - return br.lines().collect(Collectors.joining("\n")); - } catch (Exception e) { - return null; - } - } - - /** - * 读取文件内容 - * @param path - * @return - * @throws IOException - */ - public static List readContentAsStringList(String path) { - try (BufferedReader br = new BufferedReader(new InputStreamReader(getInputStream(path)))){ - return br.lines().collect(Collectors.toList()); - } catch (Exception e) { - return null; - } - } - - /** - * 读取字节内容 - * @param path - * @return - */ - public static byte[] readBytes(String path) { - try (InputStream in = getInputStream(path)){ - return readBytes(in); - } catch (Exception e) { - return null; - } - } - - public static byte[] readBytes(File file) { - try (InputStream in = new FileInputStream(file)){ - return readBytes(in); - } catch (Exception e) { - return null; - } - } - - public static byte[] readBytes(InputStream in) throws IOException { - byte[] bytes = new byte[1024]; - int length = 0; - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - while ((length = in.read(bytes)) != -1) { - baos.write(bytes, 0, length); - } - return baos.toByteArray(); - } - - public static void write(String path, String content) { -// try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(path), StandardCharsets.UTF_8)){ -// writer.write(content); -// } catch (Exception e) { -// e.printStackTrace(); -// } - try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(getOutputStream(path)))){ - bw.write(content); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public static File getDirectory(String path) { - if (path.endsWith("/./")) { - path = path.substring(0, path.length() - 2); - } - File file = new File(path); - if (file.isDirectory() || path.endsWith("/")) { - return file; - } - return file.getParentFile(); - } - - public static void makeDirs(String path) { - try { - File file = getDirectory(path); - if (null != file && !file.exists()) { - file.mkdirs(); - } - } catch (Exception e) { - // ignore - } - } - - public static boolean deleteDirs(String path) { - File file = getDirectory(path); - try { - FileDeleteStrategy.FORCE.delete(file); - } catch (Exception e) { - file = getDirectory(file.getPath()); - try { - FileDeleteStrategy.FORCE.delete(file); - } catch (IOException ex) { - return false; - } - } - return true; - } - - public static File save(String path, String fileName, String content) { - if (!path.endsWith("/")) { - path += "/"; - } - makeDirs(path); - write(path + fileName, content); - return new File(path + "/" + fileName); - } - - public static void unzipJar(String destinationDir, String jarPath) throws IOException { - File file = new File(jarPath); - JarFile jar = new JarFile(file); - for (Enumeration enums = jar.entries(); enums.hasMoreElements();) { - JarEntry entry = (JarEntry) enums.nextElement(); - String fileName = destinationDir + File.separator + entry.getName(); - File f = new File(fileName); - if (fileName.endsWith("/")) { - f.mkdirs(); - } - } - for (Enumeration enums = jar.entries(); enums.hasMoreElements();) { - JarEntry entry = (JarEntry) enums.nextElement(); - String fileName = destinationDir + File.separator + entry.getName(); - File f = new File(fileName); - if (!fileName.endsWith("/")) { - InputStream is = jar.getInputStream(entry); - FileOutputStream fos = new FileOutputStream(f); - while (is.available() > 0) { - fos.write(is.read()); - } - fos.close(); - is.close(); - } - } - } - - public static String getFileSuffix(String path) { - if (StringUtils.isBlank(path)) { - return ""; - } - int index = path.lastIndexOf("."); - if (index >= 0) { - return path.substring(index); - } - return ""; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/FunctionUtil.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/FunctionUtil.java deleted file mode 100644 index 567394d9..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/FunctionUtil.java +++ /dev/null @@ -1,108 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.util; - -import fun.asgc.neutrino.core.aop.AopCallback; -import fun.asgc.neutrino.core.base.CodeBlock; - -import java.util.ArrayList; -import java.util.List; -import java.util.function.Supplier; - -/** - * 函数工具 - * @author: aoshiguchen - * @date: 2022/7/1 - */ -public class FunctionUtil { - - /** - * 获取第一个非空值 - * @param suppliers - * @param - * @return - */ - public static T getFirstNotNull(Supplier ...suppliers) { - T res; - if (ArrayUtil.notEmpty(suppliers)) { - for (Supplier supplier : suppliers) { - if (null != supplier) { - res = supplier.get(); - if (null != res) { - return res; - } - } - } - } - return null; - } - - /** - * 忽略异常 - * @param codeBlock - */ - public static void ignoreException(CodeBlock codeBlock) { - try { - codeBlock.execute(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * 忽略异常 - * @param callback - * @param - * @return - */ - public static T ignoreException(AopCallback callback) { - try { - return callback.callback(); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - /** - * 合并list - * @param suppliers - * @param - * @return - */ - public static List mergeList(Supplier> ...suppliers) { - List list = new ArrayList<>(); - if (null != suppliers && suppliers.length > 0) { - for (Supplier> supplier : suppliers) { - if (null == supplier) { - continue; - } - List tmpList = supplier.get(); - if (CollectionUtil.isEmpty(tmpList)) { - continue; - } - list.addAll(tmpList); - } - } - return list; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/HttpServerUtil.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/HttpServerUtil.java deleted file mode 100644 index cfb94cde..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/HttpServerUtil.java +++ /dev/null @@ -1,64 +0,0 @@ -/** - * Copyright (C) 2018-2022 Zeyi information technology (Shanghai) Co., Ltd. - *

- * All right reserved. - *

- * This software is the confidential and proprietary - * information of Zeyi Company of China. - * ("Confidential Information"). You shall not disclose - * such Confidential Information and shall use it only - * in accordance with the terms of the contract agreement - * you entered into with Zeyi inc. - */ -package fun.asgc.neutrino.core.util; - -import com.alibaba.fastjson.JSONObject; -import fun.asgc.neutrino.core.web.context.HttpContextHolder; -import fun.asgc.neutrino.core.web.context.HttpResponseWrapper; -import io.netty.buffer.ByteBuf; -import io.netty.buffer.Unpooled; -import io.netty.handler.codec.http.*; -import org.apache.commons.lang3.exception.ExceptionUtils; - -/** - * - * @author: wen.y - * @date: 2022/5/28 - */ -public class HttpServerUtil { - - public static void sendResponse(HttpResponseStatus status) { - sendResponse(status, null); - } - - public static void sendResponse(HttpResponseStatus status, ByteBuf content) { - HttpResponseWrapper httpResponseWrapper = HttpContextHolder.getHttpResponseWrapper(); - httpResponseWrapper.setStatus(status); - if (null != content) { - httpResponseWrapper.setContent(content); - } - httpResponseWrapper.writeAndFlush(); - } - - public static void send404Response(String url) { - String res = String.format("404 未找到指定资源: %s", url); - sendResponse(HttpResponseStatus.NOT_FOUND, Unpooled.wrappedBuffer(res.getBytes())); - } - - public static void send500Response(Throwable throwable) { - String res = String.format("500 服务异常: %s", ExceptionUtils.getStackTrace(throwable)); - sendResponse(HttpResponseStatus.INTERNAL_SERVER_ERROR, Unpooled.wrappedBuffer(res.getBytes())); - } - - public static void send200Response(Object o) { - String res = String.valueOf(o); - if (null != o && !TypeUtil.isNormalBasicType(o.getClass())) { - res = JSONObject.toJSONString(o); - } - HttpResponseWrapper httpResponseWrapper = HttpContextHolder.getHttpResponseWrapper(); - httpResponseWrapper.setContent(Unpooled.wrappedBuffer(res.getBytes())); - httpResponseWrapper.headers().add(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON); - httpResponseWrapper.writeAndFlush(); - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/HttpUtil.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/HttpUtil.java deleted file mode 100644 index 58823f9b..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/HttpUtil.java +++ /dev/null @@ -1,65 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.util; - -import fun.asgc.neutrino.core.web.context.HttpRequestWrapper; -import io.netty.channel.ChannelHandlerContext; - -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.UnknownHostException; - -/** - * - * @author: aoshiguchen - * @date: 2022/8/2 - */ -public class HttpUtil { - - /** - * 获取客户端IP - */ - public static String getIP(ChannelHandlerContext context, HttpRequestWrapper request) { - String ip = request.getHeaderValue("clientip"); - if (ip == null) { - ip = request.getHeaderValue("X-Real-IP"); - if (ip == null) { - ip = request.getHeaderValue("X-Forwarded-For"); - if (ip == null) { - ip = ((InetSocketAddress)context.channel().remoteAddress()).getAddress().getHostAddress(); - if (ip.equals("127.0.0.1") || ip.equals("0:0:0:0:0:0:0:1")) { - //根据网卡取本机配置的IP - InetAddress inet = null; - try { - inet = InetAddress.getLocalHost(); - } catch (UnknownHostException e) { - e.printStackTrace(); - } - ip = inet.getHostAddress(); - } - } - } - } - return ip; - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/LockUtil.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/LockUtil.java deleted file mode 100644 index ec86b28f..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/LockUtil.java +++ /dev/null @@ -1,91 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.util; - -import fun.asgc.neutrino.core.base.CodeBlock; - -import java.util.function.BooleanSupplier; -import java.util.function.Supplier; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -public class LockUtil { - - /** - * 双重校验处理 - * @param isLock - * @param lock - * @param lockProcess - */ - public static void doubleCheckProcess(BooleanSupplier isLock, Object lock, CodeBlock lockProcess) throws Exception { - if (isLock.getAsBoolean()) { - synchronized (lock) { - if (isLock.getAsBoolean()) { - lockProcess.execute(); - } - } - } - } - - /** - * 双重校验处理 - * @param isLock - * @param lock - * @param lockProcess - */ - public static void doubleCheckProcessForNoException(BooleanSupplier isLock, Object lock, CodeBlock lockProcess) { - try { - doubleCheckProcess(isLock, lock, lockProcess); - } catch (Exception e) { - // ignore - e.printStackTrace(); - } - } - - /** - * 双重校验处理 - * @param isLock - * @param lock - * @param lockProcess - * @param nonLockProcess - */ - public static T doubleCheckProcess(BooleanSupplier isLock, Object lock, CodeBlock lockProcess, Supplier nonLockProcess) throws Exception { - doubleCheckProcess(isLock, lock, lockProcess); - return nonLockProcess.get(); - } - - /** - * 双重校验处理 - * @param isLock - * @param lock - * @param lockProcess - * @param nonLockProcess - */ - public static T doubleCheckProcessForNoException(BooleanSupplier isLock, Object lock, CodeBlock lockProcess, Supplier nonLockProcess) { - doubleCheckProcessForNoException(isLock, lock, lockProcess); - return nonLockProcess.get(); - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/MimeType.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/MimeType.java deleted file mode 100644 index 145f2426..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/MimeType.java +++ /dev/null @@ -1,255 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.util; - -import java.util.HashMap; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/21 - */ -public class MimeType { - - final static Pattern pattern = Pattern.compile("\\S*[?]\\S*"); - - private static Map h = new HashMap(); - static { - h.put("", "application/octet-stream"); - h.put("323", "text/h323"); - h.put("acx", "application/internet-property-stream"); - h.put("ai", "application/postscript"); - h.put("aif", "audio/x-aiff"); - h.put("aifc", "audio/x-aiff"); - h.put("aiff", "audio/x-aiff"); - h.put("asf", "video/x-ms-asf"); - h.put("asr", "video/x-ms-asf"); - h.put("asx", "video/x-ms-asf"); - h.put("au", "audio/basic"); - h.put("avi", "video/x-msvideo"); - h.put("axs", "application/olescript"); - h.put("bas", "text/plain"); - h.put("bcpio", "application/x-bcpio"); - h.put("bin", "application/octet-stream"); - h.put("bmp", "image/bmp"); - h.put("c", "text/plain"); - h.put("cat", "application/vnd.ms-pkiseccat"); - h.put("cdf", "application/x-cdf"); - h.put("cer", "application/x-x509-ca-cert"); - h.put("class", "application/octet-stream"); - h.put("clp", "application/x-msclip"); - h.put("cmx", "image/x-cmx"); - h.put("cod", "image/cis-cod"); - h.put("cpio", "application/x-cpio"); - h.put("crd", "application/x-mscardfile"); - h.put("crl", "application/pkix-crl"); - h.put("crt", "application/x-x509-ca-cert"); - h.put("csh", "application/x-csh"); - h.put("css", "text/css"); - h.put("dcr", "application/x-director"); - h.put("der", "application/x-x509-ca-cert"); - h.put("dir", "application/x-director"); - h.put("dll", "application/x-msdownload"); - h.put("dms", "application/octet-stream"); - h.put("doc", "application/msword"); - h.put("dot", "application/msword"); - h.put("dvi", "application/x-dvi"); - h.put("dxr", "application/x-director"); - h.put("eps", "application/postscript"); - h.put("etx", "text/x-setext"); - h.put("evy", "application/envoy"); - h.put("exe", "application/octet-stream"); - h.put("fif", "application/fractals"); - h.put("flr", "x-world/x-vrml"); - h.put("gif", "image/gif"); - h.put("gtar", "application/x-gtar"); - h.put("gz", "application/x-gzip"); - h.put("h", "text/plain"); - h.put("hdf", "applicatin/x-hdf"); - h.put("hlp", "application/winhlp"); - h.put("hqx", "application/mac-binhex40"); - h.put("hta", "application/hta"); - h.put("htc", "text/x-component"); - h.put("htm", "text/html"); - h.put("html", "text/html"); - h.put("htt", "text/webviewhtml"); - h.put("ico", "image/x-icon"); - h.put("ief", "image/ief"); - h.put("iii", "application/x-iphone"); - h.put("ins", "application/x-internet-signup"); - h.put("isp", "application/x-internet-signup"); - h.put("jfif", "image/pipeg"); - h.put("jpe", "image/jpeg"); - h.put("jpeg", "image/jpeg"); - h.put("jpg", "image/jpeg"); - h.put("js", "application/x-javascript"); - h.put("latex", "application/x-latex"); - h.put("lha", "application/octet-stream"); - h.put("lsf", "video/x-la-asf"); - h.put("lsx", "video/x-la-asf"); - h.put("lzh", "application/octet-stream"); - h.put("m13", "application/x-msmediaview"); - h.put("m14", "application/x-msmediaview"); - h.put("m3u", "audio/x-mpegurl"); - h.put("man", "application/x-troff-man"); - h.put("mdb", "application/x-msaccess"); - h.put("me", "application/x-troff-me"); - h.put("mht", "message/rfc822"); - h.put("mhtml", "message/rfc822"); - h.put("mid", "audio/mid"); - h.put("mny", "application/x-msmoney"); - h.put("mov", "video/quicktime"); - h.put("movie", "video/x-sgi-movie"); - h.put("mp2", "video/mpeg"); - h.put("mp3", "audio/mpeg"); - h.put("mpa", "video/mpeg"); - h.put("mpe", "video/mpeg"); - h.put("mpeg", "video/mpeg"); - h.put("mpg", "video/mpeg"); - h.put("mpp", "application/vnd.ms-project"); - h.put("mpv2", "video/mpeg"); - h.put("ms", "application/x-troff-ms"); - h.put("mvb", "application/x-msmediaview"); - h.put("nws", "message/rfc822"); - h.put("oda", "application/oda"); - h.put("p10", "application/pkcs10"); - h.put("p12", "application/x-pkcs12"); - h.put("p7b", "application/x-pkcs7-certificates"); - h.put("p7c", "application/x-pkcs7-mime"); - h.put("p7m", "application/x-pkcs7-mime"); - h.put("p7r", "application/x-pkcs7-certreqresp"); - h.put("p7s", "application/x-pkcs7-signature"); - h.put("pbm", "image/x-portable-bitmap"); - h.put("pdf", "application/pdf"); - h.put("pfx", "application/x-pkcs12"); - h.put("pgm", "image/x-portable-graymap"); - h.put("pko", "application/ynd.ms-pkipko"); - h.put("pma", "application/x-perfmon"); - h.put("pmc", "application/x-perfmon"); - h.put("pml", "application/x-perfmon"); - h.put("pmr", "application/x-perfmon"); - h.put("pmw", "application/x-perfmon"); - h.put("pnm", "image/x-portable-anymap"); - h.put("pot,", "application/vnd.ms-powerpoint"); - h.put("ppm", "image/x-portable-pixmap"); - h.put("pps", "application/vnd.ms-powerpoint"); - h.put("ppt", "application/vnd.ms-powerpoint"); - h.put("prf", "application/pics-rules"); - h.put("ps", "application/postscript"); - h.put("pub", "application/x-mspublisher"); - h.put("qt", "video/quicktime"); - h.put("ra", "audio/x-pn-realaudio"); - h.put("ram", "audio/x-pn-realaudio"); - h.put("ras", "image/x-cmu-raster"); - h.put("rgb", "image/x-rgb"); - h.put("rmi", "audio/mid"); - h.put("roff", "application/x-troff"); - h.put("rtf", "application/rtf"); - h.put("rtx", "text/richtext"); - h.put("scd", "application/x-msschedule"); - h.put("sct", "text/scriptlet"); - h.put("setpay", "application/set-payment-initiation"); - h.put("setreg", "application/set-registration-initiation"); - h.put("sh", "application/x-sh"); - h.put("shar", "application/x-shar"); - h.put("sit", "application/x-stuffit"); - h.put("snd", "audio/basic"); - h.put("spc", "application/x-pkcs7-certificates"); - h.put("spl", "application/futuresplash"); - h.put("src", "application/x-wais-source"); - h.put("sst", "application/vnd.ms-pkicertstore"); - h.put("stl", "application/vnd.ms-pkistl"); - h.put("stm", "text/html"); - h.put("svg", "image/svg+xml"); - h.put("sv4cpio", "application/x-sv4cpio"); - h.put("sv4crc", "application/x-sv4crc"); - h.put("swf", "application/x-shockwave-flash"); - h.put("t", "application/x-troff"); - h.put("tar", "application/x-tar"); - h.put("tcl", "application/x-tcl"); - h.put("tex", "application/x-tex"); - h.put("texi", "application/x-texinfo"); - h.put("texinfo", "application/x-texinfo"); - h.put("tgz", "application/x-compressed"); - h.put("tif", "image/tiff"); - h.put("tiff", "image/tiff"); - h.put("tr", "application/x-troff"); - h.put("trm", "application/x-msterminal"); - h.put("tsv", "text/tab-separated-values"); - h.put("txt", "text/plain"); - h.put("uls", "text/iuls"); - h.put("ustar", "application/x-ustar"); - h.put("vcf", "text/x-vcard"); - h.put("vrml", "x-world/x-vrml"); - h.put("wav", "audio/x-wav"); - h.put("wcm", "application/vnd.ms-works"); - h.put("wdb", "application/vnd.ms-works"); - h.put("wks", "application/vnd.ms-works"); - h.put("wmf", "application/x-msmetafile"); - h.put("wps", "application/vnd.ms-works"); - h.put("wri", "application/x-mswrite"); - h.put("wrl", "x-world/x-vrml"); - h.put("wrz", "x-world/x-vrml"); - h.put("xaf", "x-world/x-vrml"); - h.put("xbm", "image/x-xbitmap"); - h.put("xla", "application/vnd.ms-excel"); - h.put("xlc", "application/vnd.ms-excel"); - h.put("xlm", "application/vnd.ms-excel"); - h.put("xls", "application/vnd.ms-excel"); - h.put("xlt", "application/vnd.ms-excel"); - h.put("xlw", "application/vnd.ms-excel"); - h.put("xof", "x-world/x-vrml"); - h.put("xpm", "image/x-xpixmap"); - h.put("xwd", "image/x-xwindowdump"); - h.put("z", "application/x-compress"); - h.put("zip", "application/zip"); - } - - public static String getMimeType(String docType) { - String mime = h.get(docType); - if (mime == null) { - mime = "application/octet-stream"; - } - return mime; - } - - public static String parseSuffix(String url) { - try { - Matcher matcher = pattern.matcher(url); - String[] spUrl = url.toString().split("/"); - int len = spUrl.length; - String endUrl = spUrl[len - 1]; - if (matcher.find()) { - String[] spEndUrl = endUrl.split("\\?"); - endUrl = spEndUrl[0]; - } - String[] endUrlArr = endUrl.split("\\."); - return endUrlArr[endUrlArr.length - 1]; - } catch (Exception e) { - return ""; - } - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/NumberUtil.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/NumberUtil.java deleted file mode 100644 index 8dde25d6..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/NumberUtil.java +++ /dev/null @@ -1,103 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.util; - -import com.google.common.collect.Lists; - -import java.util.List; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -public class NumberUtil { - - /** - * 大小单位 - */ - private static final List SIZE_UINT = Lists.newArrayList("B", "K", "M", "G", "T"); - /** - * 单位容量 - */ - private static final int UINT_CAPACITY = 1024; - - /** - * 大小转为描述 - * @param size - * @return - */ - public static String sizeToDescription(long size, int decimals) { - double num = size * 1.0; - int unitIndex = 0; - - while (unitIndex < SIZE_UINT.size() - 1 && num >= UINT_CAPACITY) { - num /= UINT_CAPACITY; - unitIndex++; - } - - return trimZero(String.format("%." + decimals + "f", num)) + SIZE_UINT.get(unitIndex); - } - - /** - * 大小转为描述 - * @param size - * @return - */ - public static String sizeToDescription(long size) { - return sizeToDescription(size, 2); - } - - public static long descriptionToSize(String description, long defaultValue) { - try { - description = description.trim().replaceAll(" ", "").toUpperCase(); - double num = Double.valueOf(description.substring(0, description.length() - 1)); - String unit = description.substring(description.length() - 1); - int unitIndex = SIZE_UINT.indexOf(unit); - if (unitIndex > 0) { - while (unitIndex-- > 0) { - num *= UINT_CAPACITY; - } - } - return (long) num; - } catch (Exception e) { - // ignore - } - return defaultValue; - } - - public static long descriptionToSize(String description) { - return descriptionToSize(description, 0); - } - - private static String trimZero(String s) { - if (s.indexOf(".") > 0) { - // 去掉多余的0 - s = s.replaceAll("0+?$", ""); - // 如最后一位是.则去掉 - s = s.replaceAll("[.]$", ""); - } - return s; - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/ObjectUtil.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/ObjectUtil.java deleted file mode 100644 index f50ad46d..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/ObjectUtil.java +++ /dev/null @@ -1,843 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.util; - -import java.lang.reflect.Array; -import java.util.Arrays; -import java.util.Collection; -import java.util.Map; -import java.util.Optional; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -public class ObjectUtil { - - private static final int INITIAL_HASH = 7; - private static final int MULTIPLIER = 31; - - private static final String EMPTY_STRING = ""; - private static final String NULL_STRING = "null"; - private static final String ARRAY_START = "{"; - private static final String ARRAY_END = "}"; - private static final String EMPTY_ARRAY = ARRAY_START + ARRAY_END; - private static final String ARRAY_ELEMENT_SEPARATOR = ", "; - - /** - * - * @param ex - * @return - */ - public static boolean isCheckedException(Throwable ex) { - return !(ex instanceof RuntimeException || ex instanceof Error); - } - - /** - * - * @param ex - * @param declaredExceptions - * @return - */ - public static boolean isCompatibleWithThrowsClause(Throwable ex, Class... declaredExceptions) { - if (!isCheckedException(ex)) { - return true; - } - if (declaredExceptions != null) { - for (Class declaredException : declaredExceptions) { - if (declaredException.isInstance(ex)) { - return true; - } - } - } - return false; - } - - /** - * - * @param obj - * @return - */ - public static boolean isArray(Object obj) { - return (obj != null && obj.getClass().isArray()); - } - - /** - * - * @param array - * @return - */ - public static boolean isEmpty(Object[] array) { - return (array == null || array.length == 0); - } - - /** - * - * @param obj - * @return - */ - @SuppressWarnings("rawtypes") - public static boolean isEmpty(Object obj) { - if (obj == null) { - return true; - } - - if (obj instanceof Optional) { - return !((Optional) obj).isPresent(); - } - if (obj instanceof CharSequence) { - return ((CharSequence) obj).length() == 0; - } - if (obj.getClass().isArray()) { - return Array.getLength(obj) == 0; - } - if (obj instanceof Collection) { - return ((Collection) obj).isEmpty(); - } - if (obj instanceof Map) { - return ((Map) obj).isEmpty(); - } - - // else - return false; - } - - /** - * - * @param obj - * @return - */ - public static Object unwrapOptional(Object obj) { - if (obj instanceof Optional) { - Optional optional = (Optional) obj; - if (!optional.isPresent()) { - return null; - } - Object result = optional.get(); - Assert.isTrue(!(result instanceof Optional), "Multi-level Optional usage not supported"); - return result; - } - return obj; - } - - /** - * - * @param array - * @param element - * @return - */ - public static boolean containsElement(Object[] array, Object element) { - if (array == null) { - return false; - } - for (Object arrayEle : array) { - if (nullSafeEquals(arrayEle, element)) { - return true; - } - } - return false; - } - - /** - * - * @param enumValues - * @param constant - * @return - */ - public static boolean containsConstant(Enum[] enumValues, String constant) { - return containsConstant(enumValues, constant, false); - } - - /** - * - * @param enumValues - * @param constant - * @param caseSensitive - * @return - */ - public static boolean containsConstant(Enum[] enumValues, String constant, boolean caseSensitive) { - for (Enum candidate : enumValues) { - if (caseSensitive ? candidate.toString().equals(constant) : - candidate.toString().equalsIgnoreCase(constant)) { - return true; - } - } - return false; - } - - /** - * - * @param enumValues - * @param constant - * @param - * @return - */ - public static > E caseInsensitiveValueOf(E[] enumValues, String constant) { - for (E candidate : enumValues) { - if (candidate.toString().equalsIgnoreCase(constant)) { - return candidate; - } - } - throw new IllegalArgumentException("Constant [" + constant + "] does not exist in enum type " + - enumValues.getClass().getComponentType().getName()); - } - - /** - * - * @param array - * @param obj - * @param - * @param - * @return - */ - public static A[] addObjectToArray(A[] array, O obj) { - Class compType = Object.class; - if (array != null) { - compType = array.getClass().getComponentType(); - } - else if (obj != null) { - compType = obj.getClass(); - } - int newArrLength = (array != null ? array.length + 1 : 1); - @SuppressWarnings("unchecked") - A[] newArr = (A[]) Array.newInstance(compType, newArrLength); - if (array != null) { - System.arraycopy(array, 0, newArr, 0, array.length); - } - newArr[newArr.length - 1] = obj; - return newArr; - } - - /** - * - * @param source - * @return - */ - public static Object[] toObjectArray(Object source) { - if (source instanceof Object[]) { - return (Object[]) source; - } - if (source == null) { - return new Object[0]; - } - if (!source.getClass().isArray()) { - throw new IllegalArgumentException("Source is not an array: " + source); - } - int length = Array.getLength(source); - if (length == 0) { - return new Object[0]; - } - Class wrapperType = Array.get(source, 0).getClass(); - Object[] newArray = (Object[]) Array.newInstance(wrapperType, length); - for (int i = 0; i < length; i++) { - newArray[i] = Array.get(source, i); - } - return newArray; - } - - - //--------------------------------------------------------------------- - // Convenience methods for content-based equality/hash-code handling - //--------------------------------------------------------------------- - - /** - * - * @param o1 - * @param o2 - * @return - */ - public static boolean nullSafeEquals(Object o1, Object o2) { - if (o1 == o2) { - return true; - } - if (o1 == null || o2 == null) { - return false; - } - if (o1.equals(o2)) { - return true; - } - if (o1.getClass().isArray() && o2.getClass().isArray()) { - return arrayEquals(o1, o2); - } - return false; - } - - /** - * - * @param o1 - * @param o2 - * @return - */ - private static boolean arrayEquals(Object o1, Object o2) { - if (o1 instanceof Object[] && o2 instanceof Object[]) { - return Arrays.equals((Object[]) o1, (Object[]) o2); - } - if (o1 instanceof boolean[] && o2 instanceof boolean[]) { - return Arrays.equals((boolean[]) o1, (boolean[]) o2); - } - if (o1 instanceof byte[] && o2 instanceof byte[]) { - return Arrays.equals((byte[]) o1, (byte[]) o2); - } - if (o1 instanceof char[] && o2 instanceof char[]) { - return Arrays.equals((char[]) o1, (char[]) o2); - } - if (o1 instanceof double[] && o2 instanceof double[]) { - return Arrays.equals((double[]) o1, (double[]) o2); - } - if (o1 instanceof float[] && o2 instanceof float[]) { - return Arrays.equals((float[]) o1, (float[]) o2); - } - if (o1 instanceof int[] && o2 instanceof int[]) { - return Arrays.equals((int[]) o1, (int[]) o2); - } - if (o1 instanceof long[] && o2 instanceof long[]) { - return Arrays.equals((long[]) o1, (long[]) o2); - } - if (o1 instanceof short[] && o2 instanceof short[]) { - return Arrays.equals((short[]) o1, (short[]) o2); - } - return false; - } - - /** - * - * @param obj - * @return - */ - public static int nullSafeHashCode(Object obj) { - if (obj == null) { - return 0; - } - if (obj.getClass().isArray()) { - if (obj instanceof Object[]) { - return nullSafeHashCode((Object[]) obj); - } - if (obj instanceof boolean[]) { - return nullSafeHashCode((boolean[]) obj); - } - if (obj instanceof byte[]) { - return nullSafeHashCode((byte[]) obj); - } - if (obj instanceof char[]) { - return nullSafeHashCode((char[]) obj); - } - if (obj instanceof double[]) { - return nullSafeHashCode((double[]) obj); - } - if (obj instanceof float[]) { - return nullSafeHashCode((float[]) obj); - } - if (obj instanceof int[]) { - return nullSafeHashCode((int[]) obj); - } - if (obj instanceof long[]) { - return nullSafeHashCode((long[]) obj); - } - if (obj instanceof short[]) { - return nullSafeHashCode((short[]) obj); - } - } - return obj.hashCode(); - } - - /** - * - * @param array - * @return - */ - public static int nullSafeHashCode(Object[] array) { - if (array == null) { - return 0; - } - int hash = INITIAL_HASH; - for (Object element : array) { - hash = MULTIPLIER * hash + nullSafeHashCode(element); - } - return hash; - } - - /** - * - * @param array - * @return - */ - public static int nullSafeHashCode(boolean[] array) { - if (array == null) { - return 0; - } - int hash = INITIAL_HASH; - for (boolean element : array) { - hash = MULTIPLIER * hash + Boolean.hashCode(element); - } - return hash; - } - - /** - * - * @param array - * @return - */ - public static int nullSafeHashCode(byte[] array) { - if (array == null) { - return 0; - } - int hash = INITIAL_HASH; - for (byte element : array) { - hash = MULTIPLIER * hash + element; - } - return hash; - } - - /** - * - * @param array - * @return - */ - public static int nullSafeHashCode(char[] array) { - if (array == null) { - return 0; - } - int hash = INITIAL_HASH; - for (char element : array) { - hash = MULTIPLIER * hash + element; - } - return hash; - } - - /** - * - * @param array - * @return - */ - public static int nullSafeHashCode(double[] array) { - if (array == null) { - return 0; - } - int hash = INITIAL_HASH; - for (double element : array) { - hash = MULTIPLIER * hash + Double.hashCode(element); - } - return hash; - } - - /** - * - * @param array - * @return - */ - public static int nullSafeHashCode(float[] array) { - if (array == null) { - return 0; - } - int hash = INITIAL_HASH; - for (float element : array) { - hash = MULTIPLIER * hash + Float.hashCode(element); - } - return hash; - } - - /** - * - * @param array - * @return - */ - public static int nullSafeHashCode(int[] array) { - if (array == null) { - return 0; - } - int hash = INITIAL_HASH; - for (int element : array) { - hash = MULTIPLIER * hash + element; - } - return hash; - } - - /** - * - * @param array - * @return - */ - public static int nullSafeHashCode(long[] array) { - if (array == null) { - return 0; - } - int hash = INITIAL_HASH; - for (long element : array) { - hash = MULTIPLIER * hash + Long.hashCode(element); - } - return hash; - } - - /** - * - * @param array - * @return - */ - public static int nullSafeHashCode(short[] array) { - if (array == null) { - return 0; - } - int hash = INITIAL_HASH; - for (short element : array) { - hash = MULTIPLIER * hash + element; - } - return hash; - } - - //--------------------------------------------------------------------- - // Convenience methods for toString output - //--------------------------------------------------------------------- - - /** - * - * @param obj - * @return - */ - public static String identityToString(Object obj) { - if (obj == null) { - return EMPTY_STRING; - } - return obj.getClass().getName() + "@" + getIdentityHexString(obj); - } - - /** - * - * @param obj - * @return - */ - public static String getIdentityHexString(Object obj) { - return Integer.toHexString(System.identityHashCode(obj)); - } - - /** - * - * @param obj - * @return - */ - public static String getDisplayString(Object obj) { - if (obj == null) { - return EMPTY_STRING; - } - return nullSafeToString(obj); - } - - /** - * - * @param obj - * @return - */ - public static String nullSafeClassName(Object obj) { - return (obj != null ? obj.getClass().getName() : NULL_STRING); - } - - /** - * - * @param obj - * @return - */ - public static String nullSafeToString(Object obj) { - if (obj == null) { - return NULL_STRING; - } - if (obj instanceof String) { - return (String) obj; - } - if (obj instanceof Object[]) { - return nullSafeToString((Object[]) obj); - } - if (obj instanceof boolean[]) { - return nullSafeToString((boolean[]) obj); - } - if (obj instanceof byte[]) { - return nullSafeToString((byte[]) obj); - } - if (obj instanceof char[]) { - return nullSafeToString((char[]) obj); - } - if (obj instanceof double[]) { - return nullSafeToString((double[]) obj); - } - if (obj instanceof float[]) { - return nullSafeToString((float[]) obj); - } - if (obj instanceof int[]) { - return nullSafeToString((int[]) obj); - } - if (obj instanceof long[]) { - return nullSafeToString((long[]) obj); - } - if (obj instanceof short[]) { - return nullSafeToString((short[]) obj); - } - String str = obj.toString(); - return (str != null ? str : EMPTY_STRING); - } - - /** - * - * @param array - * @return - */ - public static String nullSafeToString(Object[] array) { - if (array == null) { - return NULL_STRING; - } - int length = array.length; - if (length == 0) { - return EMPTY_ARRAY; - } - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < length; i++) { - if (i == 0) { - sb.append(ARRAY_START); - } - else { - sb.append(ARRAY_ELEMENT_SEPARATOR); - } - sb.append(String.valueOf(array[i])); - } - sb.append(ARRAY_END); - return sb.toString(); - } - - /** - * - * @param array - * @return - */ - public static String nullSafeToString(boolean[] array) { - if (array == null) { - return NULL_STRING; - } - int length = array.length; - if (length == 0) { - return EMPTY_ARRAY; - } - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < length; i++) { - if (i == 0) { - sb.append(ARRAY_START); - } - else { - sb.append(ARRAY_ELEMENT_SEPARATOR); - } - - sb.append(array[i]); - } - sb.append(ARRAY_END); - return sb.toString(); - } - - /** - * - * @param array - * @return - */ - public static String nullSafeToString(byte[] array) { - if (array == null) { - return NULL_STRING; - } - int length = array.length; - if (length == 0) { - return EMPTY_ARRAY; - } - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < length; i++) { - if (i == 0) { - sb.append(ARRAY_START); - } - else { - sb.append(ARRAY_ELEMENT_SEPARATOR); - } - sb.append(array[i]); - } - sb.append(ARRAY_END); - return sb.toString(); - } - - /** - * - * @param array - * @return - */ - public static String nullSafeToString(char[] array) { - if (array == null) { - return NULL_STRING; - } - int length = array.length; - if (length == 0) { - return EMPTY_ARRAY; - } - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < length; i++) { - if (i == 0) { - sb.append(ARRAY_START); - } - else { - sb.append(ARRAY_ELEMENT_SEPARATOR); - } - sb.append("'").append(array[i]).append("'"); - } - sb.append(ARRAY_END); - return sb.toString(); - } - - /** - * - * @param array - * @return - */ - public static String nullSafeToString(double[] array) { - if (array == null) { - return NULL_STRING; - } - int length = array.length; - if (length == 0) { - return EMPTY_ARRAY; - } - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < length; i++) { - if (i == 0) { - sb.append(ARRAY_START); - } - else { - sb.append(ARRAY_ELEMENT_SEPARATOR); - } - - sb.append(array[i]); - } - sb.append(ARRAY_END); - return sb.toString(); - } - - /** - * - * @param array - * @return - */ - public static String nullSafeToString(float[] array) { - if (array == null) { - return NULL_STRING; - } - int length = array.length; - if (length == 0) { - return EMPTY_ARRAY; - } - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < length; i++) { - if (i == 0) { - sb.append(ARRAY_START); - } - else { - sb.append(ARRAY_ELEMENT_SEPARATOR); - } - - sb.append(array[i]); - } - sb.append(ARRAY_END); - return sb.toString(); - } - - /** - * - * @param array - * @return - */ - public static String nullSafeToString(int[] array) { - if (array == null) { - return NULL_STRING; - } - int length = array.length; - if (length == 0) { - return EMPTY_ARRAY; - } - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < length; i++) { - if (i == 0) { - sb.append(ARRAY_START); - } - else { - sb.append(ARRAY_ELEMENT_SEPARATOR); - } - sb.append(array[i]); - } - sb.append(ARRAY_END); - return sb.toString(); - } - - /** - * - * @param array - * @return - */ - public static String nullSafeToString(long[] array) { - if (array == null) { - return NULL_STRING; - } - int length = array.length; - if (length == 0) { - return EMPTY_ARRAY; - } - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < length; i++) { - if (i == 0) { - sb.append(ARRAY_START); - } - else { - sb.append(ARRAY_ELEMENT_SEPARATOR); - } - sb.append(array[i]); - } - sb.append(ARRAY_END); - return sb.toString(); - } - - /** - * - * @param array - * @return - */ - public static String nullSafeToString(short[] array) { - if (array == null) { - return NULL_STRING; - } - int length = array.length; - if (length == 0) { - return EMPTY_ARRAY; - } - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < length; i++) { - if (i == 0) { - sb.append(ARRAY_START); - } - else { - sb.append(ARRAY_ELEMENT_SEPARATOR); - } - sb.append(array[i]); - } - sb.append(ARRAY_END); - return sb.toString(); - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/Pair.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/Pair.java deleted file mode 100644 index 03f45bd9..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/Pair.java +++ /dev/null @@ -1,51 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.util; - -import lombok.Data; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -@Data -public class Pair { - - /** - * 第一个值 - */ - private K first; - - /** - * 第二个值 - */ - private V second; - - public static Pair of(K first, V second) { - Pair pair = new Pair<>(); - pair.setFirst(first); - pair.setSecond(second); - return pair; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/ReflectUtil.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/ReflectUtil.java deleted file mode 100644 index 726fdb93..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/ReflectUtil.java +++ /dev/null @@ -1,598 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.util; - -import com.google.common.collect.Sets; -import fun.asgc.neutrino.core.base.Orderly; -import fun.asgc.neutrino.core.cache.Cache; -import fun.asgc.neutrino.core.cache.MemoryCache; -import fun.asgc.neutrino.core.type.TypeMatchLevel; - -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.UndeclaredThrowableException; -import java.util.*; -import java.util.function.Function; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -public class ReflectUtil { - - private static Cache, Set> fieldsCache = new MemoryCache<>(); - private static Cache, Set> declaredFieldsCache = new MemoryCache<>(); - private static Cache, Set> inheritChainDeclaredFieldSetCache = new MemoryCache<>(); - private static Cache, Set> methodsCache = new MemoryCache<>(); - private static Cache, Set> declaredMethodsCache = new MemoryCache<>(); - private static Cache getMethodCache = new MemoryCache<>(); - private static Cache setMethodCache = new MemoryCache<>(); - private static Cache>> methodExceptionTypesCache = new MemoryCache<>(); - - /** - * 获取字段列表 - * @param clazz - * @return - */ - public static Set getFields(Class clazz) { - try { - return kvProcess(fieldsCache, clazz, c -> { - Field[] fields = c.getFields(); - Set fieldSet = new HashSet<>(); - if (ArrayUtil.notEmpty(fields)) { - fieldSet = Stream.of(fields).collect(Collectors.toSet()); - } - return fieldSet; - }); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - /** - * 获取字段列表 - * @param clazz - * @return - */ - public static Set getDeclaredFields(Class clazz) { - try { - return kvProcess(declaredFieldsCache, clazz, c -> { - Field[] fields = c.getDeclaredFields(); - Set fieldSet = new HashSet<>(); - if (ArrayUtil.notEmpty(fields)) { - fieldSet = Stream.of(fields).collect(Collectors.toSet()); - } - return fieldSet; - }); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - /** - * 获取继承链字段列表 - * @param clazz - * @return - */ - public static Set getInheritChainDeclaredFieldSet(Class clazz) { - return getInheritChainDeclaredFieldSet(clazz, Sets.newHashSet(Object.class)); - } - - /** - * 获取继承链字段列表 - * @param clazz - * @return - */ - public static Set getInheritChainDeclaredFieldSet(Class clazz, Set> ignoreClasses) { - try { - return kvProcess(inheritChainDeclaredFieldSetCache, - clazz, - (Class c) -> { - Set nameSet = new HashSet<>(); - Set set = new HashSet<>(); - Set> ignores = null == ignoreClasses ? new HashSet<>() : ignoreClasses; - while (null != c && !ignores.contains(c)) { - Set fields = getDeclaredFields(c); - if (CollectionUtil.notEmpty(fields)) { - for (Field field : fields) { - if (field.getName().equals("this$0") || nameSet.contains(field.getName())) { - continue; - } - nameSet.add(field.getName()); - set.add(field); - } - } - - c = c.getSuperclass(); - } - return set; - } - ); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - /** - * 获取方法列表 - * @param clazz - * @return - */ - public static Set getMethods(Class clazz) { - try { - return kvProcess(methodsCache, clazz, c -> { - Method[] methods = c.getMethods(); - Set methodSet = new HashSet<>(); - if (ArrayUtil.notEmpty(methods)) { - methodSet = Stream.of(methods).collect(Collectors.toSet()); - } - return methodSet; - }); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - /** - * 获取方法列表 - * @param clazz - * @return - */ - public static Set getDeclaredMethods(Class clazz) { - try { - return kvProcess(declaredMethodsCache, clazz, c -> { - Method[] methods = c.getDeclaredMethods(); - Set methodSet = new HashSet<>(); - if (ArrayUtil.notEmpty(methods)) { - methodSet = Stream.of(methods).collect(Collectors.toSet()); - } - return methodSet; - }); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - /** - * 获取异常集合 - * @param method - * @return - */ - public static Set> getExceptionTypes(Method method) { - try { - return kvProcess(methodExceptionTypesCache, method, c -> { - Class[] classes = method.getExceptionTypes(); - Set> classSet = new HashSet<>(); - if (ArrayUtil.notEmpty(classes)) { - classSet = Stream.of(classes).collect(Collectors.toSet()); - } - return classSet; - }); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - /** - * kv处理逻辑封装 - * @param cache - * @param k - * @param fn - * @param - * @param - * @return - */ - private static V kvProcess(Cache cache, K k, Functionfn) throws Exception { - return LockUtil.doubleCheckProcess( - () -> !cache.containsKey(k), - k, - () -> cache.set(k, fn.apply(k)), - () -> cache.get(k) - ); - } - - /** - * 获取Get方法名称 - * @param field - * @return - */ - private static String getGetMethodName(Field field) { - String fieldName = field.getName(); - String methodName = fieldName.substring(0, 1).toUpperCase().concat(fieldName.substring(1)); - return TypeUtil.isBoolean(field) ? "is" + methodName : "get" + methodName; - } - - /** - * 获取Set方法名称 - * @param field - * @return - */ - private static String getSetMethodName(Field field) { - String fieldName = field.getName(); - return "set" + fieldName.substring(0, 1).toUpperCase().concat(fieldName.substring(1)); - } - - /** - * 获取Get方法 - * @param field - * @return - */ - public static Method getGetMethod(Field field) { - try { - return kvProcess(getMethodCache, field, f -> { - String getMethodName = getGetMethodName(field); - return getMethods(field.getDeclaringClass()).stream() - .filter(method -> method.getName().equals(getMethodName) && method.getParameters().length == 0) - .findFirst().get(); - }); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - /** - * 获取valueof方法 - * @param clazz - * @param params - * @return - */ - public static Method getValueOfMethod(Class clazz, Class ...params) { - - try { - return clazz.getMethod("valueOf", params); - } catch (NoSuchMethodException e) { - // ignore - } - return null; - } - - /** - * 获取set方法 - * @param field - * @return - */ - public static Method getSetMethod(Field field) { - try { - return kvProcess(setMethodCache, field, f -> { - String setMethodName = getSetMethodName(field); - Optional methodOptional = getMethods(field.getDeclaringClass()).stream() - .filter(method -> method.getName().equals(setMethodName) && method.getParameters().length == 1 && method.getParameterTypes()[0] == field.getType()) - .findFirst(); - if (methodOptional.isPresent()) { - return methodOptional.get(); - } - int level = TypeMatchLevel.NOT.getDistanceMax(); - Method method = null; - for (Method m : getMethods(field.getDeclaringClass())) { - if (m.getName().equals(setMethodName) && m.getParameters().length == 1) { - int curLevel = TypeUtil.typeMatch(m.getParameterTypes()[0], field.getType()).getTypeDistance(); - if (curLevel < level) { - level = curLevel; - method = m; - } - } - } - if (level < TypeMatchLevel.NOT.getDistanceMin() && method != null) { - return method; - } - return null; - }); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - /** - * 通过方法设置字段的值 - * @param field - * @param obj - * @param value - */ - public static boolean setFieldValueByMethod(Field field, Object obj, Object value) { - Assert.notNull(field, "field不能为空"); - Assert.notNull(obj, "对象不能为空"); - Assert.notNull(value, "值不能为空"); - - try { - Method setMethod = getSetMethod(field); - if (null == setMethod) { - return false; - } - if (null != value) { - value = TypeUtil.conversion(value, field.getType()); - if (null == value) { - return false; - } - } - setMethod.invoke(obj, value); - return true; - } catch (Exception e) { - return false; - } - } - - /** - * 设置字段的值 - * @param fieldList - * @param obj - * @param value - * @return - */ - public static boolean setFieldValue(List fieldList, Object obj, Object value) { - if (CollectionUtil.isEmpty(fieldList)) { - return false; - } - boolean result = true; - for (Field field : fieldList) { - if (!setFieldValue(field, obj, value)) { - result = false; - } - } - return result; - } - - /** - * 设置字段的值 - * 先尝试通过set方法设置,若设置失败则通过字段直接设置 - * @param field - * @param obj - * @param value - * @return - */ - public static boolean setFieldValue(Field field, Object obj, Object value) { - Assert.notNull(field, "field不能为空"); - Assert.notNull(obj, "对象不能为空"); - - try { - return setFieldValueByMethod(field, obj , value) || setFieldValueByField(field, obj, value); - } catch (Exception e) { - return false; - } - } - - /** - * 获取字段的值 - * @param field - * @param obj - * @return - */ - public static Object getFieldValue(Field field, Object obj) { - Assert.notNull(field, "field不能为空"); - Assert.notNull(obj, "对象不能为空"); - try { - if (!field.isAccessible()) { - field.setAccessible(true); - } - return field.get(obj); - } catch (Exception e) { - // ignore - } - return null; - } - - /** - * 通过字段设置值 - * @param field - * @param obj - * @param value - * @return - */ - public static boolean setFieldValueByField(Field field, Object obj, Object value) { - Assert.notNull(field, "field不能为空!"); - Assert.notNull(obj, "对象不能为空!"); - - try { - Class fieldType = field.getType(); - - if (!field.isAccessible()) { - field.setAccessible(true); - } - if (null == value) { - if (TypeUtil.isStrictBasicType(fieldType)) { - return false; - } - field.set(obj, null); - return true; - } - value = TypeUtil.conversion(value, fieldType); - if (null != value) { - field.set(obj, value); - return true; - } - - } catch (Exception e) { - // ignore - } - return false; - } - - /** - * 获取该类的所有接口,并保持按照接口层级的顺序(顶级在最前、其次是第二级、...) - * @param clazz - * @return - */ - public static List> getInterfaceAll(Class clazz) { - List>> list = new ArrayList<>(); - if (ArrayUtil.notEmpty(clazz.getInterfaces())) { - addTo(list, clazz.getInterfaces(), 0); - int current = 0; - while (current < list.size()) { - Orderly> peek = list.get(current); - if (ArrayUtil.notEmpty(peek.getData().getInterfaces())) { - addTo(list, peek.getData().getInterfaces(), peek.getOrder() + 1); - } - current++; - } - } - return list.stream().sorted().map(Orderly::getData).collect(Collectors.toList()); - } - - private static void addTo(List>> list, Class[] classes, int level) { - if (ArrayUtil.notEmpty(classes)) { - for (Class clazz : classes) { - list.add(new Orderly>().setData(clazz).setOrder(Integer.MAX_VALUE - level)); - } - } - } - - /** - * Invoke the specified {@link Method} against the supplied target object with no arguments. - * The target object can be {@code null} when invoking a static {@link Method}. - *

Thrown exceptions are handled via a call to {@link #handleReflectionException}. - * @param method the method to invoke - * @param target the target object to invoke the method on - * @return the invocation result, if any - * @see #invokeMethod(java.lang.reflect.Method, Object, Object[]) - */ - public static Object invokeMethod(Method method, Object target) { - return invokeMethod(method, target, new Object[0]); - } - - /** - * Invoke the specified {@link Method} against the supplied target object with the - * supplied arguments. The target object can be {@code null} when invoking a - * static {@link Method}. - *

Thrown exceptions are handled via a call to {@link #handleReflectionException}. - * @param method the method to invoke - * @param target the target object to invoke the method on - * @param args the invocation arguments (may be {@code null}) - * @return the invocation result, if any - */ - public static Object invokeMethod(Method method, Object target, Object... args) { - try { - return method.invoke(target, args); - } - catch (Exception ex) { - handleReflectionException(ex); - } - throw new IllegalStateException("Should never get here"); - } - - /** - * Handle the given reflection exception. Should only be called if no - * checked exception is expected to be thrown by the target method. - *

Throws the underlying RuntimeException or Error in case of an - * InvocationTargetException with such a root cause. Throws an - * IllegalStateException with an appropriate message or - * UndeclaredThrowableException otherwise. - * @param ex the reflection exception to handle - */ - public static void handleReflectionException(Exception ex) { - if (ex instanceof NoSuchMethodException) { - throw new IllegalStateException("Method not found: " + ex.getMessage()); - } - if (ex instanceof IllegalAccessException) { - throw new IllegalStateException("Could not access method: " + ex.getMessage()); - } - if (ex instanceof InvocationTargetException) { - handleInvocationTargetException((InvocationTargetException) ex); - } - if (ex instanceof RuntimeException) { - throw (RuntimeException) ex; - } - throw new UndeclaredThrowableException(ex); - } - - /** - * Handle the given invocation target exception. Should only be called if no - * checked exception is expected to be thrown by the target method. - *

Throws the underlying RuntimeException or Error in case of such a root - * cause. Throws an UndeclaredThrowableException otherwise. - * @param ex the invocation target exception to handle - */ - public static void handleInvocationTargetException(InvocationTargetException ex) { - rethrowRuntimeException(ex.getTargetException()); - } - - /** - * Rethrow the given {@link Throwable exception}, which is presumably the - * target exception of an {@link InvocationTargetException}. - * Should only be called if no checked exception is expected to be thrown - * by the target method. - *

Rethrows the underlying exception cast to a {@link RuntimeException} or - * {@link Error} if appropriate; otherwise, throws an - * {@link UndeclaredThrowableException}. - * @param ex the exception to rethrow - * @throws RuntimeException the rethrown exception - */ - public static void rethrowRuntimeException(Throwable ex) { - if (ex instanceof RuntimeException) { - throw (RuntimeException) ex; - } - if (ex instanceof Error) { - throw (Error) ex; - } - throw new UndeclaredThrowableException(ex); - } - - /** - * Attempt to find a {@link Method} on the supplied class with the supplied name - * and no parameters. Searches all superclasses up to {@code Object}. - *

Returns {@code null} if no {@link Method} can be found. - * @param clazz the class to introspect - * @param name the name of the method - * @return the Method object, or {@code null} if none found - */ - public static Method findMethod(Class clazz, String name) { - return findMethod(clazz, name, new Class[0]); - } - - /** - * Attempt to find a {@link Method} on the supplied class with the supplied name - * and parameter types. Searches all superclasses up to {@code Object}. - *

Returns {@code null} if no {@link Method} can be found. - * @param clazz the class to introspect - * @param name the name of the method - * @param paramTypes the parameter types of the method - * (may be {@code null} to indicate any signature) - * @return the Method object, or {@code null} if none found - */ - public static Method findMethod(Class clazz, String name, Class... paramTypes) { - Assert.notNull(clazz, "Class must not be null"); - Assert.notNull(name, "Method name must not be null"); - Class searchType = clazz; - while (searchType != null) { - Set methods = (searchType.isInterface() ? Sets.newHashSet(searchType.getMethods()) : getDeclaredMethods(searchType)); - for (Method method : methods) { - if (name.equals(method.getName()) && - (paramTypes == null || Arrays.equals(paramTypes, method.getParameterTypes()))) { - return method; - } - } - searchType = searchType.getSuperclass(); - } - return null; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/StopWatch.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/StopWatch.java deleted file mode 100644 index 4b0f15d8..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/StopWatch.java +++ /dev/null @@ -1,316 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.util; - -import java.text.NumberFormat; -import java.util.LinkedList; -import java.util.List; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -public class StopWatch { - - /** - * Identifier of this stop watch. - * Handy when we have output from multiple stop watches - * and need to distinguish between them in log or console output. - */ - private final String id; - - private boolean keepTaskList = true; - - private final List taskList = new LinkedList<>(); - - /** Start time of the current task */ - private long startTimeMillis; - - /** Name of the current task */ - private String currentTaskName; - - private TaskInfo lastTaskInfo; - - private int taskCount; - - /** Total running time */ - private long totalTimeMillis; - - - /** - * Construct a new stop watch. Does not start any task. - */ - public StopWatch() { - this(""); - } - - /** - * Construct a new stop watch with the given id. - * Does not start any task. - * @param id identifier for this stop watch. - * Handy when we have output from multiple stop watches - * and need to distinguish between them. - */ - public StopWatch(String id) { - this.id = id; - } - - - /** - * Return the id of this stop watch, as specified on construction. - * @return the id (empty String by default) - * @since 4.2.2 - * @see #StopWatch(String) - */ - public String getId() { - return this.id; - } - - /** - * Determine whether the TaskInfo array is built over time. Set this to - * "false" when using a StopWatch for millions of intervals, or the task - * info structure will consume excessive memory. Default is "true". - */ - public void setKeepTaskList(boolean keepTaskList) { - this.keepTaskList = keepTaskList; - } - - - /** - * Start an unnamed task. The results are undefined if {@link #stop()} - * or timing methods are called without invoking this method. - * @see #stop() - */ - public void start() throws IllegalStateException { - start(""); - } - - /** - * Start a named task. The results are undefined if {@link #stop()} - * or timing methods are called without invoking this method. - * @param taskName the name of the task to start - * @see #stop() - */ - public void start(String taskName) throws IllegalStateException { - if (this.currentTaskName != null) { - throw new IllegalStateException("Can't start StopWatch: it's already running"); - } - this.currentTaskName = taskName; - this.startTimeMillis = System.currentTimeMillis(); - } - - /** - * Stop the current task. The results are undefined if timing - * methods are called without invoking at least one pair - * {@code start()} / {@code stop()} methods. - * @see #start() - */ - public void stop() throws IllegalStateException { - if (this.currentTaskName == null) { - throw new IllegalStateException("Can't stop StopWatch: it's not running"); - } - long lastTime = System.currentTimeMillis() - this.startTimeMillis; - this.totalTimeMillis += lastTime; - this.lastTaskInfo = new TaskInfo(this.currentTaskName, lastTime); - if (this.keepTaskList) { - this.taskList.add(this.lastTaskInfo); - } - ++this.taskCount; - this.currentTaskName = null; - } - - /** - * Return whether the stop watch is currently running. - * @see #currentTaskName() - */ - public boolean isRunning() { - return (this.currentTaskName != null); - } - - /** - * Return the name of the currently running task, if any. - * @since 4.2.2 - * @see #isRunning() - */ - public String currentTaskName() { - return this.currentTaskName; - } - - - /** - * Return the time taken by the last task. - */ - public long getLastTaskTimeMillis() throws IllegalStateException { - if (this.lastTaskInfo == null) { - throw new IllegalStateException("No tasks run: can't get last task interval"); - } - return this.lastTaskInfo.getTimeMillis(); - } - - /** - * Return the name of the last task. - */ - public String getLastTaskName() throws IllegalStateException { - if (this.lastTaskInfo == null) { - throw new IllegalStateException("No tasks run: can't get last task name"); - } - return this.lastTaskInfo.getTaskName(); - } - - /** - * Return the last task as a TaskInfo object. - */ - public TaskInfo getLastTaskInfo() throws IllegalStateException { - if (this.lastTaskInfo == null) { - throw new IllegalStateException("No tasks run: can't get last task info"); - } - return this.lastTaskInfo; - } - - - /** - * Return the total time in milliseconds for all tasks. - */ - public long getTotalTimeMillis() { - return this.totalTimeMillis; - } - - /** - * Return the total time in seconds for all tasks. - */ - public double getTotalTimeSeconds() { - return this.totalTimeMillis / 1000.0; - } - - /** - * Return the number of tasks timed. - */ - public int getTaskCount() { - return this.taskCount; - } - - /** - * Return an array of the data for tasks performed. - */ - public TaskInfo[] getTaskInfo() { - if (!this.keepTaskList) { - throw new UnsupportedOperationException("Task info is not being kept!"); - } - return this.taskList.toArray(new TaskInfo[0]); - } - - - /** - * Return a short description of the total running time. - */ - public String shortSummary() { - return "StopWatch '" + getId() + "': running time (millis) = " + getTotalTimeMillis(); - } - - /** - * Return a string with a table describing all tasks performed. - * For custom reporting, call getTaskInfo() and use the task info directly. - */ - public String prettyPrint() { - StringBuilder sb = new StringBuilder(shortSummary()); - sb.append('\n'); - if (!this.keepTaskList) { - sb.append("No task info kept"); - } - else { - sb.append("-----------------------------------------\n"); - sb.append("ms % Task name\n"); - sb.append("-----------------------------------------\n"); - NumberFormat nf = NumberFormat.getNumberInstance(); - nf.setMinimumIntegerDigits(5); - nf.setGroupingUsed(false); - NumberFormat pf = NumberFormat.getPercentInstance(); - pf.setMinimumIntegerDigits(3); - pf.setGroupingUsed(false); - for (TaskInfo task : getTaskInfo()) { - sb.append(nf.format(task.getTimeMillis())).append(" "); - sb.append(pf.format(task.getTimeSeconds() / getTotalTimeSeconds())).append(" "); - sb.append(task.getTaskName()).append("\n"); - } - } - return sb.toString(); - } - - /** - * Return an informative string describing all tasks performed - * For custom reporting, call {@code getTaskInfo()} and use the task info directly. - */ - @Override - public String toString() { - StringBuilder sb = new StringBuilder(shortSummary()); - if (this.keepTaskList) { - for (TaskInfo task : getTaskInfo()) { - sb.append("; [").append(task.getTaskName()).append("] took ").append(task.getTimeMillis()); - long percent = Math.round((100.0 * task.getTimeSeconds()) / getTotalTimeSeconds()); - sb.append(" = ").append(percent).append("%"); - } - } - else { - sb.append("; no task info kept"); - } - return sb.toString(); - } - - - /** - * Inner class to hold data about one task executed within the stop watch. - */ - public static final class TaskInfo { - - private final String taskName; - - private final long timeMillis; - - TaskInfo(String taskName, long timeMillis) { - this.taskName = taskName; - this.timeMillis = timeMillis; - } - - /** - * Return the name of this task. - */ - public String getTaskName() { - return this.taskName; - } - - /** - * Return the time in milliseconds this task took. - */ - public long getTimeMillis() { - return this.timeMillis; - } - - /** - * Return the time in seconds this task took. - */ - public double getTimeSeconds() { - return (this.timeMillis / 1000.0); - } - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/StringUtil.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/StringUtil.java deleted file mode 100644 index d2dd409b..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/StringUtil.java +++ /dev/null @@ -1,1117 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.util; - -import org.apache.commons.lang3.ObjectUtils; - -import java.io.ByteArrayOutputStream; -import java.nio.charset.Charset; -import java.util.*; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -public class StringUtil { - - private static final String FOLDER_SEPARATOR = "/"; - - private static final String WINDOWS_FOLDER_SEPARATOR = "\\"; - - private static final String TOP_PATH = ".."; - - private static final String CURRENT_PATH = "."; - - private static final char EXTENSION_SEPARATOR = '.'; - - - //--------------------------------------------------------------------- - // General convenience methods for working with Strings - //--------------------------------------------------------------------- - - /** - * - * @param str - * @return - */ - public static boolean isEmpty(String str) { - return (str == null || "".equals(str)); - } - - /** - * - * @param str - * @return - */ - public static boolean notEmpty(String str) { - return !isEmpty(str); - } - - /** - * - * @param str - * @return - */ - public static boolean hasLength(CharSequence str) { - return (str != null && str.length() > 0); - } - - /** - * - * @param str - * @return - */ - public static boolean hasLength(String str) { - return (str != null && !str.isEmpty()); - } - - /** - * - * @param str - * @return - */ - public static boolean hasText(CharSequence str) { - return (str != null && str.length() > 0 && containsText(str)); - } - - /** - * - * @param str - * @return - */ - public static boolean hasText(String str) { - return (str != null && !str.isEmpty() && containsText(str)); - } - - private static boolean containsText(CharSequence str) { - int strLen = str.length(); - for (int i = 0; i < strLen; i++) { - if (!Character.isWhitespace(str.charAt(i))) { - return true; - } - } - return false; - } - - public static boolean isNumeric(String cs) { - if (isEmpty(cs)) { - return false; - } else { - int sz = cs.length(); - - for(int i = 0; i < sz; ++i) { - if (!Character.isDigit(cs.charAt(i))) { - return false; - } - } - - return true; - } - } - - /** - * - * @param str - * @return - */ - public static boolean containsWhitespace(CharSequence str) { - if (!hasLength(str)) { - return false; - } - - int strLen = str.length(); - for (int i = 0; i < strLen; i++) { - if (Character.isWhitespace(str.charAt(i))) { - return true; - } - } - return false; - } - - /** - * - * @param str - * @return - */ - public static boolean containsWhitespace(String str) { - return containsWhitespace((CharSequence) str); - } - - /** - * - * @param str - * @return - */ - public static String trimWhitespace(String str) { - if (!hasLength(str)) { - return str; - } - - int beginIndex = 0; - int endIndex = str.length() - 1; - - while (beginIndex <= endIndex && Character.isWhitespace(str.charAt(beginIndex))) { - beginIndex++; - } - - while (endIndex > beginIndex && Character.isWhitespace(str.charAt(endIndex))) { - endIndex--; - } - - return str.substring(beginIndex, endIndex + 1); - } - - /** - * - * @param str - * @return - */ - public static String trimAllWhitespace(String str) { - if (!hasLength(str)) { - return str; - } - - int len = str.length(); - StringBuilder sb = new StringBuilder(str.length()); - for (int i = 0; i < len; i++) { - char c = str.charAt(i); - if (!Character.isWhitespace(c)) { - sb.append(c); - } - } - return sb.toString(); - } - - /** - * - * @param str - * @return - */ - public static String trimLeadingWhitespace(String str) { - if (!hasLength(str)) { - return str; - } - - StringBuilder sb = new StringBuilder(str); - while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0))) { - sb.deleteCharAt(0); - } - return sb.toString(); - } - - /** - * - * @param str - * @return - */ - public static String trimTrailingWhitespace(String str) { - if (!hasLength(str)) { - return str; - } - - StringBuilder sb = new StringBuilder(str); - while (sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1))) { - sb.deleteCharAt(sb.length() - 1); - } - return sb.toString(); - } - - /** - * - * @param str - * @param leadingCharacter - * @return - */ - public static String trimLeadingCharacter(String str, char leadingCharacter) { - if (!hasLength(str)) { - return str; - } - - StringBuilder sb = new StringBuilder(str); - while (sb.length() > 0 && sb.charAt(0) == leadingCharacter) { - sb.deleteCharAt(0); - } - return sb.toString(); - } - - /** - * - * @param str - * @param trailingCharacter - * @return - */ - public static String trimTrailingCharacter(String str, char trailingCharacter) { - if (!hasLength(str)) { - return str; - } - - StringBuilder sb = new StringBuilder(str); - while (sb.length() > 0 && sb.charAt(sb.length() - 1) == trailingCharacter) { - sb.deleteCharAt(sb.length() - 1); - } - return sb.toString(); - } - - /** - * - * @param str - * @param prefix - * @return - */ - public static boolean startsWithIgnoreCase(String str, String prefix) { - return (str != null && prefix != null && str.length() >= prefix.length() && - str.regionMatches(true, 0, prefix, 0, prefix.length())); - } - - /** - * - * @param str - * @param suffix - * @return - */ - public static boolean endsWithIgnoreCase(String str, String suffix) { - return (str != null && suffix != null && str.length() >= suffix.length() && - str.regionMatches(true, str.length() - suffix.length(), suffix, 0, suffix.length())); - } - - /** - * - * @param str - * @param index - * @param substring - * @return - */ - public static boolean substringMatch(CharSequence str, int index, CharSequence substring) { - if (index + substring.length() > str.length()) { - return false; - } - for (int i = 0; i < substring.length(); i++) { - if (str.charAt(index + i) != substring.charAt(i)) { - return false; - } - } - return true; - } - - /** - * - * @param str - * @param sub - * @return - */ - public static int countOccurrencesOf(String str, String sub) { - if (!hasLength(str) || !hasLength(sub)) { - return 0; - } - - int count = 0; - int pos = 0; - int idx; - while ((idx = str.indexOf(sub, pos)) != -1) { - ++count; - pos = idx + sub.length(); - } - return count; - } - - /** - * - * @param inString - * @param oldPattern - * @param newPattern - * @return - */ - public static String replace(String inString, String oldPattern, String newPattern) { - if (!hasLength(inString) || !hasLength(oldPattern) || newPattern == null) { - return inString; - } - int index = inString.indexOf(oldPattern); - if (index == -1) { - // no occurrence -> can return input as-is - return inString; - } - - int capacity = inString.length(); - if (newPattern.length() > oldPattern.length()) { - capacity += 16; - } - StringBuilder sb = new StringBuilder(capacity); - - int pos = 0; // our position in the old string - int patLen = oldPattern.length(); - while (index >= 0) { - sb.append(inString, pos, index); - sb.append(newPattern); - pos = index + patLen; - index = inString.indexOf(oldPattern, pos); - } - - // append any characters to the right of a match - sb.append(inString, pos, inString.length()); - return sb.toString(); - } - - /** - * - * @param inString - * @param pattern - * @return - */ - public static String delete(String inString, String pattern) { - return replace(inString, pattern, ""); - } - - /** - * - * @param inString - * @param charsToDelete - * @return - */ - public static String deleteAny(String inString, String charsToDelete) { - if (!hasLength(inString) || !hasLength(charsToDelete)) { - return inString; - } - - StringBuilder sb = new StringBuilder(inString.length()); - for (int i = 0; i < inString.length(); i++) { - char c = inString.charAt(i); - if (charsToDelete.indexOf(c) == -1) { - sb.append(c); - } - } - return sb.toString(); - } - - - //--------------------------------------------------------------------- - // Convenience methods for working with formatted Strings - //--------------------------------------------------------------------- - - /** - * - * @param str - * @return - */ - public static String quote(String str) { - return (str != null ? "'" + str + "'" : null); - } - - /** - * - * @param obj - * @return - */ - public static Object quoteIfString(Object obj) { - return (obj instanceof String ? quote((String) obj) : obj); - } - - /** - * - * @param qualifiedName - * @return - */ - public static String unqualify(String qualifiedName) { - return unqualify(qualifiedName, '.'); - } - - /** - * - * @param qualifiedName - * @param separator - * @return - */ - public static String unqualify(String qualifiedName, char separator) { - return qualifiedName.substring(qualifiedName.lastIndexOf(separator) + 1); - } - - /** - * - * @param str - * @return - */ - public static String capitalize(String str) { - return changeFirstCharacterCase(str, true); - } - - /** - * - * @param str - * @return - */ - public static String uncapitalize(String str) { - return changeFirstCharacterCase(str, false); - } - - private static String changeFirstCharacterCase(String str, boolean capitalize) { - if (!hasLength(str)) { - return str; - } - - char baseChar = str.charAt(0); - char updatedChar; - if (capitalize) { - updatedChar = Character.toUpperCase(baseChar); - } - else { - updatedChar = Character.toLowerCase(baseChar); - } - if (baseChar == updatedChar) { - return str; - } - - char[] chars = str.toCharArray(); - chars[0] = updatedChar; - return new String(chars, 0, chars.length); - } - - /** - * - * @param path - * @return - */ - public static String getFilename(String path) { - if (path == null) { - return null; - } - - int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR); - return (separatorIndex != -1 ? path.substring(separatorIndex + 1) : path); - } - - /** - * - * @param path - * @return - */ - public static String getFilenameExtension(String path) { - if (path == null) { - return null; - } - - int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR); - if (extIndex == -1) { - return null; - } - - int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR); - if (folderIndex > extIndex) { - return null; - } - - return path.substring(extIndex + 1); - } - - /** - * - * @param path - * @return - */ - public static String stripFilenameExtension(String path) { - int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR); - if (extIndex == -1) { - return path; - } - - int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR); - if (folderIndex > extIndex) { - return path; - } - - return path.substring(0, extIndex); - } - - /** - * - * @param path - * @param relativePath - * @return - */ - public static String applyRelativePath(String path, String relativePath) { - int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR); - if (separatorIndex != -1) { - String newPath = path.substring(0, separatorIndex); - if (!relativePath.startsWith(FOLDER_SEPARATOR)) { - newPath += FOLDER_SEPARATOR; - } - return newPath + relativePath; - } - else { - return relativePath; - } - } - - /** - * - * @param path - * @return - */ - public static String cleanPath(String path) { - if (!hasLength(path)) { - return path; - } - String pathToUse = replace(path, WINDOWS_FOLDER_SEPARATOR, FOLDER_SEPARATOR); - - // Strip prefix from path to analyze, to not treat it as part of the - // first path element. This is necessary to correctly parse paths like - // "file:core/../core/io/Resource.class", where the ".." should just - // strip the first "core" directory while keeping the "file:" prefix. - int prefixIndex = pathToUse.indexOf(':'); - String prefix = ""; - if (prefixIndex != -1) { - prefix = pathToUse.substring(0, prefixIndex + 1); - if (prefix.contains(FOLDER_SEPARATOR)) { - prefix = ""; - } - else { - pathToUse = pathToUse.substring(prefixIndex + 1); - } - } - if (pathToUse.startsWith(FOLDER_SEPARATOR)) { - prefix = prefix + FOLDER_SEPARATOR; - pathToUse = pathToUse.substring(1); - } - - String[] pathArray = delimitedListToStringArray(pathToUse, FOLDER_SEPARATOR); - LinkedList pathElements = new LinkedList<>(); - int tops = 0; - - for (int i = pathArray.length - 1; i >= 0; i--) { - String element = pathArray[i]; - if (CURRENT_PATH.equals(element)) { - // Points to current directory - drop it. - } - else if (TOP_PATH.equals(element)) { - // Registering top path found. - tops++; - } - else { - if (tops > 0) { - // Merging path element with element corresponding to top path. - tops--; - } - else { - // Normal path element found. - pathElements.addFirst(element); - } - } - } - - // Remaining top paths need to be retained. - for (int i = 0; i < tops; i++) { - pathElements.addFirst(TOP_PATH); - } - // If nothing else left, at least explicitly point to current path. - if (pathElements.size() == 1 && pathElements.getLast().isEmpty() && !prefix.endsWith(FOLDER_SEPARATOR)) { - pathElements.addFirst(CURRENT_PATH); - } - - return prefix + collectionToDelimitedString(pathElements, FOLDER_SEPARATOR); - } - - /** - * - * @param path1 - * @param path2 - * @return - */ - public static boolean pathEquals(String path1, String path2) { - return cleanPath(path1).equals(cleanPath(path2)); - } - - /** - * - * @param source - * @param charset - * @return - */ - public static String uriDecode(String source, Charset charset) { - int length = source.length(); - if (length == 0) { - return source; - } - Assert.notNull(charset, "Charset must not be null"); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(length); - boolean changed = false; - for (int i = 0; i < length; i++) { - int ch = source.charAt(i); - if (ch == '%') { - if (i + 2 < length) { - char hex1 = source.charAt(i + 1); - char hex2 = source.charAt(i + 2); - int u = Character.digit(hex1, 16); - int l = Character.digit(hex2, 16); - if (u == -1 || l == -1) { - throw new IllegalArgumentException("Invalid encoded sequence \"" + source.substring(i) + "\""); - } - baos.write((char) ((u << 4) + l)); - i += 2; - changed = true; - } - else { - throw new IllegalArgumentException("Invalid encoded sequence \"" + source.substring(i) + "\""); - } - } - else { - baos.write(ch); - } - } - return (changed ? new String(baos.toByteArray(), charset) : source); - } - - /** - * - * @param localeValue - * @return - */ - public static Locale parseLocale(String localeValue) { - String[] tokens = tokenizeLocaleSource(localeValue); - if (tokens.length == 1) { - Locale resolved = Locale.forLanguageTag(localeValue); - if (resolved.getLanguage().length() > 0) { - return resolved; - } - } - return parseLocaleTokens(localeValue, tokens); - } - - /** - * - * @param localeString - * @return - */ - public static Locale parseLocaleString(String localeString) { - return parseLocaleTokens(localeString, tokenizeLocaleSource(localeString)); - } - - private static String[] tokenizeLocaleSource(String localeSource) { - return tokenizeToStringArray(localeSource, "_ ", false, false); - } - - private static Locale parseLocaleTokens(String localeString, String[] tokens) { - String language = (tokens.length > 0 ? tokens[0] : ""); - String country = (tokens.length > 1 ? tokens[1] : ""); - validateLocalePart(language); - validateLocalePart(country); - - String variant = ""; - if (tokens.length > 2) { - // There is definitely a variant, and it is everything after the country - // code sans the separator between the country code and the variant. - int endIndexOfCountryCode = localeString.indexOf(country, language.length()) + country.length(); - // Strip off any leading '_' and whitespace, what's left is the variant. - variant = trimLeadingWhitespace(localeString.substring(endIndexOfCountryCode)); - if (variant.startsWith("_")) { - variant = trimLeadingCharacter(variant, '_'); - } - } - - if (variant.isEmpty() && country.startsWith("#")) { - variant = country; - country = ""; - } - - return (language.length() > 0 ? new Locale(language, country, variant) : null); - } - - private static void validateLocalePart(String localePart) { - for (int i = 0; i < localePart.length(); i++) { - char ch = localePart.charAt(i); - if (ch != ' ' && ch != '_' && ch != '#' && !Character.isLetterOrDigit(ch)) { - throw new IllegalArgumentException( - "Locale part \"" + localePart + "\" contains invalid characters"); - } - } - } - - /** - * - * @param timeZoneString - * @return - */ - public static TimeZone parseTimeZoneString(String timeZoneString) { - TimeZone timeZone = TimeZone.getTimeZone(timeZoneString); - if ("GMT".equals(timeZone.getID()) && !timeZoneString.startsWith("GMT")) { - // We don't want that GMT fallback... - throw new IllegalArgumentException("Invalid time zone specification '" + timeZoneString + "'"); - } - return timeZone; - } - - - //--------------------------------------------------------------------- - // Convenience methods for working with String arrays - //--------------------------------------------------------------------- - - /** - * - * @param collection - * @return - */ - public static String[] toStringArray(Collection collection) { - return (collection != null ? collection.toArray(new String[0]) : new String[0]); - } - - /** - * - * @param enumeration - * @return - */ - public static String[] toStringArray(Enumeration enumeration) { - return (enumeration != null ? toStringArray(Collections.list(enumeration)) : new String[0]); - } - - /** - * - * @param array - * @param str - * @return - */ - public static String[] addStringToArray(String[] array, String str) { - if (ObjectUtils.isEmpty(array)) { - return new String[] {str}; - } - - String[] newArr = new String[array.length + 1]; - System.arraycopy(array, 0, newArr, 0, array.length); - newArr[array.length] = str; - return newArr; - } - - /** - * - * @param array1 - * @param array2 - * @return - */ - public static String[] concatenateStringArrays(String[] array1, String[] array2) { - if (ObjectUtils.isEmpty(array1)) { - return array2; - } - if (ObjectUtils.isEmpty(array2)) { - return array1; - } - - String[] newArr = new String[array1.length + array2.length]; - System.arraycopy(array1, 0, newArr, 0, array1.length); - System.arraycopy(array2, 0, newArr, array1.length, array2.length); - return newArr; - } - - /** - * - * @param array - * @return - */ - public static String[] sortStringArray(String[] array) { - if (ObjectUtils.isEmpty(array)) { - return new String[0]; - } - - Arrays.sort(array); - return array; - } - - /** - * - * @param array - * @return - */ - public static String[] trimArrayElements(String[] array) { - if (ObjectUtils.isEmpty(array)) { - return new String[0]; - } - - String[] result = new String[array.length]; - for (int i = 0; i < array.length; i++) { - String element = array[i]; - result[i] = (element != null ? element.trim() : null); - } - return result; - } - - /** - * - * @param array - * @return - */ - public static String[] removeDuplicateStrings(String[] array) { - if (ObjectUtils.isEmpty(array)) { - return array; - } - - Set set = new LinkedHashSet<>(Arrays.asList(array)); - return toStringArray(set); - } - - /** - * - * @param toSplit - * @param delimiter - * @return - */ - public static String[] split(String toSplit, String delimiter) { - if (!hasLength(toSplit) || !hasLength(delimiter)) { - return null; - } - int offset = toSplit.indexOf(delimiter); - if (offset < 0) { - return null; - } - - String beforeDelimiter = toSplit.substring(0, offset); - String afterDelimiter = toSplit.substring(offset + delimiter.length()); - return new String[] {beforeDelimiter, afterDelimiter}; - } - - /** - * - * @param array - * @param delimiter - * @return - */ - public static Properties splitArrayElementsIntoProperties(String[] array, String delimiter) { - return splitArrayElementsIntoProperties(array, delimiter, null); - } - - /** - * - * @param array - * @param delimiter - * @param charsToDelete - * @return - */ - public static Properties splitArrayElementsIntoProperties( - String[] array, String delimiter, String charsToDelete) { - - if (ObjectUtils.isEmpty(array)) { - return null; - } - - Properties result = new Properties(); - for (String element : array) { - if (charsToDelete != null) { - element = deleteAny(element, charsToDelete); - } - String[] splittedElement = split(element, delimiter); - if (splittedElement == null) { - continue; - } - result.setProperty(splittedElement[0].trim(), splittedElement[1].trim()); - } - return result; - } - - /** - * - * @param str - * @param delimiters - * @return - */ - public static String[] tokenizeToStringArray(String str, String delimiters) { - return tokenizeToStringArray(str, delimiters, true, true); - } - - /** - * - * @param str - * @param delimiters - * @param trimTokens - * @param ignoreEmptyTokens - * @return - */ - public static String[] tokenizeToStringArray( - String str, String delimiters, boolean trimTokens, boolean ignoreEmptyTokens) { - - if (str == null) { - return new String[0]; - } - - StringTokenizer st = new StringTokenizer(str, delimiters); - List tokens = new ArrayList<>(); - while (st.hasMoreTokens()) { - String token = st.nextToken(); - if (trimTokens) { - token = token.trim(); - } - if (!ignoreEmptyTokens || token.length() > 0) { - tokens.add(token); - } - } - return toStringArray(tokens); - } - - /** - * - * @param str - * @param delimiter - * @return - */ - public static String[] delimitedListToStringArray(String str, String delimiter) { - return delimitedListToStringArray(str, delimiter, null); - } - - /** - * - * @param str - * @param delimiter - * @param charsToDelete - * @return - */ - public static String[] delimitedListToStringArray( - String str, String delimiter, String charsToDelete) { - - if (str == null) { - return new String[0]; - } - if (delimiter == null) { - return new String[] {str}; - } - - List result = new ArrayList<>(); - if (delimiter.isEmpty()) { - for (int i = 0; i < str.length(); i++) { - result.add(deleteAny(str.substring(i, i + 1), charsToDelete)); - } - } - else { - int pos = 0; - int delPos; - while ((delPos = str.indexOf(delimiter, pos)) != -1) { - result.add(deleteAny(str.substring(pos, delPos), charsToDelete)); - pos = delPos + delimiter.length(); - } - if (str.length() > 0 && pos <= str.length()) { - // Add rest of String, but not in case of empty input. - result.add(deleteAny(str.substring(pos), charsToDelete)); - } - } - return toStringArray(result); - } - - /** - * - * @param str - * @return - */ - public static String[] commaDelimitedListToStringArray(String str) { - return delimitedListToStringArray(str, ","); - } - - /** - * - * @param str - * @return - */ - public static Set commaDelimitedListToSet(String str) { - String[] tokens = commaDelimitedListToStringArray(str); - return new LinkedHashSet<>(Arrays.asList(tokens)); - } - - /** - * - * @param coll - * @param delim - * @param prefix - * @param suffix - * @return - */ - public static String collectionToDelimitedString( - Collection coll, String delim, String prefix, String suffix) { - - if (CollectionUtil.isEmpty(coll)) { - return ""; - } - - StringBuilder sb = new StringBuilder(); - Iterator it = coll.iterator(); - while (it.hasNext()) { - sb.append(prefix).append(it.next()).append(suffix); - if (it.hasNext()) { - sb.append(delim); - } - } - return sb.toString(); - } - - /** - * - * @param coll - * @param delim - * @return - */ - public static String collectionToDelimitedString(Collection coll, String delim) { - return collectionToDelimitedString(coll, delim, "", ""); - } - - /** - * - * @param coll - * @return - */ - public static String collectionToCommaDelimitedString(Collection coll) { - return collectionToDelimitedString(coll, ","); - } - - /** - * - * @param arr - * @param delim - * @return - */ - public static String arrayToDelimitedString(Object[] arr, String delim) { - if (ObjectUtils.isEmpty(arr)) { - return ""; - } - if (arr.length == 1) { - return ObjectUtil.nullSafeToString(arr[0]); - } - - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < arr.length; i++) { - if (i > 0) { - sb.append(delim); - } - sb.append(arr[i]); - } - return sb.toString(); - } - - /** - * - * @param arr - * @return - */ - public static String arrayToCommaDelimitedString(Object[] arr) { - return arrayToDelimitedString(arr, ","); - } - - /** - * 生成UUID - * @return - */ - public static String genUUID() { - return UUID.randomUUID().toString().replace("-", "").toUpperCase(); - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/SystemUtil.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/SystemUtil.java deleted file mode 100644 index 9f798060..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/SystemUtil.java +++ /dev/null @@ -1,128 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.util; - -import fun.asgc.neutrino.core.base.CodeBlock; -import lombok.extern.slf4j.Slf4j; - -import java.util.Objects; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -@Slf4j -public class SystemUtil { - - public static void addShutdownHook(Runnable runnable) { - Runtime.getRuntime().addShutdownHook(new Thread(runnable)); - } - - /** - * 等待进程销毁 - * @return - */ - public static RunContext waitProcessDestroy() { - return waitProcessDestroy(null); - } - - /** - * 等待进程销毁 - * @param destroy - * @return - */ - public static RunContext waitProcessDestroy(CodeBlock destroy) { - RunContext context = new RunContext(); - SystemUtil.addShutdownHook(() -> { - synchronized (context) { - if (null != destroy) { - try { - destroy.execute(); - } catch (Exception e) { - e.printStackTrace(); - } - } - context.stop(); - context.notify(); - } - }); - return context; - } - - - public static class RunContext { - private volatile boolean running = true; - - public void sync() { - synchronized (this) { - while (running) { - try { - this.wait(); - } catch (Exception e) { - // ignore - } - } - } - } - - private void stop() { - this.running = false; - } - } - - public static boolean isStartupFromJar() { - String protocol = SystemUtil.class.getResource("").getProtocol(); - return Objects.equals(protocol, "jar"); - } - - public static String getCurrentJarFilePath() { - if (!isStartupFromJar()) { - return null; - } - String path = SystemUtil.class.getResource("").getPath(); - String res = path; - if (res.startsWith("file:")) { - res = res.substring(5); - } - int index = res.indexOf("!"); - if (index >= 0) { - res = res.substring(0, index); - } - log.debug("getCurrentJarFilePath path:{} index:{} url:{}", path, index, res); - return res; - } - - public static boolean isWindows() { - String osName = System.getProperty("os.name", "unknown"); - return osName.toLowerCase().indexOf("windows") != -1; - } - - public static void trySleep(long millis) { - try { - Thread.sleep(millis); - } catch (Exception e) { - // ignore - } - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/ThreadUtil.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/ThreadUtil.java deleted file mode 100644 index a6546907..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/ThreadUtil.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.util; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -public class ThreadUtil { - - /** - * 执行一个线程 - * @param runnable - */ - public static void run(Runnable runnable) { - new Thread(runnable).start(); - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/TypeUtil.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/TypeUtil.java deleted file mode 100644 index c4639ea6..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/util/TypeUtil.java +++ /dev/null @@ -1,599 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.util; - -import com.google.common.collect.Lists; -import fun.asgc.neutrino.core.type.TypeMatchInfo; -import fun.asgc.neutrino.core.type.TypeMatchers; - -import java.lang.reflect.Field; -import java.util.*; -import java.util.stream.Collectors; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -public class TypeUtil { - - /** - * 严格意义上的基本数据类型 - */ - private static final Set> strictBasicType = new HashSet>() { - { - this.add(byte.class); - this.add(short.class); - this.add(int.class); - this.add(long.class); - this.add(float.class); - this.add(double.class); - this.add(char.class); - this.add(boolean.class); - } - }; - - /** - * 一般意义上的基本数据类型 - */ - private static final Set> normalBasicType = new HashSet>() { - { - this.addAll(strictBasicType); - - this.add(Byte.class); - this.add(Short.class); - this.add(Integer.class); - this.add(Long.class); - this.add(Float.class); - this.add(Double.class); - this.add(Character.class); - this.add(Boolean.class); - this.add(String.class); - } - }; - /** - * 基本类型的映射 - */ - private static final Map, Class> basicTypeMap = new HashMap, Class>() { - { - this.put(byte.class, byte.class); - this.put(short.class, short.class); - this.put(int.class, int.class); - this.put(long.class, long.class); - this.put(float.class, float.class); - this.put(double.class, double.class); - this.put(char.class, char.class); - this.put(boolean.class, boolean.class); - - this.put(Byte.class, byte.class); - this.put(Short.class, short.class); - this.put(Integer.class, int.class); - this.put(Long.class, long.class); - this.put(Float.class, float.class); - this.put(Double.class, double.class); - this.put(Character.class, char.class); - this.put(Boolean.class, boolean.class); - } - }; - - /** - * 包装类型的映射 - */ - private static final Map, Class> wrapTypeMap = new HashMap, Class>() { - { - this.put(byte.class, Byte.class); - this.put(short.class, Short.class); - this.put(int.class, Integer.class); - this.put(long.class, Long.class); - this.put(float.class, Float.class); - this.put(double.class, Double.class); - this.put(char.class, Character.class); - this.put(boolean.class, Boolean.class); - - this.put(Byte.class, Byte.class); - this.put(Short.class, Short.class); - this.put(Integer.class, Integer.class); - this.put(Long.class, Long.class); - this.put(Float.class, Float.class); - this.put(Double.class, Double.class); - this.put(Character.class, Character.class); - this.put(Boolean.class, Boolean.class); - - this.put(String.class, String.class); - } - }; - /** - * 基本类型列表(用于计算类型提升距离) - */ - public static final List> basicTypeList = Lists.newArrayList( - boolean.class, Boolean.class, byte.class, Byte.class, short.class, Short.class, char.class, Character.class, - int.class, Integer.class, long.class, Long.class, float.class, Float.class, double.class, Double.class - ); - - /** - * 默认值 - */ - private static final Map, Object> defaultValueMap = new HashMap, Object>() { - { - this.put(byte.class, 0); - this.put(short.class, 0); - this.put(int.class, 0); - this.put(long.class, 0); - this.put(float.class, 0); - this.put(double.class, 0); - this.put(char.class, 0); - this.put(boolean.class, false); - } - }; - - /** - * 默认的类型匹配器 - */ - private static final TypeMatchers defaultTypeMatchers = new TypeMatchers(); - - /** - * 获取字段类型 - * @param field - * @return - */ - public static Class getFieldType(Field field) { - return field.getType(); - } - - /** - * 字段类型匹配 - * @param field - * @param clazz - * @return - */ - public static boolean fieldTypeMatch(Field field, Class clazz) { - return getFieldType(field) == clazz; - } - - /** - * 是否是严格基本类型 - * @param clazz - * @return - */ - public static boolean isStrictBasicType(Class clazz) { - return strictBasicType.contains(clazz); - } - - /** - * 是否是严格基本类型 - * @param field - * @return - */ - public static boolean isStrictBasicType(Field field) { - return isStrictBasicType(getFieldType(field)); - } - - /** - * 是否是一般基本类型 - * @param clazz - * @return - */ - public static boolean isNormalBasicType(Class clazz) { - return normalBasicType.contains(clazz); - } - - /** - * 是否是数字 - * @param clazz - * @return - */ - public static boolean isNumber(Class clazz) { - return Number.class.isAssignableFrom(clazz); - } - - /** - * 是否是一般基本类型 - * @param field - * @return - */ - public static boolean isNormalBasicType(Field field) { - return isNormalBasicType(getFieldType(field)); - } - - /** - * 是否是包装类型 - * @param clazz - * @return - */ - public static boolean isWrapType(Class clazz) { - return !isStrictBasicType(clazz); - } - - /** - * 是否是包装类型 - * @param field - * @return - */ - public static boolean isWrapType(Field field) { - return !isStrictBasicType(field); - } - - /** - * 是否是byte类型 - * @param field - * @return - */ - public static boolean isByte(Field field) { - return isByte(getFieldType(field)); - } - - /** - * 是否是byte类型 - * @param clazz - * @return - */ - public static boolean isByte(Class clazz) { - return clazz == byte.class || clazz == Byte.class; - } - - /** - * 是否是short类型 - * @param field - * @return - */ - public static boolean isShort(Field field) { - return isShort(getFieldType(field)); - } - - /** - * 是否是short类型 - * @param clazz - * @return - */ - public static boolean isShort(Class clazz) { - return clazz == short.class || clazz == Short.class; - } - - /** - * 是否是integer类型 - * @param field - * @return - */ - public static boolean isInteger(Field field) { - return isInteger(getFieldType(field)); - } - - /** - * 是否是integer类型 - * @param clazz - * @return - */ - public static boolean isInteger(Class clazz) { - return clazz == int.class || clazz == Integer.class; - } - - /** - * 是否是long类型 - * @param field - * @return - */ - public static boolean isLong(Field field) { - return isLong(getFieldType(field)); - } - - /** - * 是否是long类型 - * @param clazz - * @return - */ - public static boolean isLong(Class clazz) { - return clazz == long.class || clazz == Long.class; - } - - /** - * 是否是float类型 - * @param field - * @return - */ - public static boolean isFloat(Field field) { - return isFloat(getFieldType(field)); - } - - /** - * 是否是float类型 - * @param clazz - * @return - */ - public static boolean isFloat(Class clazz) { - return clazz == float.class || clazz == Float.class; - } - - /** - * 是否是double类型 - * @param field - * @return - */ - public static boolean isDouble(Field field) { - return isDouble(getFieldType(field)); - } - - /** - * 是否是double类型 - * @param clazz - * @return - */ - public static boolean isDouble(Class clazz) { - return clazz == double.class || clazz == Double.class; - } - - /** - * 是否是char类型 - * @param field - * @return - */ - public static boolean isChar(Field field) { - Class clazz = getFieldType(field); - return clazz == char.class || clazz == Character.class; - } - - /** - * 是否是boolean类型 - * @param field - * @return - */ - public static boolean isBoolean(Field field) { - Class clazz = getFieldType(field); - return clazz == boolean.class || clazz == Boolean.class; - } - - /** - * 是否是String类型 - * @param field - * @return - */ - public static boolean isString(Field field) { - return isString(getFieldType(field)); - } - - /** - * 是否是String类型 - * @param clazz - * @return - */ - public static boolean isString(Class clazz) { - return clazz == String.class; - } - - /** - * 是否是日期类型 - * @param field - * @return - */ - public static boolean isDate(Field field) { - return isDate(getFieldType(field)); - } - - /** - * 是否是日期类型 - * @param clazz - * @return - */ - public static boolean isDate(Class clazz) { - return clazz == java.util.Date.class || clazz == java.sql.Date.class; - } - - /** - * 是否是布尔值 - * @param clazz - * @return - */ - public static boolean isBoolean(Class clazz) { - return clazz == boolean.class || clazz == Boolean.class; - } - - /** - * 是否是字符 - * @param clazz - * @return - */ - public static boolean isChar(Class clazz) { - return clazz == char.class || clazz == Character.class; - } - - /** - * 是否是map类型 - * @param clazz - * @return - */ - public static boolean isMap(Class clazz) { - return Map.class.isAssignableFrom(clazz); - } - - /** - * 获取包装类型 - * @param clazz - * @return - */ - public static Class getWrapType(Class clazz) { - if (isStrictBasicType(clazz)) { - return wrapTypeMap.get(clazz); - } - return clazz; - } - - /** - * 获取包装类型 - * @param field - * @return - */ - public static Class getWrapType(Field field) { - return getWrapType(getFieldType(field)); - } - - /** - * 是否是超类 - * @param superClass - * @param childClass - * @return - */ - public static boolean isSupper(Class superClass, Class childClass) { - return superClass.isAssignableFrom(childClass); - } - - /** - * 获取简单类名 - * @param clazz - * @return - */ - public static String getSimpleName(Class clazz) { - return clazz.getSimpleName(); - } - - /** - * 获取包名 - * @param clazz - * @return - */ - public static String getPackageName(Class clazz) { - return clazz.getPackage().getName(); - } - - /** - * 获取默认变量名 - * @param clazz - * @return - */ - public static String getDefaultVariableName(Class clazz) { - String name = getSimpleName(clazz); - return name.substring(0, 1).toLowerCase() + name.substring(1); - } - - /** - * 获取默认值 - * @param clazz - * @return - */ - public static Object getDefaultValue(Class clazz) { - return defaultValueMap.get(clazz); - } - - /** - * 是否是集合类型 - * @param clazz - * @return - */ - public static boolean isCollection(Class clazz) { - return Collection.class.isAssignableFrom(clazz); - } - - /** - * 是否可列举 - * @param clazz - * @return - */ - public static boolean isListable(Class clazz) { - return clazz.isArray() || isCollection(clazz); - } - - /** - * 是否是list - * @param clazz - * @return - */ - public static boolean isList(Class clazz) { - return List.class.isAssignableFrom(clazz); - } - - /** - * list转成其他形式 - * @param list - * @param targetType - * @return - */ - public static Object listTo(List list, Class targetType) { - if (null == list) { - return null; - } - if (isList(targetType)) { - return list; - } - // 数组 - if (targetType.isArray()) { - return list.toArray(); - } - // set - if (Set.class.isAssignableFrom(targetType)) { - return list.stream().collect(Collectors.toSet()); - } - return null; - } - - /** - * 获取继承层级 - * 此处假定继承层级最多为100层,避免计算太过耗时 - * @param superClass - * @param childClass - * @return - */ - public static int getInheritLevel(Class superClass, Class childClass) { - if (!isSupper(superClass, childClass)) { - return -1; - } - List, Integer>> list = new LinkedList<>(); - list.add(Pair.of(childClass, 0)); - while (CollectionUtil.notEmpty(list) && list.get(0).getFirst() != superClass && list.get(0).getSecond() < 100) { - Pair, Integer> current = list.remove(0); - Class clazz = current.getFirst(); - int level = current.getSecond(); - if (null != clazz.getSuperclass()) { - list.add(Pair.of(clazz.getSuperclass(), level + 1)); - } - if (null != clazz.getInterfaces() && clazz.getInterfaces().length > 0) { - for (Class inter : clazz.getInterfaces()) { - list.add(Pair.of(inter, level + 1)); - } - } - } - if (list.isEmpty()) { - return 100; - } - return Math.min(list.get(0).getSecond(), 100); - } - - /** - * 计算一个类型的值是否可以赋值给指定类型的匹配信息 - * @param fieldType - * @param valueType - * @return - */ - public static TypeMatchInfo typeMatch(Class fieldType, Class valueType) { - Assert.notNull(fieldType, "字段类型不能为空!"); - Assert.notNull(valueType, "值类型不能为空!"); - return new TypeMatchInfo(fieldType, valueType, null); - } - - /** - * 类型转换 - * @param value - * @param targetType - * @return - */ - public static T conversion(Object value, Class targetType) { - return (T)defaultTypeMatchers.conversion(value, targetType); - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/AntPathMatcher.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/AntPathMatcher.java deleted file mode 100644 index b57ccc8d..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/AntPathMatcher.java +++ /dev/null @@ -1,874 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web; - -import fun.asgc.neutrino.core.util.Assert; -import fun.asgc.neutrino.core.util.StringUtil; - -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/27 - */ -public class AntPathMatcher implements PathMatcher { - - /** Default path separator: "/" */ - public static final String DEFAULT_PATH_SEPARATOR = "/"; - - private static final int CACHE_TURNOFF_THRESHOLD = 65536; - - private static final Pattern VARIABLE_PATTERN = Pattern.compile("\\{[^/]+?\\}"); - - private static final char[] WILDCARD_CHARS = { '*', '?', '{' }; - - - private String pathSeparator; - - private PathSeparatorPatternCache pathSeparatorPatternCache; - - private boolean caseSensitive = true; - - private boolean trimTokens = false; - - private volatile Boolean cachePatterns; - - private final Map tokenizedPatternCache = new ConcurrentHashMap(256); - - final Map stringMatcherCache = new ConcurrentHashMap(256); - - - /** - * Create a new instance with the {@link #DEFAULT_PATH_SEPARATOR}. - */ - public AntPathMatcher() { - this.pathSeparator = DEFAULT_PATH_SEPARATOR; - this.pathSeparatorPatternCache = new PathSeparatorPatternCache(DEFAULT_PATH_SEPARATOR); - } - - /** - * A convenient, alternative constructor to use with a custom path separator. - * @param pathSeparator the path separator to use, must not be {@code null}. - * @since 4.1 - */ - public AntPathMatcher(String pathSeparator) { - Assert.notNull(pathSeparator, "'pathSeparator' is required"); - this.pathSeparator = pathSeparator; - this.pathSeparatorPatternCache = new PathSeparatorPatternCache(pathSeparator); - } - - - /** - * Set the path separator to use for pattern parsing. - *

Default is "/", as in Ant. - */ - public void setPathSeparator(String pathSeparator) { - this.pathSeparator = (pathSeparator != null ? pathSeparator : DEFAULT_PATH_SEPARATOR); - this.pathSeparatorPatternCache = new PathSeparatorPatternCache(this.pathSeparator); - } - - /** - * Specify whether to perform pattern matching in a case-sensitive fashion. - *

Default is {@code true}. Switch this to {@code false} for case-insensitive matching. - * @since 4.2 - */ - public void setCaseSensitive(boolean caseSensitive) { - this.caseSensitive = caseSensitive; - } - - /** - * Specify whether to trim tokenized paths and patterns. - *

Default is {@code false}. - */ - public void setTrimTokens(boolean trimTokens) { - this.trimTokens = trimTokens; - } - - /** - * Specify whether to cache parsed pattern metadata for patterns passed - * into this matcher's {@link #match} method. A value of {@code true} - * activates an unlimited pattern cache; a value of {@code false} turns - * the pattern cache off completely. - *

Default is for the cache to be on, but with the variant to automatically - * turn it off when encountering too many patterns to cache at runtime - * (the threshold is 65536), assuming that arbitrary permutations of patterns - * are coming in, with little chance for encountering a recurring pattern. - * @since 4.0.1 - * @see #getStringMatcher(String) - */ - public void setCachePatterns(boolean cachePatterns) { - this.cachePatterns = cachePatterns; - } - - private void deactivatePatternCache() { - this.cachePatterns = false; - this.tokenizedPatternCache.clear(); - this.stringMatcherCache.clear(); - } - - - @Override - public boolean isPattern(String path) { - return (path.indexOf('*') != -1 || path.indexOf('?') != -1); - } - - @Override - public boolean match(String pattern, String path) { - return doMatch(pattern, path, true, null); - } - - @Override - public boolean matchStart(String pattern, String path) { - return doMatch(pattern, path, false, null); - } - - /** - * Actually match the given {@code path} against the given {@code pattern}. - * @param pattern the pattern to match against - * @param path the path String to test - * @param fullMatch whether a full pattern match is required (else a pattern match - * as far as the given base path goes is sufficient) - * @return {@code true} if the supplied {@code path} matched, {@code false} if it didn't - */ - protected boolean doMatch(String pattern, String path, boolean fullMatch, Map uriTemplateVariables) { - if (path.startsWith(this.pathSeparator) != pattern.startsWith(this.pathSeparator)) { - return false; - } - - String[] pattDirs = tokenizePattern(pattern); - if (fullMatch && this.caseSensitive && !isPotentialMatch(path, pattDirs)) { - return false; - } - - String[] pathDirs = tokenizePath(path); - - int pattIdxStart = 0; - int pattIdxEnd = pattDirs.length - 1; - int pathIdxStart = 0; - int pathIdxEnd = pathDirs.length - 1; - - // Match all elements up to the first ** - while (pattIdxStart <= pattIdxEnd && pathIdxStart <= pathIdxEnd) { - String pattDir = pattDirs[pattIdxStart]; - if ("**".equals(pattDir)) { - break; - } - if (!matchStrings(pattDir, pathDirs[pathIdxStart], uriTemplateVariables)) { - return false; - } - pattIdxStart++; - pathIdxStart++; - } - - if (pathIdxStart > pathIdxEnd) { - // Path is exhausted, only match if rest of pattern is * or **'s - if (pattIdxStart > pattIdxEnd) { - return (pattern.endsWith(this.pathSeparator) == path.endsWith(this.pathSeparator)); - } - if (!fullMatch) { - return true; - } - if (pattIdxStart == pattIdxEnd && pattDirs[pattIdxStart].equals("*") && path.endsWith(this.pathSeparator)) { - return true; - } - for (int i = pattIdxStart; i <= pattIdxEnd; i++) { - if (!pattDirs[i].equals("**")) { - return false; - } - } - return true; - } - else if (pattIdxStart > pattIdxEnd) { - // String not exhausted, but pattern is. Failure. - return false; - } - else if (!fullMatch && "**".equals(pattDirs[pattIdxStart])) { - // Path start definitely matches due to "**" part in pattern. - return true; - } - - // up to last '**' - while (pattIdxStart <= pattIdxEnd && pathIdxStart <= pathIdxEnd) { - String pattDir = pattDirs[pattIdxEnd]; - if (pattDir.equals("**")) { - break; - } - if (!matchStrings(pattDir, pathDirs[pathIdxEnd], uriTemplateVariables)) { - return false; - } - pattIdxEnd--; - pathIdxEnd--; - } - if (pathIdxStart > pathIdxEnd) { - // String is exhausted - for (int i = pattIdxStart; i <= pattIdxEnd; i++) { - if (!pattDirs[i].equals("**")) { - return false; - } - } - return true; - } - - while (pattIdxStart != pattIdxEnd && pathIdxStart <= pathIdxEnd) { - int patIdxTmp = -1; - for (int i = pattIdxStart + 1; i <= pattIdxEnd; i++) { - if (pattDirs[i].equals("**")) { - patIdxTmp = i; - break; - } - } - if (patIdxTmp == pattIdxStart + 1) { - // '**/**' situation, so skip one - pattIdxStart++; - continue; - } - // Find the pattern between padIdxStart & padIdxTmp in str between - // strIdxStart & strIdxEnd - int patLength = (patIdxTmp - pattIdxStart - 1); - int strLength = (pathIdxEnd - pathIdxStart + 1); - int foundIdx = -1; - - strLoop: - for (int i = 0; i <= strLength - patLength; i++) { - for (int j = 0; j < patLength; j++) { - String subPat = pattDirs[pattIdxStart + j + 1]; - String subStr = pathDirs[pathIdxStart + i + j]; - if (!matchStrings(subPat, subStr, uriTemplateVariables)) { - continue strLoop; - } - } - foundIdx = pathIdxStart + i; - break; - } - - if (foundIdx == -1) { - return false; - } - - pattIdxStart = patIdxTmp; - pathIdxStart = foundIdx + patLength; - } - - for (int i = pattIdxStart; i <= pattIdxEnd; i++) { - if (!pattDirs[i].equals("**")) { - return false; - } - } - - return true; - } - - private boolean isPotentialMatch(String path, String[] pattDirs) { - if (!this.trimTokens) { - int pos = 0; - for (String pattDir : pattDirs) { - int skipped = skipSeparator(path, pos, this.pathSeparator); - pos += skipped; - skipped = skipSegment(path, pos, pattDir); - if (skipped < pattDir.length()) { - return (skipped > 0 || (pattDir.length() > 0 && isWildcardChar(pattDir.charAt(0)))); - } - pos += skipped; - } - } - return true; - } - - private int skipSegment(String path, int pos, String prefix) { - int skipped = 0; - for (int i = 0; i < prefix.length(); i++) { - char c = prefix.charAt(i); - if (isWildcardChar(c)) { - return skipped; - } - int currPos = pos + skipped; - if (currPos >= path.length()) { - return 0; - } - if (c == path.charAt(currPos)) { - skipped++; - } - } - return skipped; - } - - private int skipSeparator(String path, int pos, String separator) { - int skipped = 0; - while (path.startsWith(separator, pos + skipped)) { - skipped += separator.length(); - } - return skipped; - } - - private boolean isWildcardChar(char c) { - for (char candidate : WILDCARD_CHARS) { - if (c == candidate) { - return true; - } - } - return false; - } - - /** - * Tokenize the given path pattern into parts, based on this matcher's settings. - *

Performs caching based on {@link #setCachePatterns}, delegating to - * {@link #tokenizePath(String)} for the actual tokenization algorithm. - * @param pattern the pattern to tokenize - * @return the tokenized pattern parts - */ - protected String[] tokenizePattern(String pattern) { - String[] tokenized = null; - Boolean cachePatterns = this.cachePatterns; - if (cachePatterns == null || cachePatterns.booleanValue()) { - tokenized = this.tokenizedPatternCache.get(pattern); - } - if (tokenized == null) { - tokenized = tokenizePath(pattern); - if (cachePatterns == null && this.tokenizedPatternCache.size() >= CACHE_TURNOFF_THRESHOLD) { - // Try to adapt to the runtime situation that we're encountering: - // There are obviously too many different patterns coming in here... - // So let's turn off the cache since the patterns are unlikely to be reoccurring. - deactivatePatternCache(); - return tokenized; - } - if (cachePatterns == null || cachePatterns.booleanValue()) { - this.tokenizedPatternCache.put(pattern, tokenized); - } - } - return tokenized; - } - - /** - * Tokenize the given path String into parts, based on this matcher's settings. - * @param path the path to tokenize - * @return the tokenized path parts - */ - protected String[] tokenizePath(String path) { - return StringUtil.tokenizeToStringArray(path, this.pathSeparator, this.trimTokens, true); - } - - /** - * Test whether or not a string matches against a pattern. - * @param pattern the pattern to match against (never {@code null}) - * @param str the String which must be matched against the pattern (never {@code null}) - * @return {@code true} if the string matches against the pattern, or {@code false} otherwise - */ - private boolean matchStrings(String pattern, String str, Map uriTemplateVariables) { - return getStringMatcher(pattern).matchStrings(str, uriTemplateVariables); - } - - /** - * Build or retrieve an {@link AntPathStringMatcher} for the given pattern. - *

The default implementation checks this AntPathMatcher's internal cache - * (see {@link #setCachePatterns}), creating a new AntPathStringMatcher instance - * if no cached copy is found. - *

When encountering too many patterns to cache at runtime (the threshold is 65536), - * it turns the default cache off, assuming that arbitrary permutations of patterns - * are coming in, with little chance for encountering a recurring pattern. - *

This method may be overridden to implement a custom cache strategy. - * @param pattern the pattern to match against (never {@code null}) - * @return a corresponding AntPathStringMatcher (never {@code null}) - * @see #setCachePatterns - */ - protected AntPathStringMatcher getStringMatcher(String pattern) { - AntPathStringMatcher matcher = null; - Boolean cachePatterns = this.cachePatterns; - if (cachePatterns == null || cachePatterns.booleanValue()) { - matcher = this.stringMatcherCache.get(pattern); - } - if (matcher == null) { - matcher = new AntPathStringMatcher(pattern, this.caseSensitive); - if (cachePatterns == null && this.stringMatcherCache.size() >= CACHE_TURNOFF_THRESHOLD) { - // Try to adapt to the runtime situation that we're encountering: - // There are obviously too many different patterns coming in here... - // So let's turn off the cache since the patterns are unlikely to be reoccurring. - deactivatePatternCache(); - return matcher; - } - if (cachePatterns == null || cachePatterns.booleanValue()) { - this.stringMatcherCache.put(pattern, matcher); - } - } - return matcher; - } - - /** - * Given a pattern and a full path, determine the pattern-mapped part.

For example:

- *

Assumes that {@link #match} returns {@code true} for '{@code pattern}' and '{@code path}', but - * does not enforce this. - */ - @Override - public String extractPathWithinPattern(String pattern, String path) { - String[] patternParts = StringUtil.tokenizeToStringArray(pattern, this.pathSeparator, this.trimTokens, true); - String[] pathParts = StringUtil.tokenizeToStringArray(path, this.pathSeparator, this.trimTokens, true); - StringBuilder builder = new StringBuilder(); - boolean pathStarted = false; - - for (int segment = 0; segment < patternParts.length; segment++) { - String patternPart = patternParts[segment]; - if (patternPart.indexOf('*') > -1 || patternPart.indexOf('?') > -1) { - for (; segment < pathParts.length; segment++) { - if (pathStarted || (segment == 0 && !pattern.startsWith(this.pathSeparator))) { - builder.append(this.pathSeparator); - } - builder.append(pathParts[segment]); - pathStarted = true; - } - } - } - - return builder.toString(); - } - - @Override - public Map extractUriTemplateVariables(String pattern, String path) { - Map variables = new LinkedHashMap(); - boolean result = doMatch(pattern, path, true, variables); - if (!result) { - throw new IllegalStateException("Pattern \"" + pattern + "\" is not a match for \"" + path + "\""); - } - return variables; - } - - /** - * Combine two patterns into a new pattern. - *

This implementation simply concatenates the two patterns, unless - * the first pattern contains a file extension match (e.g., {@code *.html}). - * In that case, the second pattern will be merged into the first. Otherwise, - * an {@code IllegalArgumentException} will be thrown. - *

Examples

- * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Pattern 1Pattern 2Result
{@code null}{@code null} 
/hotels{@code null}/hotels
{@code null}/hotels/hotels
/hotels/bookings/hotels/bookings
/hotelsbookings/hotels/bookings
/hotels/*/bookings/hotels/bookings
/hotels/**/bookings/hotels/**/bookings
/hotels{hotel}/hotels/{hotel}
/hotels/*{hotel}/hotels/{hotel}
/hotels/**{hotel}/hotels/**/{hotel}
/*.html/hotels.html/hotels.html
/*.html/hotels/hotels.html
/*.html/*.txt{@code IllegalArgumentException}
- * @param pattern1 the first pattern - * @param pattern2 the second pattern - * @return the combination of the two patterns - * @throws IllegalArgumentException if the two patterns cannot be combined - */ - @Override - public String combine(String pattern1, String pattern2) { - if (!StringUtil.hasText(pattern1) && !StringUtil.hasText(pattern2)) { - return ""; - } - if (!StringUtil.hasText(pattern1)) { - return pattern2; - } - if (!StringUtil.hasText(pattern2)) { - return pattern1; - } - - boolean pattern1ContainsUriVar = (pattern1.indexOf('{') != -1); - if (!pattern1.equals(pattern2) && !pattern1ContainsUriVar && match(pattern1, pattern2)) { - // /* + /hotel -> /hotel ; "/*.*" + "/*.html" -> /*.html - // However /user + /user -> /usr/user ; /{foo} + /bar -> /{foo}/bar - return pattern2; - } - - // /hotels/* + /booking -> /hotels/booking - // /hotels/* + booking -> /hotels/booking - if (pattern1.endsWith(this.pathSeparatorPatternCache.getEndsOnWildCard())) { - return concat(pattern1.substring(0, pattern1.length() - 2), pattern2); - } - - // /hotels/** + /booking -> /hotels/**/booking - // /hotels/** + booking -> /hotels/**/booking - if (pattern1.endsWith(this.pathSeparatorPatternCache.getEndsOnDoubleWildCard())) { - return concat(pattern1, pattern2); - } - - int starDotPos1 = pattern1.indexOf("*."); - if (pattern1ContainsUriVar || starDotPos1 == -1 || this.pathSeparator.equals(".")) { - // simply concatenate the two patterns - return concat(pattern1, pattern2); - } - - String ext1 = pattern1.substring(starDotPos1 + 1); - int dotPos2 = pattern2.indexOf('.'); - String file2 = (dotPos2 == -1 ? pattern2 : pattern2.substring(0, dotPos2)); - String ext2 = (dotPos2 == -1 ? "" : pattern2.substring(dotPos2)); - boolean ext1All = (ext1.equals(".*") || ext1.equals("")); - boolean ext2All = (ext2.equals(".*") || ext2.equals("")); - if (!ext1All && !ext2All) { - throw new IllegalArgumentException("Cannot combine patterns: " + pattern1 + " vs " + pattern2); - } - String ext = (ext1All ? ext2 : ext1); - return file2 + ext; - } - - private String concat(String path1, String path2) { - boolean path1EndsWithSeparator = path1.endsWith(this.pathSeparator); - boolean path2StartsWithSeparator = path2.startsWith(this.pathSeparator); - - if (path1EndsWithSeparator && path2StartsWithSeparator) { - return path1 + path2.substring(1); - } - else if (path1EndsWithSeparator || path2StartsWithSeparator) { - return path1 + path2; - } - else { - return path1 + this.pathSeparator + path2; - } - } - - /** - * Given a full path, returns a {@link Comparator} suitable for sorting patterns in order of - * explicitness. - *

This{@code Comparator} will {@linkplain java.util.Collections#sort(List, Comparator) sort} - * a list so that more specific patterns (without uri templates or wild cards) come before - * generic patterns. So given a list with the following patterns: - *

    - *
  1. {@code /hotels/new}
  2. - *
  3. {@code /hotels/{hotel}}
  4. {@code /hotels/*}
  5. - *
- * the returned comparator will sort this list so that the order will be as indicated. - *

The full path given as parameter is used to test for exact matches. So when the given path - * is {@code /hotels/2}, the pattern {@code /hotels/2} will be sorted before {@code /hotels/1}. - * @param path the full path to use for comparison - * @return a comparator capable of sorting patterns in order of explicitness - */ - @Override - public Comparator getPatternComparator(String path) { - return new AntPatternComparator(path); - } - - - /** - * Tests whether or not a string matches against a pattern via a {@link Pattern}. - *

The pattern may contain special characters: '*' means zero or more characters; '?' means one and - * only one character; '{' and '}' indicate a URI template pattern. For example /users/{user}. - */ - protected static class AntPathStringMatcher { - - private static final Pattern GLOB_PATTERN = Pattern.compile("\\?|\\*|\\{((?:\\{[^/]+?\\}|[^/{}]|\\\\[{}])+?)\\}"); - - private static final String DEFAULT_VARIABLE_PATTERN = "(.*)"; - - private final Pattern pattern; - - private final List variableNames = new LinkedList(); - - public AntPathStringMatcher(String pattern) { - this(pattern, true); - } - - public AntPathStringMatcher(String pattern, boolean caseSensitive) { - StringBuilder patternBuilder = new StringBuilder(); - Matcher matcher = GLOB_PATTERN.matcher(pattern); - int end = 0; - while (matcher.find()) { - patternBuilder.append(quote(pattern, end, matcher.start())); - String match = matcher.group(); - if ("?".equals(match)) { - patternBuilder.append('.'); - } - else if ("*".equals(match)) { - patternBuilder.append(".*"); - } - else if (match.startsWith("{") && match.endsWith("}")) { - int colonIdx = match.indexOf(':'); - if (colonIdx == -1) { - patternBuilder.append(DEFAULT_VARIABLE_PATTERN); - this.variableNames.add(matcher.group(1)); - } - else { - String variablePattern = match.substring(colonIdx + 1, match.length() - 1); - patternBuilder.append('('); - patternBuilder.append(variablePattern); - patternBuilder.append(')'); - String variableName = match.substring(1, colonIdx); - this.variableNames.add(variableName); - } - } - end = matcher.end(); - } - patternBuilder.append(quote(pattern, end, pattern.length())); - this.pattern = (caseSensitive ? Pattern.compile(patternBuilder.toString()) : - Pattern.compile(patternBuilder.toString(), Pattern.CASE_INSENSITIVE)); - } - - private String quote(String s, int start, int end) { - if (start == end) { - return ""; - } - return Pattern.quote(s.substring(start, end)); - } - - /** - * Main entry point. - * @return {@code true} if the string matches against the pattern, or {@code false} otherwise. - */ - public boolean matchStrings(String str, Map uriTemplateVariables) { - Matcher matcher = this.pattern.matcher(str); - if (matcher.matches()) { - if (uriTemplateVariables != null) { - // SPR-8455 - if (this.variableNames.size() != matcher.groupCount()) { - throw new IllegalArgumentException("The number of capturing groups in the pattern segment " + - this.pattern + " does not match the number of URI template variables it defines, " + - "which can occur if capturing groups are used in a URI template regex. " + - "Use non-capturing groups instead."); - } - for (int i = 1; i <= matcher.groupCount(); i++) { - String name = this.variableNames.get(i - 1); - String value = matcher.group(i); - uriTemplateVariables.put(name, value); - } - } - return true; - } - else { - return false; - } - } - } - - - /** - * The default {@link Comparator} implementation returned by - * {@link #getPatternComparator(String)}. - *

In order, the most "generic" pattern is determined by the following: - *

    - *
  • if it's null or a capture all pattern (i.e. it is equal to "/**")
  • - *
  • if the other pattern is an actual match
  • - *
  • if it's a catch-all pattern (i.e. it ends with "**"
  • - *
  • if it's got more "*" than the other pattern
  • - *
  • if it's got more "{foo}" than the other pattern
  • - *
  • if it's shorter than the other pattern
  • - *
- */ - protected static class AntPatternComparator implements Comparator { - - private final String path; - - public AntPatternComparator(String path) { - this.path = path; - } - - /** - * Compare two patterns to determine which should match first, i.e. which - * is the most specific regarding the current path. - * @return a negative integer, zero, or a positive integer as pattern1 is - * more specific, equally specific, or less specific than pattern2. - */ - @Override - public int compare(String pattern1, String pattern2) { - PatternInfo info1 = new PatternInfo(pattern1); - PatternInfo info2 = new PatternInfo(pattern2); - - if (info1.isLeastSpecific() && info2.isLeastSpecific()) { - return 0; - } - else if (info1.isLeastSpecific()) { - return 1; - } - else if (info2.isLeastSpecific()) { - return -1; - } - - boolean pattern1EqualsPath = pattern1.equals(path); - boolean pattern2EqualsPath = pattern2.equals(path); - if (pattern1EqualsPath && pattern2EqualsPath) { - return 0; - } - else if (pattern1EqualsPath) { - return -1; - } - else if (pattern2EqualsPath) { - return 1; - } - - if (info1.isPrefixPattern() && info2.getDoubleWildcards() == 0) { - return 1; - } - else if (info2.isPrefixPattern() && info1.getDoubleWildcards() == 0) { - return -1; - } - - if (info1.getTotalCount() != info2.getTotalCount()) { - return info1.getTotalCount() - info2.getTotalCount(); - } - - if (info1.getLength() != info2.getLength()) { - return info2.getLength() - info1.getLength(); - } - - if (info1.getSingleWildcards() < info2.getSingleWildcards()) { - return -1; - } - else if (info2.getSingleWildcards() < info1.getSingleWildcards()) { - return 1; - } - - if (info1.getUriVars() < info2.getUriVars()) { - return -1; - } - else if (info2.getUriVars() < info1.getUriVars()) { - return 1; - } - - return 0; - } - - - /** - * Value class that holds information about the pattern, e.g. number of - * occurrences of "*", "**", and "{" pattern elements. - */ - private static class PatternInfo { - - private final String pattern; - - private int uriVars; - - private int singleWildcards; - - private int doubleWildcards; - - private boolean catchAllPattern; - - private boolean prefixPattern; - - private Integer length; - - public PatternInfo(String pattern) { - this.pattern = pattern; - if (this.pattern != null) { - initCounters(); - this.catchAllPattern = this.pattern.equals("/**"); - this.prefixPattern = !this.catchAllPattern && this.pattern.endsWith("/**"); - } - if (this.uriVars == 0) { - this.length = (this.pattern != null ? this.pattern.length() : 0); - } - } - - protected void initCounters() { - int pos = 0; - while (pos < this.pattern.length()) { - if (this.pattern.charAt(pos) == '{') { - this.uriVars++; - pos++; - } - else if (this.pattern.charAt(pos) == '*') { - if (pos + 1 < this.pattern.length() && this.pattern.charAt(pos + 1) == '*') { - this.doubleWildcards++; - pos += 2; - } - else if (pos > 0 && !this.pattern.substring(pos - 1).equals(".*")) { - this.singleWildcards++; - pos++; - } - else { - pos++; - } - } - else { - pos++; - } - } - } - - public int getUriVars() { - return this.uriVars; - } - - public int getSingleWildcards() { - return this.singleWildcards; - } - - public int getDoubleWildcards() { - return this.doubleWildcards; - } - - public boolean isLeastSpecific() { - return (this.pattern == null || this.catchAllPattern); - } - - public boolean isPrefixPattern() { - return this.prefixPattern; - } - - public int getTotalCount() { - return this.uriVars + this.singleWildcards + (2 * this.doubleWildcards); - } - - /** - * Returns the length of the given pattern, where template variables are considered to be 1 long. - */ - public int getLength() { - if (this.length == null) { - this.length = VARIABLE_PATTERN.matcher(this.pattern).replaceAll("#").length(); - } - return this.length; - } - } - } - - - /** - * A simple cache for patterns that depend on the configured path separator. - */ - private static class PathSeparatorPatternCache { - - private final String endsOnWildCard; - - private final String endsOnDoubleWildCard; - - public PathSeparatorPatternCache(String pathSeparator) { - this.endsOnWildCard = pathSeparator + "*"; - this.endsOnDoubleWildCard = pathSeparator + "**"; - } - - public String getEndsOnWildCard() { - return this.endsOnWildCard; - } - - public String getEndsOnDoubleWildCard() { - return this.endsOnDoubleWildCard; - } - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/HttpEntry.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/HttpEntry.java deleted file mode 100644 index 66ab2209..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/HttpEntry.java +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web; - -/** - * - * @author: aoshiguchen - * @date: 2022/5/28 - */ -public interface HttpEntry { - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/HttpMethod.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/HttpMethod.java deleted file mode 100644 index 8375dc0f..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/HttpMethod.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web; - -import fun.asgc.neutrino.core.util.StringUtil; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/15 - */ -public enum HttpMethod { - GET,POST,OPTIONS; - - public static HttpMethod of(String method) { - if (StringUtil.isEmpty(method)) { - return null; - } - return HttpMethod.valueOf(method.toUpperCase()); - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/HttpRequestHandler.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/HttpRequestHandler.java deleted file mode 100644 index 714e4aef..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/HttpRequestHandler.java +++ /dev/null @@ -1,336 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web; - -import com.alibaba.fastjson.JSONObject; -import fun.asgc.neutrino.core.annotation.Autowired; -import fun.asgc.neutrino.core.annotation.Component; -import fun.asgc.neutrino.core.annotation.NonIntercept; -import fun.asgc.neutrino.core.constant.MetaDataConstant; -import fun.asgc.neutrino.core.context.ApplicationConfig; -import fun.asgc.neutrino.core.util.*; -import fun.asgc.neutrino.core.web.annotation.RequestBody; -import fun.asgc.neutrino.core.web.annotation.RequestParam; -import fun.asgc.neutrino.core.web.context.HttpContextHolder; -import fun.asgc.neutrino.core.web.context.HttpRequestWrapper; -import fun.asgc.neutrino.core.web.context.HttpResponseWrapper; -import fun.asgc.neutrino.core.web.context.WebContextHolder; -import fun.asgc.neutrino.core.web.interceptor.*; -import fun.asgc.neutrino.core.web.router.DefaultHttpRouter; -import fun.asgc.neutrino.core.web.router.HttpRouteParam; -import fun.asgc.neutrino.core.web.router.HttpRouteResult; -import fun.asgc.neutrino.core.web.router.HttpRouterType; -import io.netty.buffer.Unpooled; -import io.netty.channel.ChannelHandlerContext; -import io.netty.handler.codec.http.FullHttpRequest; -import io.netty.handler.codec.http.HttpHeaderNames; -import io.netty.handler.codec.http.HttpResponseStatus; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.extern.slf4j.Slf4j; - -import java.io.ByteArrayOutputStream; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Parameter; -import java.util.*; -import java.util.zip.GZIPOutputStream; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/15 - */ -@Slf4j -@NonIntercept -@Component -public class HttpRequestHandler { - @Autowired - private ApplicationConfig applicationConfig; - @Autowired - private DefaultHttpRouter defaultHttpRouter; - private PathMatcher pathMatcher = new AntPathMatcher(); - /** - * 静态自愿缓存 - */ - private Map staticResourceCache = new ConcurrentReferenceHashMap<>(16, 0.75F, 1, ConcurrentReferenceHashMap.ReferenceType.WEAK); - - public void handle() { - ChannelHandlerContext context = HttpContextHolder.getChannelHandlerContext(); - HttpRequestWrapper requestParser = HttpContextHolder.getHttpRequestWrapper(); - HttpResponseWrapper responseWrapper = HttpContextHolder.getHttpResponseWrapper(); - log.info("HttpRequest method:{} url:{} query:{}", requestParser.getMethod().name(), requestParser.getUrl(), requestParser.getQueryParamMap()); - - try { - String routePath = requestParser.getRoutePath(); - HttpMethod httpMethod = HttpMethod.of(requestParser.getMethod().name()); - HttpContextHolder.setInterceptorList(getInterceptorsForPath(routePath)); - - if (httpMethod == HttpMethod.OPTIONS) { - postHandle(requestParser.getRoutePath(), null, null); - HttpServerUtil.sendResponse(HttpResponseStatus.OK); - return; - } - HttpRouteResult httpRouteResult = defaultHttpRouter.route(new HttpRouteParam().setMethod(httpMethod).setUrl(routePath)); - if (null == httpRouteResult) { - HttpServerUtil.send404Response(requestParser.getUrl()); - return; - } - - if (HttpRouterType.METHOD == httpRouteResult.getType()) { - if (!preHandle(httpRouteResult.getPageRoute(), httpRouteResult.getMethod())) { - postHandle(requestParser.getRoutePath(), httpRouteResult.getMethod(), null); - HttpServerUtil.sendResponse(HttpResponseStatus.UNAUTHORIZED); - return; - } - - Object invokeResult = invoke(httpRouteResult.getInstance(), httpRouteResult.getMethod()); - - if (null != WebContextHolder.getAdviceHandler()) { - invokeResult = WebContextHolder.getAdviceHandler().advice(requestParser, HttpContextHolder.getHttpResponseWrapper(), routePath, httpRouteResult.getMethod(), invokeResult); - } - - String res = String.valueOf(invokeResult); - if (null != invokeResult && !TypeUtil.isNormalBasicType(invokeResult.getClass())) { - res = JSONObject.toJSONString(invokeResult); - } - - postHandle(httpRouteResult.getPageRoute(), httpRouteResult.getMethod(), invokeResult); - - HttpResponseWrapper httpResponseWrapper = HttpContextHolder.getHttpResponseWrapper(); - httpResponseWrapper.setContent(Unpooled.wrappedBuffer(res.getBytes())); - httpResponseWrapper.headers().add(HttpHeaderNames.CONTENT_TYPE, "application/json;charset=UTF-8"); - httpResponseWrapper.writeAndFlush(); - return; - } else if(HttpRouterType.PAGE == httpRouteResult.getType()) { - // 静态页面无需前置拦截 -// if (!preHandle(httpRouteResult.getPageRoute(), null)) { -// return; -// } - - // 前端页面 - String mimeType = MimeType.getMimeType(MimeType.parseSuffix(httpRouteResult.getPageLocation())); - if (mimeType.startsWith("text/")) { - mimeType += ";charset=utf-8"; - } - - postHandle(httpRouteResult.getPageRoute(), null, null); - - HttpResponseWrapper httpResponseWrapper = HttpContextHolder.getHttpResponseWrapper(); - httpResponseWrapper.setContent(Unpooled.wrappedBuffer(getStaticResourceData(httpRouteResult.getPageLocation(), mimeType))); - httpResponseWrapper.headers().add(HttpHeaderNames.CONTENT_TYPE, mimeType); - httpResponseWrapper.headers().add(HttpHeaderNames.CONTENT_LANGUAGE, "zh-CN"); - httpResponseWrapper.headers().add(HttpHeaderNames.SERVER, MetaDataConstant.SERVER_VS); - httpResponseWrapper.headers().add(HttpHeaderNames.DATE, new Date()); - httpResponseWrapper.writeAndFlush(); - return; - } else { - HttpServerUtil.send404Response(requestParser.getUrl()); - return; - } - } catch (Throwable e) { - try { - log.error("请求处理异常:{}", requestParser.getUrl(), e); - postHandle(requestParser.getRoutePath(), null, null); - Object res = exceptionHandler(e); - if (null != res) { - HttpServerUtil.send200Response(res); - } - } catch (Exception e2) { - e2.printStackTrace(); - } - } finally { - release(); - } - } - - private byte[] getStaticResourceData(String pageLocation, String mimeType) { - DataWrapper dataWrapper = staticResourceCache.get(pageLocation); - if (null != dataWrapper) { - if (!StringUtil.isEmpty(dataWrapper.getContentEncoding())) { - HttpContextHolder.getHttpResponseWrapper().headers().add("Content-Encoding", dataWrapper.getContentEncoding()); - } - return dataWrapper.getData(); - } - byte[] res = FileUtil.readBytes(pageLocation); - if (null == res) { - res = new byte[0]; - staticResourceCache.put(pageLocation, new DataWrapper(res, null)); - return res; - } - staticResourceCache.put(pageLocation, new DataWrapper(res, null)); - if ((mimeType.startsWith("text/") || mimeType.endsWith("javascript")) && res.length > 2048) { - // 文本,且大于2kb才做gzip压缩 - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - try (GZIPOutputStream gZipOs = new GZIPOutputStream(baos)){ - gZipOs.write(res); - gZipOs.flush(); - gZipOs.finish(); - res = baos.toByteArray(); - staticResourceCache.put(pageLocation, new DataWrapper(res, "gzip")); - HttpContextHolder.getHttpResponseWrapper().headers().add("Content-Encoding", "gzip"); - } catch (Exception e) { - return null; - } - } - return res; - } - - private boolean preHandle(String route, Method targetMethod) throws Exception { - if (!CollectionUtil.isEmpty(HttpContextHolder.getInterceptorList())) { - for (HandlerInterceptor handlerInterceptor : HttpContextHolder.getInterceptorList()) { - if (!handlerInterceptor.preHandle(HttpContextHolder.getHttpRequestWrapper(), HttpContextHolder.getHttpResponseWrapper(), route, targetMethod)) { - return Boolean.FALSE; - } - } - } - return Boolean.TRUE; - } - - private void postHandle(String route, Method targetMethod, Object result) throws Exception { - if (!CollectionUtil.isEmpty(HttpContextHolder.getInterceptorList())) { - for (HandlerInterceptor handlerInterceptor : HttpContextHolder.getInterceptorList()) { - handlerInterceptor.postHandle(HttpContextHolder.getHttpRequestWrapper(), HttpContextHolder.getHttpResponseWrapper(), route, targetMethod, result); - } - } - } - - private void afterCompletion(String route, Method targetMethod) { - if (!CollectionUtil.isEmpty(HttpContextHolder.getInterceptorList())) { - for (HandlerInterceptor handlerInterceptor : HttpContextHolder.getInterceptorList()) { - handlerInterceptor.afterCompletion(HttpContextHolder.getHttpRequestWrapper(), HttpContextHolder.getHttpResponseWrapper(), route, targetMethod); - } - } - } - - private List getInterceptorsForPath(String lookupPath) { - List result = new ArrayList(); - InterceptorRegistry interceptorRegistry = WebContextHolder.getInterceptorRegistry(); - if (CollectionUtil.isEmpty(interceptorRegistry.getInterceptors())) { - return result; - } - for (Object interceptor : interceptorRegistry.getInterceptors()) { - if (interceptor instanceof HandlerInterceptor) { - result.add((HandlerInterceptor) interceptor); - } else if(interceptor instanceof MappedInterceptor) { - MappedInterceptor mappedInterceptor = (MappedInterceptor) interceptor; - if (mappedInterceptor.matches(lookupPath, pathMatcher)) { - result.add(mappedInterceptor.getInterceptor()); - } - } - } - return result; - } - - private Object exceptionHandler(Throwable e) { - if (e instanceof InvocationTargetException) { - e = ((InvocationTargetException)e).getTargetException(); - } - ExceptionHandlerRegistry exceptionHandlerRegistry = WebContextHolder.getExceptionHandlerRegistry(); - if (CollectionUtil.isEmpty(exceptionHandlerRegistry.getExceptionHandlerList())) { - log.error("Http处理异常", e); - HttpServerUtil.send500Response(e); - return null; - } - for (RestControllerExceptionHandler exceptionHandler : exceptionHandlerRegistry.getExceptionHandlerList()) { - if (exceptionHandler.support(e)) { - return exceptionHandler.handle(HttpContextHolder.getHttpRequestWrapper(), HttpContextHolder.getHttpResponseWrapper(), e); - } - } - log.error("Http处理异常", e); - HttpServerUtil.send500Response(e); - return null; - } - - private Object invoke(Object instance, Method method) throws InvocationTargetException, IllegalAccessException, InstantiationException { - Object[] params = new Object[method.getParameterCount()]; - if (method.getParameterCount() > 0) { - for (int i = 0; i < method.getParameters().length; i++) { - Parameter parameter = method.getParameters()[i]; - if (FullHttpRequest.class.isAssignableFrom(parameter.getType())) { - params[i] = HttpContextHolder.getFullHttpRequest(); - } else if (HttpRequestWrapper.class.isAssignableFrom(parameter.getType())) { - params[i] = HttpContextHolder.getHttpRequestWrapper(); - } else if (ChannelHandlerContext.class.isAssignableFrom(parameter.getType())) { - params[i] = HttpContextHolder.getChannelHandlerContext(); - } else if (parameter.isAnnotationPresent(RequestBody.class)) { - String bodyString = HttpContextHolder.getHttpRequestWrapper().getContentAsString(); - if (TypeUtil.isNormalBasicType(parameter.getType())) { - params[i] = TypeUtil.conversion(bodyString, parameter.getType()); - } else { - if (StringUtil.isEmpty(bodyString)) { - params[i] = parameter.getType().newInstance(); - } else { - params[i] = JSONObject.parseObject(bodyString, parameter.getType()); - } - } - } else if (parameter.isAnnotationPresent(RequestParam.class)) { - RequestParam requestParam = parameter.getAnnotation(RequestParam.class); - if (StringUtil.isEmpty(requestParam.value())) { - throw new RuntimeException(String.format("类:%s 方法:%s @RequestParam必须指定参数名称" )); - } - String val = HttpContextHolder.getHttpRequestWrapper().getParameter(requestParam.value()); - if (StringUtil.isEmpty(val)) { - if (requestParam.required()) { - throw new RuntimeException(String.format("类:%s 方法:%s 参数:%s 未指定" )); - } - params[i] = null; - } else { - params[i] = TypeUtil.conversion(val, parameter.getType()); - } - } else if (!TypeUtil.isNormalBasicType(parameter.getType())) { - Object obj = parameter.getType().newInstance(); - params[i] = obj; - Set fields = ReflectUtil.getDeclaredFields(parameter.getType()); - if (CollectionUtil.notEmpty(fields)) { - try { - for (Field field : fields) { - String name = field.getName(); - Object value = TypeUtil.conversion(HttpContextHolder.getHttpRequestWrapper().getParameter(name), field.getType()); - // 临时处理默认值被覆盖的问题 - if (!(null != value && TypeUtil.isStrictBasicType(field) && value.equals(TypeUtil.getDefaultValue(field.getType())))) { - ReflectUtil.setFieldValue(field, obj, value); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - } - } - } - Object invokeResult = method.invoke(instance, params); - return invokeResult; - } - - private void release() { - HttpContextHolder.remove(); - } - - @AllArgsConstructor - @Data - public static class DataWrapper { - private byte[] data; - private String contentEncoding; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/HttpResponseEntry.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/HttpResponseEntry.java deleted file mode 100644 index 62cd0d12..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/HttpResponseEntry.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -/** - * - * @author: aoshiguchen - * @date: 2022/5/28 - */ -@AllArgsConstructor -@NoArgsConstructor -@Accessors(chain = true) -@Data -public class HttpResponseEntry implements HttpEntry { - private int code; - private String status; - private String msg; -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/PathMatcher.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/PathMatcher.java deleted file mode 100644 index 42e279c5..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/PathMatcher.java +++ /dev/null @@ -1,120 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web; - -import java.util.Comparator; -import java.util.Map; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/27 - */ -public interface PathMatcher { - /** - * Does the given {@code path} represent a pattern that can be matched - * by an implementation of this interface? - *

If the return value is {@code false}, then the {@link #match} - * method does not have to be used because direct equality comparisons - * on the static path Strings will lead to the same result. - * @param path the path String to check - * @return {@code true} if the given {@code path} represents a pattern - */ - boolean isPattern(String path); - - /** - * Match the given {@code path} against the given {@code pattern}, - * according to this PathMatcher's matching strategy. - * @param pattern the pattern to match against - * @param path the path String to test - * @return {@code true} if the supplied {@code path} matched, - * {@code false} if it didn't - */ - boolean match(String pattern, String path); - - /** - * Match the given {@code path} against the corresponding part of the given - * {@code pattern}, according to this PathMatcher's matching strategy. - *

Determines whether the pattern at least matches as far as the given base - * path goes, assuming that a full path may then match as well. - * @param pattern the pattern to match against - * @param path the path String to test - * @return {@code true} if the supplied {@code path} matched, - * {@code false} if it didn't - */ - boolean matchStart(String pattern, String path); - - /** - * Given a pattern and a full path, determine the pattern-mapped part. - *

This method is supposed to find out which part of the path is matched - * dynamically through an actual pattern, that is, it strips off a statically - * defined leading path from the given full path, returning only the actually - * pattern-matched part of the path. - *

For example: For "myroot/*.html" as pattern and "myroot/myfile.html" - * as full path, this method should return "myfile.html". The detailed - * determination rules are specified to this PathMatcher's matching strategy. - *

A simple implementation may return the given full path as-is in case - * of an actual pattern, and the empty String in case of the pattern not - * containing any dynamic parts (i.e. the {@code pattern} parameter being - * a static path that wouldn't qualify as an actual {@link #isPattern pattern}). - * A sophisticated implementation will differentiate between the static parts - * and the dynamic parts of the given path pattern. - * @param pattern the path pattern - * @param path the full path to introspect - * @return the pattern-mapped part of the given {@code path} - * (never {@code null}) - */ - String extractPathWithinPattern(String pattern, String path); - - /** - * Given a pattern and a full path, extract the URI template variables. URI template - * variables are expressed through curly brackets ('{' and '}'). - *

For example: For pattern "/hotels/{hotel}" and path "/hotels/1", this method will - * return a map containing "hotel"->"1". - * @param pattern the path pattern, possibly containing URI templates - * @param path the full path to extract template variables from - * @return a map, containing variable names as keys; variables values as values - */ - Map extractUriTemplateVariables(String pattern, String path); - - /** - * Given a full path, returns a {@link Comparator} suitable for sorting patterns - * in order of explicitness for that path. - *

The full algorithm used depends on the underlying implementation, but generally, - * the returned {@code Comparator} will - * {@linkplain java.util.Collections#sort(java.util.List, java.util.Comparator) sort} - * a list so that more specific patterns come before generic patterns. - * @param path the full path to use for comparison - * @return a comparator capable of sorting patterns in order of explicitness - */ - Comparator getPatternComparator(String path); - - /** - * Combines two patterns into a new pattern that is returned. - *

The full algorithm used for combining the two pattern depends on the underlying implementation. - * @param pattern1 the first pattern - * @param pattern2 the second pattern - * @return the combination of the two patterns - * @throws IllegalArgumentException when the two patterns cannot be combined - */ - String combine(String pattern1, String pattern2); -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/WebApplicationServer.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/WebApplicationServer.java deleted file mode 100644 index c208d081..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/WebApplicationServer.java +++ /dev/null @@ -1,110 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web; - -import fun.asgc.neutrino.core.annotation.Autowired; -import fun.asgc.neutrino.core.annotation.Component; -import fun.asgc.neutrino.core.annotation.Destroy; -import fun.asgc.neutrino.core.annotation.Init; -import fun.asgc.neutrino.core.context.ApplicationConfig; -import fun.asgc.neutrino.core.context.ApplicationRunner; -import fun.asgc.neutrino.core.util.*; -import fun.asgc.neutrino.core.web.context.HttpContextHolder; -import fun.asgc.neutrino.core.web.context.WebContextHolder; -import io.netty.bootstrap.ServerBootstrap; -import io.netty.buffer.Unpooled; -import io.netty.channel.*; -import io.netty.channel.nio.NioEventLoopGroup; -import io.netty.channel.socket.SocketChannel; -import io.netty.channel.socket.nio.NioServerSocketChannel; -import io.netty.handler.codec.http.*; -import io.netty.handler.stream.ChunkedWriteHandler; -import lombok.extern.slf4j.Slf4j; - -/** - * web服务 - * @author: aoshiguchen - * @date: 2022/7/9 - */ -@Slf4j -@Component -public class WebApplicationServer implements ApplicationRunner { - @Autowired - private ApplicationConfig applicationConfig; - @Autowired - private HttpRequestHandler httpRequestHandler; - private EventLoopGroup bossGroup; - private EventLoopGroup workerGroup; - private ServerBootstrap serverBootstrap; - private ChannelFuture channelFuture; - - @Init - public void init() { - this.bossGroup = new NioEventLoopGroup(); - this.workerGroup = new NioEventLoopGroup(); - this.serverBootstrap = new ServerBootstrap(); - } - - @Override - public void run(String[] args) throws Exception { - this.serverBootstrap.group(bossGroup, workerGroup) - .channel(NioServerSocketChannel.class) - .option(ChannelOption.SO_BACKLOG, 1024) - .childOption(ChannelOption.TCP_NODELAY, true) - .childOption(ChannelOption.SO_KEEPALIVE, true) - .childOption(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator()) - .childHandler(new ChannelInitializer() { - @Override - protected void initChannel(SocketChannel ch) throws Exception { - ChannelPipeline pipeline = ch.pipeline(); - pipeline.addLast(new HttpServerCodec()); - pipeline.addLast(new ChunkedWriteHandler()); - pipeline.addLast(new HttpObjectAggregator(WebContextHolder.getMaxContentLength().intValue())); - pipeline.addLast(new SimpleChannelInboundHandler() { - @Override - protected void channelRead0(ChannelHandlerContext context, FullHttpRequest request) throws Exception { - HttpContextHolder.init(context, request); - - String uri = request.uri(); - log.debug("http request: {}", uri); - if (WebContextHolder.getHttpContextPath().equals("/") || uri.startsWith(WebContextHolder.getHttpContextPath() + "/") || uri.equals(WebContextHolder.getHttpContextPath())) { - httpRequestHandler.handle(); - } else if (uri.equals("/favicon.ico") && null != WebContextHolder.getFaviconBytes()) { - FullHttpResponse fullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(WebContextHolder.getFaviconBytes())); - fullHttpResponse.headers().add(HttpHeaderNames.CONTENT_TYPE, "image/x-icon"); - context.writeAndFlush(fullHttpResponse).addListener(ChannelFutureListener.CLOSE); - } else { - HttpServerUtil.send404Response(uri); - } - } - }); - } - }); - channelFuture = this.serverBootstrap.bind(WebContextHolder.getPort()).sync(); - log.info("HTTP服务启动,端口:{} context-path:{}", WebContextHolder.getPort(), WebContextHolder.getHttpContextPath()); - } - - @Destroy - public void destroy() { - this.channelFuture.channel().close(); - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/annotation/GetMapping.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/annotation/GetMapping.java deleted file mode 100644 index b7c065f6..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/annotation/GetMapping.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web.annotation; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/15 - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE,ElementType.METHOD}) -public @interface GetMapping { - String[] value() default {}; -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/annotation/PostMapping.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/annotation/PostMapping.java deleted file mode 100644 index 4f092a1d..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/annotation/PostMapping.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web.annotation; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/15 - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE,ElementType.METHOD}) -public @interface PostMapping { - String[] value() default {}; -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/annotation/RequestBody.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/annotation/RequestBody.java deleted file mode 100644 index 6fba2dfd..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/annotation/RequestBody.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web.annotation; - -import java.lang.annotation.*; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/23 - */ -@Target({ElementType.PARAMETER}) -@Retention(RetentionPolicy.RUNTIME) -@Documented -public @interface RequestBody { - boolean required() default true; -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/annotation/RequestMapping.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/annotation/RequestMapping.java deleted file mode 100644 index 7404b8e8..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/annotation/RequestMapping.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web.annotation; - -import fun.asgc.neutrino.core.web.HttpMethod; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/16 - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE,ElementType.METHOD}) -public @interface RequestMapping { - String[] value() default {}; - HttpMethod[] method() default {}; -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/annotation/RequestParam.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/annotation/RequestParam.java deleted file mode 100644 index 425c0fe0..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/annotation/RequestParam.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web.annotation; - -import java.lang.annotation.*; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/23 - */ -@Target({ElementType.PARAMETER}) -@Retention(RetentionPolicy.RUNTIME) -@Documented -public @interface RequestParam { - String value() default ""; - boolean required() default true; -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/annotation/RestController.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/annotation/RestController.java deleted file mode 100644 index af9dcc74..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/annotation/RestController.java +++ /dev/null @@ -1,43 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web.annotation; - -import fun.asgc.neutrino.core.annotation.Component; -import fun.asgc.neutrino.core.annotation.NonIntercept; -import fun.asgc.neutrino.core.aop.Intercept; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * @author: aoshiguchen - * @date: 2022/7/15 - */ -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.TYPE) -@Component -@Intercept(ignoreGlobal = true) -public @interface RestController { - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/config/WebMvcConfigurer.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/config/WebMvcConfigurer.java deleted file mode 100644 index a72b5143..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/config/WebMvcConfigurer.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web.config; - -import fun.asgc.neutrino.core.web.interceptor.ExceptionHandlerRegistry; -import fun.asgc.neutrino.core.web.interceptor.InterceptorRegistry; -import fun.asgc.neutrino.core.web.interceptor.RestControllerAdviceHandler; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/27 - */ -public interface WebMvcConfigurer { - - default void addInterceptors(InterceptorRegistry registry) { - - } - - default void addExceptionHandler(ExceptionHandlerRegistry registry) { - - } - - default RestControllerAdviceHandler adviceHandler() { - return null; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/context/HttpContextHolder.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/context/HttpContextHolder.java deleted file mode 100644 index 17b24afe..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/context/HttpContextHolder.java +++ /dev/null @@ -1,92 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web.context; - -import fun.asgc.neutrino.core.web.interceptor.HandlerInterceptor; -import io.netty.buffer.Unpooled; -import io.netty.channel.ChannelHandlerContext; -import io.netty.handler.codec.http.*; - -import java.util.List; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/22 - */ -public abstract class HttpContextHolder { - private static final ThreadLocal httpRequestWrapperHolder = new ThreadLocal<>(); - private static final ThreadLocal httpResponseWrapperHolder = new ThreadLocal<>(); - private static ThreadLocal fullHttpRequestHolder = new ThreadLocal<>(); - private static ThreadLocal channelHandlerContextHolder = new ThreadLocal<>(); - private static ThreadLocal> interceptorListHolder = new ThreadLocal<>(); - - public static void remove() { - httpRequestWrapperHolder.remove(); - fullHttpRequestHolder.remove(); - channelHandlerContextHolder.remove(); - interceptorListHolder.remove(); - } - - public static void setFullHttpRequest(FullHttpRequest request) { - fullHttpRequestHolder.set(request); - httpRequestWrapperHolder.set(HttpRequestWrapper.create(request)); - } - - public static void setFullHttpResponseWrapper() { - httpResponseWrapperHolder.set(HttpResponseWrapper.create()); - } - - public static void setChannelHandlerContext(ChannelHandlerContext context) { - channelHandlerContextHolder.set(context); - } - - public static void setInterceptorList(List interceptorList) { - interceptorListHolder.set(interceptorList); - } - - public static List getInterceptorList() { - return interceptorListHolder.get(); - } - - public static HttpRequestWrapper getHttpRequestWrapper() { - return httpRequestWrapperHolder.get(); - } - - public static HttpResponseWrapper getHttpResponseWrapper() { - return httpResponseWrapperHolder.get(); - } - - public static FullHttpRequest getFullHttpRequest() { - return fullHttpRequestHolder.get(); - } - - public static ChannelHandlerContext getChannelHandlerContext() { - return channelHandlerContextHolder.get(); - } - - public static void init(ChannelHandlerContext context, FullHttpRequest request) { - setChannelHandlerContext(context); - setFullHttpRequest(request); - setFullHttpResponseWrapper(); - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/context/HttpRequestWrapper.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/context/HttpRequestWrapper.java deleted file mode 100644 index 7211d23f..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/context/HttpRequestWrapper.java +++ /dev/null @@ -1,222 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web.context; - -import fun.asgc.neutrino.core.util.ArrayUtil; -import fun.asgc.neutrino.core.util.Assert; -import fun.asgc.neutrino.core.util.LockUtil; -import fun.asgc.neutrino.core.util.StringUtil; -import io.netty.buffer.ByteBuf; -import io.netty.handler.codec.http.FullHttpRequest; -import io.netty.handler.codec.http.HttpMethod; -import io.netty.util.CharsetUtil; - -import java.util.HashMap; -import java.util.Map; -import java.util.function.Function; - -/** - * Http请求解析器 - * @author: aoshiguchen - * @date: 2022/7/22 - */ -public class HttpRequestWrapper { - private FullHttpRequest request; - private String url; - private String queryString; - private Map queryParamMap = null; - private String routePath; - - private HttpRequestWrapper(FullHttpRequest request) { - this.request = request; - this.url = request.uri(); - this.queryString = ""; - - int index = url.indexOf("?"); - if (index >= 0) { - if (index < url.length() - 1) { - this.queryString = url.substring(index + 1); - } - url = getUrl().substring(0, index); - } - this.routePath = getRoutePath(url); - } - - public static HttpRequestWrapper create(FullHttpRequest request) { - return new HttpRequestWrapper(request); - } - - public String getUrl() { - return url; - } - - public String getRoutePath() { - return routePath; - } - - public String getQueryString() { - return queryString; - } - - public Map getQueryParamMap() { - return LockUtil.doubleCheckProcessForNoException( - () -> null == queryParamMap, - this, - () -> { - queryParamMap = queryStringToMap(queryString); - String contentType = getContentType(); - if (StringUtil.isEmpty(contentType)) { - return; - } - if (contentType.equals("application/x-www-form-urlencoded")) { - queryParamMap.putAll(queryStringToMap(getContentAsString())); - } else if(contentType.startsWith("multipart/form-data;")) { - // TODO 暂时简单处理,只处理纯文本情况 - String boundary = contentType.split(";")[1].split("=")[1]; - String separator = "--" + boundary; - String[] arr = getContentAsString().split(separator); - if (ArrayUtil.notEmpty(arr)) { - for (String item : arr) { - if (StringUtil.isEmpty(item)) { - continue; - } - String[] lines = item.split("\r\n"); - if (lines.length < 4) { - continue; - } - String name = lines[1].split(";")[1].split("=")[1].replaceAll("\\\"", ""); - String value = lines[3]; - queryParamMap.put(name, value); - } - } - } - }, - () -> queryParamMap - ); - } - - public HttpMethod getMethod() { - return request.method(); - } - - public ByteBuf getContent() { - return request.content(); - } - - public String getContentAsString() { - return getContent().toString(CharsetUtil.UTF_8); - } - - public String getParameter(String key) { - return getQueryParamMap().get(key); - } - - public Byte getParameterForByte(String key) { - return getParameterAndConvert(key, Byte::valueOf); - } - - public Short getParameterForShort(String key) { - return getParameterAndConvert(key, Short::valueOf); - } - - public Integer getParameterForInteger(String key) { - return getParameterAndConvert(key, Integer::valueOf); - } - - public Long getParameterForLong(String key) { - return getParameterAndConvert(key, Long::valueOf); - } - - public Float getParameterForFloat(String key) { - return getParameterAndConvert(key, Float::valueOf); - } - - public Double getParameterForDouble(String key) { - return getParameterAndConvert(key, Double::valueOf); - } - - public Boolean getParameterForBoolean(String key) { - return getParameterAndConvert(key, Boolean::valueOf); - } - - public String getParameterForString(String key) { - return getParameterAndConvert(key, Function.identity()); - } - - public T getParameterAndConvert(String key, Function convert) { - Assert.notEmpty(key, "key不能为空!"); - Assert.notNull(convert, "convert不能为空!"); - String val = getParameter(key); - if (StringUtil.notEmpty(val)) { - return convert.apply(val); - } - return null; - } - - public FullHttpRequest getRequest() { - return request; - } - - public String getHeaderValue(String name) { - return request.headers().get(name); - } - - public String getContentType() { - return request.headers().get("Content-Type"); - } - - private Map queryStringToMap(String queryString) { - Map result = new HashMap<>(); - if (StringUtil.isEmpty(queryString)) { - return result; - } - String[] params = queryString.split("&"); - for (String param : params) { - int index2 = param.indexOf("="); - String key = ""; - String val = ""; - if (index2 > 0) { - key = param.substring(0, index2); - if (index2 < param.length() - 1) { - val = param.substring(index2 + 1); - } - result.put(key, val); - } - } - return result; - } - - private String getRoutePath(String url) { - String httpContextPath = WebContextHolder.getHttpContextPath(); - if (null == url || url.length() < httpContextPath.length()) { - return url; - } - if (StringUtil.isEmpty(httpContextPath)) { - return url; - } - String res = url.substring(httpContextPath.length()); - if (StringUtil.isEmpty(res)) { - return "/"; - } - return res; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/context/HttpResponseWrapper.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/context/HttpResponseWrapper.java deleted file mode 100644 index 510324d6..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/context/HttpResponseWrapper.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web.context; - -import fun.asgc.neutrino.core.util.Assert; -import io.netty.buffer.ByteBuf; -import io.netty.buffer.ByteBufUtil; -import io.netty.buffer.Unpooled; -import io.netty.channel.ChannelFutureListener; -import io.netty.handler.codec.http.*; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/30 - */ -public class HttpResponseWrapper { - private HttpResponseStatus status; - private HttpHeaders httpHeaders; - private ByteBuf content; - - - private HttpResponseWrapper() { - this.status = HttpResponseStatus.OK; - this.httpHeaders = new DefaultHttpHeaders(); - this.content = Unpooled.EMPTY_BUFFER; - } - - public HttpHeaders headers() { - return httpHeaders; - } - - public void setContent(ByteBuf content) { - this.content = content; - } - - public void setStatus(HttpResponseStatus status) { - Assert.notNull(status, "http响应状态码不能为空!"); - this.status = status; - } - - public void writeAndFlush() { - FullHttpResponse fullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, content); - fullHttpResponse.headers().add(httpHeaders); - HttpContextHolder.getChannelHandlerContext().writeAndFlush(fullHttpResponse).addListener(ChannelFutureListener.CLOSE); - } - - public static HttpResponseWrapper create() { - return new HttpResponseWrapper(); - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/context/WebApplicationContext.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/context/WebApplicationContext.java deleted file mode 100644 index 7b1fd2f7..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/context/WebApplicationContext.java +++ /dev/null @@ -1,80 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web.context; - -import com.google.common.collect.Sets; -import fun.asgc.neutrino.core.annotation.*; -import fun.asgc.neutrino.core.bean.factory.SimpleBeanFactory; -import fun.asgc.neutrino.core.context.ApplicationContext; -import fun.asgc.neutrino.core.context.ApplicationRunner; -import fun.asgc.neutrino.core.web.HttpRequestHandler; -import fun.asgc.neutrino.core.web.WebApplicationServer; -import fun.asgc.neutrino.core.web.interceptor.ControllerGlobalInterceptor; -import fun.asgc.neutrino.core.web.router.DefaultHttpRouter; -import lombok.Data; -import lombok.experimental.Accessors; -import lombok.extern.slf4j.Slf4j; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/15 - */ -@Accessors(chain = true) -@Data -@Slf4j -@NonIntercept -@Component -public class WebApplicationContext implements ApplicationRunner { - @Autowired - private ApplicationContext applicationContext; - @Autowired - private SimpleBeanFactory applicationBeanFactory; - /** - * bean工厂 - */ - private SimpleBeanFactory webApplicationBeanFactory; - - @Init - public void init() { - this.webApplicationBeanFactory = new SimpleBeanFactory(applicationBeanFactory, "webApplicationBeanFactory"); - this.webApplicationBeanFactory.init(); - } - - @Destroy - public void destroy() { - this.webApplicationBeanFactory.destroy(); - } - - @Override - public void run(String[] args) throws Exception { - this.webApplicationBeanFactory.register( - Sets.newHashSet( - DefaultHttpRouter.class, - HttpRequestHandler.class, - ControllerGlobalInterceptor.class, - WebApplicationServer.class - ) - ); - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/context/WebContextHolder.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/context/WebContextHolder.java deleted file mode 100644 index 996740c6..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/context/WebContextHolder.java +++ /dev/null @@ -1,167 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web.context; - -import fun.asgc.neutrino.core.annotation.Autowired; -import fun.asgc.neutrino.core.annotation.Component; -import fun.asgc.neutrino.core.annotation.Init; -import fun.asgc.neutrino.core.annotation.NonIntercept; -import fun.asgc.neutrino.core.bean.BeanWrapper; -import fun.asgc.neutrino.core.bean.factory.SimpleBeanFactory; -import fun.asgc.neutrino.core.context.ApplicationConfig; -import fun.asgc.neutrino.core.context.Environment; -import fun.asgc.neutrino.core.util.*; -import fun.asgc.neutrino.core.web.annotation.RestController; -import fun.asgc.neutrino.core.web.config.WebMvcConfigurer; -import fun.asgc.neutrino.core.web.interceptor.ExceptionHandlerRegistry; -import fun.asgc.neutrino.core.web.interceptor.InterceptorRegistry; -import fun.asgc.neutrino.core.web.interceptor.RestControllerAdviceHandler; - -import java.util.List; -import java.util.stream.Collectors; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/26 - */ -@NonIntercept -@Component -public class WebContextHolder { - private static ApplicationConfig.Http http; - private static volatile String httpContextPath; - private static volatile byte[] faviconBytes; - private static volatile Long maxContentLength; - private static volatile Integer port; - private static List controllerBeanWrapperList; - private static volatile InterceptorRegistry interceptorRegistry; - private static volatile ExceptionHandlerRegistry exceptionHandlerRegistry; - private static volatile RestControllerAdviceHandler adviceHandler; - @Autowired - private ApplicationConfig applicationConfig; - @Autowired - private SimpleBeanFactory applicationBeanFactory; - @Autowired - private Environment environment; - - @Init - public void init() { - WebContextHolder.http = applicationConfig.getHttp(); - initHttpContextPath(); - initFavicon(); - initMaxContentLength(); - initControllerBeanWrapperList(); - initInterceptorRegistry(); - port = environment.getMainArgsForInteger("neutrino.http.port", http.getPort()); - } - - public static String getHttpContextPath() { - return httpContextPath; - } - - public static byte[] getFaviconBytes() { - return faviconBytes; - } - - public static Long getMaxContentLength() { - return maxContentLength; - } - - public static Integer getPort() { - return port; - } - - private static void initHttpContextPath() { - httpContextPath = http.getContextPath(); - if (StringUtil.isEmpty(httpContextPath)) { - httpContextPath = "/"; - } - if (!httpContextPath.startsWith("/")) { - httpContextPath = "/" + httpContextPath; - } - if (httpContextPath.endsWith("/")) { - httpContextPath = httpContextPath.substring(0, httpContextPath.length() - 1); - } - } - - private static void initFavicon() { - if (null == http.getStaticResource() || CollectionUtil.isEmpty(http.getStaticResource().getLocations())) { - return; - } - for (String location : http.getStaticResource().getLocations()) { - faviconBytes = FileUtil.readBytes(location.concat("favicon.ico")); - if (null != faviconBytes) { - break; - } - } - } - - private static void initMaxContentLength() { - maxContentLength = http.getMaxContentLength(); - if (StringUtil.notEmpty(http.getMaxContentLengthDesc()) && null == http.getMaxContentLength()) { - maxContentLength = NumberUtil.descriptionToSize(http.getMaxContentLengthDesc(), 64 * 1024); - } - } - - private void initControllerBeanWrapperList() { - List beanWrapperList = applicationBeanFactory.beanWrapperList(); - if (CollectionUtil.isEmpty(beanWrapperList)) { - return; - } - controllerBeanWrapperList = beanWrapperList.stream() - .filter(beanWrapper -> beanWrapper.getType().isAnnotationPresent(RestController.class)).collect(Collectors.toList()); - } - - private void initInterceptorRegistry() { - interceptorRegistry = new InterceptorRegistry(); - exceptionHandlerRegistry = new ExceptionHandlerRegistry(); - List beanWrapperList = applicationBeanFactory.beanWrapperList(); - if (CollectionUtil.isEmpty(beanWrapperList)) { - return; - } - List webMvcConfigurerList = applicationBeanFactory.getBeanList(WebMvcConfigurer.class); - if (CollectionUtil.isEmpty(webMvcConfigurerList)) { - return; - } - webMvcConfigurerList.forEach(webMvcConfigurer -> { - webMvcConfigurer.addInterceptors(interceptorRegistry); - webMvcConfigurer.addExceptionHandler(exceptionHandlerRegistry); - adviceHandler = webMvcConfigurer.adviceHandler(); - }); - } - - public static List getControllerBeanWrapperList() { - return controllerBeanWrapperList; - } - - public static InterceptorRegistry getInterceptorRegistry() { - return interceptorRegistry; - } - - public static ExceptionHandlerRegistry getExceptionHandlerRegistry() { - return exceptionHandlerRegistry; - } - - public static RestControllerAdviceHandler getAdviceHandler() { - return adviceHandler; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/exception/WebException.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/exception/WebException.java deleted file mode 100644 index 430c24d6..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/exception/WebException.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web.exception; - -import fun.asgc.neutrino.core.exception.InternalException; - -/** - * web服务异常 - * @author: aoshiguchen - * @date: 2022/7/15 - */ -public class WebException extends InternalException { - protected String method; - protected Integer code; - private String path; - protected String message; - - public WebException(String method, Integer code, String path, String message) { - super(message); - } - - public WebException(String method, Integer code, String path, String message, Throwable cause) { - super(message, cause); - } - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/exception/WebResourceNotFoundException.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/exception/WebResourceNotFoundException.java deleted file mode 100644 index 0821de7c..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/exception/WebResourceNotFoundException.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web.exception; - -/** - * web资源找不到异常 - * @author: aoshiguchen - * @date: 2022/7/15 - */ -public class WebResourceNotFoundException extends WebException { - - public WebResourceNotFoundException(String method, String path, String message) { - super(method, 404, path, message); - } - - public WebResourceNotFoundException(String method, String path, String message, Throwable cause) { - super(method, 404, path, message, cause); - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/interceptor/ControllerGlobalInterceptor.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/interceptor/ControllerGlobalInterceptor.java deleted file mode 100644 index 4c8c6f6e..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/interceptor/ControllerGlobalInterceptor.java +++ /dev/null @@ -1,121 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web.interceptor; - -import fun.asgc.neutrino.core.annotation.Component; -import fun.asgc.neutrino.core.annotation.Init; -import fun.asgc.neutrino.core.annotation.NonIntercept; -import fun.asgc.neutrino.core.aop.Aop; -import fun.asgc.neutrino.core.aop.Invocation; -import fun.asgc.neutrino.core.aop.interceptor.*; -import fun.asgc.neutrino.core.bean.BeanWrapper; -import fun.asgc.neutrino.core.util.ReflectUtil; -import fun.asgc.neutrino.core.web.annotation.GetMapping; -import fun.asgc.neutrino.core.web.annotation.PostMapping; -import fun.asgc.neutrino.core.web.annotation.RequestMapping; -import fun.asgc.neutrino.core.web.context.WebContextHolder; -import lombok.extern.slf4j.Slf4j; - -import java.lang.reflect.Method; -import java.util.List; -import java.util.Set; - -/** - * Controller全局拦截器 - * @author: aoshiguchen - * @date: 2022/7/27 - */ -@Slf4j -@NonIntercept -@Component -public class ControllerGlobalInterceptor implements Interceptor { - /** - * 拦截器包装器 - */ - private static final DefaultInterceptor interceptorWrapper = new DefaultInterceptor(ControllerGlobalInterceptor.class.getSimpleName()); - - public ControllerGlobalInterceptor() { - - } - - @Init - public void init() { - List beanWrapperList = WebContextHolder.getControllerBeanWrapperList(); - beanWrapperList.forEach(beanWrapper -> { - Set methods = ReflectUtil.getDeclaredMethods(beanWrapper.getType()); - methods.forEach(method -> { - if (method.isAnnotationPresent(GetMapping.class) || method.isAnnotationPresent(PostMapping.class) || method.isAnnotationPresent(RequestMapping.class)) { - Aop.intercept(method, this.getClass()); - } - }); - }); - } - - @Override - public void intercept(Invocation inv) throws Exception { - interceptorWrapper.intercept(inv); - } - - /** - * 注册过滤器 - * @param filter - */ - public static synchronized void registerFilter(Filter filter) { - interceptorWrapper.registerFilter(filter); - } - - /** - * 注册过滤器 - * @param filterList - */ - public static synchronized void registerFilter(List filterList) { - interceptorWrapper.registerFilter(filterList); - } - - /** - * 注册结果处理器 - * @param resultAdvice - */ - public static synchronized void registerResultAdvice(ResultAdvice resultAdvice) { - interceptorWrapper.registerResultAdvice(resultAdvice); - } - - /** - * 注册结果处理器 - * @param resultAdviceList - */ - public static synchronized void registerResultAdvice(List resultAdviceList) { - interceptorWrapper.registerResultAdvice(resultAdviceList); - } - - /** - * 注册异常处理器 - * @param exceptionHandler - */ - public static synchronized void registerExceptionHandler(ExceptionHandler exceptionHandler) { - interceptorWrapper.registerExceptionHandler(exceptionHandler); - } - - public static synchronized void registerExceptionHandler(List exceptionHandlerList) { - interceptorWrapper.registerExceptionHandler(exceptionHandlerList); - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/interceptor/ExceptionHandlerRegistry.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/interceptor/ExceptionHandlerRegistry.java deleted file mode 100644 index cd9cc6b4..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/interceptor/ExceptionHandlerRegistry.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web.interceptor; - -import java.util.ArrayList; -import java.util.List; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/29 - */ -public class ExceptionHandlerRegistry { - private final List exceptionHandlerList = new ArrayList<>(); - - public void addExceptionHandler(RestControllerExceptionHandler exceptionHandler) { - exceptionHandlerList.add(exceptionHandler); - } - - public List getExceptionHandlerList() { - return exceptionHandlerList; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/interceptor/HandlerInterceptor.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/interceptor/HandlerInterceptor.java deleted file mode 100644 index 3726047f..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/interceptor/HandlerInterceptor.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web.interceptor; - -import fun.asgc.neutrino.core.web.context.HttpRequestWrapper; -import fun.asgc.neutrino.core.web.context.HttpResponseWrapper; -import io.netty.channel.ChannelHandlerContext; - -import java.lang.reflect.Method; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/27 - */ -public interface HandlerInterceptor { - default boolean preHandle(HttpRequestWrapper requestParser, HttpResponseWrapper responseWrapper, String route, Method targetMethod) throws Exception { - return true; - } - - default void postHandle(HttpRequestWrapper requestParser, HttpResponseWrapper responseWrapper, String route, Method targetMethod, Object result) throws Exception { - } - - default void afterCompletion(HttpRequestWrapper requestParser, HttpResponseWrapper responseWrapper, String route, Method targetMethod) { - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/interceptor/InterceptorRegistration.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/interceptor/InterceptorRegistration.java deleted file mode 100644 index ffc65cb9..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/interceptor/InterceptorRegistration.java +++ /dev/null @@ -1,105 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web.interceptor; - -import fun.asgc.neutrino.core.base.Ordered; -import fun.asgc.neutrino.core.util.Assert; -import fun.asgc.neutrino.core.util.StringUtil; -import fun.asgc.neutrino.core.web.PathMatcher; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/27 - */ -public class InterceptorRegistration { - private final HandlerInterceptor interceptor; - private final List includePatterns = new ArrayList<>(); - private final List excludePatterns = new ArrayList<>(); - private PathMatcher pathMatcher; - private int order = 0; - - public InterceptorRegistration(HandlerInterceptor interceptor) { - Assert.notNull(interceptor, "Interceptor is required"); - this.interceptor = interceptor; - } - - public InterceptorRegistration addPathPatterns(String... patterns) { - return this.addPathPatterns(Arrays.asList(patterns)); - } - - public InterceptorRegistration addPathPatterns(List patterns) { - this.includePatterns.addAll(patterns); - return this; - } - - public InterceptorRegistration excludePathPatterns(String... patterns) { - return this.excludePathPatterns(Arrays.asList(patterns)); - } - - public InterceptorRegistration excludePathPatterns(List patterns) { - this.excludePatterns.addAll(patterns); - return this; - } - - public InterceptorRegistration pathMatcher(PathMatcher pathMatcher) { - this.pathMatcher = pathMatcher; - return this; - } - - public InterceptorRegistration order(int order) { - this.order = order; - return this; - } - - protected int getOrder() { - return this.order; - } - - public Object getInterceptor() { - if (this.includePatterns.isEmpty() && this.excludePatterns.isEmpty()) { - return this.interceptor; - } else { - String[] include = StringUtil.toStringArray(this.includePatterns); - String[] exclude = StringUtil.toStringArray(this.excludePatterns); - MappedInterceptor mappedInterceptor = new MappedInterceptor(include, exclude, this.interceptor); - if (this.pathMatcher != null) { - mappedInterceptor.setPathMatcher(this.pathMatcher); - } - - return mappedInterceptor; - } - } - - Ordered toOrdered() { - return new Ordered() { - @Override - public int getOrder() { - return order; - } - }; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/interceptor/InterceptorRegistry.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/interceptor/InterceptorRegistry.java deleted file mode 100644 index be2a9636..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/interceptor/InterceptorRegistry.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web.interceptor; - -import fun.asgc.neutrino.core.base.OrderComparator; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/27 - */ -public class InterceptorRegistry { - - private final List registrations = new ArrayList<>(); - - public InterceptorRegistration addInterceptor(HandlerInterceptor interceptor) { - InterceptorRegistration registration = new InterceptorRegistration(interceptor); - this.registrations.add(registration); - Collections.sort(this.registrations, INTERCEPTOR_ORDER_COMPARATOR); - return registration; - } - - /** - * Return all registered interceptors. - */ - public List getInterceptors() { - List result = new ArrayList(this.registrations.size()); - for (InterceptorRegistration registration : this.registrations) { - result.add(registration.getInterceptor()); - } - return result; - } - - - private static final Comparator INTERCEPTOR_ORDER_COMPARATOR = - OrderComparator.INSTANCE.withSourceProvider(new OrderComparator.OrderSourceProvider() { - @Override - public Object getOrderSource(final Object object) { - if (object instanceof InterceptorRegistration) { - return ((InterceptorRegistration) object).toOrdered(); - } - return null; - } - }); - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/interceptor/MappedInterceptor.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/interceptor/MappedInterceptor.java deleted file mode 100644 index ca43fa1c..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/interceptor/MappedInterceptor.java +++ /dev/null @@ -1,111 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web.interceptor; - -import fun.asgc.neutrino.core.web.PathMatcher; -import fun.asgc.neutrino.core.web.context.HttpRequestWrapper; -import fun.asgc.neutrino.core.web.context.HttpResponseWrapper; -import io.netty.channel.ChannelHandlerContext; -import org.apache.commons.lang3.ObjectUtils; - -import java.lang.reflect.Method; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/27 - */ -public class MappedInterceptor { - private final String[] includePatterns; - private final String[] excludePatterns; - private final HandlerInterceptor interceptor; - private PathMatcher pathMatcher; - - public MappedInterceptor(String[] includePatterns, HandlerInterceptor interceptor) { - this(includePatterns, null, (HandlerInterceptor)interceptor); - } - - public MappedInterceptor(String[] includePatterns, String[] excludePatterns, HandlerInterceptor interceptor) { - this.includePatterns = includePatterns; - this.excludePatterns = excludePatterns; - this.interceptor = interceptor; - } - - public void setPathMatcher(PathMatcher pathMatcher) { - this.pathMatcher = pathMatcher; - } - - public PathMatcher getPathMatcher() { - return this.pathMatcher; - } - - public String[] getPathPatterns() { - return this.includePatterns; - } - - public HandlerInterceptor getInterceptor() { - return this.interceptor; - } - - public boolean matches(String lookupPath, PathMatcher pathMatcher) { - PathMatcher pathMatcherToUse = this.pathMatcher != null ? this.pathMatcher : pathMatcher; - String[] var4; - int var5; - int var6; - String pattern; - if (!ObjectUtils.isEmpty(this.excludePatterns)) { - var4 = this.excludePatterns; - var5 = var4.length; - - for(var6 = 0; var6 < var5; ++var6) { - pattern = var4[var6]; - if (pathMatcherToUse.match(pattern, lookupPath)) { - return false; - } - } - } - - if (ObjectUtils.isEmpty(this.includePatterns)) { - return true; - } else { - var4 = this.includePatterns; - var5 = var4.length; - - for(var6 = 0; var6 < var5; ++var6) { - pattern = var4[var6]; - if (pathMatcherToUse.match(pattern, lookupPath)) { - return true; - } - } - - return false; - } - } - - public boolean preHandle(HttpRequestWrapper requestParser, HttpResponseWrapper responseWrapper, String route, Method targetMethod) throws Exception { - return this.interceptor.preHandle(requestParser, responseWrapper, route, targetMethod); - } - - public void postHandle(HttpRequestWrapper requestParser, HttpResponseWrapper responseWrapper, String route, Method targetMethod, Object result) throws Exception { - this.interceptor.postHandle(requestParser, responseWrapper, route, targetMethod, result); - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/interceptor/RestControllerAdviceHandler.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/interceptor/RestControllerAdviceHandler.java deleted file mode 100644 index 920252de..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/interceptor/RestControllerAdviceHandler.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web.interceptor; - -import fun.asgc.neutrino.core.web.context.HttpRequestWrapper; -import fun.asgc.neutrino.core.web.context.HttpResponseWrapper; -import io.netty.channel.ChannelHandlerContext; - -import java.lang.reflect.Method; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/29 - */ -public interface RestControllerAdviceHandler { - /** - * 返回结果处理 - * @param requestParser - * @param responseWrapper - * @param route - * @param targetMethod - * @param res - * @return - */ - Object advice(HttpRequestWrapper requestParser, HttpResponseWrapper responseWrapper, String route, Method targetMethod, Object res); -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/interceptor/RestControllerExceptionHandler.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/interceptor/RestControllerExceptionHandler.java deleted file mode 100644 index 8d8bacc7..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/interceptor/RestControllerExceptionHandler.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web.interceptor; - -import fun.asgc.neutrino.core.web.context.HttpRequestWrapper; -import fun.asgc.neutrino.core.web.context.HttpResponseWrapper; - -/** - * 异常处理 - * @author: aoshiguchen - * @date: 2022/7/29 - */ -public interface RestControllerExceptionHandler { - /** - * 是否支持处理该异常 - * @param e - * @return - */ - default boolean support(Throwable e) { - return true; - } - - /** - * 异常处理 - * @param e - * @return - */ - Object handle(HttpRequestWrapper requestParser, HttpResponseWrapper responseWrapper, Throwable e); -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/router/DefaultHttpRouter.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/router/DefaultHttpRouter.java deleted file mode 100644 index 7d63ce47..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/router/DefaultHttpRouter.java +++ /dev/null @@ -1,274 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web.router; - -import com.google.common.collect.Sets; -import fun.asgc.neutrino.core.annotation.*; -import fun.asgc.neutrino.core.bean.BeanWrapper; -import fun.asgc.neutrino.core.context.ApplicationConfig; -import fun.asgc.neutrino.core.util.*; -import fun.asgc.neutrino.core.web.HttpMethod; -import fun.asgc.neutrino.core.web.annotation.GetMapping; -import fun.asgc.neutrino.core.web.annotation.PostMapping; -import fun.asgc.neutrino.core.web.annotation.RequestMapping; -import fun.asgc.neutrino.core.web.context.WebContextHolder; -import lombok.extern.slf4j.Slf4j; - -import java.io.InputStream; -import java.lang.reflect.Method; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -/** - * 默认的http路由器 - * @author: aoshiguchen - * @date: 2022/7/16 - */ -@Slf4j -@NonIntercept -@Component -public class DefaultHttpRouter implements HttpRouter { - /** - * 路由缓存 - */ - private Map routeCache = new ConcurrentHashMap<>(256); - @Autowired - private ApplicationConfig applicationConfig; - - @Init - public void init() { - // 初始化方法路由 - initMethodRoute(); - // 初始化页面路由 - initPageRoute(); - } - - /** - * 初始化方法路由 - */ - private void initMethodRoute() { - log.debug("Http路由器初始化..."); - List beanWrapperList = WebContextHolder.getControllerBeanWrapperList(); - beanWrapperList.forEach(beanWrapper -> { - Set methods = null; - Set paths = null; - if (beanWrapper.getType().isAnnotationPresent(GetMapping.class)) { - GetMapping getMapping = beanWrapper.getType().getAnnotation(GetMapping.class); - methods = Sets.newHashSet(HttpMethod.GET); - if (ArrayUtil.notEmpty(getMapping.value())) { - paths = Stream.of(getMapping.value()).collect(Collectors.toSet()); - } - } else if (beanWrapper.getType().isAnnotationPresent(PostMapping.class)) { - PostMapping postMapping = beanWrapper.getType().getAnnotation(PostMapping.class); - methods = Sets.newHashSet(HttpMethod.POST); - if (ArrayUtil.notEmpty(postMapping.value())) { - paths = Stream.of(postMapping.value()).collect(Collectors.toSet()); - } - } else if (beanWrapper.getType().isAnnotationPresent(RequestMapping.class)) { - RequestMapping requestMapping = beanWrapper.getType().getAnnotation(RequestMapping.class); - if (ArrayUtil.notEmpty(requestMapping.value())) { - paths = Stream.of(requestMapping.value()).collect(Collectors.toSet()); - } - if (ArrayUtil.notEmpty(requestMapping.method())) { - methods = Stream.of(requestMapping.method()).collect(Collectors.toSet()); - } - } - - if (CollectionUtil.isEmpty(methods)){ - methods = Stream.of(HttpMethod.values()).collect(Collectors.toSet()); - } - if (CollectionUtil.isEmpty(paths)) { - paths = Sets.newHashSet(""); - } - paths = paths.stream().map(p -> { - if (p.endsWith("/")) { - return p.substring(0, p.length() - 1); - } - return p; - }).collect(Collectors.toSet()); - methodScan(beanWrapper, methods, paths); - }); - } - - /** - * 初始化页面路由 - */ - private void initPageRoute() { - ApplicationConfig.StaticResource staticResource = applicationConfig.getHttp().getStaticResource(); - if (null == staticResource || CollectionUtil.isEmpty(staticResource.getLocations())) { - return; - } - log.info("Page路由初始化..."); - staticResource.getLocations().forEach(location -> { - // TODO - }); - } - - private void methodScan(BeanWrapper beanWrapper, Set httpMethods, Set paths) { - Set methods = ReflectUtil.getDeclaredMethods(beanWrapper.getType()); - methods.forEach(method -> { - Set realityHttpMethods = null; - Set subPaths = null; - if (method.isAnnotationPresent(GetMapping.class)) { - GetMapping getMapping = method.getAnnotation(GetMapping.class); - if (!httpMethods.contains(HttpMethod.GET)) { - throw new RuntimeException(String.format("Controller[type:%s, name:%s] method:%s 方法上的GetMapping注解与类的声明发生冲突!", beanWrapper.getType().getName(), beanWrapper.getName(), method.toString())); - } - realityHttpMethods = Sets.newHashSet(HttpMethod.GET); - if (ArrayUtil.notEmpty(getMapping.value())) { - subPaths = Stream.of(getMapping.value()).collect(Collectors.toSet()); - } - } else if (method.isAnnotationPresent(PostMapping.class)) { - PostMapping postMapping = method.getAnnotation(PostMapping.class); - if (!httpMethods.contains(HttpMethod.POST)) { - throw new RuntimeException(String.format("Controller[type:%s, name:%s] method:%s 方法上的PostMapping注解与类的声明发生冲突!", beanWrapper.getType().getName(), beanWrapper.getName(), method.toString())); - } - realityHttpMethods = Sets.newHashSet(HttpMethod.POST); - if (ArrayUtil.notEmpty(postMapping.value())) { - subPaths = Stream.of(postMapping.value()).collect(Collectors.toSet()); - } - } else if (method.isAnnotationPresent(RequestMapping.class)) { - RequestMapping requestMapping = method.getAnnotation(RequestMapping.class); - if (ArrayUtil.notEmpty(requestMapping.method())) { - realityHttpMethods = Stream.of(requestMapping.method()).collect(Collectors.toSet()); - } - if (!httpMethods.containsAll(realityHttpMethods)) { - throw new RuntimeException(String.format("Controller[type:%s, name:%s] method:%s 方法上的RequestMapping注解与类的声明发生冲突!", beanWrapper.getType().getName(), beanWrapper.getName(), method.toString())); - } - if (ArrayUtil.notEmpty(requestMapping.value())) { - subPaths = Stream.of(requestMapping.value()).collect(Collectors.toSet()); - } - } else { - return; - } - if (CollectionUtil.isEmpty(realityHttpMethods)) { - realityHttpMethods = Sets.newHashSet(httpMethods); - } - if (CollectionUtil.isEmpty(subPaths)) { - subPaths = Sets.newHashSet("/"); - } - subPaths = subPaths.stream().map(p -> { - if (!p.startsWith("/")) { - return "/" + p; - } - return p; - }).collect(Collectors.toSet()); - addRoute(beanWrapper, method, realityHttpMethods, paths, subPaths); - }); - } - - private void addRoute(BeanWrapper beanWrapper, Method method, Set httpMethods, Set paths, Set subPaths) { - for (HttpMethod httpMethod : httpMethods) { - for (String path : paths) { - for (String subPath : subPaths) { - addRoute(beanWrapper, method, httpMethod, path + subPath); - } - } - } - } - - private synchronized void addRoute(BeanWrapper beanWrapper, Method method, HttpMethod httpMethod, String path) { - if (!path.startsWith("/")) { - path = "/" + path; - } - log.info("addRoute[{}#{}] httpMethod:{} path:{}", beanWrapper.getType().getName(), method.getName(), httpMethod.name(), path); - HttpRouteIdentity identity = new HttpRouteIdentity(httpMethod, path); - if (routeCache.containsKey(identity)) { - throw new RuntimeException(String.format("Controller[type:%s, name:%s] method:%s 路由存在重复!", beanWrapper.getType().getName(), beanWrapper.getName(), method.getName())); - } - routeCache.put(identity, new HttpRouteInfo() - .setType(HttpRouterType.METHOD) - .setMethod(method) - .setBeanIdentity(beanWrapper.getIdentity()) - .setPageRoute(path) - ); - } - - private synchronized void addRoute(String path, String pageLocation, String pageRoute) { - log.info("addRoute path:{} file:{}", path, pageLocation); - HttpRouteIdentity identity = new HttpRouteIdentity(HttpMethod.GET, path); - if (routeCache.containsKey(identity)) { - return; - } - pageRoute = pageRoute.replaceAll("\\\\\\\\", "\\\\"); - if (pageRoute.equals("/")) { - pageRoute += "index.html"; - } - routeCache.put(identity, new HttpRouteInfo() - .setType(HttpRouterType.PAGE) - .setPageLocation(pageLocation) - .setPageRoute(pageRoute) - ); - } - - @Override - public HttpRouteResult route(HttpRouteParam httpRouteParam) { - HttpRouteIdentity identity = new HttpRouteIdentity(httpRouteParam.getMethod(), httpRouteParam.getUrl()); - HttpRouteInfo httpRouteInfo = routeCache.get(identity); - if (null == httpRouteInfo) { - if (HttpMethod.GET == httpRouteParam.getMethod()) { - ApplicationConfig.StaticResource staticResource = applicationConfig.getHttp().getStaticResource(); - if (null != staticResource && CollectionUtil.notEmpty(staticResource.getLocations())) { - for (String location : staticResource.getLocations()) { - String path = location + httpRouteParam.getUrl(); - path = path.replaceAll("//", "/"); - if (path.endsWith("/")) { - path += "index.html"; - } - try (InputStream in = FileUtil.getInputStream(path)){ - if (null != in) { - addRoute(httpRouteParam.getUrl(), path, httpRouteParam.getUrl()); - httpRouteInfo = routeCache.get(identity); - break; - } - } catch (Exception e) { - // ignore - } - } - } - } - } - if (null == httpRouteInfo) { - return null; - } - if (HttpRouterType.PAGE == httpRouteInfo.getType()) { - return new HttpRouteResult() - .setType(httpRouteInfo.getType()) - .setPageLocation(httpRouteInfo.getPageLocation()) - .setPageRoute(httpRouteInfo.getPageRoute()); - } - return new HttpRouteResult() - .setType(httpRouteInfo.getType()) - .setMethod(httpRouteInfo.getMethod()) - .setPageRoute(httpRouteInfo.getPageRoute()) - .setInstance(BeanManager.getBean(httpRouteInfo.getBeanIdentity())); - } - - @Destroy - public void destroy() { - log.debug("Http路由器销毁..."); - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/router/HttpRouteIdentity.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/router/HttpRouteIdentity.java deleted file mode 100644 index f4b515b2..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/router/HttpRouteIdentity.java +++ /dev/null @@ -1,88 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web.router; - -import fun.asgc.neutrino.core.base.Identity; -import fun.asgc.neutrino.core.util.Assert; -import fun.asgc.neutrino.core.web.HttpMethod; - -/** - * http路由唯一标识 - * @author: aoshiguchen - * @date: 2022/7/16 - */ -public class HttpRouteIdentity implements Identity { - - /** - * http方法 - */ - private HttpMethod method; - /** - * url - */ - private String url; - /** - * hashCode - */ - private int identityHashCode; - - @Override - public boolean isOnly() { - return true; - } - - public HttpRouteIdentity(HttpMethod method, String url) { - Assert.notNull(method, "http方法不能为空!"); - Assert.notEmpty(url, "url不能为空!"); - this.method = method; - this.url = url; - this.identityHashCode = System.identityHashCode(method); - } - - public HttpMethod getMethod() { - return method; - } - - public String getUrl() { - return url; - } - - @Override - public boolean equals(Object obj) { - if (null == obj) { - return false; - } - if (obj == this) { - return true; - } - if (!(obj instanceof HttpRouteIdentity)) { - return false; - } - HttpRouteIdentity httpRouteIdentity = (HttpRouteIdentity)obj; - return this.method.equals(httpRouteIdentity.getMethod()) && this.url.equals(httpRouteIdentity.getUrl()); - } - - @Override - public int hashCode() { - return identityHashCode; - } -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/router/HttpRouteInfo.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/router/HttpRouteInfo.java deleted file mode 100644 index bf131414..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/router/HttpRouteInfo.java +++ /dev/null @@ -1,58 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web.router; - -import fun.asgc.neutrino.core.bean.BeanIdentity; -import lombok.Data; -import lombok.experimental.Accessors; - -import java.lang.reflect.Method; - -/** - * http路由信息 - * @author: aoshiguchen - * @date: 2022/7/16 - */ -@Accessors(chain = true) -@Data -public class HttpRouteInfo { - /** - * 路由类型 - */ - private HttpRouterType type; - /** - * bean唯一标识 - */ - private BeanIdentity beanIdentity; - /** - * 方法 - */ - private Method method; - /** - * 页面位置 - */ - private String pageLocation; - /** - * 页面路由 - */ - private String pageRoute; -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/router/HttpRouteParam.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/router/HttpRouteParam.java deleted file mode 100644 index 210617fb..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/router/HttpRouteParam.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web.router; - -import fun.asgc.neutrino.core.web.HttpMethod; -import lombok.Data; -import lombok.experimental.Accessors; - -/** - * http路由参数 - * @author: aoshiguchen - * @date: 2022/7/16 - */ -@Accessors(chain = true) -@Data -public class HttpRouteParam { - private HttpMethod method; - private String url; -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/router/HttpRouteResult.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/router/HttpRouteResult.java deleted file mode 100644 index 577302d2..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/router/HttpRouteResult.java +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web.router; - -import lombok.Data; -import lombok.experimental.Accessors; - -import java.lang.reflect.Method; - -/** - * http路由结果 - * @author: aoshiguchen - * @date: 2022/7/16 - */ -@Accessors(chain = true) -@Data -public class HttpRouteResult { - /** - * 路由类型 - */ - private HttpRouterType type; - /** - * 实例 - */ - private Object instance; - /** - * 方法 - */ - private Method method; - /** - * 页面位置 - */ - private String pageLocation; - /** - * 页面路由 - */ - private String pageRoute; -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/router/HttpRouter.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/router/HttpRouter.java deleted file mode 100644 index a441e2e0..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/router/HttpRouter.java +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web.router; - -/** - * http路由器 - * @author: aoshiguchen - * @date: 2022/7/16 - */ -public interface HttpRouter extends Router { - -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/router/HttpRouterType.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/router/HttpRouterType.java deleted file mode 100644 index 5bff31a7..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/router/HttpRouterType.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web.router; - -import lombok.AllArgsConstructor; -import lombok.Getter; - -/** - * http路由类型 - * @author: aoshiguchen - * @date: 2022/7/16 - */ -@Getter -@AllArgsConstructor -public enum HttpRouterType { - METHOD(1, "方法"), - PAGE(2, "页面"); - - private Integer type; - private String desc; -} diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/router/Router.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/router/Router.java deleted file mode 100644 index fe60438a..00000000 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/web/router/Router.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web.router; - -/** - * 路由器 - * @author: aoshiguchen - * @date: 2022/7/16 - */ -public interface Router { - /** - * 路由 - * @param p - * @return - */ - R route(P p); -} diff --git a/neutrino-core/src/main/resources/tpl/AsgcProxy.tpl b/neutrino-core/src/main/resources/tpl/AsgcProxy.tpl deleted file mode 100644 index a6811b5c..00000000 --- a/neutrino-core/src/main/resources/tpl/AsgcProxy.tpl +++ /dev/null @@ -1,48 +0,0 @@ -package ${package}; - -#foreach($item in ${importList}) -import ${item.getName()}; -#end - -#if(${targetIsInterface}) -public class ${proxyClassName} implements ${targetType.getSimpleName()} { -#else -public class ${proxyClassName} extends ${targetType.getSimpleName()} { -#end - -#foreach($methodInfo in ${methodInfoList}) - public ${methodInfo.returnType.getSimpleName()} ${methodInfo.methodName} (${methodInfo.parametersString})${methodInfo.throwsString}{ - Invocation inv = new Invocation(${methodInfo.methodId}L, this, () -> { -#if(!${targetIsInterface}) -#if(${methodInfo.void}) - super.${methodInfo.methodName}(${methodInfo.parameterNamesString}); - return null; -#else - return super.${methodInfo.methodName}(${methodInfo.parameterNamesString}); -#end -#else - return null; -#end - }); - try { - inv.invoke(); - } catch(RuntimeException e) { - throw e; - } catch(Exception e) { -#if(${methodInfo.throw}) - if (ProxyCache.checkMethodThrow(${methodInfo.methodId}L, e)) { - throw e; - } else { - e.printStackTrace(); - } -#else - e.printStackTrace(); -#end - } -#if(!${methodInfo.void}) - return inv.getReturnValue(); -#end - } - -#end -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/Animal.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/Animal.java deleted file mode 100644 index 107a891d..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/Animal.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/28 - */ -@Intercept(TestInterceptor.class) -public interface Animal { - - int say(String msg); - - void hello() throws Exception; -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/AsgcProxyGeneratorTest.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/AsgcProxyGeneratorTest.java deleted file mode 100644 index d9c3da0f..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/AsgcProxyGeneratorTest.java +++ /dev/null @@ -1,71 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop; - -import fun.asgc.neutrino.core.aop.proxy.AsgcProxyGenerator; -import fun.asgc.neutrino.core.base.Handler; -import org.junit.Test; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/6 - */ -public class AsgcProxyGeneratorTest { - - @Test - public void test1() { - String result = AsgcProxyGenerator.getInstance().generator("A", Panda.class); - System.out.println(result); - } - - @Test - public void test2() { - String result = AsgcProxyGenerator.getInstance().generator("A", Giraffe.class); - System.out.println(result); - } - - @Test - public void test3() throws InvocationTargetException, IllegalAccessException { - Method[] methods = A.class.getDeclaredMethods(); - methods[0].invoke(new A(), "aa", "bb"); - System.out.println(methods[0].isSynthetic()); - } - - public static class A implements Handler{ - @Override - public void handle(String s, String s2) { - System.out.println("hello"); - } - - public void a() { - - } - - - } - -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/Bear.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/Bear.java deleted file mode 100644 index b75ebc45..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/Bear.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/30 - */ -public class Bear { - public Bear() { - System.out.println("熊出生"); - } - - public void up() throws Exception { - throw new Exception("飞得太高,摔死了"); - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/Cat.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/Cat.java deleted file mode 100644 index 5bd913de..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/Cat.java +++ /dev/null @@ -1,43 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/24 - */ -public class Cat { - public Cat() { - System.out.println("猫出生"); - } - - public void climb() { - System.out.println("猫在爬"); - } - - @Intercept(TestInterceptor2.class) - public int calc(int x, int y) { - System.out.println("猫在计算"); - return x + y; - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/DefaultPlayer.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/DefaultPlayer.java deleted file mode 100644 index 9751bfe5..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/DefaultPlayer.java +++ /dev/null @@ -1,64 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/7 - */ -@Intercept(value = TestInterceptor.class, ignoreGlobal = true) -public class DefaultPlayer implements Player { - - private String name; - - public DefaultPlayer(String name) { - this.name = name; - } - - public DefaultPlayer() { - this.name = "未知设备"; - } - - @Override - public void on() { - System.out.println(String.format("%s 开机", name)); - } - - @Override - public void off() { - System.out.println(String.format("%s 关机", name)); - } - - @Override - public void play() { - System.out.println(String.format("%s 开始播放", name)); - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/Dog.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/Dog.java deleted file mode 100644 index 28baf856..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/Dog.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/23 - */ -@Intercept({TestInterceptor.class, TestInterceptor2.class}) -public class Dog { - public Dog() { - System.out.println("狗出生"); - } - public void call() { - System.out.println("汪汪汪"); - } - - @Intercept(exclude = TestInterceptor2.class) - public String say(String msg) { - return "狗说:" + msg; - } - - // static 测试static方法 - public int calc(int x, int y) { - System.out.println("计算 " + x + " + " + "y"); - return x + y; - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/Giraffe.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/Giraffe.java deleted file mode 100644 index 97a467e4..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/Giraffe.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop; - - -import fun.asgc.neutrino.core.aop.support.Singleton; - -import java.util.Arrays; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/6 - */ -public class Giraffe { - public void run(String[] args) { - System.out.println("运行:" + Arrays.toString(args)); - } - - @Singleton - public Dog getDog() { - System.out.println("new Dog"); - return new Dog(); - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/GlobalInterceptor.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/GlobalInterceptor.java deleted file mode 100644 index 31a2590b..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/GlobalInterceptor.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop; - -import fun.asgc.neutrino.core.aop.interceptor.Interceptor; -import lombok.extern.slf4j.Slf4j; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/27 - */ -@Slf4j -public class GlobalInterceptor implements Interceptor { - - @Override - public void intercept(Invocation inv) throws Exception { - log.info("全局拦截器1 class:{} method:{} args:{} before", inv.getTargetClass().getName(), inv.getTargetMethod().getName(), inv.getArgs()); - inv.invoke(); - log.info("全局拦截器1 class:{} method:{} args:{} after", inv.getTargetClass().getName(), inv.getTargetMethod().getName(), inv.getArgs()); - } - -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/Mammal.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/Mammal.java deleted file mode 100644 index 08307b7b..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/Mammal.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop; - -/** - * 哺乳动物 - * @author: aoshiguchen - * @date: 2022/6/28 - */ -public interface Mammal extends Animal { - /** - * 爬行 - */ - void crawl(); -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/Panda.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/Panda.java deleted file mode 100644 index 558699dc..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/Panda.java +++ /dev/null @@ -1,61 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop; - -import fun.asgc.neutrino.core.aop.interceptor.InnerGlobalInterceptor; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/27 - */ -public class Panda { - - public Panda() { - System.out.println("熊猫出生"); - } - - public void eat() { - System.out.println("熊猫吃竹子"); - } - - @Intercept(exclude = InnerGlobalInterceptor.class) - public void play(String project) { - System.out.println("熊猫在玩" + project); - } - - public Integer division(int x, int y) { - return x / y; - } - - public void say(String msg) { - System.out.println("熊猫说:" + msg); - } - - public String request(String a, String b) { - return String.format("参数 a:%s b:%s 处理结果", a, b); - } - - public void up() throws Exception { - throw new Exception("跳太高,摔死了!"); - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/Player.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/Player.java deleted file mode 100644 index cb0d3807..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/Player.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop; - -/** - * 播放器接口 - * @author: aoshiguchen - * @date: 2022/7/7 - */ -@Intercept(value = TestInterceptor.class, ignoreGlobal = true) -public interface Player { - /** - * 开机 - */ - void on(); - - /** - * 关机 - */ - void off(); - - /** - * 播放 - */ - void play(); -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/RadioPlayer.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/RadioPlayer.java deleted file mode 100644 index 4b5159e0..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/RadioPlayer.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/7 - */ -public class RadioPlayer extends DefaultPlayer implements SoundPlayer { - - public RadioPlayer() { - super("收音机"); - } - - @Override - public void volumeIncrease() { - System.out.println(String.format("%s 音量增加", getName())); - } - - @Override - public void volumeReduce() { - System.out.println(String.format("%s 音量减少", getName())); - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/SoundPlayer.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/SoundPlayer.java deleted file mode 100644 index f56e2903..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/SoundPlayer.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop; - -/** - * @author: aoshiguchen - * @date: 2022/7/7 - */ -public interface SoundPlayer extends Player { - /** - * 音量增加 - */ - void volumeIncrease(); - - /** - * 音量减少 - */ - void volumeReduce(); -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/Test1.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/Test1.java deleted file mode 100644 index cd35308c..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/Test1.java +++ /dev/null @@ -1,63 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop; - -import org.junit.Test; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/24 - */ -public class Test1 { - - @Test - public void dogCall() throws Exception { - Dog dog = Aop.get(Dog.class); - dog.call(); - } - - @Test - public void dogSay() throws Exception { - Dog dog = Aop.get(Dog.class); - System.out.println(dog.say("hello")); - } - - @Test - public void catClimb() throws Exception { - Cat cat = Aop.get(Cat.class); - cat.climb(); - } - - @Test - public void catCalc() throws Exception { - Cat cat = Aop.get(Cat.class); - System.out.println(cat.calc(10, 6)); - } - - @Test - public void dogCalc() throws Exception { - Dog dog = Aop.get(Dog.class); - System.out.println(dog.calc(1, 2)); - } - -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/Test2.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/Test2.java deleted file mode 100644 index c00436e7..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/Test2.java +++ /dev/null @@ -1,120 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop; - -import com.alibaba.fastjson.JSONObject; -import fun.asgc.neutrino.core.aop.interceptor.*; -import lombok.extern.slf4j.Slf4j; -import org.junit.Test; - -import java.lang.reflect.Method; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/27 - */ -@Slf4j -public class Test2 { - - { - // 注册全局拦截器 - InterceptorFactory.registerGlobalInterceptor(GlobalInterceptor.class); - // 注册过滤器 - InnerGlobalInterceptor.registerFilter(new Filter() { - @Override - public boolean filtration(Class targetClass, Method targetMethod, Object[] args) { - if (targetClass == Panda.class && targetMethod.getName().equals("say")) { - return true; - } - return false; - } - }); - // 注册结果处理器 - InnerGlobalInterceptor.registerResultAdvice(new ResultAdvice() { - @Override - public Object advice(Class targetClass, Method targetMethod, Object result) { - if (targetClass == Panda.class && targetMethod.getName().equals("request")) { - JSONObject data = new JSONObject(); - data.put("code", 0); - data.put("data", result); - return data.toJSONString(); - } - return result; - } - }); - // 注册异常处理器 - InnerGlobalInterceptor.registerExceptionHandler(new ExceptionHandler() { - @Override - public boolean support(Exception e) { - return e instanceof ArithmeticException; - } - - @Override - public Object handle(Exception e) { - log.info("除数不能为0!"); - return null; - } - }); - } - - @Test - public void eat() throws Exception { - Panda panda = Aop.get(Panda.class); - panda.eat(); - } - - @Test - public void play() throws Exception { - Panda panda = Aop.get(Panda.class); - panda.play("滑板"); - } - - @Test - public void division() throws Exception { - Panda panda = Aop.get(Panda.class); - System.out.println(panda.division(10, 5)); - panda.division(10, 0); - } - - @Test - public void say() throws Exception { - Panda panda = Aop.get(Panda.class); - panda.say("hello"); - } - - @Test - public void request() throws Exception { - Panda panda = Aop.get(Panda.class); - panda.request("xxx", "yyy"); - } - - @Test - public void up() throws Exception { - Panda panda = Aop.get(Panda.class); - try { - panda.up(); - } catch (Exception e) { - e.printStackTrace(); - } - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/Test3.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/Test3.java deleted file mode 100644 index ce3dced6..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/Test3.java +++ /dev/null @@ -1,89 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop; - -import fun.asgc.neutrino.core.aop.proxy.Proxy; -import fun.asgc.neutrino.core.util.ReflectUtil; -import org.junit.Test; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/28 - */ -public class Test3 { - - @Test - public void test1() throws Exception { - Animal animal = Aop.get(Animal.class); -// Animal animal = Proxy.getProxyFactory(ProxyStrategy.ASGC_PROXY).get(Animal.class); - System.out.println(animal); - System.out.println(animal.say("aa")); - } - - @Test - public void test2() throws Exception { -// Mammal mammal = Aop.get(Mammal.class); - Mammal mammal = Proxy.getProxyFactory(ProxyStrategy.ASGC_PROXY).get(Mammal.class); - mammal.crawl(); - - System.out.println(ReflectUtil.getInterfaceAll(Mammal.class)); - } - - @Test - public void test3() throws Exception { - Bear bear = Aop.get(Bear.class); - bear.up(); - } - - @Test - public void test4() throws InvocationTargetException, IllegalAccessException { - Method hello1 = ReflectUtil.getMethods(A.class).stream().filter(m -> m.getName().equals("hello1")).findFirst().get(); - Method hello11 = ReflectUtil.getMethods(B.class).stream().filter(m -> m.getName().equals("hello1")).findFirst().get(); - A a = new A(); - B b = new B(); -// hello1.invoke(a); -// hello1.invoke(b); - hello11.invoke(a); // 异常 - hello11.invoke(b); - } - - public static class A { - public void hello1() { - System.out.println("hello1"); - } - public void hello2() { - System.out.println("hello2"); - } - } - - public static class B extends A { - @Override - public void hello1() { - super.hello1(); - System.out.println("----"); - } - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/Test4.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/Test4.java deleted file mode 100644 index 90014799..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/Test4.java +++ /dev/null @@ -1,103 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop; - -import fun.asgc.neutrino.core.aop.proxy.Proxy; -import fun.asgc.neutrino.core.base.GlobalConfig; -import org.junit.Test; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/7 - */ -public class Test4 { - - static { - // 配置输出生成代理类源码 - GlobalConfig.setIsPrintGeneratorCode(true); - } - - @Test - public void jdk代理1() throws Exception { - Player player = Proxy.getProxyFactory(ProxyStrategy.JDK_DYNAMIC_PROXY).get(RadioPlayer.class, Player.class); - player.on(); - player.play(); - player.off(); - } - - @Test - public void jdk代理2() throws Exception { - SoundPlayer player = Proxy.getProxyFactory(ProxyStrategy.JDK_DYNAMIC_PROXY).get(RadioPlayer.class, SoundPlayer.class); - player.on(); - player.play(); - player.volumeReduce(); - player.off(); - } - - /** - * 无法被代理,应抛出异常 - * @throws Exception - */ - @Test - public void jdk代理3() throws Exception { - DefaultPlayer player = Proxy.getProxyFactory(ProxyStrategy.JDK_DYNAMIC_PROXY).get(RadioPlayer.class, DefaultPlayer.class); - player.on(); - player.play(); - player.off(); - } - - @Test - public void 子类代理1() throws Exception { - Player player = Proxy.getProxyFactory(ProxyStrategy.ASGC_PROXY).get(RadioPlayer.class, Player.class); - player.on(); - player.play(); - player.off(); - } - - @Test - public void 子类代理2() throws Exception { - DefaultPlayer player = Proxy.getProxyFactory(ProxyStrategy.ASGC_PROXY).get(RadioPlayer.class, DefaultPlayer.class); - player.on(); - player.play(); - player.off(); - System.out.println(player.getName()); - } - - @Test - public void 子类代理3() throws Exception { - SoundPlayer player = Proxy.getProxyFactory(ProxyStrategy.ASGC_PROXY).get(RadioPlayer.class, SoundPlayer.class); - player.on(); - player.play(); - player.volumeIncrease(); - player.off(); - } - - @Test - public void 子类代理4() throws Exception { - RadioPlayer player = Proxy.getProxyFactory(ProxyStrategy.ASGC_PROXY).get(RadioPlayer.class, RadioPlayer.class); - player.on(); - player.play(); - player.volumeIncrease(); - player.off(); - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/Test5.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/Test5.java deleted file mode 100644 index 5710b5c5..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/Test5.java +++ /dev/null @@ -1,65 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop; - -import fun.asgc.neutrino.core.util.ReflectUtil; -import org.junit.Test; - -import java.lang.reflect.Method; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/7 - */ -public class Test5 { - - @Test - public void test1() throws Exception { - Aop.intercept(Panda.class, TestInterceptor.class); - Panda panda = Aop.get(Panda.class); - panda.eat(); - panda.say("hello"); - } - - @Test - public void test2() throws Exception { - // 只拦截一个方法 - Method method = ReflectUtil.getMethods(Panda.class).stream().filter(m -> m.getName().equals("say")).findFirst().get(); - Aop.intercept(method, TestInterceptor.class); - - Panda panda = Aop.get(Panda.class); - panda.eat(); - - panda.say("hello"); - } - - /** - * 单例测试 - * @throws Exception - */ - @Test - public void test3() throws Exception{ - Giraffe giraffe = Aop.get(Giraffe.class); - System.out.println(giraffe.getDog() == giraffe.getDog()); - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/TestInterceptor.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/TestInterceptor.java deleted file mode 100644 index 630f28be..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/TestInterceptor.java +++ /dev/null @@ -1,51 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop; - -import fun.asgc.neutrino.core.aop.interceptor.Interceptor; -import lombok.extern.slf4j.Slf4j; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/24 - */ -@Slf4j -public class TestInterceptor implements Interceptor { - - public TestInterceptor() { - System.out.println("拦截器1实例化"); - } - - @Override - public void intercept(Invocation inv) { - try { - log.info("拦截器1 class:{} method:{} args:{} before", inv.getTargetClass().getName(), inv.getTargetMethod().getName(), inv.getArgs()); - inv.invoke(); - log.info("拦截器1 class:{} method:{} args:{} after", inv.getTargetClass().getName(), inv.getTargetMethod().getName(), inv.getArgs()); - } catch (Exception e) { - log.info("拦截器1 class:{} method:{} args:{} error", inv.getTargetClass().getName(), inv.getTargetMethod().getName(), inv.getArgs()); - e.printStackTrace(); - } - } - -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/TestInterceptor2.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/TestInterceptor2.java deleted file mode 100644 index b7e0657e..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/TestInterceptor2.java +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop; - -import fun.asgc.neutrino.core.aop.interceptor.Interceptor; -import lombok.extern.slf4j.Slf4j; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/24 - */ -@Slf4j -public class TestInterceptor2 implements Interceptor { - - public TestInterceptor2() { - System.out.println("拦截器2实例化"); - } - - @Override - public void intercept(Invocation inv) { - try { - log.info("拦截器2 class:{} method:{} args:{} before", inv.getTargetClass().getName(), inv.getTargetMethod().getName(), inv.getArgs()); - inv.invoke(); - log.info("拦截器2 class:{} method:{} args:{} after", inv.getTargetClass().getName(), inv.getTargetMethod().getName(), inv.getArgs()); - } catch (Exception e) { - log.info("拦截器2 class:{} method:{} args:{} error", inv.getTargetClass().getName(), inv.getTargetMethod().getName(), inv.getArgs()); - e.printStackTrace(); - } - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/compiler/Animal.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/compiler/Animal.java deleted file mode 100644 index a2e83c7d..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/compiler/Animal.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop.compiler; - -/** - * @author: aoshiguchen - * @date: 2022/8/18 - */ -public interface Animal { - /** - * 吃 - * @param food 食物 - */ - void eat(String food); -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/compiler/AsgcCompilerTest.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/compiler/AsgcCompilerTest.java deleted file mode 100644 index 65716fc6..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/compiler/AsgcCompilerTest.java +++ /dev/null @@ -1,175 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop.compiler; - -import fun.asgc.neutrino.core.util.ReflectUtil; -import org.junit.Test; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.stream.Stream; - -/** - * - * @author: aoshiguchen - * @date: 2022/8/17 - */ -public class AsgcCompilerTest { - - @Test - public void compileAndLoadClass1() throws ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException { - AsgcCompiler compiler = new AsgcCompiler(); - String code = "package a.b;\n" + - "public class Hello {\n" + - "\tpublic void hello() {\n" + - "\t\tSystem.out.println(\"hello\");\n" + - "\t}\n" + - "}\n"; - Class clazz = compiler.compile("a.b.Hello", code); - Method method = ReflectUtil.getMethods(clazz).stream().filter(m -> m.getName().equals("hello")).findFirst().get(); - Object instance = clazz.newInstance(); - method.invoke(instance); - } - - @Test - public void compileAndLoadClass2() throws ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException { - AsgcCompiler compiler = new AsgcCompiler(); - String code = "package a.b;\n" + - "import fun.asgc.neutrino.core.aop.compiler.Animal;\n" + - "public class Panda implements Animal {\n" + - "\tpublic void eat(String food) {\n" + - "\t\tSystem.out.println(\"熊猫正在吃\" + food);\n" + - "\t}\n" + - "}\n"; - Class clazz = compiler.compile("a.b.Panda", code); - Method method = ReflectUtil.getMethods(clazz).stream().filter(m -> m.getName().equals("eat")).findFirst().get(); - Object instance = clazz.newInstance(); - method.invoke(instance, "竹子"); - } - - @Test - public void compileAndLoadClass3() throws ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException { - AsgcCompiler compiler = new AsgcCompiler(); - compiler.addClasspath("/Users/yangwen/my/tmp/java"); - String code = "package a.b;\n" + - "import fun.asgc.cptest.Player;\n" + - "public class RadioPlayer implements Player {\n" + - "\tpublic void play() {\n" + - "\t\tSystem.out.println(\"收音机播放\");\n" + - "\t}\n" + - "}\n"; - Class clazz = compiler.compile("a.b.RadioPlayer", code); - Method method = ReflectUtil.getMethods(clazz).stream().filter(m -> m.getName().equals("play")).findFirst().get(); - Object instance = clazz.newInstance(); - method.invoke(instance); - } - - @Test - public void compileAndLoadClass4() throws ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException { - AsgcCompiler compiler = new AsgcCompiler(); - compiler.addClasspath("/Users/yangwen/my/tmp/java"); - compiler.addClasspath("/Users/yangwen/my/tmp/java/asgc-package-lab1-1.0-SNAPSHOT.jar"); - String code = "package a.b;\n" + - "import fun.asgc.lab.pkg.lab1.Dog;\n" + - "import fun.asgc.cptest.Player;\n" + - "public class RadioPlayer implements Player {\n" + - "\tpublic void play() {\n" + - "\t\tSystem.out.println(Dog.class);\n" + - "\t\tSystem.out.println(new Dog(\"大黄\").eat(\"骨头\"));\n" + - "\t\tSystem.out.println(\"收音机播放\");\n" + - "\t}\n" + - "}\n"; -// GlobalConfig.setIsSaveGeneratorCode(true); - Class clazz = compiler.compile("a.b.RadioPlayer", code); - Method method = ReflectUtil.getMethods(clazz).stream().filter(m -> m.getName().equals("play")).findFirst().get(); - Object instance = clazz.newInstance(); - method.invoke(instance); - } - - /** - * jar in jar测试 - * - * 使用jdk1.8跑,tools.jar放在classpath下 - * 测试jar in jar - * jar结构: - * asgc-package-lab2.jar - * - BOOT-INF/ - * - classes/fun/asgc/lab/pkg/lab2/ - * - Console.class - * - lib/asgc-package-lab1-1.0-SNAPSHOT.jar - * - BOOT-INF/classes/fun/asgc/lab/pkg/lab1/ - * - Dog.class - */ - @Test - public void compileAndLoadClass5() throws Exception { - AsgcCompiler compiler = new AsgcCompiler(); - compiler.addDependSpringBootJar(AsgcCompilerTest.class.getResource("/asgc-package-lab2.jar").getPath()); - String code = "package a.b;\n" + - "import fun.asgc.lab.pkg.lab2.Console;\n" + - "import fun.asgc.lab.pkg.lab1.Dog;\n" + - "public class Test {\n" + - "\tpublic void execute() {\n" + - "\t\tSystem.out.println(\"1122\");\n" + - "\t}\n" + - "\tpublic void echo(String str){\n" + - "\t\tConsole.println(str);\n" + - "\t}\n" + - "\tpublic String dogEat(String name, String food){\n" + - "\t\treturn new Dog(name).eat(food);\n" + - "\t}\n" + - "}\n"; - System.out.println(code); - Class clazz = compiler.compile("a.b.Test", code); - Method executeMethod = ReflectUtil.getMethods(clazz).stream().filter(m -> m.getName().equals("execute")).findFirst().get(); - Method echoMethod = Stream.of(clazz.getDeclaredMethods()).filter(m -> m.getName().equals("echo")).findFirst().get(); - Method dogEatMethod = Stream.of(clazz.getDeclaredMethods()).filter(m -> m.getName().equals("dogEat")).findFirst().get(); - - Object instance = clazz.newInstance(); - executeMethod.invoke(instance); - echoMethod.invoke(instance, "哈哈哈哈"); - System.out.println(dogEatMethod.invoke(instance, "大黄", "骨头")); - } - - private Object eval(String expression) { - String code = "package fun.asgc.test;\n" + - "import static java.lang.Math.*;\n" + - "public class Calc {\n" + - "\tpublic static Object invoke(){\n" + - "\t\treturn " + expression + ";\n" + - "\t}\n" + - "}\n"; - AsgcCompiler compiler = new AsgcCompiler(); - try { - Class clazz = compiler.compile( "fun.asgc.test.Calc", code); - Method method = ReflectUtil.getMethods(clazz).stream().filter(m -> m.getName().equals("invoke")).findFirst().get(); - return method.invoke(null); - } catch (ClassNotFoundException|IllegalAccessException|InvocationTargetException e) { - e.printStackTrace(); - } - return null; - } - - @Test - public void evalTest() { - System.out.println(eval("1 + max(2*3, pow(2,5)) + 100 - 5 * 40 / (2 * 4)")); - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/compiler/PackageInternalsFinderTest.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/compiler/PackageInternalsFinderTest.java deleted file mode 100644 index 7744160e..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/aop/compiler/PackageInternalsFinderTest.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.aop.compiler; - -import org.junit.Test; - -import javax.tools.JavaFileObject; -import java.io.IOException; -import java.util.List; - -/** - * - * @author: aoshiguchen - * @date: 2022/8/26 - */ -public class PackageInternalsFinderTest { - - @Test - public void testFilePathContainWhitespace() throws IOException { - PackageInternalsFinder finder = new PackageInternalsFinder(this.getClass().getClassLoader()); - List fileObjectList= finder.find("fun.asgc.neutrino.core.aop.compiler"); - System.out.println(fileObjectList); - } - -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/base/NvMapTest.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/base/NvMapTest.java deleted file mode 100644 index fe3dd00b..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/base/NvMapTest.java +++ /dev/null @@ -1,85 +0,0 @@ -package fun.asgc.neutrino.core.base; - -import org.junit.Assert; -import org.junit.Test; - -/** - * @author: aoshiguchen - * @date: 2023/3/1 - */ -public class NvMapTest { - @Test - public void test1() { - Object key1 = new Object(); - NvMap nvMap0 = NvMap.of() - .setAlias("app.server.http.http-port", "aaa") - ; - - NvMap nvMap1 = NvMap.of(nvMap0) - .set("app.server.http.http-port", 8080) - .set("app.server.http.jks_Path", "/123/456") - .set("app.server.websocket.port", "ws-port", 8888) // 设值的同时设置别名 - .set(key1, 1) - .setAlias("app.server.http.http-port", "http-port") - ; - - - NvMap nvMap2 = NvMap.of(nvMap1) - .set("app.server.http.httpPort", 8081) - .set("app.server.http.context-path", "/") - ; - - NvMap nvMap3 = NvMap.of(nvMap2) - .setAlias("app.server.http.http-port", "port") - .setAlias("http-port", "p"); - - Assert.assertTrue(!nvMap1.isEmpty()); - Assert.assertTrue(nvMap1.size() == 4); - Assert.assertTrue(nvMap1.stackSize() == 4); - Assert.assertTrue(nvMap1.get("app.server.http.http-port").equals(8080)); - Assert.assertTrue(nvMap1.get("app.server.http.httpPort").equals(8080)); - Assert.assertTrue(nvMap1.idx(0).equals(8080)); - Assert.assertTrue(nvMap1.get("app.server.http.jks_Path").equals("/123/456")); - Assert.assertTrue(nvMap1.get("app.server.http.jksPath").equals("/123/456")); - Assert.assertTrue(nvMap1.idx(1).equals("/123/456")); - Assert.assertTrue(nvMap1.containsKey("app.server.http.http-port")); - Assert.assertTrue(nvMap1.containsKey(key1)); - Assert.assertFalse(nvMap1.containsKey(new Object())); - - Assert.assertTrue(!nvMap2.isEmpty()); - Assert.assertTrue(nvMap2.size() == 2); - Assert.assertTrue(nvMap2.stackSize() == 6); - Assert.assertTrue(nvMap2.get("app.server.http.http-port").equals(8081)); - Assert.assertTrue(nvMap2.get("app.server.http.httpPort").equals(8081)); - Assert.assertTrue(nvMap2.get("app.server.http.jks-path") == null); - Assert.assertTrue(nvMap2.get("app.server.http.jksPath") == null); - Assert.assertTrue(nvMap2.get("app.server.http.context-path").equals("/")); - - Assert.assertTrue(nvMap2.stackGet("app.server.http.jks-path").equals("/123/456")); - Assert.assertTrue(nvMap2.stackGet("app.server.http.jksPath").equals("/123/456")); - Assert.assertTrue(nvMap2.stackGet("app.server.http.context-path").equals("/")); - - Assert.assertTrue(nvMap3.isEmpty()); - Assert.assertTrue(!nvMap3.isStackEmpty()); - Assert.assertTrue(nvMap3.size() == 0); - Assert.assertTrue(nvMap3.stackSize() == 6); - Assert.assertTrue(nvMap3.get("app.server.http.jks-path") == null); - Assert.assertTrue(nvMap3.get("app.server.http.jksPath") == null); - Assert.assertTrue(nvMap3.get("app.server.http.context-path") == null); - Assert.assertTrue(nvMap3.stackGet("app.server.http.jks-path").equals("/123/456")); - Assert.assertTrue(nvMap3.stackGet("app.server.http.jksPath").equals("/123/456")); - Assert.assertTrue(nvMap3.stackGet("app.server.http.context-path").equals("/")); - - Assert.assertTrue(nvMap3.stackGetOrDefault("app.server.http.timeout", 60000).equals(60000)); - - Assert.assertTrue(nvMap3.takeStr("app.server.http.http-port").equals("8081")); - Assert.assertNull(nvMap3.take(null)); - Assert.assertTrue(nvMap3.takeStr("httpPort").equals("8081")); - Assert.assertTrue(nvMap3.takeInt("http-port").equals(8081)); - Assert.assertTrue(nvMap3.takeInt("port").equals(8081)); - // 注意:第3层的别名p,指向了第1层的别名http-port - Assert.assertTrue(nvMap3.takeInt("p").equals(8081)); - Assert.assertTrue(nvMap3.takeStr("aaa").equals("8081")); - Assert.assertTrue(nvMap3.takeInt("wsPort").equals(8888)); - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/base/NvMapsTest.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/base/NvMapsTest.java deleted file mode 100644 index fda21521..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/base/NvMapsTest.java +++ /dev/null @@ -1,60 +0,0 @@ -package fun.asgc.neutrino.core.base; - -import org.junit.Test; - -import java.io.IOException; - -/** - * @author: aoshiguchen - * @date: 2023/3/6 - */ -public class NvMapsTest { - - /** - * 先给电脑设置环境变量,然后重启idea - * EUTRINO_PROXY=http-port=6000:app-name=neutrino-proxy-client - * @throws IOException - */ - @Test - public void test1() throws IOException { - // 创建NvMaps实例 - NvMaps nvMaps = NvMaps.of(); - - // 阶段1:设置内部默认值 - nvMaps.setKv("neutrino.application.name", "app-name",null); - nvMaps.setKv("neutrino.http.enable", true); - nvMaps.setKv("neutrino.http.port", "httpPort",null); - nvMaps.setKv("neutrino.http.context-path", "context-path", "/"); - nvMaps.stageDone(); - - // 阶段2:内部配置文件 - nvMaps.loadFile(NvMapsTest.class.getResource("/application.yml").getPath()); - nvMaps.stageDone(); - - // 阶段3:环境变量 - nvMaps.loadEnvironmentVariable("NEUTRINO_PROXY"); - nvMaps.stageDone(); - - // 结算4:外部配置文件 -// nvMaps.loadFile(NvMapsTest.class.getResource("/aaa.json").getPath()); - nvMaps.loadFile(NvMapsTest.class.getResource("/aaa.properties").getPath()); - nvMaps.stageDone(); - - // 阶段5:启动参数 - String[] mainArgs = new String[]{ - "httpPort=8100" - }; - nvMaps.loadMainArgs(mainArgs); - nvMaps.stageDone(); - - // 获取NvMap实例 - NvMap nvMap = nvMaps.getNvMap(); - - System.out.println(nvMap.takeInt("httpPort")); - System.out.println(nvMap.takeInt("neutrino.http.port")); - - System.out.println(nvMap.takeStr("appName")); - System.out.println(nvMap.takeStr("neutrino.application.name")); - } - -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/base/event/Test1.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/base/event/Test1.java deleted file mode 100644 index 248951f1..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/base/event/Test1.java +++ /dev/null @@ -1,81 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.base.event; - -import com.alibaba.fastjson.JSONObject; -import com.google.common.collect.Sets; -import fun.asgc.neutrino.core.util.SystemUtil; -import lombok.Data; -import lombok.experimental.Accessors; -import lombok.extern.slf4j.Slf4j; -import org.junit.Test; - -/** - * 应用事件测试 - * 1、异步执行 - * 2、业务解耦 - * 3、topic订阅 - * 4、支持多种模式无缝切换(本地模式、redis模式、rocketMQ模式、MQTT模式等) - * 5、不支持事务消息 - * @author: aoshiguchen - * @date: 2022/10/3 - */ -@Slf4j -public class Test1 { - private ApplicationEventChannel channel = new ApplicationEventChannel<>(); - private ApplicationEventPublisher publisher = new ApplicationEventPublisher<>(); - - { - publisher.bindChannel(channel); - } - - @Test - public void test1() { - ApplicationEventReceiver receiver = new ApplicationEventReceiver() { - @Override - public void receive(ApplicationEvent msg) { - log.info("data:{}", JSONObject.toJSONString(msg.data())); - } - }; -// receiver.setTopic("/**"); -// receiver.setTags(Sets.newHashSet("create")); - channel.registerReceiver(receiver); - - ApplicationEvent event = new ApplicationEvent<>(); -// event.context().setId("123"); - event.context().setTopic("/student/create"); - event.context().setTags(Sets.newHashSet("create")); - event.setData(new Student().setId("1").setName("张三").setAge(28).setSex("男")); - publisher.publish(event); - - SystemUtil.waitProcessDestroy().sync(); - } - - @Accessors(chain = true) - @Data - public static class Student { - private String id; - private String name; - private Integer age; - private String sex; - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/base/event/Test2.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/base/event/Test2.java deleted file mode 100644 index d93e8d68..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/base/event/Test2.java +++ /dev/null @@ -1,94 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.base.event; - -import com.alibaba.fastjson.JSONObject; -import com.google.common.collect.Sets; -import fun.asgc.neutrino.core.util.SystemUtil; -import lombok.Data; -import lombok.experimental.Accessors; -import lombok.extern.slf4j.Slf4j; -import org.junit.Test; - -/** - * 应用事件测试 - * 1、异步执行 - * 2、业务解耦 - * 3、topic订阅 - * 4、支持多种模式无缝切换(本地模式、redis模式、rocketMQ模式、MQTT模式等) - * 5、不支持事务消息 - * @author: aoshiguchen - * @date: 2022/10/3 - */ -@Slf4j -public class Test2 { - private ApplicationEventChannel channel = new ApplicationEventChannel<>(); - private MyTestChannel myTestChannel = new MyTestChannel(); - private ApplicationEventPublisher publisher = new ApplicationEventPublisher<>(); - - { - channel.connectChannel(myTestChannel); - publisher.bindChannel(channel); - } - - @Test - public void test1() { - ApplicationEventReceiver receiver1 = new ApplicationEventReceiver() { - @Override - public void receive(ApplicationEvent msg) { - log.info("receiver1 data:{}", JSONObject.toJSONString(msg.data())); - } - }; - ApplicationEventReceiver receiver2 = new ApplicationEventReceiver() { - @Override - public void receive(ApplicationEvent msg) { - log.info("receiver2 data:{}", JSONObject.toJSONString(msg.data())); - } - }; -// receiver.setTopic("/**"); -// receiver.setTags(Sets.newHashSet("create")); - channel.registerReceiver(receiver1); - myTestChannel.registerReceiver(receiver2); - - ApplicationEvent event = new ApplicationEvent<>(); -// event.context().setId("123"); - event.context().setTopic("/student/create"); - event.context().setTags(Sets.newHashSet("create")); - event.setData(new Student().setId("1").setName("张三").setAge(28).setSex("男")); - publisher.publish(event); - - SystemUtil.waitProcessDestroy().sync(); - } - - @Accessors(chain = true) - @Data - public static class Student { - private String id; - private String name; - private Integer age; - private String sex; - } - - public static class MyTestChannel extends ApplicationEventChannel { - - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/base/event/Test3.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/base/event/Test3.java deleted file mode 100644 index 7ca0dd9b..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/base/event/Test3.java +++ /dev/null @@ -1,83 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.base.event; - -import com.alibaba.fastjson.JSONObject; -import com.google.common.collect.Sets; -import fun.asgc.neutrino.core.util.SystemUtil; -import lombok.Data; -import lombok.experimental.Accessors; -import lombok.extern.slf4j.Slf4j; -import org.junit.Test; - -/** - * 应用事件测试 - * 1、异步执行 - * 2、业务解耦 - * 3、topic订阅 - * 4、支持多种模式无缝切换(本地模式、redis模式、rocketMQ模式、MQTT模式等) - * 5、不支持事务消息 - * @author: aoshiguchen - * @date: 2022/10/3 - */ -@Slf4j -public class Test3 { - private SimpleApplicationEventManager simpleApplicationEventManager = new SimpleApplicationEventManager<>(this); - - @Test - public void test1() { - ApplicationEventReceiver receiver1 = new ApplicationEventReceiver() { - @Override - public void receive(ApplicationEvent msg) { - log.info("receiver1 data:{}", JSONObject.toJSONString(msg.data())); - } - }; - receiver1.setTopic("/*"); - receiver1.setTags(Sets.newHashSet("tag1")); - ApplicationEventReceiver receiver2 = new ApplicationEventReceiver() { - @Override - public void receive(ApplicationEvent msg) { - log.info("receiver2 data:{}", JSONObject.toJSONString(msg.data())); - } - }; - receiver2.setTags(Sets.newHashSet("tag2")); - simpleApplicationEventManager.registerReceiver(receiver1); - simpleApplicationEventManager.registerReceiver(receiver2); - - simpleApplicationEventManager.publish("/aaa", Sets.newHashSet("tag1"), new Student().setId("1").setName("张三").setAge(28).setSex("男")); - - SystemUtil.waitProcessDestroy().sync(); - } - - @Accessors(chain = true) - @Data - public static class Student { - private String id; - private String name; - private Integer age; - private String sex; - } - - public static class MyTestChannel extends ApplicationEventChannel { - - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/base/type/Test1.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/base/type/Test1.java deleted file mode 100644 index f3c7b9da..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/base/type/Test1.java +++ /dev/null @@ -1,55 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.base.type; - -import org.junit.Test; - -import java.lang.reflect.Field; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.List; - -/** - * @author: aoshiguchen - * @date: 2022/9/24 - */ -public class Test1 { - @Test - public void test() throws NoSuchFieldException { - Field param = GenericClazz.class.getDeclaredField("param"); - Type genericType = param.getGenericType(); - ParameterizedType type = (ParameterizedType) genericType; - Type[] typeArguments = type.getActualTypeArguments(); - System.out.println("从 HashMap> 中获取 String:" + typeArguments[0]); - System.out.println("从 HashMap> 中获取 List :" + typeArguments[1]); - System.out.println( - "从 HashMap> 中获取 List :" + ((ParameterizedType) typeArguments[1]).getRawType()); - System.out.println("从 HashMap> 中获取 Integer:" + ((ParameterizedType) typeArguments[1]) - .getActualTypeArguments()[0]); - System.out.println("从 HashMap> 中获取父类型:"+param.getType().getGenericSuperclass()); - } - - public static class GenericClazz { - private HashMap> param; - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/base/type/Test2.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/base/type/Test2.java deleted file mode 100644 index 27a58f51..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/base/type/Test2.java +++ /dev/null @@ -1,49 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.base.type; - -import org.junit.Test; - -import java.util.HashMap; -import java.util.List; - -/** - * @author: aoshiguchen - * @date: 2022/9/25 - */ -public class Test2 { - - @Test - public void test1() throws NoSuchFieldException { - ResolvableType param = ResolvableType.forField(GenericClazz.class.getDeclaredField("param")); - System.out.println("从 HashMap> 中获取 String:" + param.getGeneric(0).resolve()); - System.out.println("从 HashMap> 中获取 List :" + param.getGeneric(1)); - System.out.println( - "从 HashMap> 中获取 List :" + param.getGeneric(1).resolve()); - System.out.println("从 HashMap> 中获取 Integer:" + param.getGeneric(1,0)); - System.out.println("从 HashMap> 中获取父类型:" +param.getSuperType()); - } - - public static class GenericClazz { - private HashMap> param; - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/BeanIdentityTest.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/BeanIdentityTest.java deleted file mode 100644 index 40712ac9..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/BeanIdentityTest.java +++ /dev/null @@ -1,61 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.bean; - -import fun.asgc.neutrino.core.aop.Animal; -import fun.asgc.neutrino.core.bean.test1.Cat; -import org.junit.Test; - -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/1 - */ -public class BeanIdentityTest { - - @Test - public void test1() { - System.out.println(new BeanIdentity("animal", Animal.class).equals(new BeanIdentity("animal", Animal.class))); - System.out.println(new BeanIdentity("animal", Animal.class) == new BeanIdentity("animal", Animal.class)); - } - - @Test - public void test2() { - Map map = new HashMap<>(); - map.put(new BeanIdentity("1", String.class), "1"); - map.put(new BeanIdentity("1", String.class), "2"); - System.out.println(map); - } - - @Test - public void test3() { - Cat cat = new Cat(); - Map a = new ConcurrentHashMap<>(); - a.put(new BeanIdentity("cat", Cat.class), 1); - System.out.println(a.get(new BeanIdentity("cat", Cat.class))); - } - -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test1/Animal.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test1/Animal.java deleted file mode 100644 index 72a5a592..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test1/Animal.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.bean.test1; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/4 - */ -public class Animal { - - public void call() { - System.out.println("未知动物的叫声"); - } - -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test1/Cat.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test1/Cat.java deleted file mode 100644 index 2cef5f5d..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test1/Cat.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.bean.test1; - -import fun.asgc.neutrino.core.annotation.Component; -import fun.asgc.neutrino.core.annotation.Init; -import fun.asgc.neutrino.core.annotation.NonIntercept; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/4 - */ -@NonIntercept -@Component -public class Cat extends Animal { - - @Init - public void a() { - System.out.println("11111"); - } - - @Override - public void call() { - System.out.println("喵喵喵"); - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test1/Dog.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test1/Dog.java deleted file mode 100644 index 6057a90c..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test1/Dog.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.bean.test1; - -import fun.asgc.neutrino.core.annotation.Component; -import fun.asgc.neutrino.core.annotation.NonIntercept; -import lombok.Data; -import lombok.experimental.Accessors; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/4 - */ -@Accessors(chain = true) -@Data -@Component -@NonIntercept -public class Dog extends Animal { - private String color; - @Override - public void call() { - System.out.println("汪汪汪"); - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test1/FactoryBean1.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test1/FactoryBean1.java deleted file mode 100644 index 14f96c45..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test1/FactoryBean1.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.bean.test1; - -import fun.asgc.neutrino.core.annotation.Component; -import fun.asgc.neutrino.core.annotation.NonIntercept; -import fun.asgc.neutrino.core.bean.BeanIdentity; -import fun.asgc.neutrino.core.bean.FactoryBean; -import fun.asgc.neutrino.core.exception.BeanException; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/4 - */ -@NonIntercept -@Component -public class FactoryBean1 implements FactoryBean { - - @Override - public Dog getInstance() throws BeanException { - return new Dog().setColor("黄色"); - } - - @Override - public BeanIdentity getBeanIdentity() { - return new BeanIdentity("dog10", Dog.class); - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test1/Launcher.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test1/Launcher.java deleted file mode 100644 index a0aa7f36..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test1/Launcher.java +++ /dev/null @@ -1,92 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.bean.test1; - -import fun.asgc.neutrino.core.annotation.*; -import fun.asgc.neutrino.core.base.GlobalConfig; -import fun.asgc.neutrino.core.bean.BeanMatchMode; -import fun.asgc.neutrino.core.bean.factory.SimpleBeanFactory; -import fun.asgc.neutrino.core.context.NeutrinoLauncher; - -import java.util.List; -import java.util.Set; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/4 - */ -@NeutrinoApplication -public class Launcher { - - @Autowired - private Cat cat; - @Autowired(matchMode = BeanMatchMode.ByName, value = "cat") - private Animal cat2; - @Autowired(matchMode = BeanMatchMode.ByType) - private Cat cat3; - @Autowired(matchMode = BeanMatchMode.ByType, parameterTypes = Cat.class) - private List cats1; - @Autowired(value = "cat", matchMode = BeanMatchMode.ByName, parameterTypes = Cat.class) - private List cats2; - - @Autowired - private Dog dog; - @Autowired("dog") - private Dog dog2; - @Autowired - private Dog dog10; - @Autowired - private Dog dog11; - @Autowired(value = "dog", matchMode = BeanMatchMode.ByName, parameterTypes = Dog.class) - private Object[] dogs1; - @Autowired(matchMode = BeanMatchMode.ByType, parameterTypes = Dog.class) - private Set dogs2; - @Autowired(matchMode = BeanMatchMode.ByType, parameterTypes = Animal.class) - private List list; - - @Autowired - private SimpleBeanFactory applicationBeanFactory; - - @Init - public void init() { - System.out.println("初始化---"); -// cat.call(); -// dog.call(); - } - - @Destroy - public void destroy() { - System.out.println("销毁---"); - } - - public static void main(String[] args) { - GlobalConfig.setIsPrintGeneratorCode(true); - - NeutrinoLauncher.run(Launcher.class, args).sync(); - } - - @Bean - public Dog dog11() { - return new Dog().setColor("red"); - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test1/Player.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test1/Player.java deleted file mode 100644 index 9ed5e718..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test1/Player.java +++ /dev/null @@ -1,49 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.bean.test1; - -import fun.asgc.neutrino.core.annotation.Component; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/7 - */ - -@Component -public interface Player { - - /** - * 开机 - */ - void on(); - - /** - * 关机 - */ - void off(); - - /** - * 播放 - */ - void play(); -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test1/RadioPlayer.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test1/RadioPlayer.java deleted file mode 100644 index ee48b383..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test1/RadioPlayer.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.bean.test1; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/7 - */ -public class RadioPlayer implements Player { - - @Override - public void on() { - System.out.println("收音机开机"); - } - - @Override - public void off() { - System.out.println("收音机关机"); - } - - @Override - public void play() { - System.out.println("收音机播放"); - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test1/Test1.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test1/Test1.java deleted file mode 100644 index d11133d9..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test1/Test1.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.bean.test1; - -import fun.asgc.neutrino.core.annotation.Autowired; -import fun.asgc.neutrino.core.annotation.Component; -import fun.asgc.neutrino.core.context.ApplicationRunner; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/7 - */ -@Component -public class Test1 implements ApplicationRunner { - - @Autowired - private Player player; - - @Override - public void run(String[] args) { - player.on(); - player.play(); - player.off(); - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test2/Test1.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test2/Test1.java deleted file mode 100644 index 0cce39f6..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test2/Test1.java +++ /dev/null @@ -1,73 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.bean.test2; - -import org.junit.Test; - -import java.beans.IntrospectionException; -import java.beans.PropertyDescriptor; -import java.lang.reflect.InvocationTargetException; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/5 - */ -public class Test1 { - - @Test - public void test1() throws IntrospectionException, InvocationTargetException, IllegalAccessException { - PropertyDescriptor pd1= new PropertyDescriptor("name", Person.class); - PropertyDescriptor pd2= new PropertyDescriptor("age", Person.class, "getAge", "setAge"); - - Person person = new Person(); - person.setName("张三"); - - pd1.getWriteMethod().invoke(person, "李四"); - - System.out.println(pd1.getReadMethod().invoke(person)); - - pd2.getWriteMethod().invoke(person, 20); - System.out.println(pd2.getReadMethod().invoke(person)); - } - - public static class Person { - private String name; - private int age; - - public String isName() { - return name; - } - - public int getAge() { - return age; - } - - public void setName(String name) { - this.name = name; - } - - public void setAge(int age) { - this.age = age; - } - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test3/A.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test3/A.java deleted file mode 100644 index d69baa86..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test3/A.java +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.bean.test3; - -/** - * @author: aoshiguchen - * @date: 2022/7/8 - */ -public interface A { - - Dog dog(); - - Person person(Dog dog); -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test3/Dog.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test3/Dog.java deleted file mode 100644 index bd234525..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test3/Dog.java +++ /dev/null @@ -1,43 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.bean.test3; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/8 - */ -public class Dog { - private String name; - public Dog(String name) { - this.name = name; - System.out.println(String.format("%s出生了 %s", name, this.hashCode())); - } - - public void call() { - System.out.println(String.format("%s叫:汪汪汪", this.name)); - } - - public String getName() { - return name; - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test3/Launcher.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test3/Launcher.java deleted file mode 100644 index 4b26ddd5..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test3/Launcher.java +++ /dev/null @@ -1,75 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.bean.test3; - -import fun.asgc.neutrino.core.annotation.Autowired; -import fun.asgc.neutrino.core.annotation.Bean; -import fun.asgc.neutrino.core.annotation.NeutrinoApplication; -import fun.asgc.neutrino.core.annotation.NonIntercept; -import fun.asgc.neutrino.core.context.ApplicationRunner; -import fun.asgc.neutrino.core.context.NeutrinoLauncher; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/8 - */ -@NonIntercept(false) -@NeutrinoApplication -public class Launcher implements ApplicationRunner { - @Autowired - private Person person; - @Autowired - private Person person2; - - @Override - public void run(String[] args) { - person.walkTheDog(); - System.out.println("---------------------"); - person2.walkTheDog(); - } - - public static void main(String[] args) { - NeutrinoLauncher.run(Launcher.class, args).sync(); - } - - @Bean - public Dog dog() { - System.out.println("hhahahahahahahahaah"); - return new Dog("大黄"); - } - - @Bean - public Person person(@Autowired("dog") Dog dog) { - Person person = new Person("张三"); - person.setPet(dog); - return person; - } - - @Bean - public Person person2() { - Person person = new Person("李四"); - person.setPet(dog()); - System.out.println("-----------------" + (dog() == dog())); - return person; - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test3/Person.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test3/Person.java deleted file mode 100644 index 192e298e..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test3/Person.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.bean.test3; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/8 - */ -public class Person { - private String name; - private Dog pet; - - public Person(String name) { - this.name = name; - System.out.println(String.format("%s出生了 %s", name, this.hashCode())); - } - - public void setPet(Dog pet) { - this.pet = pet; - } - - public void walkTheDog() { - System.out.println(String.format("%s在遛狗(%s %s)", this.name, pet.getName(), pet.hashCode())); - pet.call(); - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test3/TestInterceptor.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test3/TestInterceptor.java deleted file mode 100644 index db5396e7..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test3/TestInterceptor.java +++ /dev/null @@ -1,52 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.bean.test3; - -import fun.asgc.neutrino.core.aop.Invocation; -import fun.asgc.neutrino.core.aop.interceptor.Interceptor; -import lombok.extern.slf4j.Slf4j; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/24 - */ -@Slf4j -public class TestInterceptor implements Interceptor { - - public TestInterceptor() { - log.info("拦截器1实例化"); - } - - @Override - public void intercept(Invocation inv) { - try { - log.info("拦截器1 class:{} method:{} args:{} before", inv.getTargetClass().getName(), inv.getTargetMethod().getName(), inv.getArgs()); - inv.invoke(); - log.info("拦截器1 class:{} method:{} args:{} after", inv.getTargetClass().getName(), inv.getTargetMethod().getName(), inv.getArgs()); - } catch (Exception e) { - log.info("拦截器1 class:{} method:{} args:{} error", inv.getTargetClass().getName(), inv.getTargetMethod().getName(), inv.getArgs()); - e.printStackTrace(); - } - } - -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test4/Launcher.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test4/Launcher.java deleted file mode 100644 index 722db9d9..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test4/Launcher.java +++ /dev/null @@ -1,61 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.bean.test4; - -import fun.asgc.neutrino.core.annotation.NeutrinoApplication; -import fun.asgc.neutrino.core.annotation.NonIntercept; -import fun.asgc.neutrino.core.aop.support.Async; -import fun.asgc.neutrino.core.context.ApplicationRunner; -import fun.asgc.neutrino.core.context.NeutrinoLauncher; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/8 - */ -@NonIntercept(false) -@NeutrinoApplication -public class Launcher implements ApplicationRunner { - - - @Override - public void run(String[] args) { - System.out.println("1111111"); - hello(); - System.out.println("2222"); - } - - public static void main(String[] args) { - NeutrinoLauncher.run(Launcher.class, args).sync(); - } - - @Async - public void hello() { - try { - Thread.sleep(5000); - System.out.println("hello"); - } catch (Exception e) { - - } - } - -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test5/Launcher.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test5/Launcher.java deleted file mode 100644 index cd9771f6..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test5/Launcher.java +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.bean.test5; - -import fun.asgc.neutrino.core.annotation.NeutrinoApplication; -import fun.asgc.neutrino.core.context.NeutrinoLauncher; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/31 - */ -@NeutrinoApplication -public class Launcher { - - public static void main(String[] args) { - NeutrinoLauncher.run(Launcher.class, args); - } - -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test5/PreLoad1.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test5/PreLoad1.java deleted file mode 100644 index 5569489d..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test5/PreLoad1.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.bean.test5; - -import fun.asgc.neutrino.core.annotation.PreLoad; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/31 - */ -@PreLoad -public class PreLoad1 { - - public static void preLoad(String[] args) { - System.out.println("11"); - } - -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test5/Runner1.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test5/Runner1.java deleted file mode 100644 index 9f88a9e1..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test5/Runner1.java +++ /dev/null @@ -1,47 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.bean.test5; - -import fun.asgc.neutrino.core.annotation.Component; -import fun.asgc.neutrino.core.annotation.Order; -import fun.asgc.neutrino.core.context.ApplicationRunner; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/31 - */ -@Order(0) -@Component -public class Runner1 implements ApplicationRunner { - - @Override - public void run(String[] args) throws Exception { - System.out.println("1111"); - try { - Thread.sleep(3000); - } catch (Exception e) { - // - } - System.out.println("----11111"); - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test5/Runner2.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test5/Runner2.java deleted file mode 100644 index 54d22127..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/bean/test5/Runner2.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.bean.test5; - -import fun.asgc.neutrino.core.annotation.Component; -import fun.asgc.neutrino.core.annotation.Order; -import fun.asgc.neutrino.core.context.ApplicationRunner; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/31 - */ -@Order(1) -@Component -public class Runner2 implements ApplicationRunner { - - @Override - public void run(String[] args) throws Exception { - System.out.println("2222"); - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/config/YmlConfigurationParserTest.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/config/YmlConfigurationParserTest.java deleted file mode 100644 index 941348ba..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/config/YmlConfigurationParserTest.java +++ /dev/null @@ -1,126 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package fun.asgc.neutrino.core.config; - -import com.alibaba.fastjson.JSONObject; -import fun.asgc.neutrino.core.annotation.Configuration; -import fun.asgc.neutrino.core.annotation.Value; -import fun.asgc.neutrino.core.config.impl.YmlConfigurationParser; -import fun.asgc.neutrino.core.util.FileUtil; -import lombok.Data; -import org.junit.Test; - -import java.io.FileNotFoundException; -import java.util.List; -import java.util.Set; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/16 - */ -public class YmlConfigurationParserTest { - - @Test - public void test1() throws FileNotFoundException { - ConfigurationParser parser = new YmlConfigurationParser(); - Config1 config1 = parser.parse(FileUtil.getInputStream("classpath:/test1.yml"), Config1.class); - System.out.println(JSONObject.toJSONString(config1)); - } - - @Test - public void test2() throws FileNotFoundException { - ConfigurationParser parser = new YmlConfigurationParser(); - Config1 config1 = parser.parse(Config1.class); - System.out.println(JSONObject.toJSONString(config1)); - } - - @Test - public void test3() throws FileNotFoundException { - ConfigurationParser parser = new YmlConfigurationParser(); - Config2 config2 = parser.parse(Config2.class); - System.out.println(JSONObject.toJSONString(config2)); - } - - @Configuration(file = "test1.yml") - @Data - public static class Config1 { - @Value("server") - private Server serve; - private Integer a; - private String b; - private C c; - @Value("server") - private Object server; - @Value("c") - private Object cc; - - @Data - public static class Server { - private String name; - private int port; - } - - @Data - public static class C { - private D d; - public static class D { - private int e; - private Long f; - private String g; - private List h; - @Value("f") - private Integer ff; - @Value("h") - private Set hh; - @Value("h") - private String[] hhh; - private Integer[] i; - @Value("i") - private List ii; - @Value("i") - private Object iii; - } - } - } - - @Configuration(file = "test1.yml", prefix = "c.d") - public static class Config2 { - private int e; - private Long f; - private String g; - private List h; - @Value("f") - private Integer ff; - @Value("h") - private Set hh; - @Value("h") - private String[] hhh; - private Integer[] i; - @Value("i") - private List ii; - @Value("i") - private Object iii; - } - -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/dao/DaoTest.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/dao/DaoTest.java deleted file mode 100644 index 6bd401bf..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/dao/DaoTest.java +++ /dev/null @@ -1,139 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.dao; - -import com.zaxxer.hikari.HikariDataSource; -import fun.asgc.neutrino.core.db.annotation.Column; -import fun.asgc.neutrino.core.db.annotation.Id; -import lombok.Data; -import lombok.ToString; -import lombok.experimental.Accessors; -import org.junit.Test; - -import javax.activation.DataSource; -import java.sql.SQLException; -import java.util.Date; -import java.util.List; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/28 - */ -public class DaoTest { - private HikariDataSource dataSource; - private DBType dbType; - - { - dataSource = new HikariDataSource(); - dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf8"); - dataSource.setUsername("root"); - dataSource.setPassword("YWasgc@10520"); - dbType = DBType.MYSQL; - } - - @Test - public void add() throws SQLException { - Dao userDao = new DefaultDaoImpl<>(dataSource, dbType, User.class); - User user = new User(); - user.setId(4L); - user.setName("赵六"); - user.setAge(24); - user.setEmail("zhaoliu@qq.com"); - user.setSex("女"); - user.setCreateTime22(new Date()); - userDao.add(user); - } - - @Test - public void findOneById() throws SQLException { - Dao userDao = new DefaultDaoImpl<>(dataSource, dbType, User.class); - User user = userDao.findOneById(3); - System.out.println(user); - } - - @Test - public void findOne1() throws SQLException { - Dao userDao = new DefaultDaoImpl<>(dataSource, dbType, User.class); - User user = userDao.findOne(new User() - .setId(1L), "id"); - System.out.println(user); - } - - @Test - public void findOne2() throws SQLException { - Dao userDao = new DefaultDaoImpl<>(dataSource, dbType, User.class); - User user = userDao.findOne(new User() - .setAge(23), "age"); - System.out.println(user); - } - - @Test - public void findOne3() throws SQLException { - Dao userDao = new DefaultDaoImpl<>(dataSource, dbType, User.class); - User user = userDao.findOne(new User() - .setAge(23) - .setName("张三"), "age", "name"); - System.out.println(user); - } - - @Test - public void find1() throws SQLException { - Dao userDao = new DefaultDaoImpl<>(dataSource, dbType, User.class); - List userList = userDao.find(); - System.out.println(userList); - } - - @Test - public void find2() throws SQLException { - Dao userDao = new DefaultDaoImpl<>(dataSource, dbType, User.class); - List userList = userDao.find(new User().setAge(21), "age"); - System.out.println(userList); - } - - @Test - public void count1() throws SQLException { - Dao userDao = new DefaultDaoImpl<>(dataSource, dbType, User.class); - System.out.println(userDao.count()); - } - - @Test - public void count2() throws SQLException { - Dao userDao = new DefaultDaoImpl<>(dataSource, dbType, User.class); - System.out.println(userDao.count(new User().setAge(21), "age")); - } - - @ToString - @Accessors(chain = true) - @Data - public static class User { - @Id - private Long id; - private String name; - private Integer age; - private String email; - private String sex; - @Column("create_time") - private Date createTime22; - private Date updateTime; - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/dao/SqlDialectForMysqlTest.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/dao/SqlDialectForMysqlTest.java deleted file mode 100644 index 2e29b5fe..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/dao/SqlDialectForMysqlTest.java +++ /dev/null @@ -1,63 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.dao; - -import fun.asgc.neutrino.core.db.annotation.Id; -import lombok.Data; -import lombok.experimental.Accessors; -import org.junit.Test; - -import java.util.Date; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/28 - */ -public class SqlDialectForMysqlTest { - - @Test - public void test1() { - SqlDialect sqlDialect = new SqlDialectForMysql(); - User user = new User(); - user.setName("11'"); - user.setAge(20); - user.setSex("男"); - user.setEmail("11@qq.com"); - user.setCreateTime(new Date()); - System.out.println(sqlDialect.add(user)); - } - - - @Accessors(chain = true) - @Data - public static class User { - @Id - private Long id; - private String name; - private Integer age; - private String email; - private String sex; - private Date createTime; - private Date updateTime; - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/mapper/Configuration.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/mapper/Configuration.java deleted file mode 100644 index 00b568eb..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/mapper/Configuration.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.mapper; - -import com.zaxxer.hikari.HikariDataSource; -import fun.asgc.neutrino.core.annotation.Bean; -import fun.asgc.neutrino.core.annotation.Component; -import fun.asgc.neutrino.core.annotation.Order; -import fun.asgc.neutrino.core.db.template.JdbcTemplate; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/28 - */ -@Order(0) -@Component -public class Configuration { - - @Bean - public JdbcTemplate jdbcTemplate() { - HikariDataSource dataSource = new HikariDataSource(); - dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf8"); - dataSource.setUsername("root"); - dataSource.setPassword("YWasgc@10520"); - return new JdbcTemplate(dataSource); - } - -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/mapper/Launcher.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/mapper/Launcher.java deleted file mode 100644 index 1cc68487..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/mapper/Launcher.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.mapper; - -import fun.asgc.neutrino.core.annotation.*; -import fun.asgc.neutrino.core.context.NeutrinoLauncher; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/28 - */ -@NeutrinoApplication -public class Launcher { - public static void main(String[] args) { - NeutrinoLauncher.runSync(Launcher.class, args); - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/mapper/Test1.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/mapper/Test1.java deleted file mode 100644 index c04e13ea..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/mapper/Test1.java +++ /dev/null @@ -1,66 +0,0 @@ -/** - * Copyright (C) 2018-2022 Zeyi information technology (Shanghai) Co., Ltd. - *

- * All right reserved. - *

- * This software is the confidential and proprietary - * information of Zeyi Company of China. - * ("Confidential Information"). You shall not disclose - * such Confidential Information and shall use it only - * in accordance with the terms of the contract agreement - * you entered into with Zeyi inc. - */ -package fun.asgc.neutrino.core.db.mapper; - -import com.alibaba.fastjson.JSONObject; -import fun.asgc.neutrino.core.annotation.Autowired; -import fun.asgc.neutrino.core.annotation.Component; -import fun.asgc.neutrino.core.annotation.Init; -import fun.asgc.neutrino.core.aop.interceptor.InnerGlobalInterceptor; -import fun.asgc.neutrino.core.context.ApplicationRunner; -import lombok.extern.slf4j.Slf4j; - -import java.util.Date; -import java.util.List; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/28 - */ -@Slf4j -@Component -public class Test1 implements ApplicationRunner { - @Autowired - private UserMapper userMapper; - @Autowired - private TestGlobalExceptionHandler testGlobalExceptionHandler; - - @Init - public void init() { - log.info("初始化,注册全局异常拦截器{}...", testGlobalExceptionHandler.hashCode()); - InnerGlobalInterceptor.registerExceptionHandler(testGlobalExceptionHandler); - } - - @Override - public void run(String[] args) { - User user = userMapper.findOneById(1L); - log.info("查询结果1:{}", JSONObject.toJSONString(user)); - List userList = userMapper.findAll(); - log.info("查询结果2:{}", JSONObject.toJSONString(userList)); - log.info("查询结果3:{}", userMapper.count()); - - User user2 = new User(); - user2.setId(6L); - user2.setName("李八"); - user2.setAge(24); - user2.setEmail("liba@qq.com"); - user2.setSex("男"); - user2.setCreateTime(new Date()); - try { - System.out.println(userMapper.add(user2)); - } catch (Exception e) { - e.printStackTrace(); - } - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/mapper/TestExceptionHandler.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/mapper/TestExceptionHandler.java deleted file mode 100644 index 69713d5e..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/mapper/TestExceptionHandler.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Copyright (C) 2018-2022 Zeyi information technology (Shanghai) Co., Ltd. - *

- * All right reserved. - *

- * This software is the confidential and proprietary - * information of Zeyi Company of China. - * ("Confidential Information"). You shall not disclose - * such Confidential Information and shall use it only - * in accordance with the terms of the contract agreement - * you entered into with Zeyi inc. - */ -package fun.asgc.neutrino.core.db.mapper; - -import fun.asgc.neutrino.core.aop.interceptor.ExceptionHandler; -import lombok.extern.slf4j.Slf4j; - -import java.sql.SQLException; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/30 - */ -@Slf4j -public class TestExceptionHandler implements ExceptionHandler { - - /** - * 此处若拦截成功,则全局异常拦截不会执行 - * @param e - * @return - */ - @Override - public boolean support(Exception e) { -// return e instanceof SQLException; - return false; - } - - @Override - public Object handle(Exception e) { - log.error("SQL执行异常", e); - return null; - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/mapper/TestGlobalExceptionHandler.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/mapper/TestGlobalExceptionHandler.java deleted file mode 100644 index 1d2ac469..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/mapper/TestGlobalExceptionHandler.java +++ /dev/null @@ -1,43 +0,0 @@ -/** - * Copyright (C) 2018-2022 Zeyi information technology (Shanghai) Co., Ltd. - *

- * All right reserved. - *

- * This software is the confidential and proprietary - * information of Zeyi Company of China. - * ("Confidential Information"). You shall not disclose - * such Confidential Information and shall use it only - * in accordance with the terms of the contract agreement - * you entered into with Zeyi inc. - */ -package fun.asgc.neutrino.core.db.mapper; - -import fun.asgc.neutrino.core.annotation.Component; -import fun.asgc.neutrino.core.aop.interceptor.ExceptionHandler; -import lombok.extern.slf4j.Slf4j; - -/** - * 全局异常处理 - * @author: aoshiguchen - * @date: 2022/6/30 - */ -@Slf4j -@Component -public class TestGlobalExceptionHandler implements ExceptionHandler { - - /** - * - * @param e - * @return - */ - @Override - public boolean support(Exception e) { - return false; - } - - @Override - public Object handle(Exception e) { - log.error("全局异常 {}" + this.hashCode(), e); - return null; - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/mapper/User.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/mapper/User.java deleted file mode 100644 index e2bcb39d..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/mapper/User.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.mapper; - -import fun.asgc.neutrino.core.db.annotation.Id; -import fun.asgc.neutrino.core.db.annotation.Table; -import lombok.Data; -import lombok.ToString; - -import java.util.Date; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/28 - */ -@ToString -@Data -@Table("user") -public class User { - @Id - private Long id; - private String name; - private Integer age; - private String email; - private String sex; - private Date createTime; - private Date updateTime; -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/mapper/UserMapper.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/mapper/UserMapper.java deleted file mode 100644 index 40f67485..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/mapper/UserMapper.java +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.mapper; - -import fun.asgc.neutrino.core.annotation.Component; -import fun.asgc.neutrino.core.aop.Intercept; -import fun.asgc.neutrino.core.db.annotation.Insert; -import fun.asgc.neutrino.core.db.annotation.ResultType; -import fun.asgc.neutrino.core.db.annotation.Select; - -import java.util.List; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/28 - */ -@Intercept(exceptionHandler = TestExceptionHandler.class) -@Component -public interface UserMapper extends SqlMapper { - - @Select("select * from user where id = ?") - User findOneById(Long id); - - @ResultType(User.class) - @Select("select * from user") - List findAll(); - - @Select("select count(1) from user") - int count(); - - @Insert("insert into user(`id`,`name`,`age`,`email`,`sex`,`create_time`) values(:id,:name,:age,:email,:sex,:createTime)") - int add(User user) throws Exception; -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/template/JdbcTemplateTestForMySql.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/template/JdbcTemplateTestForMySql.java deleted file mode 100644 index bd41edbc..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/template/JdbcTemplateTestForMySql.java +++ /dev/null @@ -1,184 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.template; - -import com.zaxxer.hikari.HikariDataSource; -import fun.asgc.neutrino.core.db.annotation.Id; -import lombok.Data; -import lombok.experimental.Accessors; -import org.junit.Test; - -import java.sql.SQLException; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/27 - */ -public class JdbcTemplateTestForMySql { - private JdbcTemplate jdbcTemplate; - - { - HikariDataSource dataSource = new HikariDataSource(); - dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf8"); - dataSource.setUsername("root"); - dataSource.setPassword("YWasgc@10520"); - jdbcTemplate = new JdbcTemplate(dataSource); - } - - @Test - public void 新增数据1() throws SQLException { - jdbcTemplate.update("insert into user(`id`,`name`,`age`,`email`,`sex`,`create_time`) values(?,?,?,?,?,?)", 1, "张三", 21, "zhangsan@qq.com", "男", new Date()); - } - - @Test - public void 数据新增2() throws SQLException { - Map params = new HashMap<>(); - params.put("id", 2); - params.put("name", "李四"); - params.put("age", 22); - params.put("email", "lisi@qq.com"); - params.put("sex", "女"); - params.put("createTime", new Date()); - jdbcTemplate.updateByMap("insert into user(`id`,`name`,`age`,`email`,`sex`,`create_time`) values(:id,:name,:age,:email,:sex,:createTime)", params); - } - - @Test - public void 数据新增3() throws SQLException { - User user = new User(); - user.setId(3L); - user.setName("王五"); - user.setAge(23); - user.setEmail("wangwu@qq.com"); - user.setSex("男"); - user.setCreateTime(new Date()); - jdbcTemplate.updateByModel("insert into user(`id`,`name`,`age`,`email`,`sex`,`create_time`) values(:id,:name,:age,:email,:sex,:createTime)", user); - } - - @Test - public void 更新数据1() throws SQLException { - jdbcTemplate.update("update user set age = ? ,update_time = ? where id = ?", 31, new Date(), 1); - } - - @Test - public void 更新数据2() throws SQLException { - Map params = new HashMap<>(); - params.put("id", 2); - params.put("updateTime", new Date()); - params.put("age", 32); - jdbcTemplate.updateByMap("update user set age = :age ,update_time = :updateTime where id = :id", params); - } - - @Test - public void 更新数据3() throws SQLException { - User user = new User(); - user.setId(3L); - user.setAge(33); - user.setUpdateTime(new Date()); - jdbcTemplate.updateByModel("update user set age = :age ,update_time = :updateTime where id = :id", user); - } - - @Test - public void 删除数据1() throws SQLException { - jdbcTemplate.update("delete from user where id = ?", 1L); - } - - @Test - public void 删除数据2() throws SQLException { - Map params = new HashMap<>(); - params.put("id", 2); - jdbcTemplate.updateByMap("delete from user where id = :id", params); - } - - @Test - public void 删除数据3() throws SQLException { - User user = new User(); - user.setId(3L); - jdbcTemplate.updateByModel("delete from user where id = :id", user); - } - - @Test - public void 查询单个行记录1() throws SQLException { - Map map = jdbcTemplate.queryForMap("select * from user where id = ?", 1); - System.out.println(map); - } - - @Test - public void 查询单个行记录2() throws SQLException { - User user = jdbcTemplate.query(User.class, "select * from user where id = 1"); - System.out.println(user); - } - - @Test - public void 查询单个字段记录1() throws SQLException { - String name = jdbcTemplate.queryForString("select name from user where id = ?", 1); - System.out.println(name); - } - - @Test - public void 查询单个字段记录2() throws SQLException { - int age = jdbcTemplate.queryForInt("select age from user where id = 1"); - System.out.println(age); - } - - @Test - public void 查询单个字段记录3() throws SQLException { - Long count = jdbcTemplate.queryForLong("select count(1) from user"); - System.out.println(count); - } - - @Test - public void 查询多个行记录1() throws SQLException { - List list = jdbcTemplate.queryForListMap("select * from user"); - System.out.println(list); - } - - @Test - public void 查询多个行记录2() throws SQLException { - List list = jdbcTemplate.queryForList(User.class, "select * from user"); - System.out.println(list); - } - - @Test - public void 查询多个字段记录1() throws SQLException { - List list = jdbcTemplate.queryForListInt("select age from user"); - System.out.println(list); - } - - - @Accessors(chain = true) - @Data - public static class User { - @Id - private Long id; - private String name; - private Integer age; - private String email; - private String sex; - private Date createTime; - private Date updateTime; - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/template/JdbcTemplateTestForSqlite.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/template/JdbcTemplateTestForSqlite.java deleted file mode 100644 index b194631e..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/template/JdbcTemplateTestForSqlite.java +++ /dev/null @@ -1,82 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.template; - -import com.zaxxer.hikari.HikariDataSource; -import fun.asgc.neutrino.core.db.annotation.Id; -import lombok.Data; -import lombok.experimental.Accessors; -import org.junit.Test; - -import java.sql.SQLException; -import java.util.Date; -import java.util.List; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/8 - */ -public class JdbcTemplateTestForSqlite { - private JdbcTemplate jdbcTemplate; - - { - HikariDataSource dataSource = new HikariDataSource(); -// dataSource.setUrl("jdbc:sqlite:" + JdbcTemplateTestForSqlite.class.getResource("/sqlite.db").getPath()); - dataSource.setJdbcUrl("jdbc:sqlite:../data.db"); - dataSource.setDriverClassName("org.sqlite.JDBC"); - jdbcTemplate = new JdbcTemplate(dataSource); - } - - @Test - public void 新增数据1() throws SQLException { - jdbcTemplate.update("insert into user(`id`,`name`,`age`,`email`,`sex`,`create_time`) values(?,?,?,?,?,?)", 1, "张三", 21, "zhangsan@qq.com", "男", new Date()); - } - - @Test - public void 查询单个行记录2() throws SQLException { - User user = jdbcTemplate.query(User.class, "select * from user where id = 1"); - System.out.println(user); - } - - @Test - public void 查询列表() throws SQLException { - // 此处只能传数组,不能传集合 - List userList = jdbcTemplate.queryForList(User.class, "select * from user where id in (?,?,?,?)", new Object[]{1,2,3,4}); - System.out.println(userList); - } - - @Accessors(chain = true) - @Data - public static class User { - @Id - private Long id; - private String name; - private Integer age; - private String email; - private String sex; - private Date createTime; - private Date updateTime; - } - -} - diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/template/JdbcTemplateTestForSqlite2.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/template/JdbcTemplateTestForSqlite2.java deleted file mode 100644 index e52d76d5..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/template/JdbcTemplateTestForSqlite2.java +++ /dev/null @@ -1,43 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.db.template; - -import org.junit.Test; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/31 - */ -public class JdbcTemplateTestForSqlite2 { - @Test - public void test1() throws ClassNotFoundException, SQLException { - Class.forName("org.sqlite.JDBC"); - //建立一个数据库名zieckey.db的连接,如果不存在就在当前目录下创建之 - Connection conn = DriverManager.getConnection("jdbc:sqlite:aa.db"); - System.out.println(conn); - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/quartz/test1/Launcher.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/quartz/test1/Launcher.java deleted file mode 100644 index f4ad19e2..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/quartz/test1/Launcher.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.quartz.test1; - -import fun.asgc.neutrino.core.annotation.Init; -import fun.asgc.neutrino.core.annotation.NeutrinoApplication; -import fun.asgc.neutrino.core.context.NeutrinoLauncher; -import org.quartz.*; -import org.quartz.impl.StdSchedulerFactory; - -/** - * - * @author: aoshiguchen - * @date: 2022/8/31 - */ -@NeutrinoApplication -public class Launcher { - - @Init - public void init() throws SchedulerException { - TriggerKey triggerKey = TriggerKey.triggerKey("1"); - JobKey jobKey = new JobKey("1"); - - SchedulerFactory schedulerFactory = new StdSchedulerFactory(); - Scheduler scheduler = schedulerFactory.getScheduler(); - - CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("0/5 * * * * ?").withMisfireHandlingInstructionDoNothing(); - CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(triggerKey).withSchedule(cronScheduleBuilder).build(); - - Class jobClass_ = RemoteHttpJobBean.class; // Class.forName(jobInfo.getJobClass()); - JobDetail jobDetail = JobBuilder.newJob(jobClass_).withIdentity(jobKey).build(); - - scheduler.scheduleJob(jobDetail, cronTrigger); - scheduler.start(); - } - - public static void main(String[] args) { - NeutrinoLauncher.runSync(Launcher.class, args); - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/quartz/test1/RemoteHttpJobBean.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/quartz/test1/RemoteHttpJobBean.java deleted file mode 100755 index f8a8ba5f..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/quartz/test1/RemoteHttpJobBean.java +++ /dev/null @@ -1,66 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.quartz.test1; - -import fun.asgc.neutrino.core.util.DateUtil; -import org.quartz.*; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.Date; - -/** - * http job bean - * “@DisallowConcurrentExecution” diable concurrent, thread size can not be only one, better given more - * @author xuxueli 2015-12-17 18:20:34 - */ -public class RemoteHttpJobBean implements Job { - private static Logger logger = LoggerFactory.getLogger(RemoteHttpJobBean.class); - - @Override - public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { -// try { -// BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this); -// MutablePropertyValues pvs = new MutablePropertyValues(); -// pvs.addPropertyValues(context.getScheduler().getContext()); -// pvs.addPropertyValues(context.getMergedJobDataMap()); -// bw.setPropertyValues(pvs, true); -// } catch (SchedulerException var4) { -// throw new JobExecutionException(var4); -// } -// -// this.executeInternal(context); - System.out.println("job执行:" + DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss")); - } - - protected void executeInternal(JobExecutionContext context) - throws JobExecutionException { - -// // load jobId -// JobKey jobKey = context.getTrigger().getJobKey(); -// Integer jobId = Integer.valueOf(jobKey.getName()); -// -// // trigger -// JobTriggerPoolHelper.trigger(jobId, TriggerTypeEnum.CRON, -1, null, null); - } - -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/quartz/test2/JobCallback.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/quartz/test2/JobCallback.java deleted file mode 100644 index 1bd14b1e..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/quartz/test2/JobCallback.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.quartz.test2; - -import fun.asgc.neutrino.core.quartz.IJobCallback; -import fun.asgc.neutrino.core.quartz.JobInfo; -import lombok.extern.slf4j.Slf4j; - -/** - * - * @author: aoshiguchen - * @date: 2022/9/4 - */ -@Slf4j -public class JobCallback implements IJobCallback { - - @Override - public void executeLog(JobInfo jobInfo, String param, Throwable throwable) { - if (null == throwable) { - log.info("job[name={}]执行完毕", jobInfo.getId(), jobInfo.getName()); - } else { - log.error("job[name={}]执行异常", jobInfo.getId(), jobInfo.getName(), throwable); - } - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/quartz/test2/Launcher.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/quartz/test2/Launcher.java deleted file mode 100644 index 517c55ef..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/quartz/test2/Launcher.java +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.quartz.test2; - -import fun.asgc.neutrino.core.annotation.Bean; -import fun.asgc.neutrino.core.annotation.EnableJob; -import fun.asgc.neutrino.core.annotation.NeutrinoApplication; -import fun.asgc.neutrino.core.context.NeutrinoLauncher; -import fun.asgc.neutrino.core.quartz.DefaultJobSource; -import fun.asgc.neutrino.core.quartz.JobExecutor; - -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -/** - * - * @author: aoshiguchen - * @date: 2022/9/4 - */ -@EnableJob -@NeutrinoApplication -public class Launcher { - - public static void main(String[] args) { - NeutrinoLauncher.runSync(Launcher.class, args); - } - - @Bean - public JobExecutor jobExecutor() { - JobExecutor executor = new JobExecutor(); - executor.setJobSource(new DefaultJobSource()); - executor.setThreadPoolExecutor(new ThreadPoolExecutor(5, 20, 10L, TimeUnit.SECONDS, new LinkedBlockingQueue<>())); - executor.setJobCallback(new JobCallback()); - return executor; - } - -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/quartz/test2/TestJob1.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/quartz/test2/TestJob1.java deleted file mode 100644 index 195f2fe2..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/quartz/test2/TestJob1.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.quartz.test2; - -import fun.asgc.neutrino.core.annotation.Component; -import fun.asgc.neutrino.core.annotation.NonIntercept; -import fun.asgc.neutrino.core.quartz.IJobHandler; -import fun.asgc.neutrino.core.quartz.annotation.JobHandler; -import lombok.extern.slf4j.Slf4j; - -/** - * - * @author: aoshiguchen - * @date: 2022/9/4 - */ -@Slf4j -@NonIntercept -@Component -@JobHandler(name = "TestJob1", cron = "0/5 * * * * ?", param = "123") -public class TestJob1 implements IJobHandler { - - @Override - public void execute(String param) throws Exception { - log.info("TestJob1 execute param:{}", param); - } - -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/security/SecurityManagerTest.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/security/SecurityManagerTest.java deleted file mode 100644 index a288942d..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/security/SecurityManagerTest.java +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.security; - -import java.io.BufferedReader; -import java.io.FileReader; -import java.io.IOException; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.util.stream.Collectors; - -/** - * @author: aoshiguchen - * @date: 2022/9/25 - */ -public class SecurityManagerTest { - - public static void main(String[] args) { - // -Djava.security.manager -Djava.security.policy=/work/tmp/policy1.policy - System.out.println("SecurityManager: " + System.getSecurityManager()); - - try (BufferedReader br = new BufferedReader(new FileReader("/work/tmp/test.txt"))){ - System.out.println("content:\n" + br.lines().collect(Collectors.joining())); - } catch (IOException e) { - throw new RuntimeException(e); - } - - AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Object run() { - System.out.println(System.getProperty("file.encoding")); - return null; - } - }); -// System.out.println(System.getProperty("file.encoding")); - } - -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/util/ClassUtilTest.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/util/ClassUtilTest.java deleted file mode 100644 index bc088ff9..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/util/ClassUtilTest.java +++ /dev/null @@ -1,83 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.util; - -import org.junit.Test; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.URL; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/4 - */ -public class ClassUtilTest { - - @Test - public void hasNoArgsConstructor() { -// System.out.println(ClassUtil.hasNoArgsConstructor(ClassUtilTest.class)); - Pattern pattern = Pattern.compile("\\$\\{[\\s\\p{Zs}]*(.*):(.*)[\\s\\p{Zs}]*\\}"); - String s = "${ a:bb11 }"; - Matcher m = pattern.matcher(s); - if (m.find()) { - System.out.println(m.group(1)); - System.out.println(m.group(2)); - } - - } - - @Test - public void test1() throws InvocationTargetException, IllegalAccessException { - Method method = ReflectUtil.getMethods(Student.class).stream().filter(m -> m.getName().equals("say")).findFirst().get(); - Student student = new Student(); - method.invoke(student, new Object[]{"1", "2"}); - } - - @Test - public void test2() throws InvocationTargetException, IllegalAccessException { - Method method = ReflectUtil.getMethods(Student.class).stream().filter(m -> m.getName().equals("hello")).findFirst().get(); - Student student = new Student(); - method.invoke(student, new Object[0]); - } - - public static class Student { - public void say(String msg1, String msg2) { - System.out.println("msg1:" + msg1 + " msg2:" + msg2); - } - public void hello() { - System.out.println("hello"); - } - } - - @Test - public void scan() throws Exception { - String path = "jar:file:/Users/yangwen/my/tmp/java/neutrino-proxy-server-1.0-SNAPSHOT-jar-with-dependencies.jar!/"; - URL url = new URL(path); - Set> c = ClassUtil.scan("fun.asgc.neutrino.proxy.server", url); - System.out.println(c); - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/util/FileUtilTest.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/util/FileUtilTest.java deleted file mode 100644 index 1f3adc04..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/util/FileUtilTest.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.util; - -import org.junit.Test; - -import java.io.File; -import java.net.MalformedURLException; - -/** - * - * @author: wen.y - * @date: 2022/7/23 - */ -public class FileUtilTest { - @Test - public void test1() throws MalformedURLException { -// URL url = FileUtilTest.class.getResource("/tpl/AsgcProxy.tpl"); - File url = new File("jar:file:/Users/yangwen/tmp/neutrino-core-1.0-SNAPSHOT.jar!/tpl/AsgcProxy.tpl"); - System.out.println(url); - } - - @Test - public void test2() { - System.out.println(FileUtilTest.class.getResource("").getProtocol()); - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/util/LockUtilTest.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/util/LockUtilTest.java deleted file mode 100644 index 8a03d78f..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/util/LockUtilTest.java +++ /dev/null @@ -1,77 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.util; - -import fun.asgc.neutrino.core.aop.interceptor.ExceptionHandler; -import lombok.Data; -import org.checkerframework.checker.units.qual.A; -import org.junit.Test; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/20 - */ -public class LockUtilTest { - private static volatile A a; - - /** - * 没有双重校验锁,并发执行容易产生多个实例 - */ - @Test - public void test1() { - for (int i = 0; i < 10; i++) { - ThreadUtil.run(() -> { - if (a == null) { - a = new A(); - } - }); - } - SystemUtil.waitProcessDestroy().sync(); - } - - /** - * 使用双重校验锁,并发执行,只产生一个实例 - */ - @Test - public void test2() { - for (int i = 0; i < 10; i++) { - ThreadUtil.run(() -> { - try { - LockUtil.doubleCheckProcess(() -> a == null, - LockUtilTest.class, - () -> a = new A()); - } catch (Exception e) { - e.printStackTrace(); - } - }); - } - SystemUtil.waitProcessDestroy().sync(); - } - - @Data - public static class A { -// public A() { -// System.out.println("new instance."); -// } - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/util/SystemUtilTest.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/util/SystemUtilTest.java deleted file mode 100644 index 23915655..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/util/SystemUtilTest.java +++ /dev/null @@ -1,49 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.util; - -import org.junit.Test; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/20 - */ -public class SystemUtilTest { - - @Test - public void run() { - ThreadUtil.run(() -> { - for (int i = 0; i < 10; i ++) { - try { - System.out.println(i); - Thread.sleep(1000); - } catch (Exception e) { - - } - } - }); - - SystemUtil.waitProcessDestroy(() -> System.out.println("进程销毁")).sync(); - } - -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/util/TypeUtilTest.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/util/TypeUtilTest.java deleted file mode 100644 index 4609c98f..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/util/TypeUtilTest.java +++ /dev/null @@ -1,192 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.util; - -import com.google.common.collect.Lists; -import fun.asgc.neutrino.core.type.*; -import lombok.Data; -import lombok.experimental.Accessors; -import org.junit.Test; - -import java.util.List; -import java.util.Set; - -/** - * - * @author: aoshiguchen - * @date: 2022/6/17 - */ -public class TypeUtilTest { - - private static TypeMatchers typeMatchers = new TypeMatchers(); - - static { - typeMatchers.registerCustomTypeMatcher(new TypeMatcher() { - @Override - public TypeMatchInfo match(Class clazz, Class targetClass) { - TypeMatchInfo typeMatchInfo = new TypeMatchInfo(clazz, targetClass, this); - if (clazz == String.class && targetClass == Animal.class) { - typeMatchInfo.setTypeDistance(TypeMatchLevel.CUSTOM.getDistanceMin() + 1); - typeMatchInfo.setTypeConverter(((value, targetType) -> new Animal().setName((String)value))); - } - return typeMatchInfo; - } - }); - typeMatchers.registerCustomTypeMatcher(new TypeMatcher() { - @Override - public TypeMatchInfo match(Class clazz, Class targetClass) { - TypeMatchInfo typeMatchInfo = new TypeMatchInfo(clazz, targetClass, this); - if (clazz == String.class && targetClass == Cat.class) { - typeMatchInfo.setTypeDistance(TypeMatchLevel.CUSTOM.getDistanceMin() + 2); - typeMatchInfo.setTypeConverter((value, targetType) -> { - String[] tmp = ((String)value).split(":"); - Cat cat = new Cat(); - if (tmp.length >= 1) { - cat.setName(tmp[0]); - } - if (tmp.length >= 2) { - cat.setAge(Integer.valueOf(tmp[1])); - } - return cat; - }); - } - return typeMatchInfo; - } - }); - } - - @Test - public void conversionNull() { - System.out.println(typeMatchers.conversion(null, boolean.class)); - System.out.println(typeMatchers.conversion(null, byte.class)); - System.out.println(typeMatchers.conversion(null, short.class)); - System.out.println(typeMatchers.conversion(null, char.class)); - System.out.println(typeMatchers.conversion(null, int.class)); - System.out.println(typeMatchers.conversion(null, long.class)); - System.out.println(typeMatchers.conversion(null, float.class)); - System.out.println(typeMatchers.conversion(null, double.class)); - System.out.println(typeMatchers.conversion(null, Boolean.class)); - System.out.println(typeMatchers.conversion(null, Byte.class)); - System.out.println(typeMatchers.conversion(null, Short.class)); - System.out.println(typeMatchers.conversion(null, Character.class)); - System.out.println(typeMatchers.conversion(null, Integer.class)); - System.out.println(typeMatchers.conversion(null, Long.class)); - System.out.println(typeMatchers.conversion(null, Float.class)); - System.out.println(typeMatchers.conversion(null, Double.class)); - System.out.println(typeMatchers.conversion(null, String.class)); - System.out.println(typeMatchers.conversion(null, List.class)); - - System.out.println(typeMatchers.conversion(null, Animal.class)); - System.out.println(typeMatchers.conversion(null, Cat.class)); - } - - @Test - public void conversionString() { - typeMatchers.setEnableExtensionMatcher(false); - System.out.println(typeMatchers.conversion("true", boolean.class)); - System.out.println(typeMatchers.conversion("100", byte.class)); - System.out.println(typeMatchers.conversion("101", short.class)); - System.out.println(typeMatchers.conversion("a", char.class)); - System.out.println(typeMatchers.conversion("1000", int.class)); - System.out.println(typeMatchers.conversion("500000", long.class)); - System.out.println(typeMatchers.conversion("1.3", float.class)); - System.out.println(typeMatchers.conversion("566.0099", double.class)); - System.out.println(typeMatchers.conversion("false", Boolean.class)); - System.out.println(typeMatchers.conversion("88", Byte.class)); - System.out.println(typeMatchers.conversion("444", Short.class)); - System.out.println(typeMatchers.conversion("B", Character.class)); - System.out.println(typeMatchers.conversion("99", Integer.class)); - System.out.println(typeMatchers.conversion("5666666", Long.class)); - System.out.println(typeMatchers.conversion("10.24", Float.class)); - System.out.println(typeMatchers.conversion("3.1415926", Double.class)); - System.out.println(typeMatchers.conversion('a', String.class)); - - System.out.println(typeMatchers.conversion("aabb", Animal.class)); - System.out.println(typeMatchers.conversion("aabb:10", Cat.class)); - - System.out.println(typeMatchers.conversion(new String[]{"11","22","33","22"}, List.class)); - System.out.println(typeMatchers.conversion(new Integer[]{10, 20, 30,20}, List.class)); - System.out.println(typeMatchers.conversion(new Boolean[]{true, true, false}, List.class)); - System.out.println(typeMatchers.conversion(new Animal[]{new Animal("aa"), new Animal("bb"), new Animal("cc"),}, List.class)); - - System.out.println(typeMatchers.conversion(Lists.newArrayList("11","22","33","22"), Object[].class)); - - System.out.println(typeMatchers.conversion(new String[]{"11","22","33","22"}, Set.class)); - System.out.println(typeMatchers.conversion(new Integer[]{10, 20, 30,20}, Set.class)); - System.out.println(typeMatchers.conversion(new Boolean[]{true, true, false}, Set.class)); - - } - - @Test - public void conversionInt() { - typeMatchers.setEnableExtensionMatcher(true); - - System.out.println(typeMatchers.conversion(100, boolean.class)); - System.out.println(typeMatchers.conversion(101, byte.class)); - System.out.println(typeMatchers.conversion(102, short.class)); - System.out.println(typeMatchers.conversion(103, char.class)); - System.out.println(typeMatchers.conversion(104, int.class)); - System.out.println(typeMatchers.conversion(105, long.class)); - System.out.println(typeMatchers.conversion(106, float.class)); - System.out.println(typeMatchers.conversion(107, double.class)); - System.out.println(typeMatchers.conversion(108, Boolean.class)); - System.out.println(typeMatchers.conversion(109, Byte.class)); - System.out.println(typeMatchers.conversion(110, Short.class)); - System.out.println(typeMatchers.conversion(111, Character.class)); - System.out.println(typeMatchers.conversion(112, Integer.class)); - System.out.println(typeMatchers.conversion(113, Long.class)); - System.out.println(typeMatchers.conversion(114, Float.class)); - System.out.println(typeMatchers.conversion(115, Double.class)); - System.out.println(typeMatchers.conversion(116, String.class)); - System.out.println(typeMatchers.conversion(200, List.class)); - - System.out.println(typeMatchers.conversion(117, Animal.class)); - System.out.println(typeMatchers.conversion(118, Cat.class)); - } - - @Test - public void getInheritLevel() { - System.out.println(TypeUtil.getInheritLevel(Cat.class, Cat.class)); - System.out.println(TypeUtil.getInheritLevel(Cat.class, Animal.class)); - System.out.println(TypeUtil.getInheritLevel(Animal.class, Cat.class)); - System.out.println(TypeUtil.getInheritLevel(Object.class, Cat.class)); - } - - - @Accessors(chain = true) - @Data - public static class Animal { - private String name; - public Animal() { - - } - public Animal(String name) { - this.name = name; - } - } - - @Accessors(chain = true) - @Data - private static class Cat extends Animal { - private int age; - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/web/HttpMethodTest.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/web/HttpMethodTest.java deleted file mode 100644 index 40b33cfe..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/web/HttpMethodTest.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web; - -import org.junit.Test; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/15 - */ -public class HttpMethodTest { - - @Test - public void test1() { - HttpMethod method = HttpMethod.of("Get"); - System.out.println(method); - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/web/interceptor/InterceptorRegistryTest.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/web/interceptor/InterceptorRegistryTest.java deleted file mode 100644 index 86e14f31..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/web/interceptor/InterceptorRegistryTest.java +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web.interceptor; - -import fun.asgc.neutrino.core.web.AntPathMatcher; -import org.junit.Test; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/28 - */ -public class InterceptorRegistryTest { - - @Test - public void test1() { - AntPathMatcher antPathMatcher = new AntPathMatcher(); - System.out.println(antPathMatcher.match("/a/*", "/a/11")); - System.out.println(antPathMatcher.match("/a/*", "/a/11/22")); - System.out.println(antPathMatcher.match("/a/**", "/a/11/22")); - System.out.println(antPathMatcher.match("/a/*.html", "/a/11/22")); - System.out.println(antPathMatcher.match("/a/*.html", "/a/11.html")); - System.out.println(antPathMatcher.match("/a/*.html", "/a/11/a.html")); - System.out.println(antPathMatcher.match("/a/**/*.html", "/a/11/a.html")); - System.out.println(antPathMatcher.match("/a/**/*.html", "/a/11/22/33/a.html")); - System.out.println(antPathMatcher.match("/", "/a/11/22/33/a.html")); - System.out.println(antPathMatcher.match("/**", "/a/11/22/33/a.html")); - System.out.println(antPathMatcher.match("*.html", "/a/11/22/33/a.html")); - System.out.println(antPathMatcher.match("**.html", "/a/11/22/33/a.html")); - System.out.println(antPathMatcher.match("**/**.html", "/a/11/22/33/a.html")); - System.out.println(antPathMatcher.match("/**/*.html", "/a/11/22/33/a.html")); - System.out.println(antPathMatcher.match("/**/*.html", "/a.html")); - } - -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/web/test1/BaseAuthInterceptor.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/web/test1/BaseAuthInterceptor.java deleted file mode 100644 index d4575e8b..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/web/test1/BaseAuthInterceptor.java +++ /dev/null @@ -1,58 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web.test1; - -import fun.asgc.neutrino.core.web.context.HttpRequestWrapper; -import fun.asgc.neutrino.core.web.context.HttpResponseWrapper; -import fun.asgc.neutrino.core.web.interceptor.HandlerInterceptor; -import io.netty.channel.ChannelHandlerContext; -import lombok.extern.slf4j.Slf4j; - -import java.lang.reflect.Method; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/28 - */ -@Slf4j -public class BaseAuthInterceptor implements HandlerInterceptor { - - /** - * 登录验证 - * @param requestParser - * @param responseWrapper - * @param route - * @param targetMethod - * @return - * @throws Exception - */ - @Override - public boolean preHandle(HttpRequestWrapper requestParser, HttpResponseWrapper responseWrapper, String route, Method targetMethod) throws Exception { - // 登录验证 - String authorize = requestParser.getHeaderValue("Authorize"); - if (!"123abc".equals(authorize)) { - throw new UserNotLoginException(); - } - return Boolean.TRUE; - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/web/test1/GlobalAdviceHandler.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/web/test1/GlobalAdviceHandler.java deleted file mode 100644 index b9dd7c9c..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/web/test1/GlobalAdviceHandler.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web.test1; - -import fun.asgc.neutrino.core.web.context.HttpRequestWrapper; -import fun.asgc.neutrino.core.web.context.HttpResponseWrapper; -import fun.asgc.neutrino.core.web.interceptor.RestControllerAdviceHandler; -import io.netty.channel.ChannelHandlerContext; - -import java.lang.reflect.Method; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/29 - */ -public class GlobalAdviceHandler implements RestControllerAdviceHandler { - - @Override - public Object advice(HttpRequestWrapper requestParser, HttpResponseWrapper responseWrapper, String route, Method targetMethod, Object res) { - if (res instanceof JsonResult) { - return res; - } - return new JsonResult<>() - .setCode(0) - .setData(res); - } - -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/web/test1/GlobalExceptionHandler.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/web/test1/GlobalExceptionHandler.java deleted file mode 100644 index 58469aff..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/web/test1/GlobalExceptionHandler.java +++ /dev/null @@ -1,51 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web.test1; - -import fun.asgc.neutrino.core.web.context.HttpRequestWrapper; -import fun.asgc.neutrino.core.web.context.HttpResponseWrapper; -import fun.asgc.neutrino.core.web.interceptor.RestControllerExceptionHandler; -import io.netty.channel.ChannelHandlerContext; -import org.apache.commons.lang3.exception.ExceptionUtils; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/29 - */ -public class GlobalExceptionHandler implements RestControllerExceptionHandler { - - @Override - public Object handle(HttpRequestWrapper requestParser, HttpResponseWrapper responseWrapper, Throwable e) { - if (e instanceof UserNotLoginException) { - return new JsonResult<>() - .setCode(101) - .setMsg("账号未登录") - .setStack(ExceptionUtils.getStackTrace(e)); - } - return new JsonResult<>() - .setCode(1) - .setMsg("系统异常") - .setStack(ExceptionUtils.getStackTrace(e)); - } - -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/web/test1/JsonResult.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/web/test1/JsonResult.java deleted file mode 100644 index 4d8ee245..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/web/test1/JsonResult.java +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web.test1; - -import lombok.Data; -import lombok.experimental.Accessors; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/29 - */ -@Accessors(chain = true) -@Data -public class JsonResult { - private Integer code; - private String msg; - private T data; - private String stack; -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/web/test1/Launcher.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/web/test1/Launcher.java deleted file mode 100644 index a2293018..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/web/test1/Launcher.java +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web.test1; - -import fun.asgc.neutrino.core.annotation.NeutrinoApplication; -import fun.asgc.neutrino.core.context.NeutrinoLauncher; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/23 - */ -@NeutrinoApplication -public class Launcher { - - public static void main(String[] args) { - NeutrinoLauncher.runSync(Launcher.class, args); - } - -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/web/test1/Param1.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/web/test1/Param1.java deleted file mode 100644 index 445043e0..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/web/test1/Param1.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web.test1; - -import lombok.Data; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/26 - */ -@Data -public class Param1 { - private Integer x; - private Integer y; - private String msg; -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/web/test1/Param2.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/web/test1/Param2.java deleted file mode 100644 index 095f21fb..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/web/test1/Param2.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web.test1; - -import lombok.Data; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/26 - */ -@Data -public class Param2 { - - private String name; - private Integer age; - -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/web/test1/TestController.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/web/test1/TestController.java deleted file mode 100644 index 111647f5..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/web/test1/TestController.java +++ /dev/null @@ -1,76 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web.test1; - -import com.alibaba.fastjson.JSONObject; -import fun.asgc.neutrino.core.annotation.Autowired; -import fun.asgc.neutrino.core.web.annotation.*; -import fun.asgc.neutrino.core.web.context.HttpContextHolder; -import io.netty.buffer.Unpooled; -import io.netty.channel.ChannelFutureListener; -import io.netty.channel.ChannelHandlerContext; -import io.netty.handler.codec.http.*; -import lombok.extern.slf4j.Slf4j; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/23 - */ -@Slf4j -@RestController -@RequestMapping("/test1") -public class TestController { - @Autowired - private TestService testService; - - @GetMapping("hello") - public String hello() { - System.out.println("拿到参数 a = " + HttpContextHolder.getHttpRequestWrapper().getParameterForInteger("a")); - return testService.hello(); - } - - @GetMapping("add") - public Integer add(@RequestParam("x") int x, @RequestParam("y") int y, Param1 p) { - log.info("另一种取参方式 msg:{}", HttpContextHolder.getHttpRequestWrapper().getParameterForString("msg")); - log.info("p : {}", JSONObject.toJSONString(p)); - return x + y; - } - - @GetMapping("hello2") - public void hello2(ChannelHandlerContext context) { - FullHttpResponse fullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer("aoshiguchen".getBytes())); - fullHttpResponse.headers().add(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON); - context.writeAndFlush(fullHttpResponse).addListener(ChannelFutureListener.CLOSE); - } - - @GetMapping("hello3") - public void hello3(@RequestParam("a") String a, @RequestParam("b") String b, @RequestParam(value = "c", required = false) String c) { - log.info("a:{} b:{} c:{}", a, b, c); - } - - @PostMapping("hello4") - public String hello4(@RequestParam("a") String a, Param1 p, @RequestBody String body, @RequestBody Param2 p2) { - log.info("a: {} p:{} body:{} p2:{}", a, JSONObject.toJSONString(p), body, JSONObject.toJSONString(p2)); - return "hello4"; - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/web/test1/TestService.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/web/test1/TestService.java deleted file mode 100644 index 23230ff6..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/web/test1/TestService.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web.test1; - -import fun.asgc.neutrino.core.annotation.Component; - -import java.text.SimpleDateFormat; -import java.util.Date; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/23 - */ -@Component -public class TestService { - private static final SimpleDateFormat SDF = new SimpleDateFormat( "yyyy-MM-dd :HH:mm:ss"); - - public String hello() { - return "hello 现在时间是:" + SDF.format(new Date()); - } -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/web/test1/UserNotLoginException.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/web/test1/UserNotLoginException.java deleted file mode 100644 index 66e6ead0..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/web/test1/UserNotLoginException.java +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web.test1; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/28 - */ -public class UserNotLoginException extends Exception { -} diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/web/test1/WebConfigurerAdapter.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/web/test1/WebConfigurerAdapter.java deleted file mode 100644 index cf2c173c..00000000 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/web/test1/WebConfigurerAdapter.java +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Copyright (c) 2022 aoshiguchen - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package fun.asgc.neutrino.core.web.test1; - -import fun.asgc.neutrino.core.annotation.Configuration; -import fun.asgc.neutrino.core.web.config.WebMvcConfigurer; -import fun.asgc.neutrino.core.web.interceptor.ExceptionHandlerRegistry; -import fun.asgc.neutrino.core.web.interceptor.InterceptorRegistry; -import fun.asgc.neutrino.core.web.interceptor.RestControllerAdviceHandler; - -/** - * - * @author: aoshiguchen - * @date: 2022/7/28 - */ -@Configuration -public class WebConfigurerAdapter implements WebMvcConfigurer { - - @Override - public void addInterceptors(InterceptorRegistry registry) { - registry.addInterceptor(new BaseAuthInterceptor()) - .addPathPatterns("/**").excludePathPatterns("/**/*.html", "/**/*.js", "/**/*.ico"); - } - - @Override - public void addExceptionHandler(ExceptionHandlerRegistry registry) { - registry.addExceptionHandler(new GlobalExceptionHandler()); - } - - @Override - public RestControllerAdviceHandler adviceHandler() { - return new GlobalAdviceHandler(); - } -} diff --git a/neutrino-core/src/test/resources/aaa.json b/neutrino-core/src/test/resources/aaa.json deleted file mode 100644 index 32f78e64..00000000 --- a/neutrino-core/src/test/resources/aaa.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "neutrino": { - "application": { - "name": "test-app" - }, - "http": { - "port": 8000 - } - } -} \ No newline at end of file diff --git a/neutrino-core/src/test/resources/aaa.properties b/neutrino-core/src/test/resources/aaa.properties deleted file mode 100644 index ca8af323..00000000 --- a/neutrino-core/src/test/resources/aaa.properties +++ /dev/null @@ -1,2 +0,0 @@ -#neutrino.application.name=test -app-name=test1 \ No newline at end of file diff --git a/neutrino-core/src/test/resources/application.yml b/neutrino-core/src/test/resources/application.yml deleted file mode 100644 index 7123ece4..00000000 --- a/neutrino-core/src/test/resources/application.yml +++ /dev/null @@ -1,12 +0,0 @@ -neutrino: - application: - name: neutrino-proxy-server - http: - enable: false - port: 8080 - context-path: /test - max-content-length-desc: 128K - static-resource: - locations: - - "classpath:/static/" - - "classpath:/template/" diff --git a/neutrino-core/src/test/resources/sqlite.db b/neutrino-core/src/test/resources/sqlite.db deleted file mode 100644 index c67e431c..00000000 Binary files a/neutrino-core/src/test/resources/sqlite.db and /dev/null differ diff --git a/neutrino-core/src/test/resources/static/favicon.ico b/neutrino-core/src/test/resources/static/favicon.ico deleted file mode 100644 index 474afb8c..00000000 Binary files a/neutrino-core/src/test/resources/static/favicon.ico and /dev/null differ diff --git a/neutrino-core/src/test/resources/static/js/test.js b/neutrino-core/src/test/resources/static/js/test.js deleted file mode 100644 index 37b5d1e4..00000000 --- a/neutrino-core/src/test/resources/static/js/test.js +++ /dev/null @@ -1,3 +0,0 @@ -function hello() { - alert("hello"); -} diff --git a/neutrino-core/src/test/resources/template/index.html b/neutrino-core/src/test/resources/template/index.html deleted file mode 100644 index 0450a6c8..00000000 --- a/neutrino-core/src/test/resources/template/index.html +++ /dev/null @@ -1,12 +0,0 @@ - - - 测试页面 - - - - -

hello,欢迎来到中微子代理

- - diff --git a/neutrino-core/src/test/resources/test1.yml b/neutrino-core/src/test/resources/test1.yml deleted file mode 100644 index 4fc68f79..00000000 --- a/neutrino-core/src/test/resources/test1.yml +++ /dev/null @@ -1,19 +0,0 @@ -server: - name: neutrino-configuration - port: 8080 -a: 1 -b: hello -c: - d: - e: 1 - f: 2 - g: ab - h: - - 1 - - 2 - - 3 - - aaa - i: - - 10 - - 20 - - 30 diff --git a/pom.xml b/pom.xml index d34ac732..bc38063a 100644 --- a/pom.xml +++ b/pom.xml @@ -17,7 +17,6 @@ ${revision} - neutrino-core neutrino-proxy-core neutrino-proxy-client neutrino-proxy-server