From c4ff209d72fa4d63e2e05c49f8ffef6e59fd3cc8 Mon Sep 17 00:00:00 2001 From: alex Date: Tue, 19 Jul 2022 11:34:31 +0800 Subject: [PATCH 01/14] fix code analyze issue --- .gitignore | 1 - build.gradle | 25 +++++++++--------- gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 55190 bytes gradle/wrapper/gradle-wrapper.properties | 6 +++++ settings.gradle | 2 +- src/gaea.app/build.gradle | 20 +++++++------- .../synebula/gaea/app/cmd/LazyCommandApp.kt | 2 -- .../com/synebula/gaea/app/component/Logger.kt | 2 +- .../gaea/app/component/aop/AppAspect.kt | 7 +++-- .../gaea/app/component/{ => bus}/EventBus.kt | 16 +++++------ .../{ => bus}/EventBusSubscriberProcessor.kt | 12 ++++----- src/gaea.mongo/build.gradle | 4 +-- .../com/synebula/gaea/mongo/MongoExt.kt | 2 +- .../synebula/gaea/mongo/query/MongoQuery.kt | 2 +- .../kotlin/com/synebula/gaea/bus/IMessage.kt | 3 +++ .../IEventBus.kt => bus/IMessageBus.kt} | 12 ++++----- .../com/synebula/gaea/data/code/DateCode.kt | 6 ++--- .../gaea/data/code/FixedRandomCode.kt | 9 ++++--- .../synebula/gaea/data/code/SnowflakeCode.kt | 6 ++--- .../com/synebula/gaea/data/date/DateTime.kt | 1 - .../gaea/domain/model/AggregateRecord.kt | 21 --------------- .../model/complex/ComplexAggregateRoot.kt | 3 --- .../domain/model/complex/ComplexEntity.kt | 5 ---- .../model/complex/IComplexAggregateRoot.kt | 9 ------- .../domain/model/complex/IComplexEntity.kt | 7 ----- .../com/synebula/gaea/domain/record/Record.kt | 21 +++++++++++++++ .../synebula/gaea/domain/service/Command.kt | 1 + .../synebula/gaea/domain/service/ICommand.kt | 6 +++++ .../gaea/domain/service/LazyService.kt | 1 - .../kotlin/com/synebula/gaea/event/IEvent.kt | 4 --- .../com/synebula/gaea/io/scan/ClassPath.kt | 5 ++-- .../com/synebula/gaea/io/scan/ClassScanner.kt | 17 +++++++----- .../kotlin/com/synebula/gaea/log/Level.kt | 5 +++- .../synebula/gaea/log/logger/IDebugLogger.kt | 1 - .../synebula/gaea/log/logger/IErrorLogger.kt | 1 - .../synebula/gaea/log/logger/IInfoLogger.kt | 1 - .../synebula/gaea/log/logger/ITraceLogger.kt | 1 - .../synebula/gaea/log/logger/IWarnLogger.kt | 1 - 38 files changed, 117 insertions(+), 131 deletions(-) create mode 100644 gradle/wrapper/gradle-wrapper.jar create mode 100644 gradle/wrapper/gradle-wrapper.properties rename src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/{ => bus}/EventBus.kt (66%) rename src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/{ => bus}/EventBusSubscriberProcessor.kt (83%) create mode 100644 src/gaea/src/main/kotlin/com/synebula/gaea/bus/IMessage.kt rename src/gaea/src/main/kotlin/com/synebula/gaea/{event/IEventBus.kt => bus/IMessageBus.kt} (62%) delete mode 100644 src/gaea/src/main/kotlin/com/synebula/gaea/domain/model/AggregateRecord.kt delete mode 100644 src/gaea/src/main/kotlin/com/synebula/gaea/domain/model/complex/ComplexAggregateRoot.kt delete mode 100644 src/gaea/src/main/kotlin/com/synebula/gaea/domain/model/complex/ComplexEntity.kt delete mode 100644 src/gaea/src/main/kotlin/com/synebula/gaea/domain/model/complex/IComplexAggregateRoot.kt delete mode 100644 src/gaea/src/main/kotlin/com/synebula/gaea/domain/model/complex/IComplexEntity.kt create mode 100644 src/gaea/src/main/kotlin/com/synebula/gaea/domain/record/Record.kt delete mode 100644 src/gaea/src/main/kotlin/com/synebula/gaea/event/IEvent.kt diff --git a/.gitignore b/.gitignore index 02cfcc9..824ab1d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,5 @@ .* gradlew* build -gradle !.gitignore \ No newline at end of file diff --git a/build.gradle b/build.gradle index 4355845..b1eda40 100644 --- a/build.gradle +++ b/build.gradle @@ -1,11 +1,12 @@ buildscript { ext { - kotlin_version = '1.3.72' + kotlin_version = '1.7.0' + spring_version = "2.7.0" } repositories { mavenLocal() - maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' } + maven { url 'https://maven.aliyun.com/nexus/content/groups/public/' } mavenCentral() } @@ -15,40 +16,38 @@ buildscript { } allprojects { + ext { + version '2.0' + } + group 'com.synebula' version version } subprojects { - ext { - version '0.13.1' - spring_version = "2.3.0.RELEASE" - } - buildscript { repositories { mavenLocal() - maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' } + maven { url 'https://maven.aliyun.com/nexus/content/groups/public/' } mavenCentral() } } repositories { mavenLocal() - maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' } + maven { url 'https://maven.aliyun.com/nexus/content/groups/public/' } mavenCentral() } apply plugin: 'idea' apply plugin: 'java' apply plugin: 'kotlin' - apply plugin: 'maven' apply plugin: 'maven-publish' dependencies { - compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" - compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - testCompile group: 'junit', name: 'junit', version: '4.12' + api "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" + api "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" + testApi group: 'junit', name: 'junit', version: '4.12' } sourceCompatibility = 1.8 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..87b738cbd051603d91cc39de6cb000dd98fe6b02 GIT binary patch literal 55190 zcmafaW0WS*vSoFbZQHhO+s0S6%`V%vZQJa!ZQHKus_B{g-pt%P_q|ywBQt-*Stldc z$+IJ3?^KWm27v+sf`9-50uuadKtMnL*BJ;1^6ynvR7H?hQcjE>7)art9Bu0Pcm@7C z@c%WG|JzYkP)<@zR9S^iR_sA`azaL$mTnGKnwDyMa;8yL_0^>Ba^)phg0L5rOPTbm7g*YIRLg-2^{qe^`rb!2KqS zk~5wEJtTdD?)3+}=eby3x6%i)sb+m??NHC^u=tcG8p$TzB<;FL(WrZGV&cDQb?O0GMe6PBV=V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eTnc( z3!r8G=K>zb`|bLLI0N|eFJk%s)B>oJ^M@AQzqR;HUjLsOqW<0v>1ksT_#24*U@R3HJu*A^#1o#P3%3_jq>icD@<`tqU6ICEgZrME(xX#?i^Z z%Id$_uyQGlFD-CcaiRtRdGn|K`Lq5L-rx7`vYYGH7I=eLfHRozPiUtSe~Tt;IN2^gCXmf2#D~g2@9bhzK}3nphhG%d?V7+Zq{I2?Gt*!NSn_r~dd$ zqkUOg{U=MI?Ehx@`(X%rQB?LP=CjJ*V!rec{#0W2WshH$X#9zep!K)tzZoge*LYd5 z@g?-j5_mtMp>_WW`p*UNUZTFN{_+#m*bJzt{hvAdkF{W40{#L3w6gzPztnsA_4?&0 z(+>pv!zB16rR-(nm(^c>Z(its{ny677vT8sF564^mlZvJ!h65}OW%Hn|2OXbOQM%b z{6C54Z2v;^hyMQ;UH+HwFD2!F!VlQ}6Z{L0_9g5~CH0@Mqz?ZC`^QkhOU#$Lx<4`B zyZsa9uPF!rZDo8ZVfzzR#raQ>5|)k~_Ef*wDqG^76o)j!C4 zykvT*o$!-MBko@?{b~*Zf2*YMlImrK`cEp|#D7f%Twm<|C|dWD = bean.javaClass.methods for (method in methods) { // check the annotations on that method - val annotations: Array = method.getAnnotations() + val annotations: Array = method.annotations for (annotation in annotations) { - // if it contains the Subscribe annotation + // if it contains Subscribe annotation if (annotation.annotationClass == Subscribe::class) { // 如果这是一个Guava @Subscribe注解的事件监听器方法,说明所在bean实例 // 对应一个Guava事件监听器类,将该bean实例注册到Guava事件总线 - eventBus?.register(bean) + messageBus?.register(bean) return bean } } diff --git a/src/gaea.mongo/build.gradle b/src/gaea.mongo/build.gradle index 1ba6df0..f0a51c4 100644 --- a/src/gaea.mongo/build.gradle +++ b/src/gaea.mongo/build.gradle @@ -1,6 +1,6 @@ dependencies { - compile project(":src:gaea") - compile("org.springframework.boot:spring-boot-starter-data-mongodb:$spring_version") + api project(":src:gaea") + api("org.springframework.boot:spring-boot-starter-data-mongodb:$spring_version") } publishing { diff --git a/src/gaea.mongo/src/main/kotlin/com/synebula/gaea/mongo/MongoExt.kt b/src/gaea.mongo/src/main/kotlin/com/synebula/gaea/mongo/MongoExt.kt index 1c1349f..c75d204 100644 --- a/src/gaea.mongo/src/main/kotlin/com/synebula/gaea/mongo/MongoExt.kt +++ b/src/gaea.mongo/src/main/kotlin/com/synebula/gaea/mongo/MongoExt.kt @@ -55,7 +55,7 @@ fun Query.where( list.add(tryRangeWhere(param.key, value, onFieldType)) } else { //判断执行查询子元素还是本字段 - val field = if (where.children.isEmpty()) key else where.children + val field = where.children.ifEmpty { key } var criteria = Criteria.where(field) criteria = when (where.operator) { Operator.eq -> criteria.`is`(value) diff --git a/src/gaea.mongo/src/main/kotlin/com/synebula/gaea/mongo/query/MongoQuery.kt b/src/gaea.mongo/src/main/kotlin/com/synebula/gaea/mongo/query/MongoQuery.kt index c32a19e..01bd5f6 100644 --- a/src/gaea.mongo/src/main/kotlin/com/synebula/gaea/mongo/query/MongoQuery.kt +++ b/src/gaea.mongo/src/main/kotlin/com/synebula/gaea/mongo/query/MongoQuery.kt @@ -92,7 +92,7 @@ open class MongoQuery(var template: MongoTemplate, var logger: ILogger? = null) if (!validViewCollection || this.template.collectionExists(name)) name else { - throw RuntimeException("找不到名为[$table]的集合") + throw RuntimeException("找不到名为[${clazz.name}]的集合") } } } diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/bus/IMessage.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/IMessage.kt new file mode 100644 index 0000000..e560295 --- /dev/null +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/IMessage.kt @@ -0,0 +1,3 @@ +package com.synebula.gaea.bus + +interface IMessage \ No newline at end of file diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/event/IEventBus.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/IMessageBus.kt similarity index 62% rename from src/gaea/src/main/kotlin/com/synebula/gaea/event/IEventBus.kt rename to src/gaea/src/main/kotlin/com/synebula/gaea/bus/IMessageBus.kt index c0b6850..0f435e2 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/event/IEventBus.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/IMessageBus.kt @@ -1,6 +1,6 @@ -package com.synebula.gaea.event +package com.synebula.gaea.bus -interface IEventBus { +interface IMessageBus { /** * 注册事件Listener @@ -16,13 +16,13 @@ interface IEventBus { /** * 同步发布事件 - * @param event 事件 + * @param message 事件 */ - fun publish(event: IEvent) + fun publish(message: IMessage) /** * 异步发布事件 - * @param event 事件 + * @param message 事件 */ - fun publishAsync(event: IEvent) + fun publishAsync(message: IMessage) } \ No newline at end of file diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/data/code/DateCode.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/data/code/DateCode.kt index 4afe5e4..a21d4c1 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/data/code/DateCode.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/data/code/DateCode.kt @@ -11,13 +11,13 @@ import java.util.* * 参数:年=y,月=M,日=d,时=H,分=m,秒=s,毫秒=S。位数最好使用默认最大长度。 */ class DateCode(pattern: String = "yyyyMMdd") : ICodeGenerator { - var formator = SimpleDateFormat() + var formatter = SimpleDateFormat() init { - formator.applyPattern(pattern) + formatter.applyPattern(pattern) } override fun generate(): Long { - return java.lang.Long.parseLong(formator.format(Date())) + return java.lang.Long.parseLong(formatter.format(Date())) } } diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/data/code/FixedRandomCode.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/data/code/FixedRandomCode.kt index 001657b..4adceac 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/data/code/FixedRandomCode.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/data/code/FixedRandomCode.kt @@ -1,6 +1,7 @@ package com.synebula.gaea.data.code import java.util.* +import kotlin.math.pow /** * 固定长度随机编号生成。 @@ -9,8 +10,8 @@ import java.util.* * @since 2016年10月24日 上午10:58:05 */ class FixedRandomCode( - //生成的随机编号长度。 - var length: Int + //生成的随机编号长度。 + var length: Int, ) : ICodeGenerator { /** @@ -32,12 +33,12 @@ class FixedRandomCode( var format = String.format("%s%d%dd", "%", 0, calcMaxLength) val count = this.length / calcMaxLength for (i in 0 until count) { - buffer.append(String.format(format, (random.nextDouble() * Math.pow(10.0, calcMaxLength.toDouble())).toInt())) + buffer.append(String.format(format, (random.nextDouble() * 10.0.pow(calcMaxLength.toDouble())).toInt())) } val last = this.length % calcMaxLength if (last != 0) { format = String.format("%s%d%dd", "%", 0, last) - buffer.append(String.format(format, (random.nextDouble() * Math.pow(10.0, last.toDouble())).toInt())) + buffer.append(String.format(format, (random.nextDouble() * 10.0.pow(last.toDouble())).toInt())) } return buffer.toString() } diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/data/code/SnowflakeCode.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/data/code/SnowflakeCode.kt index 3e1c6f1..faa5ea7 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/data/code/SnowflakeCode.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/data/code/SnowflakeCode.kt @@ -13,7 +13,7 @@ package com.synebula.gaea.data.code * 0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000

* 1位标识,由于long基本类型在Java中是带符号的,最高位是符号位,正数是0,负数是1,所以id一般是正数,最高位是0

* 41位时间截(毫秒级),注意,41位时间截不是存储当前时间的时间截,而是存储时间截的差值(当前时间截 - 开始时间截)

- * 得到的值),这里的的开始时间截,一般是我们的id生成器开始使用的时间,由我们程序来指定的(如下下面程序Snowflake类的twepoch属性)。

+ * 得到的值),这里的的开始时间截,一般是我们的id生成器开始使用的时间,由我们程序来指定的(如下下面程序Snowflake类的origin属性)。

* 41位的时间截,可以使用69年,年T = (1L << 41) / (1000L * 60 * 60 * 24 * 365) = 69

* 10位的数据机器位,可以部署在1024个节点,包括5位datacenter和5位worker

* 12位序列,毫秒内的计数,12位的计数顺序号支持每个节点每毫秒(同一机器,同一时间截)产生4096个ID序号

@@ -35,7 +35,7 @@ open class SnowflakeCode( /** * 开始时间截 (2018-01-01) */ - private val twepoch = 1514736000000L + private val origin = 1514736000000L /** * 机器id所占的位数 @@ -142,7 +142,7 @@ open class SnowflakeCode( lastTimestamp = current //移位并通过或运算拼到一起组成64位的ID - return (current - twepoch shl timestampLeftShift + return (current - origin shl timestampLeftShift or (datacenter shl datacenterShift) or (worker shl workerShift) or sequence) diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/data/date/DateTime.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/data/date/DateTime.kt index 053b4a9..ef6ee10 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/data/date/DateTime.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/data/date/DateTime.kt @@ -275,7 +275,6 @@ class DateTime() : Comparable { * @return true or false */ fun isBetween(start: DateTime, end: DateTime): Boolean { - //return this in start..end return start.dateNoTime.compareTo(this.dateNoTime) * this.dateNoTime.compareTo(end.dateNoTime) >= 0 } diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/model/AggregateRecord.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/model/AggregateRecord.kt deleted file mode 100644 index 77b1c3f..0000000 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/model/AggregateRecord.kt +++ /dev/null @@ -1,21 +0,0 @@ -package com.synebula.gaea.domain.model - -import java.util.* - -/** - * 记录聚合根 - * 聚合根外添加了创建和修改的人\时间信息 - */ -abstract class AggregateRecord : AggregateRoot() { - var creator: String? = null - var creatorName: String? = null - var created: Date = Date() - set(value) { - field = value - modified = value - } - - var modifier: String? = null - var modifierName: String? = null - var modified: Date = Date() -} \ No newline at end of file diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/model/complex/ComplexAggregateRoot.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/model/complex/ComplexAggregateRoot.kt deleted file mode 100644 index 48e25fc..0000000 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/model/complex/ComplexAggregateRoot.kt +++ /dev/null @@ -1,3 +0,0 @@ -package com.synebula.gaea.domain.model.complex - -abstract class ComplexAggregateRoot : ComplexEntity(), IComplexAggregateRoot diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/model/complex/ComplexEntity.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/model/complex/ComplexEntity.kt deleted file mode 100644 index 4d734e9..0000000 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/model/complex/ComplexEntity.kt +++ /dev/null @@ -1,5 +0,0 @@ -package com.synebula.gaea.domain.model.complex - - -abstract class ComplexEntity : IComplexEntity { -} diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/model/complex/IComplexAggregateRoot.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/model/complex/IComplexAggregateRoot.kt deleted file mode 100644 index 487dc15..0000000 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/model/complex/IComplexAggregateRoot.kt +++ /dev/null @@ -1,9 +0,0 @@ -package com.synebula.gaea.domain.model.complex - -/** - * 继承本接口,说明对象为聚合根。 - * - * @param 主键的类型。 - * @author alex - */ -interface IComplexAggregateRoot : IComplexEntity diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/model/complex/IComplexEntity.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/model/complex/IComplexEntity.kt deleted file mode 100644 index 0bbca4d..0000000 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/model/complex/IComplexEntity.kt +++ /dev/null @@ -1,7 +0,0 @@ -package com.synebula.gaea.domain.model.complex - -import com.synebula.gaea.domain.model.IEntity - -interface IComplexEntity : IEntity { - var secondary: TSecond? -} diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/record/Record.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/record/Record.kt new file mode 100644 index 0000000..61ad642 --- /dev/null +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/record/Record.kt @@ -0,0 +1,21 @@ +package com.synebula.gaea.domain.record + +import java.util.* + + +/** + * 记录信息 + * 添加了创建和修改的人\时间信息 + */ +abstract class Record { + + //记录增加信息 + var creator: String? = null + var creatorName: String? = null + var createTime: Date = Date() + + //记录修改信息 + var modifier: String? = null + var modifierName: String? = null + var modifyTime: Date = Date() +} \ No newline at end of file diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/Command.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/Command.kt index 2c07161..6ac0eb1 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/Command.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/Command.kt @@ -8,5 +8,6 @@ package com.synebula.gaea.domain.service * @since 2020-05-15 */ open class Command : ICommand { + override var payload = "" override var timestamp = 0L } diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/ICommand.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/ICommand.kt index 41e4512..fe3543b 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/ICommand.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/ICommand.kt @@ -8,6 +8,12 @@ package com.synebula.gaea.domain.service * @since 2020-05-15 */ interface ICommand { + + /** + * 命令载荷, 实际的业务数据 + */ + var payload: String + /** * 时间戳。 */ diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/LazyService.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/LazyService.kt index a0f6f4b..2e49652 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/LazyService.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/LazyService.kt @@ -1,6 +1,5 @@ package com.synebula.gaea.domain.service -import com.synebula.gaea.data.IObjectConverter import com.synebula.gaea.data.message.DataMessage import com.synebula.gaea.data.message.Message import com.synebula.gaea.domain.model.IAggregateRoot diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/event/IEvent.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/event/IEvent.kt deleted file mode 100644 index 59132cb..0000000 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/event/IEvent.kt +++ /dev/null @@ -1,4 +0,0 @@ -package com.synebula.gaea.event - -interface IEvent { -} \ No newline at end of file diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/io/scan/ClassPath.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/io/scan/ClassPath.kt index 7aa60b5..90cbd6f 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/io/scan/ClassPath.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/io/scan/ClassPath.kt @@ -34,10 +34,11 @@ object ClassPath { // 判断路径最后一个字符是不是"/",如果不是加上 path = if (path.lastIndexOf("/") != path.length - 1) "$path/" else path - var resources: Enumeration? = null + val resources: Enumeration? try { resources = ClassLoaderContext.get().getResources(path) - } catch (e: IOException) { + } catch (ex: IOException) { + throw RuntimeException(ex) } while (resources!!.hasMoreElements()) { diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/io/scan/ClassScanner.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/io/scan/ClassScanner.kt index 3b03ef0..1cb3474 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/io/scan/ClassScanner.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/io/scan/ClassScanner.kt @@ -30,7 +30,8 @@ class ClassScanner(private var packageName: String) { /** * 文件过滤器 */ - private val fileFilter = FileFilter { file -> file.isDirectory || file.name.endsWith(".class") || file.name.endsWith(".jar") } + private val fileFilter = + FileFilter { file -> file.isDirectory || file.name.endsWith(".class") || file.name.endsWith(".jar") } /** @@ -81,12 +82,15 @@ class ClassScanner(private var packageName: String) { val files = scanDirectory(realPath) for (file in files) { val fileName = file.toString() - if (fileName.contains(".jar") && !fileName.endsWith(".class")) + if (fileName.contains(".jar") && !fileName.endsWith(".class")) { scanJar(file) - else if (fileName.endsWith(".class")) - scanClass(realPath, file) + } +// else if (fileName.endsWith(".class")) { +// } + scanClass(realPath, file) } - } catch (e: UnsupportedEncodingException) { + } catch (ex: UnsupportedEncodingException) { + throw ex } } } @@ -145,6 +149,7 @@ class ClassScanner(private var packageName: String) { } jar.close() } catch (ex: Throwable) { + throw ex } } @@ -191,7 +196,7 @@ class ClassScanner(private var packageName: String) { } } } catch (ex: Throwable) { - + throw ex } } diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/log/Level.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/log/Level.kt index 429ad23..e636cf5 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/log/Level.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/log/Level.kt @@ -2,25 +2,28 @@ package com.synebula.gaea.log /** * 日志等级 - * @author Looly */ enum class Level { /** * 'TRACE' log level. */ TRACE, + /** * 'DEBUG' log level. */ DEBUG, + /** * 'INFO' log level. */ INFO, + /** * 'WARN' log level. */ WARN, + /** * 'ERROR' log level. */ diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/log/logger/IDebugLogger.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/log/logger/IDebugLogger.kt index 5a1cbb1..ba80a59 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/log/logger/IDebugLogger.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/log/logger/IDebugLogger.kt @@ -3,7 +3,6 @@ package com.synebula.gaea.log.logger /** * DEBUG级别日志接口 * - * @author Looly */ interface IDebugLogger { /** diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/log/logger/IErrorLogger.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/log/logger/IErrorLogger.kt index c561a55..5fb200c 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/log/logger/IErrorLogger.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/log/logger/IErrorLogger.kt @@ -2,7 +2,6 @@ package com.synebula.gaea.log.logger /** * ERROR级别日志接口 - * @author Looly */ interface IErrorLogger { /** diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/log/logger/IInfoLogger.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/log/logger/IInfoLogger.kt index fed35bd..453ade2 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/log/logger/IInfoLogger.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/log/logger/IInfoLogger.kt @@ -2,7 +2,6 @@ package com.synebula.gaea.log.logger /** * INFO级别日志接口 - * @author Looly */ interface IInfoLogger { /** diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/log/logger/ITraceLogger.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/log/logger/ITraceLogger.kt index ed29589..c4b89c8 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/log/logger/ITraceLogger.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/log/logger/ITraceLogger.kt @@ -3,7 +3,6 @@ package com.synebula.gaea.log.logger /** * TRACE级别日志接口 * - * @author Looly */ interface ITraceLogger { /** diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/log/logger/IWarnLogger.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/log/logger/IWarnLogger.kt index 803aded..731e21a 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/log/logger/IWarnLogger.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/log/logger/IWarnLogger.kt @@ -2,7 +2,6 @@ package com.synebula.gaea.log.logger /** * WARN级别日志接口 - * @author Looly */ interface IWarnLogger { /** From 072c48f888247e20b328a8c41243f2be3a9f7f5b Mon Sep 17 00:00:00 2001 From: alex Date: Tue, 19 Jul 2022 15:31:48 +0800 Subject: [PATCH 02/14] fix typo nullable issue --- src/gaea.app/build.gradle | 2 +- .../kotlin/com/synebula/gaea/app/Application.kt | 2 +- .../kotlin/com/synebula/gaea/app/IApplication.kt | 16 ++++++++-------- .../com/synebula/gaea/app/LazyApplication.kt | 2 +- .../com/synebula/gaea/app/cmd/CommandApp.kt | 2 +- .../com/synebula/gaea/app/cmd/LazyCommandApp.kt | 2 +- .../com/synebula/gaea/app/query/QueryApp.kt | 2 +- .../query/{MongoQuery.kt => MongodbQuery.kt} | 8 ++++---- .../{MongoRepository.kt => MongodbRepository.kt} | 10 +++++----- 9 files changed, 23 insertions(+), 23 deletions(-) rename src/gaea.mongo/src/main/kotlin/com/synebula/gaea/mongo/query/{MongoQuery.kt => MongodbQuery.kt} (91%) rename src/gaea.mongo/src/main/kotlin/com/synebula/gaea/mongo/repository/{MongoRepository.kt => MongodbRepository.kt} (86%) diff --git a/src/gaea.app/build.gradle b/src/gaea.app/build.gradle index e4d0ae6..ece6833 100644 --- a/src/gaea.app/build.gradle +++ b/src/gaea.app/build.gradle @@ -15,7 +15,7 @@ dependencies { api group: 'net.sf.dozer', name: 'dozer', version: '5.5.1' api group: 'org.apache.poi', name: 'poi-ooxml', version: '5.0.0' api group: 'com.google.code.gson', name: 'gson', version: '2.8.6' - api group: 'com.google.guava', name: 'guava', version: '30.1.1-jre' + api group: 'com.google.guava', name: 'guava', version: '31.1-jre' api group: 'com.auth0', name: 'java-jwt', version: '3.14.0' } diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/Application.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/Application.kt index fdcbd6d..3340151 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/Application.kt +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/Application.kt @@ -22,7 +22,7 @@ open class Application( override var clazz: Class, override var service: IService, override var query: IQuery, - override var logger: ILogger? + override var logger: ILogger, ) : ICommandApp, IQueryApp { @Resource diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/IApplication.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/IApplication.kt index 56bf9fa..d0b3dfe 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/IApplication.kt +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/IApplication.kt @@ -16,7 +16,7 @@ interface IApplication { /** * 日志组件 */ - var logger: ILogger? + var logger: ILogger /** @@ -26,11 +26,11 @@ interface IApplication { val msg = HttpMessage() try { process(msg) - logger?.debug(this, "$name business execute success") + logger.debug(this, "$name business execute success") } catch (ex: Exception) { msg.status = Status.Error msg.message = if (error.isEmpty()) ex.message ?: "" else "$error: ${ex.message}" - logger?.error(this, ex, "[$name]$error: ${ex.message}") + logger.error(this, ex, "[$name]$error: ${ex.message}") } return msg } @@ -42,9 +42,9 @@ interface IApplication { val msg = HttpMessage() try { process(msg) - logger?.debug(this, "$name business execute success") + logger.debug(this, "$name business execute success") } catch (ex: Exception) { - logger?.error(this, ex, "[$name]$error。异常消息将抛出!: ${ex.message}") + logger.error(this, ex, "[$name]$error。异常消息将抛出!: ${ex.message}") throw RuntimeException(error, ex) } return msg @@ -59,12 +59,12 @@ interface IApplication { val authentication = SecurityContextHolder.getContext().authentication.principal.toString() try { val gson = Gson() - return gson.fromJson(authentication, clazz) + return gson.fromJson(authentication, clazz) } catch (ex: Exception) { - logger?.error(this, ex, "[$name]解析用户信息异常!用户信息:$authentication: ${ex.message}") + logger.error(this, ex, "[$name]解析用户信息异常!用户信息:$authentication: ${ex.message}") } } catch (ex: Exception) { - logger?.error(this, ex, "[$name]获取用户信息异常!${ex.message}") + logger.error(this, ex, "[$name]获取用户信息异常!${ex.message}") } return null } diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/LazyApplication.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/LazyApplication.kt index 628a9e9..59c127b 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/LazyApplication.kt +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/LazyApplication.kt @@ -22,7 +22,7 @@ open class LazyApplication, TKey>( override var clazz: Class, //view class type override var service: ILazyService, override var query: IQuery, - override var logger: ILogger? + override var logger: ILogger, ) : ILazyCommandApp, IQueryApp { @Resource diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/CommandApp.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/CommandApp.kt index 78860e9..b461115 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/CommandApp.kt +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/CommandApp.kt @@ -16,7 +16,7 @@ import javax.annotation.Resource open class CommandApp( override var name: String, override var service: IService, - override var logger: ILogger? + override var logger: ILogger, ) : ICommandApp { @Resource override var jsonSerializer: IJsonSerializer? = null diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/LazyCommandApp.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/LazyCommandApp.kt index da637dd..79f5138 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/LazyCommandApp.kt +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/LazyCommandApp.kt @@ -16,7 +16,7 @@ import javax.annotation.Resource open class LazyCommandApp, TKey>( override var name: String, override var service: ILazyService, - override var logger: ILogger? + override var logger: ILogger, ) : ILazyCommandApp { @Resource override var jsonSerializer: IJsonSerializer? = null diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/query/QueryApp.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/query/QueryApp.kt index 7b1a295..fc18d1c 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/query/QueryApp.kt +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/query/QueryApp.kt @@ -14,5 +14,5 @@ open class QueryApp( override var name: String, override var clazz: Class, override var query: IQuery, - override var logger: ILogger? + override var logger: ILogger, ) : IQueryApp \ No newline at end of file diff --git a/src/gaea.mongo/src/main/kotlin/com/synebula/gaea/mongo/query/MongoQuery.kt b/src/gaea.mongo/src/main/kotlin/com/synebula/gaea/mongo/query/MongodbQuery.kt similarity index 91% rename from src/gaea.mongo/src/main/kotlin/com/synebula/gaea/mongo/query/MongoQuery.kt rename to src/gaea.mongo/src/main/kotlin/com/synebula/gaea/mongo/query/MongodbQuery.kt index 01bd5f6..b610d41 100644 --- a/src/gaea.mongo/src/main/kotlin/com/synebula/gaea/mongo/query/MongoQuery.kt +++ b/src/gaea.mongo/src/main/kotlin/com/synebula/gaea/mongo/query/MongodbQuery.kt @@ -16,11 +16,11 @@ import org.springframework.data.mongodb.core.query.Criteria import org.springframework.data.mongodb.core.query.Query /** - * 实现IQuery的Mongo查询类 - * @param template MongoRepo对象 + * 实现IQuery的Mongodb查询类 + * @param template MongodbRepo对象 */ -open class MongoQuery(var template: MongoTemplate, var logger: ILogger? = null) : IQuery { +open class MongodbQuery(var template: MongoTemplate, var logger: ILogger) : IQuery { /** * 使用View解析是collection时是否校验存在,默认不校验 @@ -87,7 +87,7 @@ open class MongoQuery(var template: MongoTemplate, var logger: ILogger? = null) return if (table != null) return table.name else { - this.logger?.info(this, "视图类没有标记[Collection]注解,无法获取Collection名称。尝试使用View<${clazz.name}>名称解析集合") + this.logger.info(this, "视图类没有标记[Collection]注解,无法获取Collection名称。尝试使用View<${clazz.name}>名称解析集合") val name = clazz.simpleName.removeSuffix("View").firstCharLowerCase() if (!validViewCollection || this.template.collectionExists(name)) name diff --git a/src/gaea.mongo/src/main/kotlin/com/synebula/gaea/mongo/repository/MongoRepository.kt b/src/gaea.mongo/src/main/kotlin/com/synebula/gaea/mongo/repository/MongodbRepository.kt similarity index 86% rename from src/gaea.mongo/src/main/kotlin/com/synebula/gaea/mongo/repository/MongoRepository.kt rename to src/gaea.mongo/src/main/kotlin/com/synebula/gaea/mongo/repository/MongodbRepository.kt index 75c7869..fedd944 100644 --- a/src/gaea.mongo/src/main/kotlin/com/synebula/gaea/mongo/repository/MongoRepository.kt +++ b/src/gaea.mongo/src/main/kotlin/com/synebula/gaea/mongo/repository/MongodbRepository.kt @@ -8,18 +8,18 @@ import org.springframework.data.mongodb.core.MongoTemplate import org.springframework.data.mongodb.core.query.Query /** - * 实现ITypedRepository的mongo仓储类 - * @param repo MongoRepo对象 + * 实现ITypedRepository的Mongodb仓储类 + * @param repo MongodbRepo对象 */ -open class MongoRepository(private var repo: MongoTemplate) : IRepository { +open class MongodbRepository(private var repo: MongoTemplate) : IRepository { override fun , TKey> remove(id: TKey, clazz: Class) { this.repo.remove(whereId(id), clazz) } override fun , TKey> get( - id: TKey, - clazz: Class + id: TKey, + clazz: Class, ): TAggregateRoot? { return this.repo.findOne(whereId(id), clazz) } From 7692fb502b8ef9fe1cf9a97582845d099c95bdf5 Mon Sep 17 00:00:00 2001 From: alex Date: Wed, 27 Jul 2022 10:40:24 +0800 Subject: [PATCH 03/14] add bus code --- .../gaea/bus/AllowConcurrentSubscribe.kt | 28 ++ .../kotlin/com/synebula/gaea/bus/AsyncBus.kt | 68 +++++ .../main/kotlin/com/synebula/gaea/bus/Bus.kt | 254 ++++++++++++++++ .../com/synebula/gaea/bus/DeadMessage.kt | 36 +++ .../com/synebula/gaea/bus/Dispatcher.kt | 151 ++++++++++ .../main/kotlin/com/synebula/gaea/bus/IBus.kt | 41 +++ .../kotlin/com/synebula/gaea/bus/IMessage.kt | 3 - .../com/synebula/gaea/bus/IMessageBus.kt | 28 -- .../com/synebula/gaea/bus/LoggingHandler.kt | 34 +++ .../kotlin/com/synebula/gaea/bus/Subscribe.kt | 36 +++ .../com/synebula/gaea/bus/Subscriber.kt | 128 ++++++++ .../gaea/bus/SubscriberExceptionContext.kt | 31 ++ .../gaea/bus/SubscriberExceptionHandler.kt | 24 ++ .../synebula/gaea/bus/SubscriberRegistry.kt | 193 ++++++++++++ .../gaea/bus/messagebus/AsyncMessageBus.kt | 71 +++++ .../gaea/bus/messagebus/IMessageBus.kt | 39 +++ .../gaea/bus/messagebus/MessageBus.kt | 280 ++++++++++++++++++ .../bus/messagebus/TopicSubscriberRegistry.kt | 184 ++++++++++++ .../kotlin/com/synebula/gaea/bus/BusTest.kt | 94 ++++++ 19 files changed, 1692 insertions(+), 31 deletions(-) create mode 100644 src/gaea/src/main/kotlin/com/synebula/gaea/bus/AllowConcurrentSubscribe.kt create mode 100644 src/gaea/src/main/kotlin/com/synebula/gaea/bus/AsyncBus.kt create mode 100644 src/gaea/src/main/kotlin/com/synebula/gaea/bus/Bus.kt create mode 100644 src/gaea/src/main/kotlin/com/synebula/gaea/bus/DeadMessage.kt create mode 100644 src/gaea/src/main/kotlin/com/synebula/gaea/bus/Dispatcher.kt create mode 100644 src/gaea/src/main/kotlin/com/synebula/gaea/bus/IBus.kt delete mode 100644 src/gaea/src/main/kotlin/com/synebula/gaea/bus/IMessage.kt delete mode 100644 src/gaea/src/main/kotlin/com/synebula/gaea/bus/IMessageBus.kt create mode 100644 src/gaea/src/main/kotlin/com/synebula/gaea/bus/LoggingHandler.kt create mode 100644 src/gaea/src/main/kotlin/com/synebula/gaea/bus/Subscribe.kt create mode 100644 src/gaea/src/main/kotlin/com/synebula/gaea/bus/Subscriber.kt create mode 100644 src/gaea/src/main/kotlin/com/synebula/gaea/bus/SubscriberExceptionContext.kt create mode 100644 src/gaea/src/main/kotlin/com/synebula/gaea/bus/SubscriberExceptionHandler.kt create mode 100644 src/gaea/src/main/kotlin/com/synebula/gaea/bus/SubscriberRegistry.kt create mode 100644 src/gaea/src/main/kotlin/com/synebula/gaea/bus/messagebus/AsyncMessageBus.kt create mode 100644 src/gaea/src/main/kotlin/com/synebula/gaea/bus/messagebus/IMessageBus.kt create mode 100644 src/gaea/src/main/kotlin/com/synebula/gaea/bus/messagebus/MessageBus.kt create mode 100644 src/gaea/src/main/kotlin/com/synebula/gaea/bus/messagebus/TopicSubscriberRegistry.kt create mode 100644 src/gaea/src/test/kotlin/com/synebula/gaea/bus/BusTest.kt diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/bus/AllowConcurrentSubscribe.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/AllowConcurrentSubscribe.kt new file mode 100644 index 0000000..1fe2f13 --- /dev/null +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/AllowConcurrentSubscribe.kt @@ -0,0 +1,28 @@ +/* + * Copyright (C) 2007 The Guava Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package com.synebula.gaea.bus + +/** + * Marks an message subscriber method as being thread-safe. This annotation indicates that MessageBus + * may invoke the message subscriber simultaneously from multiple threads. + * + * + * This does not mark the method, and so should be used in combination with [Subscribe]. + * + * @author Cliff + * @since 10.0 + */ +@Retention(AnnotationRetention.RUNTIME) +@Target(AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER) +annotation class AllowConcurrentSubscribe \ No newline at end of file diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/bus/AsyncBus.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/AsyncBus.kt new file mode 100644 index 0000000..1da1f56 --- /dev/null +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/AsyncBus.kt @@ -0,0 +1,68 @@ +/* + * Copyright (C) 2007 The Guava Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package com.synebula.gaea.bus + +import java.util.concurrent.Executor + +/** + * An [Bus] that takes the Executor of your choice and uses it to dispatch messages, + * allowing dispatch to occur asynchronously. + * + * @author Cliff + * @since 10.0 + */ +class AsyncBus : Bus { + /** + * Creates a new AsyncMessageBus that will use `executor` to dispatch messages. Assigns `identifier` as the bus's name for logging purposes. + * + * @param identifier short name for the bus, for logging purposes. + * @param executor Executor to use to dispatch messages. It is the caller's responsibility to shut + * down the executor after the last message has been posted to this message bus. + */ + constructor(identifier: String, executor: Executor) : super( + identifier, + executor, + Dispatcher.legacyAsync(), + LoggingHandler() + ) + + /** + * Creates a new AsyncMessageBus that will use `executor` to dispatch messages. + * + * @param executor Executor to use to dispatch messages. It is the caller's responsibility to shut + * down the executor after the last message has been posted to this message bus. + * @param subscriberExceptionHandler Handler used to handle exceptions thrown from subscribers. + * See [SubscriberExceptionHandler] for more information. + * @since 16.0 + */ + constructor(executor: Executor, subscriberExceptionHandler: SubscriberExceptionHandler) : super( + "default", + executor, + Dispatcher.legacyAsync(), + subscriberExceptionHandler + ) + + /** + * Creates a new AsyncMessageBus that will use `executor` to dispatch messages. + * + * @param executor Executor to use to dispatch messages. It is the caller's responsibility to shut + * down the executor after the last message has been posted to this message bus. + */ + constructor(executor: Executor) : super( + "default", + executor, + Dispatcher.legacyAsync(), + LoggingHandler() + ) +} \ No newline at end of file diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/bus/Bus.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/Bus.kt new file mode 100644 index 0000000..bf36e15 --- /dev/null +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/Bus.kt @@ -0,0 +1,254 @@ +/* + * Copyright (C) 2007 The Guava Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package com.synebula.gaea.bus + +import java.lang.reflect.Method +import java.util.* +import java.util.concurrent.Executor +import java.util.logging.Level +import java.util.logging.Logger + +/** + * Dispatches messages to listeners, and provides ways for listeners to register themselves. + * + *

Avoid MessageBus

+ * + * + * **We recommend against using MessageBus.** It was designed many years ago, and newer + * libraries offer better ways to decouple components and react to messages. + * + * + * To decouple components, we recommend a dependency-injection framework. For Android code, most + * apps use [Dagger](https://dagger.dev). For server code, common options include [Guice](https://github.com/google/guice/wiki/Motivation) and [Spring](https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-introduction). + * Frameworks typically offer a way to register multiple listeners independently and then request + * them together as a set ([Dagger](https://dagger.dev/dev-guide/multibindings), [Guice](https://github.com/google/guice/wiki/Multibindings), [Spring](https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-autowired-annotation)). + * + * + * To react to messages, we recommend a reactive-streams framework like [RxJava](https://github.com/ReactiveX/RxJava/wiki) (supplemented with its [RxAndroid](https://github.com/ReactiveX/RxAndroid) extension if you are building for + * Android) or [Project Reactor](https://projectreactor.io/). (For the basics of + * translating code from using an message bus to using a reactive-streams framework, see these two + * guides: [1](https://blog.jkl.gg/implementing-an-message-bus-with-rxjava-rxbus/), [2](https://lorentzos.com/rxjava-as-message-bus-the-right-way-10a36bdd49ba).) Some usages + * of MessageBus may be better written using [Kotlin coroutines](https://kotlinlang.org/docs/coroutines-guide.html), including [Flow](https://kotlinlang.org/docs/flow.html) and [Channels](https://kotlinlang.org/docs/channels.html). Yet other usages are better served + * by individual libraries that provide specialized support for particular use cases. + * + * + * Disadvantages of MessageBus include: + * + * + * * It makes the cross-references between producer and subscriber harder to find. This can + * complicate debugging, lead to unintentional reentrant calls, and force apps to eagerly + * initialize all possible subscribers at startup time. + * * It uses reflection in ways that break when code is processed by optimizers/minimizer like + * [R8 and Proguard](https://developer.android.com/studio/build/shrink-code). + * * It doesn't offer a way to wait for multiple messages before taking action. For example, it + * doesn't offer a way to wait for multiple producers to all report that they're "ready," nor + * does it offer a way to batch multiple messages from a single producer together. + * * It doesn't support backpressure and other features needed for resilience. + * * It doesn't provide much control of threading. + * * It doesn't offer much monitoring. + * * It doesn't propagate exceptions, so apps don't have a way to react to them. + * * It doesn't interoperate well with RxJava, coroutines, and other more commonly used + * alternatives. + * * It imposes requirements on the lifecycle of its subscribers. For example, if an message + * occurs between when one subscriber is removed and the next subscriber is added, the message + * is dropped. + * * Its performance is suboptimal, especially under Android. + * * It [doesn't support parameterized + * types](https://github.com/google/guava/issues/1431). + * * With the introduction of lambdas in Java 8, MessageBus went from less verbose than listeners + * to [more verbose](https://github.com/google/guava/issues/3311). + * + * + *

MessageBus Summary

+ * + * + * The MessageBus allows publish-subscribe-style communication between components without requiring + * the components to explicitly register with one another (and thus be aware of each other). It is + * designed exclusively to replace traditional Java in-process message distribution using explicit + * registration. It is *not* a general-purpose publish-subscribe system, nor is it intended + * for interprocess communication. + * + *

Receiving Messages

+ * + * + * To receive messages, an object should: + * + * + * 1. Expose a public method, known as the *message subscriber*, which accepts a single + * argument of the type of message desired; + * 1. Mark it with a [Subscribe] annotation; + * 1. Pass itself to an MessageBus instance's [.register] method. + * + * + *

Posting Messages

+ * + * + * To post an message, simply provide the message object to the [.post] method. The + * MessageBus instance will determine the type of message and route it to all registered listeners. + * + * + * Messages are routed based on their type an message will be delivered to any subscriber for + * any type to which the message is *assignable.* This includes implemented interfaces, all + * superclasses, and all interfaces implemented by superclasses. + * + * + * When `post` is called, all registered subscribers for an message are run in sequence, so + * subscribers should be reasonably quick. If an message may trigger an extended process (such as a + * database load), spawn a thread or queue it for later. (For a convenient way to do this, use an + * [AsyncBus].) + * + *

Subscriber Methods

+ * + * + * Message subscriber methods must accept only one argument: the message. + * + * + * Subscribers should not, in general, throw. If they do, the MessageBus will catch and log the + * exception. This is rarely the right solution for error handling and should not be relied upon; it + * is intended solely to help find problems during development. + * + * + * The MessageBus guarantees that it will not call a subscriber method from multiple threads + * simultaneously, unless the method explicitly allows it by bearing the [ ] annotation. If this annotation is not present, subscriber methods need not + * worry about being reentrant, unless also called from outside the MessageBus. + * + *

Dead Messages

+ * + * + * If an message is posted, but no registered subscribers can accept it, it is considered "dead." + * To give the system a second chance to handle dead messages, they are wrapped in an instance of + * [DeadMessage] and reposted. + * + * + * If a subscriber for a supertype of all messages (such as Object) is registered, no message will + * ever be considered dead, and no DeadMessages will be generated. Accordingly, while DeadMessage + * extends [Object], a subscriber registered to receive any Object will never receive a + * DeadMessage. + * + * + * This class is safe for concurrent use. + * + * + * See the Guava User Guide article on [`MessageBus`](https://github.com/google/guava/wiki/MessageBusExplained). + * + * @author Cliff + * @since 10.0 + * @param identifier a brief name for this bus, for logging purposes. Should/home/alex/privacy/project/myths/gaea be a valid Java + * @param executor the default executor this event bus uses for dispatching events to subscribers. + * @param dispatcher message dispatcher. + * @param exceptionHandler Handler for subscriber exceptions. + */ +open class Bus( + override val identifier: String, + override val executor: Executor, + val dispatcher: Dispatcher, + val exceptionHandler: SubscriberExceptionHandler, +) : IBus { + + private val subscribers: SubscriberRegistry = SubscriberRegistry(this) + + /** + * Creates a new MessageBus with the given `identifier`. + * + * @param identifier a brief name for this bus, for logging purposes. Should/home/alex/privacy/project/myths/gaea be a valid Java + * identifier. + */ + @JvmOverloads + constructor(identifier: String = "default") : this( + identifier, + Executor { it.run() }, + Dispatcher.perThreadDispatchQueue(), + LoggingHandler() + ) + + /** + * Creates a new MessageBus with the given [SubscriberExceptionHandler]. + * + * @param exceptionHandler Handler for subscriber exceptions. + * @since 16.0 + */ + constructor(exceptionHandler: SubscriberExceptionHandler) : this( + "default", + Executor { it.run() }, + Dispatcher.perThreadDispatchQueue(), + exceptionHandler + ) + + + /** + * Registers all subscriber methods on `object` to receive messages. + * + * @param subscriber object whose subscriber methods should be registered. + */ + override fun register(subscriber: Any) { + subscribers.register(subscriber) + } + + override fun register(subscriber: Any, method: Method) { + subscribers.register(subscriber, method) + } + + /** + * Unregisters all subscriber methods on a registered `object`. + * + * @param subscriber object whose subscriber methods should be unregistered. + * @throws IllegalArgumentException if the object was not previously registered. + */ + override fun unregister(subscriber: Any) { + subscribers.unregister(subscriber) + } + + /** + * Posts an message to all registered subscribers. This method will return successfully after the + * message has been posted to all subscribers, and regardless of any exceptions thrown by + * subscribers. + * + * + * If no subscribers have been subscribed for `message`'s class, and `message` is not + * already a [DeadMessage], it will be wrapped in a DeadMessage and reposted. + * + * @param message message to post. + */ + override fun publish(message: Any) { + val messageSubscribers = subscribers.getSubscribers(message) + if (messageSubscribers.hasNext()) { + dispatcher.dispatch(message, messageSubscribers) + } else if (message !is DeadMessage) { + // the message had no subscribers and was not itself a DeadMessage + publish(DeadMessage(this, message)) + } + } + + + /** Handles the given exception thrown by a subscriber with the given context. */ + override fun handleException(cause: Throwable?, context: SubscriberExceptionContext) { + try { + exceptionHandler.handleException(cause, context) + } catch (e2: Throwable) { + // if the handler threw an exception... well, just log it + logger.log( + Level.SEVERE, String.format(Locale.ROOT, "Exception %s thrown while handling exception: %s", e2, cause), + e2 + ) + } + } + + override fun toString(): String { + return "Bus(identifier='$identifier', executor=$executor, dispatcher=$dispatcher, exceptionHandler=$exceptionHandler, subscribers=$subscribers)" + } + + companion object { + private val logger = Logger.getLogger(Bus::class.java.name) + } +} \ No newline at end of file diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/bus/DeadMessage.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/DeadMessage.kt new file mode 100644 index 0000000..1c044ac --- /dev/null +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/DeadMessage.kt @@ -0,0 +1,36 @@ +/* + * Copyright (C) 2007 The Guava Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package com.synebula.gaea.bus + +/** + * Wraps an message that was posted, but which had no subscribers and thus could not be delivered. + * + * + * Registering a DeadMessage subscriber is useful for debugging or logging, as it can detect + * misconfigurations in a system's message distribution. + * + * @author Cliff + * @since 10.0 + * + * Creates a new DeadMessage. + * + * @param source object broadcasting the DeadMessage (generally the [Bus]). + * @param message the message that could not be delivered. + */ +class DeadMessage(val source: Any?, val message: Any?) { + + override fun toString(): String { + return "DeadMessage(source=$source, message=$message)" + } +} \ No newline at end of file diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/bus/Dispatcher.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/Dispatcher.kt new file mode 100644 index 0000000..daab5f6 --- /dev/null +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/Dispatcher.kt @@ -0,0 +1,151 @@ +/* + * Copyright (C) 2014 The Guava Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package com.synebula.gaea.bus + +import java.util.* +import java.util.concurrent.ConcurrentLinkedQueue + +/** + * Handler for dispatching messages to subscribers, providing different message ordering guarantees that + * make sense for different situations. + * + * + * **Note:** The dispatcher is orthogonal to the subscriber's `Executor`. The dispatcher + * controls the order in which messages are dispatched, while the executor controls how (i.e. on which + * thread) the subscriber is actually called when an message is dispatched to it. + * + * @author Colin Decker + */ +abstract class Dispatcher { + /** Dispatches the given `message` to the given `subscribers`. */ + abstract fun dispatch(message: T, subscribers: Iterator>?) + + /** Implementation of a [.perThreadDispatchQueue] dispatcher. */ + private class PerThreadQueuedDispatcher : Dispatcher() { + // This dispatcher matches the original dispatch behavior of MessageBus. + /** Per-thread queue of messages to dispatch. */ + private val queue: ThreadLocal>> = object : ThreadLocal>>() { + override fun initialValue(): Queue> { + return ArrayDeque() + } + } + + /** Per-thread dispatch state, used to avoid reentrant message dispatching. */ + private val dispatching: ThreadLocal = object : ThreadLocal() { + override fun initialValue(): Boolean { + return false + } + } + + override fun dispatch(message: T, subscribers: Iterator>?) { + val queueForThread = queue.get() + queueForThread.offer(Message(message, subscribers)) + if (!dispatching.get()) { + dispatching.set(true) + try { + var nextMessage: Message? + while (queueForThread.poll().also { nextMessage = it } != null) { + while (nextMessage!!.subscribers!!.hasNext()) { + nextMessage!!.subscribers!!.next().dispatchMessage(nextMessage!!.message) + } + } + } finally { + dispatching.remove() + queue.remove() + } + } + } + + private class Message(val message: Any, val subscribers: Iterator>?) + } + + /** Implementation of a [.legacyAsync] dispatcher. */ + private class LegacyAsyncDispatcher : Dispatcher() { + // This dispatcher matches the original dispatch behavior of AsyncMessageBus. + // + // We can't really make any guarantees about the overall dispatch order for this dispatcher in + // a multithreaded environment for a couple reasons: + // + // 1. Subscribers to messages posted on different threads can be interleaved with each other + // freely. (A message on one thread, B message on another could yield any of + // [a1, a2, a3, b1, b2], [a1, b2, a2, a3, b2], [a1, b2, b3, a2, a3], etc.) + // 2. It's possible for subscribers to actually be dispatched to in a different order than they + // were added to the queue. It's easily possible for one thread to take the head of the + // queue, immediately followed by another thread taking the next element in the queue. That + // second thread can then dispatch to the subscriber it took before the first thread does. + // + // All this makes me really wonder if there's any value in queueing here at all. A dispatcher + // that simply loops through the subscribers and dispatches the message to each would actually + // probably provide a stronger order guarantee, though that order would obviously be different + // in some cases. + /** Global message queue. */ + private val queue = ConcurrentLinkedQueue>() + override fun dispatch(message: T, subscribers: Iterator>?) { + while (subscribers!!.hasNext()) { + queue.add(MessageWithSubscriber(message, subscribers.next())) + } + var e: MessageWithSubscriber? + while (queue.poll().also { e = it } != null) { + e!!.subscriber!!.dispatchMessage(e!!.message) + } + } + + private class MessageWithSubscriber(val message: T, val subscriber: Subscriber?) + } + + /** Implementation of [.immediate]. */ + private class ImmediateDispatcher : Dispatcher() { + override fun dispatch(message: T, subscribers: Iterator>?) { + while (subscribers!!.hasNext()) { + subscribers.next().dispatchMessage(message) + } + } + } + + companion object { + /** + * Returns a dispatcher that queues messages that are posted reentrantly on a thread that is already + * dispatching an message, guaranteeing that all messages posted on a single thread are dispatched to + * all subscribers in the order they are posted. + * + * + * When all subscribers are dispatched to using a *direct* executor (which dispatches on + * the same thread that posts the message), this yields a breadth-first dispatch order on each + * thread. That is, all subscribers to a single message A will be called before any subscribers to + * any messages B and C that are posted to the message bus by the subscribers to A. + */ + fun perThreadDispatchQueue(): Dispatcher { + return PerThreadQueuedDispatcher() + } + + /** + * Returns a dispatcher that queues messages that are posted in a single global queue. This behavior + * matches the original behavior of AsyncMessageBus exactly, but is otherwise not especially useful. + * For async dispatch, an [immediate][.immediate] dispatcher should generally be + * preferable. + */ + fun legacyAsync(): Dispatcher { + return LegacyAsyncDispatcher() + } + + /** + * Returns a dispatcher that dispatches messages to subscribers immediately as they're posted + * without using an intermediate queue to change the dispatch order. This is effectively a + * depth-first dispatch order, vs. breadth-first when using a queue. + */ + fun immediate(): Dispatcher { + return ImmediateDispatcher() + } + } +} \ No newline at end of file diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/bus/IBus.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/IBus.kt new file mode 100644 index 0000000..207b5e3 --- /dev/null +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/IBus.kt @@ -0,0 +1,41 @@ +package com.synebula.gaea.bus + +import java.lang.reflect.Method +import java.util.concurrent.Executor + +interface IBus { + + val identifier: String + + val executor: Executor + + /** + * 注册事件Listener + * @param subscriber subscriber所在类 + */ + fun register(subscriber: Any) + + /** + * 取消注册事件Listener + * @param subscriber Listener所在类 + */ + fun register(subscriber: Any, method: Method) + + /** + * 取消注册事件Listener + * @param subscriber Listener所在类 + */ + fun unregister(subscriber: Any) + + /** + * 同步发布事件 + * @param message 事件 + */ + fun publish(message: T) + + + /** + * 异常处理 + */ + fun handleException(cause: Throwable?, context: SubscriberExceptionContext) +} \ No newline at end of file diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/bus/IMessage.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/IMessage.kt deleted file mode 100644 index e560295..0000000 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/bus/IMessage.kt +++ /dev/null @@ -1,3 +0,0 @@ -package com.synebula.gaea.bus - -interface IMessage \ No newline at end of file diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/bus/IMessageBus.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/IMessageBus.kt deleted file mode 100644 index 0f435e2..0000000 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/bus/IMessageBus.kt +++ /dev/null @@ -1,28 +0,0 @@ -package com.synebula.gaea.bus - -interface IMessageBus { - - /** - * 注册事件Listener - * @param obj Listener所在类 - */ - fun register(obj: Any) - - /** - * 取消注册事件Listener - * @param obj Listener所在类 - */ - fun unregister(obj: Any) - - /** - * 同步发布事件 - * @param message 事件 - */ - fun publish(message: IMessage) - - /** - * 异步发布事件 - * @param message 事件 - */ - fun publishAsync(message: IMessage) -} \ No newline at end of file diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/bus/LoggingHandler.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/LoggingHandler.kt new file mode 100644 index 0000000..0cab54a --- /dev/null +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/LoggingHandler.kt @@ -0,0 +1,34 @@ +package com.synebula.gaea.bus + +import java.util.logging.Level +import java.util.logging.Logger + + +/** Simple logging handler for subscriber exceptions. */ +internal class LoggingHandler : SubscriberExceptionHandler { + override fun handleException(exception: Throwable?, context: SubscriberExceptionContext) { + val logger = logger(context) + if (logger.isLoggable(Level.SEVERE)) { + logger.log(Level.SEVERE, message(context), exception) + } + } + + companion object { + private fun logger(context: SubscriberExceptionContext): Logger { + return Logger.getLogger(Bus::class.java.name + "." + context.bus.identifier) + } + + private fun message(context: SubscriberExceptionContext): String { + val method = context.subscriberMethod + return ("Exception thrown by subscriber method " + + method.name + + '(' + + method.parameterTypes[0].name + + ')' + + " on subscriber " + + context.subscriber + + " when dispatching message: " + + context.message) + } + } +} \ No newline at end of file diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/bus/Subscribe.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/Subscribe.kt new file mode 100644 index 0000000..2a7ab0d --- /dev/null +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/Subscribe.kt @@ -0,0 +1,36 @@ +/* + * Copyright (C) 2007 The Guava Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package com.synebula.gaea.bus + +/** + * Marks a method as a message subscriber. + * + * + * The type of message will be indicated by the method's first (and only) parameter, which cannot + * be primitive. If this annotation is applied to methods with zero parameters, or more than one + * parameter, the object containing the method will not be able to register for message delivery from + * the [Bus]. + * + * + * Unless also annotated with @[AllowConcurrentSubscribe], message subscriber methods will be + * invoked serially by each message bus that they are registered with. + * + * @author Cliff + * @since 10.0 + * + * @param topics method subscribe topics, only for [com.synebula.gaea.bus.messagebus.MessageBus] + */ +@Retention(AnnotationRetention.RUNTIME) +@Target(AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER) +annotation class Subscribe(val topics: Array = []) \ No newline at end of file diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/bus/Subscriber.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/Subscriber.kt new file mode 100644 index 0000000..c66d422 --- /dev/null +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/Subscriber.kt @@ -0,0 +1,128 @@ +/* + * Copyright (C) 2014 The Guava Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package com.synebula.gaea.bus + +import java.lang.reflect.InvocationTargetException +import java.lang.reflect.Method +import java.util.concurrent.Executor + +/** + * A subscriber method on a specific object, plus the executor that should be used for dispatching + * messages to it. + * + * + * Two subscribers are equivalent when they refer to the same method on the same object (not + * class). This property is used to ensure that no subscriber method is registered more than once. + * + * @author Colin Decker + * + * @param bus The message bus this subscriber belongs to. + * @param target The object with the subscriber method. + * @param method Subscriber method. + */ +open class Subscriber private constructor( + private val bus: IBus, + val target: Any, + val method: Method, +) { + /** Executor to use for dispatching messages to this subscriber. */ + private val executor: Executor? + + init { + method.isAccessible = true + executor = bus.executor + } + + /** Dispatches `message` to this subscriber using the proper executor. */ + fun dispatchMessage(message: Any) { + executor!!.execute { + try { + invokeSubscriberMethod(message) + } catch (e: InvocationTargetException) { + bus.handleException(e.cause, context(message)) + } + } + } + + /** + * Invokes the subscriber method. This method can be overridden to make the invocation + * synchronized. + */ + @Throws(InvocationTargetException::class) + open fun invokeSubscriberMethod(message: Any) { + try { + method.invoke(target, message) + } catch (e: IllegalArgumentException) { + throw Error("Method rejected target/argument: $message", e) + } catch (e: IllegalAccessException) { + throw Error("Method became inaccessible: $message", e) + } catch (e: InvocationTargetException) { + if (e.cause is Error) { + throw (e.cause as Error?)!! + } + throw e + } + } + + /** Gets the context for the given message. */ + private fun context(message: Any): SubscriberExceptionContext { + return SubscriberExceptionContext(bus, message, target, method) + } + + override fun hashCode(): Int { + return (31 + method.hashCode()) * 31 + System.identityHashCode(target) + } + + override fun equals(other: Any?): Boolean { + if (other is Subscriber<*>) { + // Use == so that different equal instances will still receive messages. + // We only guard against the case that the same object is registered + // multiple times + return target === other.target && method == other.method + } + return false + } + + /** + * Subscriber that synchronizes invocations of a method to ensure that only one thread may enter + * the method at a time. + */ + internal class SynchronizedSubscriber(bus: IBus, target: Any, method: Method) : + Subscriber(bus, target, method) { + @Throws(InvocationTargetException::class) + override fun invokeSubscriberMethod(message: Any) { + synchronized(this) { super.invokeSubscriberMethod(message) } + } + } + + companion object { + /** Creates a `Subscriber` for `method` on `subscriber`. */ + fun create(bus: IBus, subscriber: Any, method: Method): Subscriber { + return if (isDeclaredThreadSafe(method)) Subscriber( + bus, + subscriber, + method + ) else SynchronizedSubscriber( + bus, subscriber, method + ) + } + + /** + * Checks whether `method` is thread-safe, as indicated by the presence of the [ ] annotation. + */ + private fun isDeclaredThreadSafe(method: Method): Boolean { + return method.getAnnotation(AllowConcurrentSubscribe::class.java) != null + } + } +} diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/bus/SubscriberExceptionContext.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/SubscriberExceptionContext.kt new file mode 100644 index 0000000..d0b9bb4 --- /dev/null +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/SubscriberExceptionContext.kt @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2013 The Guava Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package com.synebula.gaea.bus + +import java.lang.reflect.Method + +/** + * Context for an exception thrown by a subscriber. + * + * @since 16.0 + * + * @param bus The [IBus] that handled the message and the subscriber. Useful for + * broadcasting a new message based on the error. + * @param message The message object that caused the subscriber to throw. + * @param subscriber The source subscriber context. + * @param subscriberMethod the subscribed method. + */ +class SubscriberExceptionContext internal constructor( + val bus: IBus, val message: Any, val subscriber: Any, val subscriberMethod: Method, +) \ No newline at end of file diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/bus/SubscriberExceptionHandler.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/SubscriberExceptionHandler.kt new file mode 100644 index 0000000..14c40f2 --- /dev/null +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/SubscriberExceptionHandler.kt @@ -0,0 +1,24 @@ +/* + * Copyright (C) 2013 The Guava Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package com.synebula.gaea.bus + +/** + * Handler for exceptions thrown by message subscribers. + * + * @since 16.0 + */ +interface SubscriberExceptionHandler { + /** Handles exceptions thrown by subscribers. */ + fun handleException(exception: Throwable?, context: SubscriberExceptionContext) +} \ No newline at end of file diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/bus/SubscriberRegistry.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/SubscriberRegistry.kt new file mode 100644 index 0000000..05138f0 --- /dev/null +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/SubscriberRegistry.kt @@ -0,0 +1,193 @@ +/* + * Copyright (C) 2014 The Guava Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package com.synebula.gaea.bus + +import com.synebula.gaea.reflect.Types +import java.lang.reflect.Method +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.CopyOnWriteArraySet + +/** + * Registry of subscribers to a single message bus. + * + * @author Colin Decker + */ +open class SubscriberRegistry(private val bus: IBus) { + /** + * All registered subscribers, indexed by message type. + * + * + * The [CopyOnWriteArraySet] values make it easy and relatively lightweight to get an + * immutable snapshot of all current subscribers to a message without any locking. + */ + private val subscribers = ConcurrentHashMap, CopyOnWriteArraySet>>() + + + /** Registers all subscriber methods on the given subscriber object. */ + open fun register(subscriber: Any) { + val listenerMethods = findAllSubscribers(subscriber) + for ((eventType, messageMethodsInListener) in listenerMethods) { + var messageSubscribers = subscribers[eventType] + if (messageSubscribers == null) { + val newSet = CopyOnWriteArraySet>() + messageSubscribers = subscribers.putIfAbsent(eventType, newSet) ?: newSet + } + messageSubscribers.addAll(messageMethodsInListener) + } + } + + /** Registers subscriber method on the given subscriber object. */ + open fun register(subscriber: Any, method: Method) { + val parameterTypes = method.parameterTypes + val eventType = parameterTypes[0] + check(parameterTypes.size == 1) { + "Method $method has @SubscribeTopic annotation but has ${parameterTypes.size} parameters. Subscriber methods must have exactly 1 parameter." + } + check(!parameterTypes[0].isPrimitive) { + "@SubscribeTopic method $method's parameter is ${parameterTypes[0].name}. Subscriber methods cannot accept primitives. " + } + var messageSubscribers = subscribers[eventType] + if (messageSubscribers == null) { + val newSet = CopyOnWriteArraySet>() + messageSubscribers = subscribers.putIfAbsent(eventType, newSet) ?: newSet + } + messageSubscribers.add(Subscriber.create(bus, subscriber, method)) + } + + + /** Unregisters all subscribers on the given subscriber object. */ + open fun unregister(subscriber: Any) { + val listenerMethods = findAllSubscribers(subscriber) + for ((eventType, listenerMethodsForType) in listenerMethods) { + val currentSubscribers = subscribers[eventType] + require(!(currentSubscribers == null || !currentSubscribers.removeAll(listenerMethodsForType.toSet()))) { + // if removeAll returns true, all we really know is that at least one subscriber was + // removed... however, barring something very strange we can assume that if at least one + // subscriber was removed, all subscribers on subscriber for that message type were... after + // all, the definition of subscribers on a particular class is totally static + "missing message subscriber for an annotated method. Is $subscriber registered?" + } + + // don't try to remove the set if it's empty; that can't be done safely without a lock + // anyway, if the set is empty it'll just be wrapping an array of length 0 + } + } + + /** + * Gets an iterator representing an immutable snapshot of all subscribers to the given message at + * the time this method is called. + */ + fun getSubscribers(eventType: Any): Iterator> { + val eventSubscribers: CopyOnWriteArraySet> = + subscribers[eventType.javaClass] ?: CopyOnWriteArraySet() + return eventSubscribers.iterator() + } + + /** + * Returns all subscribers for the given subscriber grouped by the type of message they subscribe to. + */ + private fun findAllSubscribers(subscriber: Any): Map, List>> { + val methodsInListener = mutableMapOf, List>>() + val clazz: Class<*> = subscriber.javaClass + for (method in getAnnotatedMethods(clazz)) { + val parameterTypes = method.parameterTypes + val eventType = parameterTypes[0] + val methods = methodsInListener[eventType]?.toMutableList() ?: mutableListOf() + methods.add(Subscriber.create(bus, subscriber, method)) + methodsInListener[eventType] = methods + } + return methodsInListener.toMap() + } + + + class MethodIdentifier(method: Method) { + private val name: String = method.name + private val parameterTypes: List> = listOf(*method.parameterTypes) + + override fun hashCode(): Int { + var result = name.hashCode() + for (element in parameterTypes) result = 31 * result + element.hashCode() + return result + } + + override fun equals(other: Any?): Boolean { + if (other is MethodIdentifier) { + return name == other.name && parameterTypes == other.parameterTypes + } + return false + } + } + + /** + * A thread-safe cache that contains the mapping from each class to all methods in that class and + * all super-classes, that are annotated with `@Subscribe`. The cache is shared across all + * instances of this class; this greatly improves performance if multiple MessageBus instances are + * created and objects of the same class are registered on all of them. + */ + protected val subscriberMethodsCache = mapOf, List>() + + @Synchronized + protected fun getAnnotatedMethods(clazz: Class<*>): List { + var methods = subscriberMethodsCache[clazz] + if (methods == null) + methods = getAnnotatedMethodsNotCached(clazz, Subscribe::class.java) + return methods + } + + protected fun getAnnotatedMethodsNotCached( + clazz: Class<*>, + annotationClass: Class, + ): List { + val supertypes = flattenHierarchy(clazz) + val identifiers = mutableMapOf() + for (supertype in supertypes) { + for (method in supertype.declaredMethods) { + if (method.isAnnotationPresent(annotationClass) && !method.isSynthetic) { + val parameterTypes = method.parameterTypes + check(parameterTypes.size == 1) { + "Method $method has @SubscribeTopic annotation but has ${parameterTypes.size} parameters. Subscriber methods must have exactly 1 parameter." + } + check(!parameterTypes[0].isPrimitive) { + "@SubscribeTopic method $method's parameter is ${parameterTypes[0].name}. Subscriber methods cannot accept primitives. " + } + + val identifier = MethodIdentifier(method) + if (!identifiers.containsKey(identifier)) { + identifiers[identifier] = method + } + } + } + } + return identifiers.values.toList() + } + + companion object { + + /** Global cache of classes to their flattened hierarchy of supertypes. */ + protected val flattenHierarchyCache = mutableMapOf, Set>>() + + /** + * Flattens a class's type hierarchy into a set of `Class` objects including all + * superclasses (transitively) and all interfaces implemented by these superclasses. + */ + fun flattenHierarchy(clazz: Class<*>): Set> { + var supertypes = flattenHierarchyCache[clazz] + if (supertypes == null) { + supertypes = Types.supertypes(clazz) + flattenHierarchyCache[clazz] = supertypes + } + return supertypes + } + } +} \ No newline at end of file diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/bus/messagebus/AsyncMessageBus.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/messagebus/AsyncMessageBus.kt new file mode 100644 index 0000000..30cb8b5 --- /dev/null +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/messagebus/AsyncMessageBus.kt @@ -0,0 +1,71 @@ +/* + * Copyright (C) 2007 The Guava Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package com.synebula.gaea.bus.messagebus + +import com.synebula.gaea.bus.Dispatcher +import com.synebula.gaea.bus.LoggingHandler +import com.synebula.gaea.bus.SubscriberExceptionHandler +import java.util.concurrent.Executor + +/** + * An [MessageBus] that takes the Executor of your choice and uses it to dispatch events, + * allowing dispatch to occur asynchronously. + * + * @author Cliff + * @since 10.0 + */ +class AsyncMessageBus : MessageBus { + /** + * Creates a new AsyncEventBus that will use `executor` to dispatch events. Assigns `identifier` as the bus's name for logging purposes. + * + * @param identifier short name for the bus, for logging purposes. + * @param executor Executor to use to dispatch events. It is the caller's responsibility to shut + * down the executor after the last event has been posted to this event bus. + */ + constructor(identifier: String, executor: Executor) : super( + identifier, + executor, + Dispatcher.legacyAsync(), + LoggingHandler() + ) + + /** + * Creates a new AsyncEventBus that will use `executor` to dispatch events. + * + * @param executor Executor to use to dispatch events. It is the caller's responsibility to shut + * down the executor after the last event has been posted to this event bus. + * @param subscriberExceptionHandler Handler used to handle exceptions thrown from subscribers. + * See [SubscriberExceptionHandler] for more information. + * @since 16.0 + */ + constructor(executor: Executor, subscriberExceptionHandler: SubscriberExceptionHandler) : super( + "default", + executor, + Dispatcher.legacyAsync(), + subscriberExceptionHandler + ) + + /** + * Creates a new AsyncEventBus that will use `executor` to dispatch events. + * + * @param executor Executor to use to dispatch events. It is the caller's responsibility to shut + * down the executor after the last event has been posted to this event bus. + */ + constructor(executor: Executor) : super( + "default", + executor, + Dispatcher.legacyAsync(), + LoggingHandler() + ) +} \ No newline at end of file diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/bus/messagebus/IMessageBus.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/messagebus/IMessageBus.kt new file mode 100644 index 0000000..da731fb --- /dev/null +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/messagebus/IMessageBus.kt @@ -0,0 +1,39 @@ +package com.synebula.gaea.bus.messagebus + +import com.synebula.gaea.bus.IBus +import java.lang.reflect.Method + +interface IMessageBus : IBus { + + /** + * 注册事件Listener + * @param topics 主题 + * @param subscriber subscriber对象 + */ + fun register(topics: Array, subscriber: Any) + + /** + * 注册事件Listener + * @param topics 主题 + * @param subscriber subscriber对象 + * @param method Listener方法 + */ + fun register(topics: Array, subscriber: Any, method: Method) + + + /** + * 取消注册事件Listener + * @param topic 主题 + * @param subscriber subscriber对象 + */ + fun unregister(topic: String, subscriber: Any) + + + /** + * 同步发布事件 + * @param topic 主题 + * @param message 事件 + */ + fun publish(topic: String, message: T) + +} \ No newline at end of file diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/bus/messagebus/MessageBus.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/messagebus/MessageBus.kt new file mode 100644 index 0000000..db6a4aa --- /dev/null +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/messagebus/MessageBus.kt @@ -0,0 +1,280 @@ +/* + * Copyright (C) 2007 The Guava Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package com.synebula.gaea.bus.messagebus + +import com.synebula.gaea.bus.* +import java.lang.reflect.Method +import java.util.* +import java.util.concurrent.Executor +import java.util.logging.Level +import java.util.logging.Logger + +/** + * Dispatches events to listeners, and provides ways for listeners to register themselves. + * + *

Avoid EventBus

+ * + * + * **We recommend against using EventBus.** It was designed many years ago, and newer + * libraries offer better ways to decouple components and react to events. + * + * + * To decouple components, we recommend a dependency-injection framework. For Android code, most + * apps use [Dagger](https://dagger.dev). For server code, common options include [Guice](https://github.com/google/guice/wiki/Motivation) and [Spring](https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-introduction). + * Frameworks typically offer a way to register multiple listeners independently and then request + * them together as a set ([Dagger](https://dagger.dev/dev-guide/multibindings), [Guice](https://github.com/google/guice/wiki/Multibindings), [Spring](https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-autowired-annotation)). + * + * + * To react to events, we recommend a reactive-streams framework like [RxJava](https://github.com/ReactiveX/RxJava/wiki) (supplemented with its [RxAndroid](https://github.com/ReactiveX/RxAndroid) extension if you are building for + * Android) or [Project Reactor](https://projectreactor.io/). (For the basics of + * translating code from using an event bus to using a reactive-streams framework, see these two + * guides: [1](https://blog.jkl.gg/implementing-an-event-bus-with-rxjava-rxbus/), [2](https://lorentzos.com/rxjava-as-event-bus-the-right-way-10a36bdd49ba).) Some usages + * of EventBus may be better written using [Kotlin coroutines](https://kotlinlang.org/docs/coroutines-guide.html), including [Flow](https://kotlinlang.org/docs/flow.html) and [Channels](https://kotlinlang.org/docs/channels.html). Yet other usages are better served + * by individual libraries that provide specialized support for particular use cases. + * + * + * Disadvantages of EventBus include: + * + * + * * It makes the cross-references between producer and subscriber harder to find. This can + * complicate debugging, lead to unintentional reentrant calls, and force apps to eagerly + * initialize all possible subscribers at startup time. + * * It uses reflection in ways that break when code is processed by optimizers/minimizer like + * [R8 and Proguard](https://developer.android.com/studio/build/shrink-code). + * * It doesn't offer a way to wait for multiple events before taking action. For example, it + * doesn't offer a way to wait for multiple producers to all report that they're "ready," nor + * does it offer a way to batch multiple events from a single producer together. + * * It doesn't support backpressure and other features needed for resilience. + * * It doesn't provide much control of threading. + * * It doesn't offer much monitoring. + * * It doesn't propagate exceptions, so apps don't have a way to react to them. + * * It doesn't interoperate well with RxJava, coroutines, and other more commonly used + * alternatives. + * * It imposes requirements on the lifecycle of its subscribers. For example, if an event + * occurs between when one subscriber is removed and the next subscriber is added, the event + * is dropped. + * * Its performance is suboptimal, especially under Android. + * * It [doesn't support parameterized + * types](https://github.com/google/guava/issues/1431). + * * With the introduction of lambdas in Java 8, EventBus went from less verbose than listeners + * to [more verbose](https://github.com/google/guava/issues/3311). + * + * + *

EventBus Summary

+ * + * + * The EventBus allows publish-subscribe-style communication between components without requiring + * the components to explicitly register with one another (and thus be aware of each other). It is + * designed exclusively to replace traditional Java in-process event distribution using explicit + * registration. It is *not* a general-purpose publish-subscribe system, nor is it intended + * for interprocess communication. + * + *

Receiving Events

+ * + * + * To receive events, an object should: + * + * + * 1. Expose a public method, known as the *event subscriber*, which accepts a single + * argument of the type of event desired; + * 1. Mark it with a [Subscribe] annotation; + * 1. Pass itself to an EventBus instance's [.register] method. + * + * + *

Posting Events

+ * + * + * To post an event, simply provide the event object to the [.post] method. The + * EventBus instance will determine the type of event and route it to all registered listeners. + * + * + * Events are routed based on their type an event will be delivered to any subscriber for + * any type to which the event is *assignable.* This includes implemented interfaces, all + * superclasses, and all interfaces implemented by superclasses. + * + * + * When `post` is called, all registered subscribers for an event are run in sequence, so + * subscribers should be reasonably quick. If an event may trigger an extended process (such as a + * database load), spawn a thread or queue it for later. (For a convenient way to do this, use an + * [AsyncMessageBus].) + * + *

Subscriber Methods

+ * + * + * Event subscriber methods must accept only one argument: the event. + * + * + * Subscribers should not, in general, throw. If they do, the EventBus will catch and log the + * exception. This is rarely the right solution for error handling and should not be relied upon; it + * is intended solely to help find problems during development. + * + * + * The EventBus guarantees that it will not call a subscriber method from multiple threads + * simultaneously, unless the method explicitly allows it by bearing the [ ] annotation. If this annotation is not present, subscriber methods need not + * worry about being reentrant, unless also called from outside the EventBus. + * + *

Dead Events

+ * + * + * If an event is posted, but no registered subscribers can accept it, it is considered "dead." + * To give the system a second chance to handle dead events, they are wrapped in an instance of + * [DeadMessage] and reposted. + * + * + * If a subscriber for a supertype of all events (such as Object) is registered, no event will + * ever be considered dead, and no DeadEvents will be generated. Accordingly, while DeadMessage + * extends [Object], a subscriber registered to receive any Object will never receive a + * DeadMessage. + * + * + * This class is safe for concurrent use. + * + * + * See the Guava User Guide article on [`EventBus`](https://github.com/google/guava/wiki/EventBusExplained). + * + * @author Cliff + * @param identifier a brief name for this bus, for logging purposes. Should/home/alex/privacy/project/myths/gaea be a valid Java + * @param executor the default executor this event bus uses for dispatching events to subscribers. + * @param dispatcher message dispatcher. + * @param exceptionHandler Handler for subscriber exceptions. + */ +open class MessageBus internal constructor( + override val identifier: String, + override val executor: Executor, + val dispatcher: Dispatcher, + val exceptionHandler: SubscriberExceptionHandler, +) : IMessageBus { + val DEAD_TOPIC = "DEAD_TOPIC" + + val subscribers = TopicSubscriberRegistry(this) + + /** + * Creates a new EventBus with the given `identifier`. + * + * @param identifier a brief name for this bus, for logging purposes. Should/home/alex/privacy/project/myths/gaea be a valid Java + * identifier. + */ + @JvmOverloads + constructor(identifier: String = "default") : this( + identifier, + Executor { it.run() }, + Dispatcher.perThreadDispatchQueue(), + LoggingHandler() + ) + + /** + * Creates a new EventBus with the given [SubscriberExceptionHandler]. + * + * @param exceptionHandler Handler for subscriber exceptions. + * @since 16.0 + */ + constructor(exceptionHandler: SubscriberExceptionHandler) : this( + "default", + Executor { it.run() }, + Dispatcher.perThreadDispatchQueue(), + exceptionHandler + ) + + override fun register(topics: Array, subscriber: Any) { + subscribers.register(topics, subscriber) + } + + /** + * Registers subscriber method on `object` to receive messages. + * + * @param topics method subscribe topic. + * @param subscriber subscriber method declare object. + * @param method subscriber method should be registered. + */ + override fun register(topics: Array, subscriber: Any, method: Method) { + subscribers.register(topics, subscriber, method) + } + + + /** + * Registers all subscriber methods on `object` to receive messages. + * + * @param subscriber object whose subscriber methods should be registered. + */ + override fun register(subscriber: Any) { + subscribers.register(subscriber) + } + + override fun register(subscriber: Any, method: Method) { + subscribers.register(subscriber, method) + } + + /** + * Unregisters all subscriber methods on a registered `object`. + * + * @param subscriber object whose subscriber methods should be unregistered. + * @throws IllegalArgumentException if the object was not previously registered. + */ + override fun unregister(subscriber: Any) { + subscribers.unregister(subscriber) + } + + override fun unregister(topic: String, subscriber: Any) { + subscribers.unregister(topic, subscriber) + } + + /** + * Posts an message to all registered subscribers. This method will return successfully after the + * message has been posted to all subscribers, and regardless of any exceptions thrown by + * subscribers. + * + * @param message message to post. + */ + override fun publish(message: T) { + val messageSubscribers = subscribers.getSubscribers(message.javaClass.name) + if (messageSubscribers.hasNext()) { + dispatcher.dispatch(message, messageSubscribers) + } else { + // the message had no subscribers and was not itself a DeadMessage + publish(DEAD_TOPIC, message) + } + } + + override fun publish(topic: String, message: T) { + val messageSubscribers = subscribers.getSubscribers(topic) + if (messageSubscribers.hasNext()) { + dispatcher.dispatch(message, messageSubscribers) + } else if (topic != DEAD_TOPIC) { + // the message had no subscribers and was not itself a DeadMessage + publish(DEAD_TOPIC, message) + } + } + + + /** Handles the given exception thrown by a subscriber with the given context. */ + override fun handleException(cause: Throwable?, context: SubscriberExceptionContext) { + try { + exceptionHandler.handleException(cause, context) + } catch (e2: Throwable) { + // if the handler threw an exception... well, just log it + logger.log( + Level.SEVERE, String.format(Locale.ROOT, "Exception %s thrown while handling exception: %s", e2, cause), + e2 + ) + } + } + + override fun toString(): String { + return "MessageBus(identifier='$identifier', executor=$executor, dispatcher=$dispatcher, exceptionHandler=$exceptionHandler, subscribers=$subscribers)" + } + + companion object { + private val logger = Logger.getLogger(Bus::class.java.name) + } +} \ No newline at end of file diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/bus/messagebus/TopicSubscriberRegistry.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/messagebus/TopicSubscriberRegistry.kt new file mode 100644 index 0000000..6c8d0f7 --- /dev/null +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/messagebus/TopicSubscriberRegistry.kt @@ -0,0 +1,184 @@ +/* + * Copyright (C) 2014 The Guava Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package com.synebula.gaea.bus.messagebus + +import com.synebula.gaea.bus.Subscribe +import com.synebula.gaea.bus.Subscriber +import com.synebula.gaea.bus.SubscriberRegistry +import java.lang.reflect.Method +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.CopyOnWriteArraySet + +/** + * Registry of subscribers to a single message bus. + * + * @author Colin Decker + */ +open class TopicSubscriberRegistry(private val bus: IMessageBus) : SubscriberRegistry(bus) { + /** + * All registered subscribers, indexed by message type. + * + * + * The [CopyOnWriteArraySet] values make it easy and relatively lightweight to get an + * immutable snapshot of all current subscribers to an message without any locking. + */ + private val subscribers = ConcurrentHashMap>>() + + open fun register(topics: Array, subscriber: Any) { + val listenerMethods = findAllSubscribers(subscriber) + for (topic in topics) { + for ((_, messageMethodsInListener) in listenerMethods) { + var messageSubscribers = subscribers[topic] + if (messageSubscribers == null) { + val newSet = CopyOnWriteArraySet>() + messageSubscribers = subscribers.putIfAbsent(topic, newSet) ?: newSet + } + messageSubscribers.addAll(messageMethodsInListener) + } + } + } + + open fun register(topics: Array, subscriber: Any, method: Method) { + for (topic in topics) { + var messageSubscribers = subscribers[topic] + if (messageSubscribers == null) { + val newSet = CopyOnWriteArraySet>() + messageSubscribers = subscribers.putIfAbsent(topic, newSet) ?: newSet + } + messageSubscribers.add(Subscriber.create(this.bus, subscriber, method)) + } + } + + /** Registers all subscriber methods on the given subscriber object. */ + override fun register(subscriber: Any) { + val listenerMethods = findAllSubscribers(subscriber) + for ((topic, messageMethodsInListener) in listenerMethods) { + var messageSubscribers = subscribers[topic] + if (messageSubscribers == null) { + val newSet = CopyOnWriteArraySet>() + messageSubscribers = subscribers.putIfAbsent(topic, newSet) ?: newSet + } + messageSubscribers.addAll(messageMethodsInListener) + } + } + + /** Registers subscriber method on the given subscriber object. */ + override fun register(subscriber: Any, method: Method) { + val parameterTypes = method.parameterTypes + check(parameterTypes.size == 1) { + "Method $method has @SubscribeTopic annotation but has ${parameterTypes.size} parameters. Subscriber methods must have exactly 1 parameter." + } + check(!parameterTypes[0].isPrimitive) { + "@SubscribeTopic method $method's parameter is ${parameterTypes[0].name}. Subscriber methods cannot accept primitives. " + } + + val eventType = parameterTypes[0] + val topic = eventType.name + var messageSubscribers = subscribers[topic] + if (messageSubscribers == null) { + val newSet = CopyOnWriteArraySet>() + messageSubscribers = subscribers.putIfAbsent(topic, newSet) ?: newSet + } + messageSubscribers.add(Subscriber.create(bus, subscriber, method)) + } + + /** Unregisters all subscribers on the given subscriber object. */ + override fun unregister(subscriber: Any) { + val listenerMethods = findAllSubscribers(subscriber) + for ((topic, listenerMethodsForType) in listenerMethods) { + val currentSubscribers = subscribers[topic] + require(!(currentSubscribers == null || !currentSubscribers.removeAll(listenerMethodsForType.toSet()))) { + // if removeAll returns true, all we really know is that at least one subscriber was + // removed... however, barring something very strange we can assume that if at least one + // subscriber was removed, all subscribers on subscriber for that message type were... after + // all, the definition of subscribers on a particular class is totally static + "missing message subscriber for an annotated method. Is $subscriber registered?" + } + + // don't try to remove the set if it's empty; that can't be done safely without a lock + // anyway, if the set is empty it'll just be wrapping an array of length 0 + } + } + + /** Unregisters all subscribers by topic on the given subscriber object. */ + open fun unregister(topic: String, subscriber: Any) { + val listenerMethods = findAllSubscribers(subscriber) + if (listenerMethods[topic] == null) return //不包含topic则推出 + val currentSubscribers = subscribers[topic] + require(!(currentSubscribers == null || !currentSubscribers.removeAll(listenerMethods[topic]!!.toSet()))) { + // if removeAll returns true, all we really know is that at least one subscriber was + // removed... however, barring something very strange we can assume that if at least one + // subscriber was removed, all subscribers on subscriber for that message type were... after + // all, the definition of subscribers on a particular class is totally static + "missing message subscriber for an annotated method. Is $subscriber registered?" + } + + // don't try to remove the set if it's empty; that can't be done safely without a lock + // anyway, if the set is empty it'll just be wrapping an array of length 0 + } + + + /** + * Gets an iterator representing an immutable snapshot of all subscribers to the given message at + * the time this method is called. + */ + fun getSubscribers(topic: String): Iterator> { + val topicSubscribers: CopyOnWriteArraySet> = subscribers[topic] ?: CopyOnWriteArraySet() + return topicSubscribers.iterator() + } + + /** + * Returns all subscribers for the given subscriber grouped by the type of message they subscribe to. + */ + private fun findAllSubscribers(subscriber: Any): Map>> { + val methodsInListener = mutableMapOf>>() + val clazz: Class<*> = subscriber.javaClass + for (method in getAnnotatedMethods(clazz)) { + var topics = method.getAnnotation(Subscribe::class.java).topics + + //如果没有定义topic,则使用消息类名称做topic + if (topics.isEmpty()) { + val parameterTypes = method.parameterTypes + val messageType = parameterTypes[0] + topics = arrayOf(messageType.name) + } + for (topic in topics) { + val listeners = methodsInListener.getOrDefault(topic, mutableListOf()) + listeners.add(Subscriber.create(bus, subscriber, method)) + methodsInListener[topic] = listeners + } + } + return methodsInListener + } + + + class MethodIdentifier(method: Method) { + private val name: String = method.name + private val parameterTypes: List> = listOf(*method.parameterTypes) + + override fun hashCode(): Int { + var result = name.hashCode() + for (element in parameterTypes) result = 31 * result + element.hashCode() + return result + } + + override fun equals(other: Any?): Boolean { + if (other is MethodIdentifier) { + return name == other.name && parameterTypes == other.parameterTypes + } + return false + } + } + +} \ No newline at end of file diff --git a/src/gaea/src/test/kotlin/com/synebula/gaea/bus/BusTest.kt b/src/gaea/src/test/kotlin/com/synebula/gaea/bus/BusTest.kt new file mode 100644 index 0000000..0022320 --- /dev/null +++ b/src/gaea/src/test/kotlin/com/synebula/gaea/bus/BusTest.kt @@ -0,0 +1,94 @@ +package com.synebula.gaea.bus + +import com.synebula.gaea.bus.messagebus.AsyncMessageBus +import com.synebula.gaea.bus.messagebus.IMessageBus +import com.synebula.gaea.bus.messagebus.MessageBus +import org.junit.Test +import java.util.concurrent.Executors + + +class BusTest { + + @Test + fun testBus() { + val bus: IBus = Bus() + val subscriber = TestSubscriber() + bus.register(subscriber) + bus.publish("Hello world") + bus.publish(subscriber) + bus.publish(1) + } + + @Test + fun testAsyncBus() { + val bus: IBus = AsyncBus(Executors.newFixedThreadPool(10)) + val subscriber = TestSubscriber() + bus.register(subscriber, subscriber.javaClass.declaredMethods[0]) + bus.register(subscriber, subscriber.javaClass.declaredMethods[1]) + bus.publish("Hello world") + bus.publish(subscriber) + } + + @Test + fun testMessageBus() { + val bus: IMessageBus = MessageBus() + val subscriber = TestTopicSubscriber() + bus.register(subscriber) + bus.publish("hello", "Hello world") + bus.publish("whoami", subscriber) + } + + @Test + fun testMessageBus2() { + val bus: IMessageBus = AsyncMessageBus(Executors.newFixedThreadPool(10)) + val subscriber = TestTopicSubscriber() + val subscriber2 = TestTopicSubscriber2() + bus.register(subscriber) + bus.register(subscriber2) + bus.publish("hello", "Hello world") + bus.publish("whoami", subscriber) + + bus.unregister(subscriber2) + bus.publish("hello", "Hello world") + bus.publish("whoami", subscriber) + } + + internal class TestSubscriber { + @Subscribe + fun echo(name: String) { + println(name) + } + + @Subscribe + fun whoAmI(testSubscriber: TestSubscriber) { + println(testSubscriber.javaClass.name) + } + + } + + internal class TestTopicSubscriber { + @Subscribe(topics = ["hello"]) + fun echo(name: String) { + println(name) + } + + @Subscribe(topics = ["whoami"]) + fun whoAmI(testSubscriber: TestTopicSubscriber) { + println(testSubscriber.javaClass.name) + } + + } + + internal class TestTopicSubscriber2 { + @Subscribe(topics = ["hello"]) + fun echo(name: String) { + println("2 $name") + } + + @Subscribe(topics = ["whoami"]) + fun whoAmI(testSubscriber: TestTopicSubscriber) { + println("2 ${testSubscriber.javaClass.name}") + } + + } +} \ No newline at end of file From a0cfba5dd986c919631a9263c7b90df01a8a0890 Mon Sep 17 00:00:00 2001 From: alex Date: Wed, 27 Jul 2022 15:23:19 +0800 Subject: [PATCH 04/14] =?UTF-8?q?=E4=BF=AE=E6=94=B9ID=E6=B3=9B=E5=9E=8B?= =?UTF-8?q?=E5=90=8D=E7=A7=B0=EF=BC=8C=E9=87=8D=E6=9E=84Serialization?= =?UTF-8?q?=E5=86=85=E5=AE=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/synebula/gaea/app/Application.kt | 7 +-- ...azyApplication.kt => SimpleApplication.kt} | 22 ++++++--- .../com/synebula/gaea/app/cmd/CommandApp.kt | 6 +-- .../com/synebula/gaea/app/cmd/ICommandApp.kt | 8 +-- ...LazyCommandApp.kt => ISimpleCommandApp.kt} | 10 ++-- ...{LazyCommandApp.kt => SimpleCommandApp.kt} | 8 +-- .../gaea/app/component/DozerConverter.kt | 6 +-- .../synebula/gaea/app/component/poi/Excel.kt | 4 +- .../app/component/security/WebSecurity.kt | 49 ++++++++++--------- .../com/synebula/gaea/app/query/IQueryApp.kt | 4 +- .../com/synebula/gaea/app/query/QueryApp.kt | 4 +- .../com/synebula/gaea/mongo/MongoExt.kt | 2 +- .../synebula/gaea/mongo/query/MongodbQuery.kt | 2 +- .../mongo/repository/MongodbRepository.kt | 19 ++++--- .../synebula/gaea/data/IObjectConverter.kt | 21 -------- .../synebula/gaea/data/message/DataMessage.kt | 2 +- .../synebula/gaea/data/message/IMessage.kt | 16 ++++++ .../message/{Message.kt => StatusMessage.kt} | 2 +- .../gaea/data/serialization/IDeserializer.kt | 7 +-- .../gaea/data/serialization/IObjectMapper.kt | 10 ++++ .../gaea/data/serialization/ISerializer.kt | 8 +-- .../serialization/json/IJsonDeserializer.kt | 13 ++--- .../serialization/json/IJsonSerializer.kt | 13 ++--- .../gaea/domain/model/AggregateRoot.kt | 2 +- .../com/synebula/gaea/domain/model/Entity.kt | 2 +- .../gaea/domain/model/IAggregateRoot.kt | 2 +- .../com/synebula/gaea/domain/model/IEntity.kt | 6 +-- .../com/synebula/gaea/domain/record/Record.kt | 2 +- .../gaea/domain/repository/IRepository.kt | 10 ++-- .../domain/repository/ISpecificRepository.kt | 15 ++---- .../domain/repository/context/IContext.kt | 6 +-- .../synebula/gaea/domain/service/IService.kt | 12 ++--- .../{ILazyService.kt => ISimpleService.kt} | 12 ++--- .../synebula/gaea/domain/service/Service.kt | 40 +++++++-------- .../{LazyService.kt => SimpleService.kt} | 22 ++++----- .../kotlin/com/synebula/gaea/query/IQuery.kt | 2 +- .../kotlin/com/synebula/gaea/reflect/Types.kt | 23 +++++++++ 37 files changed, 210 insertions(+), 189 deletions(-) rename src/gaea.app/src/main/kotlin/com/synebula/gaea/app/{LazyApplication.kt => SimpleApplication.kt} (50%) rename src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/{ILazyCommandApp.kt => ISimpleCommandApp.kt} (78%) rename src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/{LazyCommandApp.kt => SimpleCommandApp.kt} (71%) delete mode 100644 src/gaea/src/main/kotlin/com/synebula/gaea/data/IObjectConverter.kt create mode 100644 src/gaea/src/main/kotlin/com/synebula/gaea/data/message/IMessage.kt rename src/gaea/src/main/kotlin/com/synebula/gaea/data/message/{Message.kt => StatusMessage.kt} (92%) create mode 100644 src/gaea/src/main/kotlin/com/synebula/gaea/data/serialization/IObjectMapper.kt rename src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/{ILazyService.kt => ISimpleService.kt} (68%) rename src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/{LazyService.kt => SimpleService.kt} (78%) create mode 100644 src/gaea/src/main/kotlin/com/synebula/gaea/reflect/Types.kt diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/Application.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/Application.kt index 3340151..759905e 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/Application.kt +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/Application.kt @@ -13,17 +13,18 @@ import javax.annotation.Resource * 联合服务,同时实现了ICommandApp和IQueryApp接口 * * @param name 业务名称 + * @param clazz 试图业务对象 * @param service 业务domain服务 * @param query 业务查询服务 * @param logger 日志组件 */ -open class Application( +open class Application( override var name: String, override var clazz: Class, - override var service: IService, + override var service: IService, override var query: IQuery, override var logger: ILogger, -) : ICommandApp, IQueryApp { +) : ICommandApp, IQueryApp { @Resource override var jsonSerializer: IJsonSerializer? = null diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/LazyApplication.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/SimpleApplication.kt similarity index 50% rename from src/gaea.app/src/main/kotlin/com/synebula/gaea/app/LazyApplication.kt rename to src/gaea.app/src/main/kotlin/com/synebula/gaea/app/SimpleApplication.kt index 59c127b..de5dc96 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/LazyApplication.kt +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/SimpleApplication.kt @@ -1,30 +1,38 @@ package com.synebula.gaea.app -import com.synebula.gaea.app.cmd.ILazyCommandApp +import com.google.common.reflect.TypeToken +import com.synebula.gaea.app.cmd.ISimpleCommandApp import com.synebula.gaea.app.query.IQueryApp import com.synebula.gaea.data.serialization.json.IJsonSerializer +import com.synebula.gaea.domain.model.AggregateRoot import com.synebula.gaea.domain.model.IAggregateRoot -import com.synebula.gaea.domain.service.ILazyService +import com.synebula.gaea.domain.service.ISimpleService import com.synebula.gaea.log.ILogger import com.synebula.gaea.query.IQuery import javax.annotation.Resource /** - * 联合服务,同时实现了ILazyCommandApp和IQueryApp接口 + * 简单的服务, 取消了Command对象 * * @param name 业务名称 + * @param clazz 业务对象类型 * @param service 业务domain服务 * @param query 业务查询服务 * @param logger 日志组件 */ -open class LazyApplication, TKey>( +open class SimpleApplication, ID>( override var name: String, - override var clazz: Class, //view class type - override var service: ILazyService, + override var clazz: Class, + override var service: ISimpleService, override var query: IQuery, override var logger: ILogger, -) : ILazyCommandApp, IQueryApp { +) : ISimpleCommandApp, IQueryApp { @Resource override var jsonSerializer: IJsonSerializer? = null +} + +fun main() { + val rawType = TypeToken.of(AggregateRoot::class.java).types.rawTypes() + println(rawType) } \ No newline at end of file diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/CommandApp.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/CommandApp.kt index b461115..516dd1a 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/CommandApp.kt +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/CommandApp.kt @@ -13,11 +13,11 @@ import javax.annotation.Resource * @param service 业务domain服务 * @param logger 日志组件 */ -open class CommandApp( +open class CommandApp( override var name: String, - override var service: IService, + override var service: IService, override var logger: ILogger, -) : ICommandApp { +) : ICommandApp { @Resource override var jsonSerializer: IJsonSerializer? = null } \ No newline at end of file diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/ICommandApp.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/ICommandApp.kt index 9976caf..d92374d 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/ICommandApp.kt +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/ICommandApp.kt @@ -16,10 +16,10 @@ import org.springframework.web.bind.annotation.* * @version 0.1 * @since 2020-05-15 */ -interface ICommandApp : IApplication { +interface ICommandApp : IApplication { var jsonSerializer: IJsonSerializer? - var service: IService + var service: IService @PostMapping @MethodName("添加") @@ -29,14 +29,14 @@ interface ICommandApp : IApplication { @PutMapping("/{id:.+}") @MethodName("更新") - fun update(@PathVariable id: TKey, @RequestBody command: TCommand): HttpMessage { + fun update(@PathVariable id: ID, @RequestBody command: TCommand): HttpMessage { this.service.update(id, command) return HttpMessage() } @DeleteMapping("/{id:.+}") @MethodName("删除") - fun remove(@PathVariable id: TKey): HttpMessage { + fun remove(@PathVariable id: ID): HttpMessage { val msg = HttpMessage() try { msg.data = this.service.remove(id) diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/ILazyCommandApp.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/ISimpleCommandApp.kt similarity index 78% rename from src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/ILazyCommandApp.kt rename to src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/ISimpleCommandApp.kt index b3e1aec..bc4451b 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/ILazyCommandApp.kt +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/ISimpleCommandApp.kt @@ -6,7 +6,7 @@ import com.synebula.gaea.app.struct.HttpMessage import com.synebula.gaea.data.message.Status import com.synebula.gaea.data.serialization.json.IJsonSerializer import com.synebula.gaea.domain.model.IAggregateRoot -import com.synebula.gaea.domain.service.ILazyService +import com.synebula.gaea.domain.service.ISimpleService import org.springframework.web.bind.annotation.* /** @@ -16,10 +16,10 @@ import org.springframework.web.bind.annotation.* * @version 0.1 * @since 2020-05-15 */ -interface ILazyCommandApp, TKey> : IApplication { +interface ISimpleCommandApp, ID> : IApplication { var jsonSerializer: IJsonSerializer? - var service: ILazyService + var service: ISimpleService @PostMapping @MethodName("添加") @@ -29,14 +29,14 @@ interface ILazyCommandApp, TKey> : IApplication { @PutMapping("/{id:.+}") @MethodName("更新") - fun update(@PathVariable id: TKey, @RequestBody entity: TRoot): HttpMessage { + fun update(@PathVariable id: ID, @RequestBody entity: TRoot): HttpMessage { this.service.update(id, entity) return HttpMessage() } @DeleteMapping("/{id:.+}") @MethodName("删除") - fun remove(@PathVariable id: TKey): HttpMessage { + fun remove(@PathVariable id: ID): HttpMessage { val msg = HttpMessage() try { msg.data = this.service.remove(id) diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/LazyCommandApp.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/SimpleCommandApp.kt similarity index 71% rename from src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/LazyCommandApp.kt rename to src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/SimpleCommandApp.kt index 79f5138..84c881f 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/LazyCommandApp.kt +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/SimpleCommandApp.kt @@ -2,7 +2,7 @@ package com.synebula.gaea.app.cmd import com.synebula.gaea.data.serialization.json.IJsonSerializer import com.synebula.gaea.domain.model.IAggregateRoot -import com.synebula.gaea.domain.service.ILazyService +import com.synebula.gaea.domain.service.ISimpleService import com.synebula.gaea.log.ILogger import javax.annotation.Resource @@ -13,11 +13,11 @@ import javax.annotation.Resource * @param service 业务domain服务 * @param logger 日志组件 */ -open class LazyCommandApp, TKey>( +open class SimpleCommandApp, ID>( override var name: String, - override var service: ILazyService, + override var service: ISimpleService, override var logger: ILogger, -) : ILazyCommandApp { +) : ISimpleCommandApp { @Resource override var jsonSerializer: IJsonSerializer? = null } \ No newline at end of file diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/DozerConverter.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/DozerConverter.kt index a2f7421..66dd9f5 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/DozerConverter.kt +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/DozerConverter.kt @@ -1,12 +1,12 @@ package com.synebula.gaea.app.component -import com.synebula.gaea.data.IObjectConverter +import com.synebula.gaea.data.serialization.IObjectMapper import org.dozer.DozerBeanMapper import org.springframework.stereotype.Component @Component -class DozerConverter : IObjectConverter { +class DozerConverter : IObjectMapper { private val converter = DozerBeanMapper() - override fun convert(src: Any, dest: Class): T = converter.map(src, dest) + override fun deserialize(src: Any, targetClass: Class): T = converter.map(src, targetClass) } \ No newline at end of file diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/poi/Excel.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/poi/Excel.kt index b8e2626..923dbd0 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/poi/Excel.kt +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/poi/Excel.kt @@ -45,7 +45,7 @@ object Excel { //声明列对象 // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制 var row = sheet.createRow(0) - row.height = 25 * 20 + row.height = (25 * 20).toShort() var cell: HSSFCell //创建标题 for (col in data.columnNames.indices) { @@ -69,7 +69,7 @@ object Excel { for (i in data.data.indices) { try { row = sheet.createRow(i + 1) - row.height = 20 * 20 + row.height = (20 * 20).toShort() col = 0 while (col < data.data[i].size) { cell = row.createCell(col) diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/security/WebSecurity.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/security/WebSecurity.kt index c0f6f3c..fa6208f 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/security/WebSecurity.kt +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/security/WebSecurity.kt @@ -4,11 +4,11 @@ import com.synebula.gaea.app.struct.HttpMessage import com.synebula.gaea.data.message.Status import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.annotation.Bean +import org.springframework.security.authentication.AuthenticationManager import org.springframework.security.config.annotation.web.builders.HttpSecurity -import org.springframework.security.config.annotation.web.builders.WebSecurity -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter +import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer import org.springframework.security.config.http.SessionCreationPolicy +import org.springframework.security.web.SecurityFilterChain import org.springframework.stereotype.Component import org.springframework.web.cors.CorsConfiguration import org.springframework.web.cors.CorsConfigurationSource @@ -16,38 +16,41 @@ import org.springframework.web.cors.UrlBasedCorsConfigurationSource @Component -@EnableWebSecurity -class WebSecurity : WebSecurityConfigurerAdapter() { +class WebSecurity { @Autowired lateinit var tokenManager: TokenManager + @Autowired + lateinit var authenticationManager: AuthenticationManager + /** * 安全配置 */ @Throws(Exception::class) - override fun configure(http: HttpSecurity) { + fun filterChain(http: HttpSecurity): SecurityFilterChain { // 跨域共享 http.cors() - .and().csrf().disable() // 跨域伪造请求限制无效 - .authorizeRequests() - .anyRequest().authenticated()// 资源任何人都可访问 - .and() - .addFilter(WebAuthorization(authenticationManager(), tokenManager))// 添加JWT鉴权拦截器 - .sessionManagement() - .sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 设置Session的创建策略为:Spring Security永不创建HttpSession 不使用HttpSession来获取SecurityContext - .and() - .exceptionHandling() - .authenticationEntryPoint { _, response, _ -> - response.status = Status.Success - response.characterEncoding = "utf-8" - response.contentType = "text/javascript;charset=utf-8" - response.writer.print(HttpMessage(Status.Unauthorized, "用户未登录,请重新登录后尝试!")) - } + .and().csrf().disable() // 跨域伪造请求限制无效 + .authorizeRequests() + .anyRequest().authenticated()// 资源任何人都可访问 + .and() + .addFilter(WebAuthorization(authenticationManager, tokenManager))// 添加JWT鉴权拦截器 + .sessionManagement() + .sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 设置Session的创建策略为:Spring Security永不创建HttpSession 不使用HttpSession来获取SecurityContext + .and() + .exceptionHandling() + .authenticationEntryPoint { _, response, _ -> + response.status = Status.Success + response.characterEncoding = "utf-8" + response.contentType = "text/javascript;charset=utf-8" + response.writer.print(HttpMessage(Status.Unauthorized, "用户未登录,请重新登录后尝试!")) + } + return http.build() } @Throws(Exception::class) - override fun configure(web: WebSecurity) { - web.ignoring().antMatchers("/sign/**") + fun filterChain(): WebSecurityCustomizer { + return WebSecurityCustomizer { web -> web.ignoring().antMatchers("/sign/**") } } /** diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/query/IQueryApp.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/query/IQueryApp.kt index ff5ded0..dda9478 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/query/IQueryApp.kt +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/query/IQueryApp.kt @@ -9,7 +9,7 @@ import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.RequestParam -interface IQueryApp : IApplication { +interface IQueryApp : IApplication { /** * 查询服务 */ @@ -22,7 +22,7 @@ interface IQueryApp : IApplication { @MethodName("获取数据") @GetMapping("/{id:.+}") - fun get(@PathVariable id: TKey): HttpMessage { + fun get(@PathVariable id: ID): HttpMessage { val data = this.query.get(id, clazz) val msg = HttpMessage() msg.data = data diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/query/QueryApp.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/query/QueryApp.kt index fc18d1c..729f48c 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/query/QueryApp.kt +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/query/QueryApp.kt @@ -10,9 +10,9 @@ import com.synebula.gaea.query.IQuery * @param query 业务查询服务 * @param logger 日志组件 */ -open class QueryApp( +open class QueryApp( override var name: String, override var clazz: Class, override var query: IQuery, override var logger: ILogger, -) : IQueryApp \ No newline at end of file +) : IQueryApp \ No newline at end of file diff --git a/src/gaea.mongo/src/main/kotlin/com/synebula/gaea/mongo/MongoExt.kt b/src/gaea.mongo/src/main/kotlin/com/synebula/gaea/mongo/MongoExt.kt index c75d204..ecf65cd 100644 --- a/src/gaea.mongo/src/main/kotlin/com/synebula/gaea/mongo/MongoExt.kt +++ b/src/gaea.mongo/src/main/kotlin/com/synebula/gaea/mongo/MongoExt.kt @@ -116,7 +116,7 @@ fun Query.where(params: Map?, clazz: Class<*>): Query { * * @param id 业务ID */ -fun whereId(id: TKey): Query = Query.query(Criteria.where("_id").`is`(id)) +fun whereId(id: ID): Query = Query.query(Criteria.where("_id").`is`(id)) /** * 获取排序对象 diff --git a/src/gaea.mongo/src/main/kotlin/com/synebula/gaea/mongo/query/MongodbQuery.kt b/src/gaea.mongo/src/main/kotlin/com/synebula/gaea/mongo/query/MongodbQuery.kt index b610d41..fe117cb 100644 --- a/src/gaea.mongo/src/main/kotlin/com/synebula/gaea/mongo/query/MongodbQuery.kt +++ b/src/gaea.mongo/src/main/kotlin/com/synebula/gaea/mongo/query/MongodbQuery.kt @@ -27,7 +27,7 @@ open class MongodbQuery(var template: MongoTemplate, var logger: ILogger) : IQue */ var validViewCollection = false - override fun get(id: TKey, clazz: Class): TView? { + override fun get(id: ID, clazz: Class): TView? { return this.template.findOne(whereId(id), clazz, this.collection(clazz)) } diff --git a/src/gaea.mongo/src/main/kotlin/com/synebula/gaea/mongo/repository/MongodbRepository.kt b/src/gaea.mongo/src/main/kotlin/com/synebula/gaea/mongo/repository/MongodbRepository.kt index fedd944..4c2b469 100644 --- a/src/gaea.mongo/src/main/kotlin/com/synebula/gaea/mongo/repository/MongodbRepository.kt +++ b/src/gaea.mongo/src/main/kotlin/com/synebula/gaea/mongo/repository/MongodbRepository.kt @@ -13,29 +13,32 @@ import org.springframework.data.mongodb.core.query.Query */ open class MongodbRepository(private var repo: MongoTemplate) : IRepository { - override fun , TKey> remove(id: TKey, clazz: Class) { + override fun , ID> remove(id: ID, clazz: Class) { this.repo.remove(whereId(id), clazz) } - override fun , TKey> get( - id: TKey, + override fun , ID> get( + id: ID, clazz: Class, ): TAggregateRoot? { return this.repo.findOne(whereId(id), clazz) } - override fun , TKey> update( - obj: TAggregateRoot, - clazz: Class + override fun , ID> update( + obj: TAggregateRoot, + clazz: Class, ) { this.repo.save(obj) } - override fun , TKey> add(obj: TAggregateRoot, clazz: Class) { + override fun , ID> add(obj: TAggregateRoot, clazz: Class) { this.repo.save(obj) } - override fun , TKey> add(obj: List, clazz: Class) { + override fun , ID> add( + obj: List, + clazz: Class, + ) { this.repo.insert(obj, clazz) } diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/data/IObjectConverter.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/data/IObjectConverter.kt deleted file mode 100644 index 3deb5f2..0000000 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/data/IObjectConverter.kt +++ /dev/null @@ -1,21 +0,0 @@ -package com.synebula.gaea.data - -/** - * 对象转换器,支持对象之间的转换。 - * - * @author alex - * @version 0.1 - * @since 2020-05-15 - */ -interface IObjectConverter { - - /** - * 转换源对象到目标对象。 - * - * @param src 源对象。 - * @param dest 目标对象。 - * @param 目标对象类型。 - * @return 目标对象 - */ - fun convert(src: Any, dest: Class): T -} diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/data/message/DataMessage.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/data/message/DataMessage.kt index 96bd46e..ef129e1 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/data/message/DataMessage.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/data/message/DataMessage.kt @@ -8,7 +8,7 @@ import java.util.* * * @param T 消息数据类型 */ -open class DataMessage() : Message() { +open class DataMessage() : StatusMessage() { /** * 传递的业务数据 diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/data/message/IMessage.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/data/message/IMessage.kt new file mode 100644 index 0000000..dbf332d --- /dev/null +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/data/message/IMessage.kt @@ -0,0 +1,16 @@ +package com.synebula.gaea.data.message + +/** + * 消息结构 + */ +interface IMessage { + /** + * 命令载荷, 实际的业务数据 + */ + var message: String + + /** + * 时间戳。 + */ + var timestamp: Long +} \ No newline at end of file diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/data/message/Message.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/data/message/StatusMessage.kt similarity index 92% rename from src/gaea/src/main/kotlin/com/synebula/gaea/data/message/Message.kt rename to src/gaea/src/main/kotlin/com/synebula/gaea/data/message/StatusMessage.kt index c003dca..a0a960b 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/data/message/Message.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/data/message/StatusMessage.kt @@ -1,6 +1,6 @@ package com.synebula.gaea.data.message -open class Message { +open class StatusMessage { /** * 状态。200成功,400错误,500异常 */ diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/data/serialization/IDeserializer.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/data/serialization/IDeserializer.kt index e0d170d..d6efe44 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/data/serialization/IDeserializer.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/data/serialization/IDeserializer.kt @@ -2,16 +2,17 @@ package com.synebula.gaea.data.serialization /** * 序列化器 + * @param 源数据类型 */ -interface IDeserializer { +interface IDeserializer { /** * 反序列化 * - * @param 源数据类型 * @param 目标数据类型 * @param src 源数据 + * @param targetClass 目标对象。 * @return 目标数据 */ - fun deserialize(src: S): T + fun deserialize(src: S, targetClass: Class): T } \ No newline at end of file diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/data/serialization/IObjectMapper.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/data/serialization/IObjectMapper.kt new file mode 100644 index 0000000..4ddbb65 --- /dev/null +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/data/serialization/IObjectMapper.kt @@ -0,0 +1,10 @@ +package com.synebula.gaea.data.serialization + +/** + * 对象映射器,支持对象之间的转换。 + * + * @author alex + * @version 0.1 + * @since 2020-05-15 + */ +interface IObjectMapper : IDeserializer diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/data/serialization/ISerializer.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/data/serialization/ISerializer.kt index 925c518..e3ca229 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/data/serialization/ISerializer.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/data/serialization/ISerializer.kt @@ -2,16 +2,16 @@ package com.synebula.gaea.data.serialization /** * 序列化器 + * @param 目标数据类型 */ -interface ISerializer { +interface ISerializer { /** * 序列化 - * * @param 源数据类型 - * @param 目标数据类型 + * * @param src 源数据 * @return 目标数据 */ - fun serialize(src: S): T + fun serialize(src: S): T } \ No newline at end of file diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/data/serialization/json/IJsonDeserializer.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/data/serialization/json/IJsonDeserializer.kt index da7c13b..09acb01 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/data/serialization/json/IJsonDeserializer.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/data/serialization/json/IJsonDeserializer.kt @@ -1,15 +1,8 @@ package com.synebula.gaea.data.serialization.json +import com.synebula.gaea.data.serialization.IDeserializer + /** * 序列化器 */ -interface IJsonDeserializer { - /** - * 反序列化 - * - * @param 目标数据类型 - * @param src Json字符串数据 - * @return 目标数据 - */ - fun deserialize(src: String): T -} \ No newline at end of file +interface IJsonDeserializer : IDeserializer \ No newline at end of file diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/data/serialization/json/IJsonSerializer.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/data/serialization/json/IJsonSerializer.kt index e154644..9130125 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/data/serialization/json/IJsonSerializer.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/data/serialization/json/IJsonSerializer.kt @@ -1,15 +1,8 @@ package com.synebula.gaea.data.serialization.json +import com.synebula.gaea.data.serialization.ISerializer + /** * 序列化器 */ -interface IJsonSerializer { - /** - * 序列化 - * - * @param 源数据类型 - * @param src 源数据 - * @return Json字符串 - */ - fun serialize(src: S): String -} \ No newline at end of file +interface IJsonSerializer : ISerializer \ No newline at end of file diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/model/AggregateRoot.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/model/AggregateRoot.kt index c1bb7fb..3f7962f 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/model/AggregateRoot.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/model/AggregateRoot.kt @@ -1,5 +1,5 @@ package com.synebula.gaea.domain.model -abstract class AggregateRoot : Entity(), IAggregateRoot { +abstract class AggregateRoot : Entity(), IAggregateRoot { override var alive: Boolean = true } diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/model/Entity.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/model/Entity.kt index 95d3fe8..8aa77b7 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/model/Entity.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/model/Entity.kt @@ -1,3 +1,3 @@ package com.synebula.gaea.domain.model -abstract class Entity : IEntity +abstract class Entity : IEntity diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/model/IAggregateRoot.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/model/IAggregateRoot.kt index b442100..2222405 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/model/IAggregateRoot.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/model/IAggregateRoot.kt @@ -5,7 +5,7 @@ package com.synebula.gaea.domain.model * * @author alex **/ -interface IAggregateRoot : IEntity { +interface IAggregateRoot : IEntity { /** * 实体对象是否有效。 diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/model/IEntity.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/model/IEntity.kt index 3016f06..ea99e25 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/model/IEntity.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/model/IEntity.kt @@ -5,13 +5,13 @@ package com.synebula.gaea.domain.model * * @author alex * - * @param 主键的类型。 + * @param 主键的类型。 **/ -interface IEntity { +interface IEntity { /** * 实体ID */ - var id: TKey? + var id: ID? } diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/record/Record.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/record/Record.kt index 61ad642..b6ae3c2 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/record/Record.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/record/Record.kt @@ -7,7 +7,7 @@ import java.util.* * 记录信息 * 添加了创建和修改的人\时间信息 */ -abstract class Record { +abstract class Record { //记录增加信息 var creator: String? = null diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/IRepository.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/IRepository.kt index 8c653ef..67d4ea2 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/IRepository.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/IRepository.kt @@ -13,7 +13,7 @@ interface IRepository { * @param obj 需要插入的对象。 * @return 返回原对象,如果对象ID为自增,则补充自增ID。 */ - fun , TKey> add(obj: TAggregateRoot, clazz: Class) + fun , ID> add(obj: TAggregateRoot, clazz: Class) /** * 插入多个个对象。 @@ -21,7 +21,7 @@ interface IRepository { * @param obj 需要插入的对象。 * @return 返回原对象,如果对象ID为自增,则补充自增ID。 */ - fun , TKey> add(obj: List, clazz: Class) + fun , ID> add(obj: List, clazz: Class) /** * 更新对象。 @@ -29,7 +29,7 @@ interface IRepository { * @param obj 需要更新的对象。 * @return */ - fun , TKey> update(obj: TAggregateRoot, clazz: Class) + fun , ID> update(obj: TAggregateRoot, clazz: Class) /** * 通过id删除该条数据 @@ -37,7 +37,7 @@ interface IRepository { * @param id id * @param clazz 操作数据的类型 */ - fun , TKey> remove(id: TKey, clazz: Class) + fun , ID> remove(id: ID, clazz: Class) /** * 根据ID获取对象。 @@ -46,7 +46,7 @@ interface IRepository { * @param clazz 操作数据的类型 * @return 聚合根 */ - fun , TKey> get(id: TKey, clazz: Class): TAggregateRoot? + fun , ID> get(id: ID, clazz: Class): TAggregateRoot? /** diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/ISpecificRepository.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/ISpecificRepository.kt index 06e8564..d15ec31 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/ISpecificRepository.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/ISpecificRepository.kt @@ -10,7 +10,7 @@ import com.synebula.gaea.domain.model.IAggregateRoot * @param this T is the parameter * @author alex */ -interface ISpecificRepository, TKey> { +interface ISpecificRepository, ID> { /** * 仓储的对象类 @@ -39,7 +39,7 @@ interface ISpecificRepository, TKey> { * @param id * @return */ - fun remove(id: TKey) + fun remove(id: ID) /** * 根据ID获取对象。 @@ -47,16 +47,7 @@ interface ISpecificRepository, TKey> { * @param id 对象ID。 * @return */ - fun get(id: TKey): TAggregateRoot - - /** - * 根据ID获取对象。 - * - * @param id id - * @param clazz 操作数据的类型 - * @return 聚合根 - */ - fun , TKey> get(id: TKey, clazz: Class): T + fun get(id: ID): TAggregateRoot /** diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/context/IContext.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/context/IContext.kt index 9c4cb5a..f585580 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/context/IContext.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/context/IContext.kt @@ -12,19 +12,19 @@ interface IContext : IUnitOfWork { * 将指定的聚合根标注为“新建”状态。 * @param obj */ - fun , TKey> add(obj: TType) + fun , ID> add(obj: TType) /** * 将指定的聚合根标注为“更改”状态。 * * @param obj */ - fun , TKey> update(obj: TType) + fun , ID> update(obj: TType) /** * 将指定的聚合根标注为“删除”状态。 * * @param obj */ - fun , TKey> remove(obj: TType) + fun , ID> remove(obj: TType) } diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/IService.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/IService.kt index 46d39a1..6cabe08 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/IService.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/IService.kt @@ -1,7 +1,7 @@ package com.synebula.gaea.domain.service import com.synebula.gaea.data.message.DataMessage -import com.synebula.gaea.data.message.Message +import com.synebula.gaea.data.message.StatusMessage import com.synebula.gaea.log.ILogger @@ -11,24 +11,24 @@ import com.synebula.gaea.log.ILogger * @version 0.0.1 * @since 2016年9月18日 下午2:23:15 */ -interface IService { +interface IService { /** * 日志组件。 */ var logger: ILogger - fun add(command: ICommand): DataMessage + fun add(command: ICommand): DataMessage - fun update(id: TKey, command: ICommand) + fun update(id: ID, command: ICommand) - fun remove(id: TKey) + fun remove(id: ID) /** * 添加一个删除对象前执行监听器。 * @param key 监听器标志。 * @param func 监听方法。 */ - fun addBeforeRemoveListener(key: String, func: (id: TKey) -> Message) + fun addBeforeRemoveListener(key: String, func: (id: ID) -> StatusMessage) /** * 移除一个删除对象前执行监听器。 diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/ILazyService.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/ISimpleService.kt similarity index 68% rename from src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/ILazyService.kt rename to src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/ISimpleService.kt index 2d2efec..6d8fbff 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/ILazyService.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/ISimpleService.kt @@ -1,7 +1,7 @@ package com.synebula.gaea.domain.service import com.synebula.gaea.data.message.DataMessage -import com.synebula.gaea.data.message.Message +import com.synebula.gaea.data.message.StatusMessage import com.synebula.gaea.domain.model.IAggregateRoot import com.synebula.gaea.log.ILogger @@ -12,24 +12,24 @@ import com.synebula.gaea.log.ILogger * @version 0.0.1 * @since 2016年9月18日 下午2:23:15 */ -interface ILazyService, TKey> { +interface ISimpleService, ID> { /** * 日志组件。 */ var logger: ILogger - fun add(root: TAggregateRoot): DataMessage + fun add(root: TAggregateRoot): DataMessage - fun update(id: TKey, root: TAggregateRoot) + fun update(id: ID, root: TAggregateRoot) - fun remove(id: TKey) + fun remove(id: ID) /** * 添加一个删除对象前执行监听器。 * @param key 监听器标志。 * @param func 监听方法。 */ - fun addBeforeRemoveListener(key: String, func: (id: TKey) -> Message) + fun addBeforeRemoveListener(key: String, func: (id: ID) -> StatusMessage) /** * 移除一个删除对象前执行监听器。 diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/Service.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/Service.kt index c68a1f1..eee85ec 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/Service.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/Service.kt @@ -1,8 +1,8 @@ package com.synebula.gaea.domain.service -import com.synebula.gaea.data.IObjectConverter import com.synebula.gaea.data.message.DataMessage -import com.synebula.gaea.data.message.Message +import com.synebula.gaea.data.message.StatusMessage +import com.synebula.gaea.data.serialization.IObjectMapper import com.synebula.gaea.domain.model.IAggregateRoot import com.synebula.gaea.domain.repository.IRepository import com.synebula.gaea.log.ILogger @@ -14,30 +14,30 @@ import com.synebula.gaea.log.ILogger * * @param repository 仓储对象 * @param clazz 聚合根类对象 - * @param converter 对象转换组件 + * @param deserializer 对象转换组件 * @param logger 日志组件 * @author alex * @version 0.1 * @since 2020-05-17 */ -open class Service, TKey>( - protected open var clazz: Class, - protected open var repository: IRepository, - protected open var converter: IObjectConverter, - override var logger: ILogger -) : IService { +open class Service, ID>( + protected open var clazz: Class, + protected open var repository: IRepository, + protected open var deserializer: IObjectMapper, + override var logger: ILogger, +) : IService { /** * 删除对象前执行监听器。 */ - protected val beforeRemoveListeners = mutableMapOf Message>() + protected val beforeRemoveListeners = mutableMapOf StatusMessage>() /** * 添加一个删除对象前执行监听器。 * @param key 监听器标志。 * @param func 监听方法。 */ - override fun addBeforeRemoveListener(key: String, func: (id: TKey) -> Message) { + override fun addBeforeRemoveListener(key: String, func: (id: ID) -> StatusMessage) { this.beforeRemoveListeners[key] = func } @@ -49,23 +49,23 @@ open class Service, TKey>( this.beforeRemoveListeners.remove(key) } - override fun add(command: ICommand): DataMessage { - val msg = DataMessage() - val root = this.convert(command) + override fun add(command: ICommand): DataMessage { + val msg = DataMessage() + val root = this.deserialize(command) this.repository.add(root, this.clazz) msg.data = root.id return msg } - override fun update(id: TKey, command: ICommand) { - val root = this.convert(command) + override fun update(id: ID, command: ICommand) { + val root = this.deserialize(command) root.id = id this.repository.update(root, this.clazz) } - override fun remove(id: TKey) { + override fun remove(id: ID) { val functions = this.beforeRemoveListeners.values - var msg: Message + var msg: StatusMessage for (func in functions) { msg = func(id) if (!msg.success()) { @@ -81,9 +81,9 @@ open class Service, TKey>( * @param command 需要转换的命令 * @return 聚合根 */ - protected open fun convert(command: ICommand): TAggregateRoot { + protected open fun deserialize(command: ICommand): TAggregateRoot { try { - return converter.convert(command, this.clazz) + return deserializer.deserialize(command, this.clazz) } catch (ex: Exception) { throw RuntimeException("command not match aggregate root", ex) } diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/LazyService.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/SimpleService.kt similarity index 78% rename from src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/LazyService.kt rename to src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/SimpleService.kt index 2e49652..1a216bc 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/LazyService.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/SimpleService.kt @@ -1,7 +1,7 @@ package com.synebula.gaea.domain.service import com.synebula.gaea.data.message.DataMessage -import com.synebula.gaea.data.message.Message +import com.synebula.gaea.data.message.StatusMessage import com.synebula.gaea.domain.model.IAggregateRoot import com.synebula.gaea.domain.repository.IRepository import com.synebula.gaea.log.ILogger @@ -18,23 +18,23 @@ import com.synebula.gaea.log.ILogger * @version 0.1 * @since 2020-05-17 */ -open class LazyService, TKey>( +open class SimpleService, ID>( protected open var clazz: Class, protected open var repository: IRepository, - override var logger: ILogger -) : ILazyService { + override var logger: ILogger, +) : ISimpleService { /** * 删除对象前执行监听器。 */ - protected val beforeRemoveListeners = mutableMapOf Message>() + protected val beforeRemoveListeners = mutableMapOf StatusMessage>() /** * 添加一个删除对象前执行监听器。 * @param key 监听器标志。 * @param func 监听方法。 */ - override fun addBeforeRemoveListener(key: String, func: (id: TKey) -> Message) { + override fun addBeforeRemoveListener(key: String, func: (id: ID) -> StatusMessage) { this.beforeRemoveListeners[key] = func } @@ -46,21 +46,21 @@ open class LazyService, TKey>( this.beforeRemoveListeners.remove(key) } - override fun add(root: TAggregateRoot): DataMessage { - val msg = DataMessage() + override fun add(root: TAggregateRoot): DataMessage { + val msg = DataMessage() this.repository.add(root, this.clazz) msg.data = root.id return msg } - override fun update(id: TKey, root: TAggregateRoot) { + override fun update(id: ID, root: TAggregateRoot) { root.id = id this.repository.update(root, this.clazz) } - override fun remove(id: TKey) { + override fun remove(id: ID) { val functions = this.beforeRemoveListeners.values - var msg: Message + var msg: StatusMessage for (func in functions) { msg = func(id) if (!msg.success()) { diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/query/IQuery.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/query/IQuery.kt index debcd0a..adce2a8 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/query/IQuery.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/query/IQuery.kt @@ -12,7 +12,7 @@ interface IQuery { * @param id 对象Key。 * @return 视图结果 */ - fun get(id: TKey, clazz: Class): TView? + fun get(id: ID, clazz: Class): TView? /** * 根据实体类条件查询所有符合条件记录 diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/reflect/Types.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/reflect/Types.kt new file mode 100644 index 0000000..75ac061 --- /dev/null +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/reflect/Types.kt @@ -0,0 +1,23 @@ +package com.synebula.gaea.reflect + +import com.synebula.gaea.bus.SubscriberRegistry + +object Types { + /** + * 获取类的所有父类型。 + */ + fun supertypes(clazz: Class<*>): Set> { + val supertypes = mutableSetOf>() + supertypes.add(clazz) + if (clazz.superclass != null) + supertypes.addAll(SubscriberRegistry.flattenHierarchy(clazz.superclass)) + if (clazz.interfaces.isNotEmpty()) { + supertypes.addAll(clazz.interfaces.map { SubscriberRegistry.flattenHierarchy(it) }.reduce { r, c -> + val all = r.toMutableSet() + all.addAll(c) + all + }) + } + return supertypes + } +} \ No newline at end of file From 1c4ca8a7211b4ef4204395f82481f7c862a0ec95 Mon Sep 17 00:00:00 2001 From: alex Date: Wed, 27 Jul 2022 15:46:28 +0800 Subject: [PATCH 05/14] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=B3=A8=E9=87=8A?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../gaea/data/serialization/IDeserializer.kt | 4 +-- .../gaea/data/serialization/ISerializer.kt | 4 +-- .../domain/repository/ISpecificRepository.kt | 2 +- .../domain/repository/context/IContext.kt | 12 ++++----- .../specifications/AndNotSpecification.kt | 17 ++++-------- .../specifications/AndSpecification.kt | 16 +++--------- .../specifications/AnySpecification.kt | 3 +-- .../specifications/CompositeSpecification.kt | 26 +++++-------------- .../specifications/ICompositeSpecification.kt | 3 +-- .../specifications/ISpecification.kt | 17 +++++------- .../specifications/NoneSpecification.kt | 3 +-- .../specifications/NotSpecification.kt | 2 +- .../specifications/OrNotSpecification.kt | 17 ++++-------- .../specifications/OrSpecification.kt | 12 ++++----- .../specifications/Specification.kt | 6 +++++ .../com/synebula/gaea/io/scan/ClassScanner.kt | 2 +- 16 files changed, 54 insertions(+), 92 deletions(-) diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/data/serialization/IDeserializer.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/data/serialization/IDeserializer.kt index d6efe44..1db2a39 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/data/serialization/IDeserializer.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/data/serialization/IDeserializer.kt @@ -2,14 +2,14 @@ package com.synebula.gaea.data.serialization /** * 序列化器 - * @param 源数据类型 + * @param S 源数据类型 */ interface IDeserializer { /** * 反序列化 * - * @param 目标数据类型 + * @param T 目标数据类型 * @param src 源数据 * @param targetClass 目标对象。 * @return 目标数据 diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/data/serialization/ISerializer.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/data/serialization/ISerializer.kt index e3ca229..21db27c 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/data/serialization/ISerializer.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/data/serialization/ISerializer.kt @@ -2,13 +2,13 @@ package com.synebula.gaea.data.serialization /** * 序列化器 - * @param 目标数据类型 + * @param T 目标数据类型 */ interface ISerializer { /** * 序列化 - * @param 源数据类型 + * @param S 源数据类型 * * @param src 源数据 * @return 目标数据 diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/ISpecificRepository.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/ISpecificRepository.kt index d15ec31..8b1b8cd 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/ISpecificRepository.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/ISpecificRepository.kt @@ -36,7 +36,7 @@ interface ISpecificRepository, ID> { /** * 通过id删除该条数据 * - * @param id + * @param id 对象ID。 * @return */ fun remove(id: ID) diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/context/IContext.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/context/IContext.kt index f585580..2e22c5f 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/context/IContext.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/context/IContext.kt @@ -10,21 +10,21 @@ import com.synebula.gaea.domain.model.IAggregateRoot interface IContext : IUnitOfWork { /** * 将指定的聚合根标注为“新建”状态。 - * @param obj + * @param obj 聚合根 */ - fun , ID> add(obj: TType) + fun , ID> add(obj: T) /** * 将指定的聚合根标注为“更改”状态。 * - * @param obj + * @param obj 聚合根 */ - fun , ID> update(obj: TType) + fun , ID> update(obj: T) /** * 将指定的聚合根标注为“删除”状态。 * - * @param obj + * @param obj 聚合根 */ - fun , ID> remove(obj: TType) + fun , ID> remove(obj: T) } diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/specifications/AndNotSpecification.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/specifications/AndNotSpecification.kt index 2ba6898..c5f3fa7 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/specifications/AndNotSpecification.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/specifications/AndNotSpecification.kt @@ -5,19 +5,12 @@ package com.synebula.gaea.domain.repository.specifications * * @author alex * - * @param - * 规约对象的类型。 + * @param T 规约对象的类型。 + * @param left 表达式左侧规约对象。 + * @param right 表达式右侧规约对象。 */ -class AndNotSpecification -/** - * 构造一个新的混合规约对象。 - * - * @param left - * 表达式左侧规约对象。 - * @param right - * 表达式右侧规约对象。 - */ -(left: ISpecification, right: ISpecification) : CompositeSpecification(left, right) { +class AndNotSpecification(left: ISpecification, right: ISpecification) : + CompositeSpecification(left, right) { override fun isSatisfiedBy(obj: T): Boolean { return left.isSatisfiedBy(obj) && NotSpecification(right).isSatisfiedBy(obj) diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/specifications/AndSpecification.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/specifications/AndSpecification.kt index bf500ce..0ed1584 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/specifications/AndSpecification.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/specifications/AndSpecification.kt @@ -5,19 +5,11 @@ package com.synebula.gaea.domain.repository.specifications * * @author alex * - * @param - * 规约对象的类型。 + * @param T 规约对象的类型。 + * @param left 表达式左侧规约对象。 + * @param right 表达式右侧规约对象。 */ -class AndSpecification -/** - * 构造一个新的混合规约对象。 - * - * @param left - * 表达式左侧规约对象。 - * @param right - * 表达式右侧规约对象。 - */ -(left: ISpecification, right: ISpecification) : CompositeSpecification(left, right) { +class AndSpecification(left: ISpecification, right: ISpecification) : CompositeSpecification(left, right) { override fun isSatisfiedBy(obj: T): Boolean { return left.isSatisfiedBy(obj) && right.isSatisfiedBy(obj) diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/specifications/AnySpecification.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/specifications/AnySpecification.kt index e876883..163a956 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/specifications/AnySpecification.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/specifications/AnySpecification.kt @@ -5,8 +5,7 @@ package com.synebula.gaea.domain.repository.specifications * * @author alex * - * @param - * 规约对象的类型。 + * @param T 规约对象的类型。 */ class AnySpecification : Specification() { diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/specifications/CompositeSpecification.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/specifications/CompositeSpecification.kt index d392344..34dde5d 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/specifications/CompositeSpecification.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/specifications/CompositeSpecification.kt @@ -4,23 +4,11 @@ package com.synebula.gaea.domain.repository.specifications * 实现了接口ICompositeSpecification,混合规约的基类。 * @author alex * - * @param - */ -abstract class CompositeSpecification -/** - * 构造一个新的混合规约对象。 - * - * @param left - * 表达式左侧规约对象。 - * @param right - * 表达式右侧规约对象。 + * @param T 规约对象的类型。 + * @param left 表达式左侧规约对象。 + * @param right 表达式右侧规约对象。 */ -( - /** - * 表达式左侧规约对象。 - */ - override val left: ISpecification, - /** - * 表达式右侧规约对象。 - */ - override val right: ISpecification) : Specification(), ICompositeSpecification +abstract class CompositeSpecification( + override val left: ISpecification, + override val right: ISpecification +) : Specification(), ICompositeSpecification diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/specifications/ICompositeSpecification.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/specifications/ICompositeSpecification.kt index fa715ec..92a7d06 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/specifications/ICompositeSpecification.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/specifications/ICompositeSpecification.kt @@ -5,8 +5,7 @@ package com.synebula.gaea.domain.repository.specifications * * @author alex * - * @param - * 规约对象的类型。 + * @param T 规约对象的类型。 */ interface ICompositeSpecification : ISpecification { diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/specifications/ISpecification.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/specifications/ISpecification.kt index 86d8006..477aef5 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/specifications/ISpecification.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/specifications/ISpecification.kt @@ -5,14 +5,13 @@ package com.synebula.gaea.domain.repository.specifications * * @author alex * - * @param + * @param T 规约对象的类型。 */ interface ISpecification { /** * 判断是否符合条件。 * - * @param obj - * 规约类型的对象。 + * @param obj 规约类型的对象。 * @return 符合条件的返回True。 */ fun isSatisfiedBy(obj: T): Boolean @@ -20,8 +19,7 @@ interface ISpecification { /** * 结合当前规约对象和另一规约对象进行与判断。 * - * @param other - * 需要进行与结合的另一个规约对象。 + * @param other 需要进行与结合的另一个规约对象。 * @return 结合后的规约对象。 */ fun and(other: ISpecification): ISpecification @@ -29,8 +27,7 @@ interface ISpecification { /** * 结合当前规约对象和另一规约对象进行或判断。 * - * @param other - * 需要进行或结合的另一个规约对象。 + * @param other 需要进行或结合的另一个规约对象。 * @return 结合后的规约对象。 */ fun or(other: ISpecification): ISpecification @@ -38,8 +35,7 @@ interface ISpecification { /** * 结合当前规约对象和另一规约对象进行与且非判断 * - * @param other - * 需要进行非结合的另一个规约对象。 + * @param other 需要进行非结合的另一个规约对象。 * @return 结合后的规约对象。 */ fun andNot(other: ISpecification): ISpecification @@ -47,8 +43,7 @@ interface ISpecification { /** * 结合当前规约对象和另一规约对象进行或非判断。 * - * @param other - * 需要进行或非结合的另一个规约对象。 + * @param other 需要进行或非结合的另一个规约对象。 * @return 结合后的规约对象。 */ fun orNot(other: ISpecification): ISpecification diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/specifications/NoneSpecification.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/specifications/NoneSpecification.kt index 7dac9f1..c007f71 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/specifications/NoneSpecification.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/specifications/NoneSpecification.kt @@ -5,8 +5,7 @@ package com.synebula.gaea.domain.repository.specifications * * @author alex * - * @param - * 规约对象的类型。 + * @param T 规约对象的类型。 */ class NoneSpecification : Specification() { diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/specifications/NotSpecification.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/specifications/NotSpecification.kt index f9cc24e..fe36b32 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/specifications/NotSpecification.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/specifications/NotSpecification.kt @@ -5,7 +5,7 @@ package com.synebula.gaea.domain.repository.specifications * * @author alex * - * @param 规约对象的类型。 + * @param T 规约对象的类型。 * * @param spec 需要逆反的规约对象。 * diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/specifications/OrNotSpecification.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/specifications/OrNotSpecification.kt index 504ec8d..8d35832 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/specifications/OrNotSpecification.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/specifications/OrNotSpecification.kt @@ -5,19 +5,12 @@ package com.synebula.gaea.domain.repository.specifications * * @author alex * - * @param - * 规约对象的类型。 + * @param T 规约对象的类型。 + * @param left 表达式左侧规约对象。 + * @param right 表达式右侧规约对象。 */ -class OrNotSpecification -/** - * 构造一个新的混合规约对象。 - * - * @param left - * 表达式左侧规约对象。 - * @param right - * 表达式右侧规约对象。 - */ -(left: ISpecification, right: ISpecification) : CompositeSpecification(left, right) { +class OrNotSpecification(left: ISpecification, right: ISpecification) : + CompositeSpecification(left, right) { override fun isSatisfiedBy(obj: T): Boolean { return left.isSatisfiedBy(obj) || NotSpecification(right).isSatisfiedBy(obj) diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/specifications/OrSpecification.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/specifications/OrSpecification.kt index e9297b2..5aeb8f8 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/specifications/OrSpecification.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/specifications/OrSpecification.kt @@ -1,16 +1,14 @@ package com.synebula.gaea.domain.repository.specifications -class OrSpecification /** * 构造一个新的混合规约对象。 * - * @param left - * 表达式左侧规约对象。 - * @param right - * 表达式右侧规约对象。 + * @param T 规约对象的类型。 + * + * @param left 表达式左侧规约对象。 + * @param right 表达式右侧规约对象。 */ -(left: ISpecification, right: ISpecification) : CompositeSpecification(left, right) { - +class OrSpecification(left: ISpecification, right: ISpecification) : CompositeSpecification(left, right) { override fun isSatisfiedBy(obj: T): Boolean { return left.isSatisfiedBy(obj) || right.isSatisfiedBy(obj) } diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/specifications/Specification.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/specifications/Specification.kt index 0a0fdd8..c688a12 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/specifications/Specification.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/specifications/Specification.kt @@ -1,5 +1,11 @@ package com.synebula.gaea.domain.repository.specifications +/** + * 抽象的的规约对象。 + * + * @param T 规约对象的类型。 + * + */ abstract class Specification : ISpecification { abstract override fun isSatisfiedBy(obj: T): Boolean diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/io/scan/ClassScanner.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/io/scan/ClassScanner.kt index 1cb3474..2a6b2ed 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/io/scan/ClassScanner.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/io/scan/ClassScanner.kt @@ -38,7 +38,7 @@ class ClassScanner(private var packageName: String) { * 构造方法。 * * @param packageName 需要扫描的包名。 - * @param classFilter + * @param classFilter 过滤器 */ constructor(packageName: String, vararg classFilter: IClassFilter) : this(packageName) { this.classFilters = classFilter From 29ad3073a8dbc63ea6512825a71e162d20e20fb0 Mon Sep 17 00:00:00 2001 From: alex Date: Wed, 27 Jul 2022 16:29:25 +0800 Subject: [PATCH 06/14] =?UTF-8?q?=E9=87=8D=E6=9E=84=E5=90=8D=E7=A7=B0?= =?UTF-8?q?=E5=92=8C=E6=B3=A8=E9=87=8A=E5=86=85=E5=AE=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../kotlin/com/synebula/gaea/app/cmd/ICommandApp.kt | 8 ++++---- .../com/synebula/gaea/app/cmd/ISimpleCommandApp.kt | 8 ++++---- .../com/synebula/gaea/app/component/aop/AppAspect.kt | 12 ++++++------ .../gaea/app/component/aop/annotation/Handler.kt | 5 +++++ .../aop/annotation/{MethodName.kt => Method.kt} | 4 ++-- .../aop/annotation/{ModuleName.kt => Module.kt} | 3 ++- .../kotlin/com/synebula/gaea/app/query/IQueryApp.kt | 8 ++++---- 7 files changed, 27 insertions(+), 21 deletions(-) rename src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/aop/annotation/{MethodName.kt => Method.kt} (77%) rename src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/aop/annotation/{ModuleName.kt => Module.kt} (69%) diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/ICommandApp.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/ICommandApp.kt index d92374d..8ac4982 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/ICommandApp.kt +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/ICommandApp.kt @@ -1,7 +1,7 @@ package com.synebula.gaea.app.cmd import com.synebula.gaea.app.IApplication -import com.synebula.gaea.app.component.aop.annotation.MethodName +import com.synebula.gaea.app.component.aop.annotation.Method import com.synebula.gaea.app.struct.HttpMessage import com.synebula.gaea.data.message.Status import com.synebula.gaea.data.serialization.json.IJsonSerializer @@ -22,20 +22,20 @@ interface ICommandApp : IApplication { var service: IService @PostMapping - @MethodName("添加") + @Method("添加") fun add(@RequestBody command: TCommand): HttpMessage { return HttpMessage(service.add(command)) } @PutMapping("/{id:.+}") - @MethodName("更新") + @Method("更新") fun update(@PathVariable id: ID, @RequestBody command: TCommand): HttpMessage { this.service.update(id, command) return HttpMessage() } @DeleteMapping("/{id:.+}") - @MethodName("删除") + @Method("删除") fun remove(@PathVariable id: ID): HttpMessage { val msg = HttpMessage() try { diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/ISimpleCommandApp.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/ISimpleCommandApp.kt index bc4451b..6c7b89c 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/ISimpleCommandApp.kt +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/ISimpleCommandApp.kt @@ -1,7 +1,7 @@ package com.synebula.gaea.app.cmd import com.synebula.gaea.app.IApplication -import com.synebula.gaea.app.component.aop.annotation.MethodName +import com.synebula.gaea.app.component.aop.annotation.Method import com.synebula.gaea.app.struct.HttpMessage import com.synebula.gaea.data.message.Status import com.synebula.gaea.data.serialization.json.IJsonSerializer @@ -22,20 +22,20 @@ interface ISimpleCommandApp, ID> : IApplication { var service: ISimpleService @PostMapping - @MethodName("添加") + @Method("添加") fun add(@RequestBody entity: TRoot): HttpMessage { return HttpMessage(service.add(entity)) } @PutMapping("/{id:.+}") - @MethodName("更新") + @Method("更新") fun update(@PathVariable id: ID, @RequestBody entity: TRoot): HttpMessage { this.service.update(id, entity) return HttpMessage() } @DeleteMapping("/{id:.+}") - @MethodName("删除") + @Method("删除") fun remove(@PathVariable id: ID): HttpMessage { val msg = HttpMessage() try { diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/aop/AppAspect.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/aop/AppAspect.kt index 1c82838..1c696d8 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/aop/AppAspect.kt +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/aop/AppAspect.kt @@ -3,8 +3,8 @@ package com.synebula.gaea.app.component.aop import com.google.gson.Gson import com.synebula.gaea.app.IApplication import com.synebula.gaea.app.component.aop.annotation.Handler -import com.synebula.gaea.app.component.aop.annotation.MethodName -import com.synebula.gaea.app.component.aop.annotation.ModuleName +import com.synebula.gaea.app.component.aop.annotation.Method +import com.synebula.gaea.app.component.aop.annotation.Module import com.synebula.gaea.app.struct.HttpMessage import com.synebula.gaea.data.message.Status import com.synebula.gaea.exception.NoticeUserException @@ -54,7 +54,7 @@ abstract class AppAspect { val handleClazz = applicationContext.getBean(handler.value.java) handleClazz.handle(clazz, func, point.args) } - if (funcAnnotation is MethodName) + if (funcAnnotation is Method) funcName = funcAnnotation.name } @@ -66,9 +66,9 @@ abstract class AppAspect { if (IApplication::class.java.isAssignableFrom(clazz)) { moduleName = (point.`this` as IApplication).name } else { - val name = clazz.annotations.find { it is ModuleName } - if (name != null && name is ModuleName) { - moduleName = name.value + val name = clazz.annotations.find { it is Module } + if (name != null && name is Module) { + moduleName = name.name } } var message = "$moduleName - $funcName 异常" diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/aop/annotation/Handler.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/aop/annotation/Handler.kt index 73b5b47..ff159f9 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/aop/annotation/Handler.kt +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/aop/annotation/Handler.kt @@ -3,6 +3,11 @@ package com.synebula.gaea.app.component.aop.annotation import com.synebula.gaea.app.component.aop.handler.AnnotationHandler import kotlin.reflect.KClass +/** + * 标注在注解,表明注解的处理方法 + * + * @param value 注解处理方法 + */ @Target(AnnotationTarget.ANNOTATION_CLASS) @Retention(AnnotationRetention.RUNTIME) annotation class Handler(val value: KClass) \ No newline at end of file diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/aop/annotation/MethodName.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/aop/annotation/Method.kt similarity index 77% rename from src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/aop/annotation/MethodName.kt rename to src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/aop/annotation/Method.kt index 3f09685..3c198a3 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/aop/annotation/MethodName.kt +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/aop/annotation/Method.kt @@ -5,9 +5,9 @@ import java.lang.annotation.Inherited /** * 标记方法名称,由AOP负责记录异常时使用该名称 * - * @param name 异常消息 + * @param name 方法名称 */ @Inherited @Target(AnnotationTarget.FUNCTION) @Retention(AnnotationRetention.RUNTIME) -annotation class MethodName(val name: String) +annotation class Method(val name: String) diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/aop/annotation/ModuleName.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/aop/annotation/Module.kt similarity index 69% rename from src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/aop/annotation/ModuleName.kt rename to src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/aop/annotation/Module.kt index 3ab6e15..03ec88b 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/aop/annotation/ModuleName.kt +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/aop/annotation/Module.kt @@ -2,7 +2,8 @@ package com.synebula.gaea.app.component.aop.annotation /** * 模块的业务名称 + * @param name 模块名称 */ @Target(AnnotationTarget.CLASS) @Retention(AnnotationRetention.RUNTIME) -annotation class ModuleName(val value: String) +annotation class Module(val name: String) diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/query/IQueryApp.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/query/IQueryApp.kt index dda9478..f6f0865 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/query/IQueryApp.kt +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/query/IQueryApp.kt @@ -1,7 +1,7 @@ package com.synebula.gaea.app.query import com.synebula.gaea.app.IApplication -import com.synebula.gaea.app.component.aop.annotation.MethodName +import com.synebula.gaea.app.component.aop.annotation.Method import com.synebula.gaea.app.struct.HttpMessage import com.synebula.gaea.query.IQuery import com.synebula.gaea.query.Params @@ -20,7 +20,7 @@ interface IQueryApp : IApplication { */ var clazz: Class - @MethodName("获取数据") + @Method("获取数据") @GetMapping("/{id:.+}") fun get(@PathVariable id: ID): HttpMessage { val data = this.query.get(id, clazz) @@ -29,14 +29,14 @@ interface IQueryApp : IApplication { return msg } - @MethodName("获取列表数据") + @Method("获取列表数据") @GetMapping fun list(@RequestParam params: LinkedHashMap): HttpMessage { val data = this.query.list(params, clazz) return HttpMessage(data) } - @MethodName("获取分页数据") + @Method("获取分页数据") @GetMapping("/segments/{size}/pages/{page}") fun paging( @PathVariable size: Int, From b7cfd0a7f9d5e19ab2ad3b0b381cf5133366113a Mon Sep 17 00:00:00 2001 From: alex Date: Fri, 29 Jul 2022 15:28:14 +0800 Subject: [PATCH 07/14] fix import; update .gradle; add ISpecificQuery --- build.gradle | 12 ++--- src/gaea.app/build.gradle | 4 -- .../synebula/gaea/app/SimpleApplication.kt | 7 --- .../gaea/app/component/bus/EventBus.kt | 38 +------------- .../bus/EventBusSubscriberProcessor.kt | 6 +-- src/gaea.mongo/build.gradle | 3 -- src/gaea/build.gradle | 4 +- .../domain/repository/ISpecificRepository.kt | 4 +- .../com/synebula/gaea/query/ISpecificQuery.kt | 49 +++++++++++++++++++ 9 files changed, 61 insertions(+), 66 deletions(-) create mode 100644 src/gaea/src/main/kotlin/com/synebula/gaea/query/ISpecificQuery.kt diff --git a/build.gradle b/build.gradle index b1eda40..6bc8aba 100644 --- a/build.gradle +++ b/build.gradle @@ -15,16 +15,10 @@ buildscript { } } -allprojects { - ext { - version '2.0' - } - - group 'com.synebula' - version version -} - subprojects { + group 'com.synebula' + version '1.0.0' + buildscript { repositories { mavenLocal() diff --git a/src/gaea.app/build.gradle b/src/gaea.app/build.gradle index ece6833..772fc05 100644 --- a/src/gaea.app/build.gradle +++ b/src/gaea.app/build.gradle @@ -15,16 +15,12 @@ dependencies { api group: 'net.sf.dozer', name: 'dozer', version: '5.5.1' api group: 'org.apache.poi', name: 'poi-ooxml', version: '5.0.0' api group: 'com.google.code.gson', name: 'gson', version: '2.8.6' - api group: 'com.google.guava', name: 'guava', version: '31.1-jre' api group: 'com.auth0', name: 'java-jwt', version: '3.14.0' } publishing { publications { publish(MavenPublication) { - group 'com.synebula' - artifactId 'gaea.app' - version "$version" from components.java } } diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/SimpleApplication.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/SimpleApplication.kt index de5dc96..1a9102b 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/SimpleApplication.kt +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/SimpleApplication.kt @@ -1,10 +1,8 @@ package com.synebula.gaea.app -import com.google.common.reflect.TypeToken import com.synebula.gaea.app.cmd.ISimpleCommandApp import com.synebula.gaea.app.query.IQueryApp import com.synebula.gaea.data.serialization.json.IJsonSerializer -import com.synebula.gaea.domain.model.AggregateRoot import com.synebula.gaea.domain.model.IAggregateRoot import com.synebula.gaea.domain.service.ISimpleService import com.synebula.gaea.log.ILogger @@ -31,8 +29,3 @@ open class SimpleApplication, ID>( @Resource override var jsonSerializer: IJsonSerializer? = null } - -fun main() { - val rawType = TypeToken.of(AggregateRoot::class.java).types.rawTypes() - println(rawType) -} \ No newline at end of file diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/bus/EventBus.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/bus/EventBus.kt index 7d26813..acd6c29 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/bus/EventBus.kt +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/bus/EventBus.kt @@ -1,42 +1,8 @@ package com.synebula.gaea.app.component.bus -import com.google.common.eventbus.AsyncEventBus -import com.google.common.eventbus.EventBus -import com.synebula.gaea.bus.IMessage -import com.synebula.gaea.bus.IMessageBus +import com.synebula.gaea.bus.Bus import org.springframework.stereotype.Component -import java.util.concurrent.Executors @Component -class EventBus : IMessageBus { - - /** - * 同步事件总线 - */ - var eventBus = EventBus() - - /** - * 异步事件总线 - */ - var asyncEventBus = AsyncEventBus(Executors.newFixedThreadPool(2)) - - override fun register(obj: Any) { - eventBus.register(obj) - asyncEventBus.register(obj) - } - - override fun unregister(obj: Any) { - eventBus.unregister(obj) - asyncEventBus.unregister(obj) - } - - override fun publish(message: IMessage) { - eventBus.post(message) - } - - override fun publishAsync(message: IMessage) { - asyncEventBus.post(message) - } - -} +class EventBus : Bus() diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/bus/EventBusSubscriberProcessor.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/bus/EventBusSubscriberProcessor.kt index 6360801..2a00a4d 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/bus/EventBusSubscriberProcessor.kt +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/bus/EventBusSubscriberProcessor.kt @@ -1,7 +1,7 @@ package com.synebula.gaea.app.component.bus -import com.google.common.eventbus.Subscribe -import com.synebula.gaea.bus.IMessageBus +import com.synebula.gaea.bus.IBus +import com.synebula.gaea.bus.Subscribe import org.springframework.beans.BeansException import org.springframework.beans.factory.annotation.Autowired import org.springframework.beans.factory.config.BeanPostProcessor @@ -14,7 +14,7 @@ class EventBusSubscriberProcessor : BeanPostProcessor { // 事件总线bean由Spring IoC容器负责创建,这里只需要通过@Autowired注解注入该bean即可使用事件总线 @Autowired - var messageBus: IMessageBus? = null + var messageBus: IBus? = null @Throws(BeansException::class) override fun postProcessBeforeInitialization(bean: Any, beanName: String): Any { diff --git a/src/gaea.mongo/build.gradle b/src/gaea.mongo/build.gradle index f0a51c4..41f2957 100644 --- a/src/gaea.mongo/build.gradle +++ b/src/gaea.mongo/build.gradle @@ -6,9 +6,6 @@ dependencies { publishing { publications { publish(MavenPublication) { - group 'com.synebula' - artifactId 'gaea.mongo' - version "$version" from components.java } } diff --git a/src/gaea/build.gradle b/src/gaea/build.gradle index f049c0d..69db5b0 100644 --- a/src/gaea/build.gradle +++ b/src/gaea/build.gradle @@ -1,8 +1,8 @@ publishing { publications { publish(MavenPublication) { - group 'com.synebula' - artifactId 'gaea' + group "${project.group}" + artifactId "${project.name}" version "$version" from components.java } diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/ISpecificRepository.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/ISpecificRepository.kt index 8b1b8cd..e9501c0 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/ISpecificRepository.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/ISpecificRepository.kt @@ -5,9 +5,9 @@ import com.synebula.gaea.domain.model.IAggregateRoot /** * 继承本接口表示对象为仓储类。 * 定义了提供增删改的仓储接口。 - * 本接口泛型定义在类上,不需要显式提供聚合根的class对象,class对象作为类的成员变量声明。 + * 本接口泛型定义在类上,方法中不需要显式提供聚合根的class对象,class对象作为类的成员变量声明。 * - * @param this T is the parameter + * @param TAggregateRoot 聚合根类型 * @author alex */ interface ISpecificRepository, ID> { diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/query/ISpecificQuery.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/query/ISpecificQuery.kt new file mode 100644 index 0000000..fbe4c77 --- /dev/null +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/query/ISpecificQuery.kt @@ -0,0 +1,49 @@ +package com.synebula.gaea.query + +/** + * 查询基接口。 + * 本接口泛型定义在类上,方法中不需要显式提供聚合根的class对象,class对象作为类的成员变量声明。 + * @author alex + */ +interface ISpecificQuery { + /** + * 根据Key获取对象。 + * + * @param id 对象Key。 + * @return 视图结果 + */ + fun get(id: ID): TView? + + /** + * 根据实体类条件查询所有符合条件记录 + * + * @param params 查询条件。 + * @return 视图列表 + */ + fun list(params: Map?): List + + /** + * 根据条件查询符合条件记录的数量 + * + * @param params 查询条件。 + * @return 数量 + */ + fun count(params: Map?): Int + + /** + * 根据实体类条件查询所有符合条件记录(分页查询) + * + * @param params 分页条件 + * @return 分页数据 + */ + fun paging(params: Params): Page + + /** + * 查询条件范围内数据。 + * @param field 查询字段 + * @param params 查询条件 + * + * @return 视图列表 + */ + fun range(field: String, params: List): List +} From 07684e814df28000ba84c82495e8500d8aa32266 Mon Sep 17 00:00:00 2001 From: alex Date: Thu, 18 Aug 2022 14:35:01 +0800 Subject: [PATCH 08/14] 1.1.0 add service / repository / query spring auto config function --- build.gradle | 4 +- settings.gradle | 6 +- src/gaea.app/build.gradle | 2 + .../com/synebula/gaea/app/Application.kt | 4 +- .../synebula/gaea/app/SimpleApplication.kt | 4 +- .../app/autoconfig/service/ServiceFactory.kt | 15 +++ .../app/autoconfig/service/ServiceProxy.kt | 56 +++++++++ .../app/autoconfig/service/ServiceRegister.kt | 50 ++++++++ .../app/autoconfig/service/ServiceScan.kt | 12 ++ .../com/synebula/gaea/app/query/IQueryApp.kt | 15 +-- .../com/synebula/gaea/app/query/QueryApp.kt | 3 +- src/{gaea.mongo => gaea.mongodb}/build.gradle | 1 + .../com/synebula/gaea/mongodb}/MongoExt.kt | 14 +-- .../mongodb/autoconfig/MongodbRepoFactory.kt | 15 +++ .../mongodb/autoconfig/MongodbRepoProxy.kt | 84 ++++++++++++++ .../mongodb/autoconfig/MongodbRepoRegister.kt | 54 +++++++++ .../mongodb/autoconfig/MongodbRepoScan.kt | 12 ++ .../gaea/mongodb/query/MongodbQuery.kt | 102 ++++++++++++++++ .../mongodb/query/MongodbUniversalQuery.kt} | 30 ++--- .../mongodb/repository/MongodbRepository.kt | 47 ++++++++ .../repository/MongodbUniversalRepository.kt} | 34 ++++-- src/gaea.spring/build.gradle | 22 ++++ .../gaea/spring/autoconfig/Factory.kt | 44 +++++++ .../synebula/gaea/spring/autoconfig/Proxy.kt | 43 +++++++ .../gaea/spring/autoconfig/ProxyType.kt | 3 + .../gaea/spring/autoconfig/Register.kt | 109 ++++++++++++++++++ .../gaea/domain/repository/IRepository.kt | 41 ++++--- .../domain/repository/ISpecificRepository.kt | 61 ---------- .../domain/repository/IUniversalRepository.kt | 65 +++++++++++ .../synebula/gaea/domain/service/IService.kt | 48 +++++--- .../gaea/domain/service/ISimpleService.kt | 43 ++++--- .../synebula/gaea/domain/service/Service.kt | 98 ++++++++-------- .../gaea/domain/service/ServiceDependency.kt | 16 +++ .../gaea/domain/service/SimpleService.kt | 61 ++++------ .../kotlin/com/synebula/gaea/query/IQuery.kt | 19 +-- .../{ISpecificQuery.kt => IUniversalQuery.kt} | 16 +-- .../gaea/query/{type => }/Operator.kt | 2 +- .../synebula/gaea/query/{type => }/Order.kt | 2 +- .../kotlin/com/synebula/gaea/query/Params.kt | 2 - .../gaea/query/{annotation => }/Table.kt | 2 +- .../gaea/query/{annotation => }/Where.kt | 4 +- .../kotlin/com/synebula/gaea/reflect/Types.kt | 8 +- 42 files changed, 1001 insertions(+), 272 deletions(-) create mode 100644 src/gaea.app/src/main/kotlin/com/synebula/gaea/app/autoconfig/service/ServiceFactory.kt create mode 100644 src/gaea.app/src/main/kotlin/com/synebula/gaea/app/autoconfig/service/ServiceProxy.kt create mode 100644 src/gaea.app/src/main/kotlin/com/synebula/gaea/app/autoconfig/service/ServiceRegister.kt create mode 100644 src/gaea.app/src/main/kotlin/com/synebula/gaea/app/autoconfig/service/ServiceScan.kt rename src/{gaea.mongo => gaea.mongodb}/build.gradle (87%) rename src/{gaea.mongo/src/main/kotlin/com/synebula/gaea/mongo => gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb}/MongoExt.kt (93%) create mode 100644 src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/autoconfig/MongodbRepoFactory.kt create mode 100644 src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/autoconfig/MongodbRepoProxy.kt create mode 100644 src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/autoconfig/MongodbRepoRegister.kt create mode 100644 src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/autoconfig/MongodbRepoScan.kt create mode 100644 src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/query/MongodbQuery.kt rename src/{gaea.mongo/src/main/kotlin/com/synebula/gaea/mongo/query/MongodbQuery.kt => gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/query/MongodbUniversalQuery.kt} (82%) create mode 100644 src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/repository/MongodbRepository.kt rename src/{gaea.mongo/src/main/kotlin/com/synebula/gaea/mongo/repository/MongodbRepository.kt => gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/repository/MongodbUniversalRepository.kt} (55%) create mode 100644 src/gaea.spring/build.gradle create mode 100644 src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/autoconfig/Factory.kt create mode 100644 src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/autoconfig/Proxy.kt create mode 100644 src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/autoconfig/ProxyType.kt create mode 100644 src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/autoconfig/Register.kt delete mode 100644 src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/ISpecificRepository.kt create mode 100644 src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/IUniversalRepository.kt create mode 100644 src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/ServiceDependency.kt rename src/gaea/src/main/kotlin/com/synebula/gaea/query/{ISpecificQuery.kt => IUniversalQuery.kt} (61%) rename src/gaea/src/main/kotlin/com/synebula/gaea/query/{type => }/Operator.kt (92%) rename src/gaea/src/main/kotlin/com/synebula/gaea/query/{type => }/Order.kt (84%) rename src/gaea/src/main/kotlin/com/synebula/gaea/query/{annotation => }/Table.kt (51%) rename src/gaea/src/main/kotlin/com/synebula/gaea/query/{annotation => }/Where.kt (83%) diff --git a/build.gradle b/build.gradle index 6bc8aba..1b16f91 100644 --- a/build.gradle +++ b/build.gradle @@ -1,6 +1,6 @@ buildscript { ext { - kotlin_version = '1.7.0' + kotlin_version = '1.6.10' spring_version = "2.7.0" } @@ -17,7 +17,7 @@ buildscript { subprojects { group 'com.synebula' - version '1.0.0' + version '1.1.0' buildscript { repositories { diff --git a/settings.gradle b/settings.gradle index 55f9af1..1647a40 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,4 +1,8 @@ rootProject.name = 'gaea' include 'src:gaea' include 'src:gaea.app' -include 'src:gaea.mongo' +include 'src:gaea.mongodb' +include 'src:gaea.spring' +include 'src:gaea.spring' +findProject(':src:gaea.spring')?.name = 'gaea.spring' + diff --git a/src/gaea.app/build.gradle b/src/gaea.app/build.gradle index 772fc05..9af631c 100644 --- a/src/gaea.app/build.gradle +++ b/src/gaea.app/build.gradle @@ -8,6 +8,8 @@ apply plugin: 'kotlin-spring' dependencies { api project(":src:gaea") + api project(":src:gaea.spring") + api("org.springframework.boot:spring-boot-starter-web:$spring_version") api("org.springframework.boot:spring-boot-starter-aop:$spring_version") api("org.springframework.boot:spring-boot-starter-mail:$spring_version") diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/Application.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/Application.kt index 759905e..7e0a5c7 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/Application.kt +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/Application.kt @@ -13,16 +13,14 @@ import javax.annotation.Resource * 联合服务,同时实现了ICommandApp和IQueryApp接口 * * @param name 业务名称 - * @param clazz 试图业务对象 * @param service 业务domain服务 * @param query 业务查询服务 * @param logger 日志组件 */ open class Application( override var name: String, - override var clazz: Class, override var service: IService, - override var query: IQuery, + override var query: IQuery, override var logger: ILogger, ) : ICommandApp, IQueryApp { diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/SimpleApplication.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/SimpleApplication.kt index 1a9102b..e06f139 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/SimpleApplication.kt +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/SimpleApplication.kt @@ -13,16 +13,14 @@ import javax.annotation.Resource * 简单的服务, 取消了Command对象 * * @param name 业务名称 - * @param clazz 业务对象类型 * @param service 业务domain服务 * @param query 业务查询服务 * @param logger 日志组件 */ open class SimpleApplication, ID>( override var name: String, - override var clazz: Class, override var service: ISimpleService, - override var query: IQuery, + override var query: IQuery, override var logger: ILogger, ) : ISimpleCommandApp, IQueryApp { diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/autoconfig/service/ServiceFactory.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/autoconfig/service/ServiceFactory.kt new file mode 100644 index 0000000..e3447dd --- /dev/null +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/autoconfig/service/ServiceFactory.kt @@ -0,0 +1,15 @@ +package com.synebula.gaea.app.autoconfig.service + +import com.synebula.gaea.spring.autoconfig.Factory +import com.synebula.gaea.spring.autoconfig.Proxy +import org.springframework.beans.factory.BeanFactory + +class ServiceFactory( + supertype: Class<*>, + var beanFactory: BeanFactory, + var implementBeanNames: Array = arrayOf() +) : Factory(supertype) { + override fun createProxy(): Proxy { + return ServiceProxy(supertype, this.beanFactory, this.implementBeanNames) + } +} \ No newline at end of file diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/autoconfig/service/ServiceProxy.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/autoconfig/service/ServiceProxy.kt new file mode 100644 index 0000000..5aa6bce --- /dev/null +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/autoconfig/service/ServiceProxy.kt @@ -0,0 +1,56 @@ +package com.synebula.gaea.app.autoconfig.service + +import com.synebula.gaea.data.serialization.IObjectMapper +import com.synebula.gaea.domain.repository.IRepository +import com.synebula.gaea.domain.service.IService +import com.synebula.gaea.domain.service.Service +import com.synebula.gaea.domain.service.ServiceDependency +import com.synebula.gaea.spring.autoconfig.Proxy +import org.springframework.beans.factory.BeanFactory +import java.io.InvalidClassException +import java.lang.reflect.Method + +class ServiceProxy( + private var supertype: Class<*>, private var beanFactory: BeanFactory, implementBeanNames: Array = arrayOf() +) : Proxy() { + + private var service: IService<*> + + init { + // 如果没有实现类, 使用Service类代理 + if (implementBeanNames.isEmpty()) { + // 如果没有实现类并且没有ServiceDependency注解, 则抛出异常 + if (!this.supertype.declaredAnnotations.any { it.annotationClass == ServiceDependency::class }) { + throw InvalidClassException( + "interface ${this.supertype.name} must has implementation class or annotation by ${ServiceDependency::class.qualifiedName}" + ) + } + val serviceDependency = this.supertype.getDeclaredAnnotation(ServiceDependency::class.java) + val repo = this.beanFactory.getBean(serviceDependency.repo.java) + val mapper = this.beanFactory.getBean(IObjectMapper::class.java) + val constructor = Service::class.java.getConstructor( + Class::class.java, IRepository::class.java, IObjectMapper::class.java + ) + this.service = constructor.newInstance(serviceDependency.clazz.java, repo, mapper) + } else { + this.service = this.beanFactory.getBean(implementBeanNames[0]) as IService<*> + } + } + + /** + * 执行代理方法 + * + * @param proxy 代理对象 + * @param method 需要执行的方法 + * @param args 参数列表 + * @return 方法执行结果 + */ + override fun exec(proxy: Any, method: Method, args: Array): Any? { + try { + val proxyMethod = this.service.javaClass.getDeclaredMethod(method.name, *method.parameterTypes) + return proxyMethod.invoke(this.service, *args) + } catch (ex: NoSuchMethodException) { + throw NoSuchMethodException("method [${method.toGenericString()}] not implements in class [${this.service::class.java}], you must implements interface [${this.supertype.name}] ") + } + } +} \ No newline at end of file diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/autoconfig/service/ServiceRegister.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/autoconfig/service/ServiceRegister.kt new file mode 100644 index 0000000..d62878b --- /dev/null +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/autoconfig/service/ServiceRegister.kt @@ -0,0 +1,50 @@ +package com.synebula.gaea.app.autoconfig.service + +import com.synebula.gaea.domain.service.IService +import com.synebula.gaea.spring.autoconfig.Register +import org.springframework.beans.factory.config.BeanDefinition +import org.springframework.beans.factory.support.BeanDefinitionBuilder +import org.springframework.beans.factory.support.GenericBeanDefinition +import org.springframework.core.annotation.AnnotationAttributes +import org.springframework.core.type.AnnotationMetadata + +class ServiceRegister : Register() { + override fun scan(metadata: AnnotationMetadata): Map { + val result = mutableMapOf() + + // 获取注解参数信息:basePackages + val attributes = AnnotationAttributes( + metadata.getAnnotationAttributes( + ServiceScan::class.java.name + ) ?: mapOf() + ) + val basePackages = attributes.getStringArray("basePackages") + val beanDefinitions = this.doScan(basePackages, arrayOf(this.interfaceFilter(arrayOf(IService::class.java)))) + beanDefinitions.forEach { beanDefinition -> + // 获取实际的bean类型 + val beanClazz: Class<*> = try { + Class.forName(beanDefinition.beanClassName) + } catch (e: ClassNotFoundException) { + throw e + } + + // 尝试获取实际继承类型 + val implBeanDefinitions = this.doScan(basePackages, arrayOf(this.interfaceFilter(arrayOf(beanClazz)))) + implBeanDefinitions.forEach { + it.isAutowireCandidate = false + result[it.beanClassName!!] = it + } + + // 构造BeanDefinition + val builder = BeanDefinitionBuilder.genericBeanDefinition(beanClazz) + builder.addConstructorArgValue(beanClazz) + builder.addConstructorArgValue(this._beanFactory) + builder.addConstructorArgValue(implBeanDefinitions.map { it.beanClassName }) + val definition = builder.rawBeanDefinition as GenericBeanDefinition + definition.beanClass = ServiceFactory::class.java + definition.autowireMode = GenericBeanDefinition.AUTOWIRE_BY_TYPE + result[beanClazz.name] = definition + } + return result + } +} \ No newline at end of file diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/autoconfig/service/ServiceScan.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/autoconfig/service/ServiceScan.kt new file mode 100644 index 0000000..a988ac2 --- /dev/null +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/autoconfig/service/ServiceScan.kt @@ -0,0 +1,12 @@ +package com.synebula.gaea.app.autoconfig.service + +import org.springframework.context.annotation.Import +import java.lang.annotation.Inherited + + +@Target(AnnotationTarget.ANNOTATION_CLASS, AnnotationTarget.CLASS) +@Retention(AnnotationRetention.RUNTIME) +@MustBeDocumented +@Inherited +@Import(ServiceRegister::class) +annotation class ServiceScan(val basePackages: Array = []) \ No newline at end of file diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/query/IQueryApp.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/query/IQueryApp.kt index f6f0865..e06f38f 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/query/IQueryApp.kt +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/query/IQueryApp.kt @@ -13,17 +13,12 @@ interface IQueryApp : IApplication { /** * 查询服务 */ - var query: IQuery - - /** - * 查询的View类型 - */ - var clazz: Class + var query: IQuery @Method("获取数据") @GetMapping("/{id:.+}") fun get(@PathVariable id: ID): HttpMessage { - val data = this.query.get(id, clazz) + val data = this.query.get(id) val msg = HttpMessage() msg.data = data return msg @@ -32,19 +27,19 @@ interface IQueryApp : IApplication { @Method("获取列表数据") @GetMapping fun list(@RequestParam params: LinkedHashMap): HttpMessage { - val data = this.query.list(params, clazz) + val data = this.query.list(params) return HttpMessage(data) } @Method("获取分页数据") - @GetMapping("/segments/{size}/pages/{page}") + @GetMapping("/size/{size}/pages/{page}") fun paging( @PathVariable size: Int, @PathVariable page: Int, @RequestParam parameters: LinkedHashMap ): HttpMessage { val params = Params(page, size, parameters) - val data = this.query.paging(params, clazz) + val data = this.query.paging(params) return HttpMessage(data) } } \ No newline at end of file diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/query/QueryApp.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/query/QueryApp.kt index 729f48c..a301a17 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/query/QueryApp.kt +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/query/QueryApp.kt @@ -12,7 +12,6 @@ import com.synebula.gaea.query.IQuery */ open class QueryApp( override var name: String, - override var clazz: Class, - override var query: IQuery, + override var query: IQuery, override var logger: ILogger, ) : IQueryApp \ No newline at end of file diff --git a/src/gaea.mongo/build.gradle b/src/gaea.mongodb/build.gradle similarity index 87% rename from src/gaea.mongo/build.gradle rename to src/gaea.mongodb/build.gradle index 41f2957..b99693a 100644 --- a/src/gaea.mongo/build.gradle +++ b/src/gaea.mongodb/build.gradle @@ -1,5 +1,6 @@ dependencies { api project(":src:gaea") + api project(":src:gaea.spring") api("org.springframework.boot:spring-boot-starter-data-mongodb:$spring_version") } diff --git a/src/gaea.mongo/src/main/kotlin/com/synebula/gaea/mongo/MongoExt.kt b/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/MongoExt.kt similarity index 93% rename from src/gaea.mongo/src/main/kotlin/com/synebula/gaea/mongo/MongoExt.kt rename to src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/MongoExt.kt index ecf65cd..e8f57a2 100644 --- a/src/gaea.mongo/src/main/kotlin/com/synebula/gaea/mongo/MongoExt.kt +++ b/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/MongoExt.kt @@ -1,9 +1,9 @@ -package com.synebula.gaea.mongo +package com.synebula.gaea.mongodb import com.synebula.gaea.data.date.DateTime -import com.synebula.gaea.query.annotation.Where -import com.synebula.gaea.query.type.Operator -import com.synebula.gaea.query.type.Order +import com.synebula.gaea.query.Operator +import com.synebula.gaea.query.Order +import com.synebula.gaea.query.Where import org.springframework.data.domain.Sort import org.springframework.data.mongodb.core.query.Criteria import org.springframework.data.mongodb.core.query.Query @@ -30,9 +30,9 @@ fun Query.select(fields: Array): Query { * @param onWhere 获取字段查询方式的方法 */ fun Query.where( - params: Map?, - onWhere: ((v: String) -> Where?) = { null }, - onFieldType: ((v: String) -> Class<*>?) = { null } + params: Map?, + onWhere: ((v: String) -> Where?) = { null }, + onFieldType: ((v: String) -> Class<*>?) = { null } ): Query { val list = arrayListOf() if (params != null) { diff --git a/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/autoconfig/MongodbRepoFactory.kt b/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/autoconfig/MongodbRepoFactory.kt new file mode 100644 index 0000000..dbdeacf --- /dev/null +++ b/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/autoconfig/MongodbRepoFactory.kt @@ -0,0 +1,15 @@ +package com.synebula.gaea.mongodb.autoconfig + +import com.synebula.gaea.spring.autoconfig.Factory +import com.synebula.gaea.spring.autoconfig.Proxy +import org.springframework.beans.factory.BeanFactory + +class MongodbRepoFactory( + supertype: Class<*>, + var beanFactory: BeanFactory, + var implementBeanNames: Array = arrayOf() +) : Factory(supertype) { + override fun createProxy(): Proxy { + return MongodbRepoProxy(supertype, this.beanFactory, this.implementBeanNames) + } +} \ No newline at end of file diff --git a/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/autoconfig/MongodbRepoProxy.kt b/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/autoconfig/MongodbRepoProxy.kt new file mode 100644 index 0000000..b4eb4a8 --- /dev/null +++ b/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/autoconfig/MongodbRepoProxy.kt @@ -0,0 +1,84 @@ +package com.synebula.gaea.mongodb.autoconfig + +import com.synebula.gaea.domain.repository.IRepository +import com.synebula.gaea.log.ILogger +import com.synebula.gaea.mongodb.query.MongodbQuery +import com.synebula.gaea.mongodb.repository.MongodbRepository +import com.synebula.gaea.query.IQuery +import com.synebula.gaea.spring.autoconfig.Proxy +import org.springframework.beans.factory.BeanFactory +import org.springframework.data.mongodb.core.MongoTemplate +import java.io.InvalidClassException +import java.lang.reflect.Method +import java.lang.reflect.ParameterizedType + +class MongodbRepoProxy( + private var supertype: Class<*>, private var beanFactory: BeanFactory, implementBeanNames: Array = arrayOf() +) : Proxy() { + + private var repo: IRepository<*, *>? = null + + private var query: IQuery<*, *>? = null + + init { + if (this.supertype.interfaces.any { it == IRepository::class.java }) { + // 如果是IRepository子接口 + if (implementBeanNames.isEmpty()) { + val genericInterfaces = this.supertype.genericInterfaces.find { + it.typeName.startsWith(IRepository::class.java.typeName) + }!! + val constructor = MongodbRepository::class.java.getConstructor( + Class::class.java, MongoTemplate::class.java + ) + this.repo = constructor.newInstance( + (genericInterfaces as ParameterizedType).actualTypeArguments[0], + this.beanFactory.getBean(MongoTemplate::class.java) + ) + } else { + this.repo = this.beanFactory.getBean(implementBeanNames[0]) as IRepository<*, *> + } + } else { + // 否则是IQuery子接口 + if (implementBeanNames.isEmpty()) { + val genericInterfaces = this.supertype.genericInterfaces.find { + it.typeName.startsWith(IQuery::class.java.typeName) + }!! + val constructor = MongodbQuery::class.java.getConstructor( + Class::class.java, MongoTemplate::class.java, ILogger::class.java + ) + this.query = constructor.newInstance( + (genericInterfaces as ParameterizedType).actualTypeArguments[0], + this.beanFactory.getBean(MongoTemplate::class.java), + this.beanFactory.getBean(ILogger::class.java), + ) + } else { + this.query = this.beanFactory.getBean(implementBeanNames[0]) as IQuery<*, *> + } + } + } + + /** + * 执行代理方法 + * + * @param proxy 代理对象 + * @param method 需要执行的方法 + * @param args 参数列表 + * @return 方法执行结果 + */ + override fun exec(proxy: Any, method: Method, args: Array): Any? { + val proxyClazz = if (this.repo != null) { + this.repo!!.javaClass + } else if (this.query != null) { + this.query!!.javaClass + } else + throw InvalidClassException("class ${this.supertype.name} property repo and query are both null") + + try { + val proxyMethod: Method = proxyClazz.getDeclaredMethod(method.name, *method.parameterTypes) + return proxyMethod.invoke(this.repo, *args) + } catch (ex: NoSuchMethodException) { + throw NoSuchMethodException("method [${method.toGenericString()}] not implements in class [${proxyClazz}], you must implements interface [${this.supertype.name}] ") + } + } + +} \ No newline at end of file diff --git a/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/autoconfig/MongodbRepoRegister.kt b/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/autoconfig/MongodbRepoRegister.kt new file mode 100644 index 0000000..f62cf4c --- /dev/null +++ b/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/autoconfig/MongodbRepoRegister.kt @@ -0,0 +1,54 @@ +package com.synebula.gaea.mongodb.autoconfig + +import com.synebula.gaea.domain.repository.IRepository +import com.synebula.gaea.query.IQuery +import com.synebula.gaea.spring.autoconfig.Register +import org.springframework.beans.factory.config.BeanDefinition +import org.springframework.beans.factory.support.BeanDefinitionBuilder +import org.springframework.beans.factory.support.GenericBeanDefinition +import org.springframework.core.annotation.AnnotationAttributes +import org.springframework.core.type.AnnotationMetadata + +class MongodbRepoRegister : Register() { + override fun scan(metadata: AnnotationMetadata): Map { + val result = mutableMapOf() + + // 获取注解参数信息:basePackages + val attributes = AnnotationAttributes( + metadata.getAnnotationAttributes( + MongodbRepoScan::class.java.name + ) ?: mapOf() + ) + val basePackages = attributes.getStringArray("basePackages") + val beanDefinitions = this.doScan( + basePackages, + arrayOf(this.interfaceFilter(arrayOf(IRepository::class.java, IQuery::class.java))) + ) + beanDefinitions.forEach { beanDefinition -> + // 获取实际的bean类型 + val beanClazz: Class<*> = try { + Class.forName(beanDefinition.beanClassName) + } catch (ex: ClassNotFoundException) { + throw ex + } + + // 尝试获取实际继承类型 + val implBeanDefinitions = this.doScan(basePackages, arrayOf(this.interfaceFilter(arrayOf(beanClazz)))) + implBeanDefinitions.forEach { + it.isAutowireCandidate = false + result[it.beanClassName!!] = it + } + + // 构造BeanDefinition + val builder = BeanDefinitionBuilder.genericBeanDefinition(beanClazz) + builder.addConstructorArgValue(beanClazz) + builder.addConstructorArgValue(this._beanFactory) + builder.addConstructorArgValue(implBeanDefinitions.map { it.beanClassName }) + val definition = builder.rawBeanDefinition as GenericBeanDefinition + definition.beanClass = MongodbRepoFactory::class.java + definition.autowireMode = GenericBeanDefinition.AUTOWIRE_BY_TYPE + result[beanClazz.name] = definition + } + return result + } +} \ No newline at end of file diff --git a/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/autoconfig/MongodbRepoScan.kt b/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/autoconfig/MongodbRepoScan.kt new file mode 100644 index 0000000..ef8aa03 --- /dev/null +++ b/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/autoconfig/MongodbRepoScan.kt @@ -0,0 +1,12 @@ +package com.synebula.gaea.mongodb.autoconfig + +import org.springframework.context.annotation.Import +import java.lang.annotation.Inherited + + +@Target(AnnotationTarget.ANNOTATION_CLASS, AnnotationTarget.CLASS) +@Retention(AnnotationRetention.RUNTIME) +@MustBeDocumented +@Inherited +@Import(MongodbRepoRegister::class) +annotation class MongodbRepoScan(val basePackages: Array = []) \ No newline at end of file diff --git a/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/query/MongodbQuery.kt b/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/query/MongodbQuery.kt new file mode 100644 index 0000000..93bff5b --- /dev/null +++ b/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/query/MongodbQuery.kt @@ -0,0 +1,102 @@ +package com.synebula.gaea.mongodb.query + +import com.synebula.gaea.ext.fieldNames +import com.synebula.gaea.ext.firstCharLowerCase +import com.synebula.gaea.log.ILogger +import com.synebula.gaea.mongodb.order +import com.synebula.gaea.mongodb.select +import com.synebula.gaea.mongodb.where +import com.synebula.gaea.mongodb.whereId +import com.synebula.gaea.query.IQuery +import com.synebula.gaea.query.Page +import com.synebula.gaea.query.Params +import com.synebula.gaea.query.Table +import org.springframework.data.mongodb.core.MongoTemplate +import org.springframework.data.mongodb.core.query.Criteria +import org.springframework.data.mongodb.core.query.Query + +/** + * 实现IQuery的Mongodb查询类 + * @param template MongodbRepo对象 + */ + +open class MongodbQuery(override var clazz: Class, var template: MongoTemplate, var logger: ILogger) : + IQuery { + + /** + * 使用View解析是collection时是否校验存在,默认不校验 + */ + var validViewCollection = false + + override fun get(id: ID): TView? { + return this.template.findOne(whereId(id), clazz, this.collection(clazz)) + } + + override fun list(params: Map?): List { + val fields = this.fields(clazz) + val query = Query() + query.where(params, clazz) + query.select(fields) + return this.find(query, clazz) + } + + override fun count(params: Map?): Int { + val query = Query() + return this.template.count(query.where(params, clazz), this.collection(clazz)).toInt() + } + + override fun paging(params: Params): Page { + val query = Query() + val fields = this.fields(clazz) + val result = Page(params.page, params.size) + result.total = this.count(params.parameters) + //如果总数和索引相同,说明该页没有数据,直接跳到上一页 + if (result.total == result.index) { + params.page -= 1 + result.page -= 1 + } + query.select(fields) + query.where(params.parameters, clazz) + query.with(order(params.orders)) + query.skip(params.index).limit(params.size) + result.data = this.find(query, clazz) + return result + } + + override fun range(field: String, params: List): List { + return this.find(Query.query(Criteria.where(field).`in`(params)), clazz) + } + + protected fun find(query: Query, clazz: Class): List { + return this.template.find(query, clazz, this.collection(clazz)) + } + + protected fun fields(clazz: Class): Array { + val fields = mutableListOf() + fields.addAll(clazz.fieldNames()) + var parent = clazz.superclass + while (parent != Any::class.java) { + fields.addAll(clazz.superclass.fieldNames()) + parent = parent.superclass + } + return fields.toTypedArray() + } + + /** + * 获取collection + */ + protected fun collection(clazz: Class): String { + val table: Table? = clazz.getDeclaredAnnotation( + Table::class.java + ) + return if (table != null) return table.name + else { + this.logger.info(this, "视图类没有标记[Collection]注解,无法获取Collection名称。尝试使用View<${clazz.name}>名称解析集合") + val name = clazz.simpleName.removeSuffix("View").firstCharLowerCase() + if (!validViewCollection || this.template.collectionExists(name)) name + else { + throw RuntimeException("找不到名为[${clazz.name}]的集合") + } + } + } +} diff --git a/src/gaea.mongo/src/main/kotlin/com/synebula/gaea/mongo/query/MongodbQuery.kt b/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/query/MongodbUniversalQuery.kt similarity index 82% rename from src/gaea.mongo/src/main/kotlin/com/synebula/gaea/mongo/query/MongodbQuery.kt rename to src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/query/MongodbUniversalQuery.kt index fe117cb..f88dfbc 100644 --- a/src/gaea.mongo/src/main/kotlin/com/synebula/gaea/mongo/query/MongodbQuery.kt +++ b/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/query/MongodbUniversalQuery.kt @@ -1,16 +1,17 @@ -package com.synebula.gaea.mongo.query +package com.synebula.gaea.mongodb.query + import com.synebula.gaea.ext.fieldNames import com.synebula.gaea.ext.firstCharLowerCase import com.synebula.gaea.log.ILogger -import com.synebula.gaea.mongo.order -import com.synebula.gaea.mongo.select -import com.synebula.gaea.mongo.where -import com.synebula.gaea.mongo.whereId -import com.synebula.gaea.query.IQuery +import com.synebula.gaea.mongodb.order +import com.synebula.gaea.mongodb.select +import com.synebula.gaea.mongodb.where +import com.synebula.gaea.mongodb.whereId +import com.synebula.gaea.query.IUniversalQuery import com.synebula.gaea.query.Page import com.synebula.gaea.query.Params -import com.synebula.gaea.query.annotation.Table +import com.synebula.gaea.query.Table import org.springframework.data.mongodb.core.MongoTemplate import org.springframework.data.mongodb.core.query.Criteria import org.springframework.data.mongodb.core.query.Query @@ -19,8 +20,7 @@ import org.springframework.data.mongodb.core.query.Query * 实现IQuery的Mongodb查询类 * @param template MongodbRepo对象 */ - -open class MongodbQuery(var template: MongoTemplate, var logger: ILogger) : IQuery { +open class MongodbUniversalQuery(var template: MongoTemplate, var logger: ILogger) : IUniversalQuery { /** * 使用View解析是collection时是否校验存在,默认不校验 @@ -36,7 +36,7 @@ open class MongodbQuery(var template: MongoTemplate, var logger: ILogger) : IQue val query = Query() query.where(params, clazz) query.select(fields) - return this.template.find(query, clazz, this.collection(clazz)) + return this.find(query, clazz) } override fun count(params: Map?, clazz: Class): Int { @@ -58,12 +58,16 @@ open class MongodbQuery(var template: MongoTemplate, var logger: ILogger) : IQue query.where(params.parameters, clazz) query.with(order(params.orders)) query.skip(params.index).limit(params.size) - result.data = this.template.find(query, clazz, this.collection(clazz)) + result.data = this.find(query, clazz) return result } override fun range(field: String, params: List, clazz: Class): List { - return this.template.find(Query.query(Criteria.where(field).`in`(params)), clazz, this.collection(clazz)) + return this.find(Query.query(Criteria.where(field).`in`(params)), clazz) + } + + protected fun find(query: Query, clazz: Class): List { + return this.template.find(query, clazz, this.collection(clazz)) } fun fields(clazz: Class): Array { @@ -82,7 +86,7 @@ open class MongodbQuery(var template: MongoTemplate, var logger: ILogger) : IQue */ fun collection(clazz: Class): String { val table: Table? = clazz.getDeclaredAnnotation( - Table::class.java + Table::class.java ) return if (table != null) return table.name diff --git a/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/repository/MongodbRepository.kt b/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/repository/MongodbRepository.kt new file mode 100644 index 0000000..8c3a348 --- /dev/null +++ b/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/repository/MongodbRepository.kt @@ -0,0 +1,47 @@ +package com.synebula.gaea.mongodb.repository + +import com.synebula.gaea.domain.model.IAggregateRoot +import com.synebula.gaea.domain.repository.IRepository +import com.synebula.gaea.mongodb.where +import com.synebula.gaea.mongodb.whereId +import org.springframework.data.mongodb.core.MongoTemplate +import org.springframework.data.mongodb.core.query.Query + +/** + * 实现[IRepository]的Mongodb仓储类 + * @param repo MongodbRepo对象 + */ +open class MongodbRepository, ID>( + override var clazz: Class, + protected var repo: MongoTemplate +) : IRepository { + + override fun add(obj: TAggregateRoot) { + this.repo.save(obj) + } + + override fun add(list: List) { + this.repo.insert(list, clazz) + } + + override fun remove(id: ID) { + this.repo.remove(whereId(id), clazz) + } + + override fun get(id: ID): TAggregateRoot? { + return this.repo.findOne(whereId(id), clazz) + } + + override fun update(obj: TAggregateRoot) { + this.repo.save(obj) + } + + override fun update(list: List) { + this.repo.save(list) + } + + override fun count(params: Map?): Int { + val query = Query() + return this.repo.count(query.where(params, clazz), clazz).toInt() + } +} diff --git a/src/gaea.mongo/src/main/kotlin/com/synebula/gaea/mongo/repository/MongodbRepository.kt b/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/repository/MongodbUniversalRepository.kt similarity index 55% rename from src/gaea.mongo/src/main/kotlin/com/synebula/gaea/mongo/repository/MongodbRepository.kt rename to src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/repository/MongodbUniversalRepository.kt index 4c2b469..93a3d87 100644 --- a/src/gaea.mongo/src/main/kotlin/com/synebula/gaea/mongo/repository/MongodbRepository.kt +++ b/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/repository/MongodbUniversalRepository.kt @@ -1,9 +1,9 @@ -package com.synebula.gaea.mongo.repository +package com.synebula.gaea.mongodb.repository import com.synebula.gaea.domain.model.IAggregateRoot -import com.synebula.gaea.domain.repository.IRepository -import com.synebula.gaea.mongo.where -import com.synebula.gaea.mongo.whereId +import com.synebula.gaea.domain.repository.IUniversalRepository +import com.synebula.gaea.mongodb.where +import com.synebula.gaea.mongodb.whereId import org.springframework.data.mongodb.core.MongoTemplate import org.springframework.data.mongodb.core.query.Query @@ -11,7 +11,7 @@ import org.springframework.data.mongodb.core.query.Query * 实现ITypedRepository的Mongodb仓储类 * @param repo MongodbRepo对象 */ -open class MongodbRepository(private var repo: MongoTemplate) : IRepository { +open class MongodbUniversalRepository(private var repo: MongoTemplate) : IUniversalRepository { override fun , ID> remove(id: ID, clazz: Class) { this.repo.remove(whereId(id), clazz) @@ -25,21 +25,33 @@ open class MongodbRepository(private var repo: MongoTemplate) : IRepository { } override fun , ID> update( - obj: TAggregateRoot, + root: TAggregateRoot, clazz: Class, ) { - this.repo.save(obj) + this.repo.save(root) } - override fun , ID> add(obj: TAggregateRoot, clazz: Class) { - this.repo.save(obj) + /** + * 更新多个个对象。 + * + * @param roots 需要更新的对象。 + */ + override fun , ID> update( + roots: List, + clazz: Class + ) { + this.repo.save(roots) + } + + override fun , ID> add(root: TAggregateRoot, clazz: Class) { + this.repo.save(root) } override fun , ID> add( - obj: List, + roots: List, clazz: Class, ) { - this.repo.insert(obj, clazz) + this.repo.insert(roots, clazz) } override fun count(params: Map?, clazz: Class): Int { diff --git a/src/gaea.spring/build.gradle b/src/gaea.spring/build.gradle new file mode 100644 index 0000000..95e297c --- /dev/null +++ b/src/gaea.spring/build.gradle @@ -0,0 +1,22 @@ +buildscript { + dependencies { + classpath("org.jetbrains.kotlin:kotlin-allopen:$kotlin_version") + } +} + +apply plugin: 'kotlin-spring' + +dependencies { + implementation project(":src:gaea") + implementation("org.springframework.boot:spring-boot-starter-web:$spring_version") + implementation group: 'com.google.code.gson', name: 'gson', version: '2.8.6' +} + +publishing { + publications { + publish(MavenPublication) { + from components.java + } + } +} + diff --git a/src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/autoconfig/Factory.kt b/src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/autoconfig/Factory.kt new file mode 100644 index 0000000..2c399a1 --- /dev/null +++ b/src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/autoconfig/Factory.kt @@ -0,0 +1,44 @@ +package com.synebula.gaea.spring.autoconfig + +import org.springframework.beans.factory.FactoryBean +import org.springframework.cglib.proxy.Enhancer +import java.lang.reflect.Proxy as JdkProxy + +/** + * 代理生成工厂 + * + * @param supertype 需要被代理的父类型 + * @param proxyType 代理类型:JDK 或 CGLIB + */ +abstract class Factory( + protected val supertype: Class<*>, + protected val proxyType: ProxyType = ProxyType.Cglib +) : FactoryBean { + override fun getObject(): Any { + val handler: Proxy = this.createProxy() + + //JDK 方式代理代码, 暂时选用cglib + val proxy: Any = if (proxyType == ProxyType.JDK) { + JdkProxy.newProxyInstance( + this.supertype.classLoader, arrayOf(this.supertype), handler + ) + } else { //cglib代理 + val enhancer = Enhancer() + enhancer.setSuperclass(supertype) + enhancer.setCallback(handler) + enhancer.create() + } + + return proxy + } + + override fun getObjectType(): Class<*> { + return supertype + } + + override fun isSingleton(): Boolean { + return true + } + + abstract fun createProxy(): Proxy +} \ No newline at end of file diff --git a/src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/autoconfig/Proxy.kt b/src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/autoconfig/Proxy.kt new file mode 100644 index 0000000..201ba8a --- /dev/null +++ b/src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/autoconfig/Proxy.kt @@ -0,0 +1,43 @@ +package com.synebula.gaea.spring.autoconfig + +import org.springframework.cglib.proxy.MethodInterceptor +import org.springframework.cglib.proxy.MethodProxy +import java.lang.reflect.InvocationHandler +import java.lang.reflect.Method + +abstract class Proxy : MethodInterceptor, InvocationHandler { + + /** + * JDK 方式代理代码 + */ + @Throws(Throwable::class) + override fun invoke(proxy: Any, method: Method, args: Array): Any? { + return if (Any::class.java == method.declaringClass) { + method.invoke(this, *args) + } else { + exec(proxy, method, args) + } + } + + /** + * 暂时选用cglib 方式代理代码 + */ + @Throws(Throwable::class) + override fun intercept(proxy: Any, method: Method, args: Array, methodProxy: MethodProxy): Any? { + return if (Any::class.java == method.declaringClass) { + methodProxy.invoke(this, args) + } else { + exec(proxy, method, args) + } + } + + /** + * 执行代理方法 + * + * @param proxy 代理对象 + * @param method 需要执行的方法 + * @param args 参数列表 + * @return 方法执行结果 + */ + abstract fun exec(proxy: Any, method: Method, args: Array): Any? +} \ No newline at end of file diff --git a/src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/autoconfig/ProxyType.kt b/src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/autoconfig/ProxyType.kt new file mode 100644 index 0000000..7ba44cc --- /dev/null +++ b/src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/autoconfig/ProxyType.kt @@ -0,0 +1,3 @@ +package com.synebula.gaea.spring.autoconfig + +enum class ProxyType { JDK, Cglib } \ No newline at end of file diff --git a/src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/autoconfig/Register.kt b/src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/autoconfig/Register.kt new file mode 100644 index 0000000..f9d70d5 --- /dev/null +++ b/src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/autoconfig/Register.kt @@ -0,0 +1,109 @@ +package com.synebula.gaea.spring.autoconfig + +import org.springframework.beans.BeansException +import org.springframework.beans.factory.BeanClassLoaderAware +import org.springframework.beans.factory.BeanFactory +import org.springframework.beans.factory.BeanFactoryAware +import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition +import org.springframework.beans.factory.config.BeanDefinition +import org.springframework.beans.factory.support.BeanDefinitionRegistry +import org.springframework.context.EnvironmentAware +import org.springframework.context.ResourceLoaderAware +import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider +import org.springframework.context.annotation.ImportBeanDefinitionRegistrar +import org.springframework.core.env.Environment +import org.springframework.core.io.ResourceLoader +import org.springframework.core.type.AnnotationMetadata +import org.springframework.core.type.classreading.MetadataReader +import org.springframework.core.type.classreading.MetadataReaderFactory +import org.springframework.core.type.filter.TypeFilter +import org.springframework.util.ClassUtils +import java.util.* + +abstract class Register : ImportBeanDefinitionRegistrar, ResourceLoaderAware, BeanClassLoaderAware, + EnvironmentAware, BeanFactoryAware { + + protected var _classLoader: ClassLoader? = null + protected var _environment: Environment? = null + protected var _resourceLoader: ResourceLoader? = null + protected var _beanFactory: BeanFactory? = null + + override fun registerBeanDefinitions(metadata: AnnotationMetadata, registry: BeanDefinitionRegistry) { + val beanDefinitions = this.scan(metadata) + beanDefinitions.forEach { registry.registerBeanDefinition(it.key, it.value) } + } + + abstract fun scan(metadata: AnnotationMetadata): Map + + /** + * 根据过滤器扫描直接包下bean + * + * @param packages 指定的扫描包 + * @param filters 过滤器 + * @return 扫描后的bean定义 + */ + protected fun doScan(packages: Array?, filters: Array): List { + val scanner: ClassPathScanningCandidateComponentProvider = + object : ClassPathScanningCandidateComponentProvider() { + override fun isCandidateComponent(beanDefinition: AnnotatedBeanDefinition): Boolean { + try { + val metadata = beanDefinition.metadata + val target = ClassUtils.forName(metadata.className, _classLoader) + return !target.isAnnotation + } catch (ignored: Exception) { + } + return false + } + } + scanner.environment = _environment!! + scanner.resourceLoader = _resourceLoader!! + for (filter in filters) { + scanner.addIncludeFilter(filter) + } + val beanDefinitions: MutableList = LinkedList() + for (basePackage in packages!!) { + beanDefinitions.addAll(scanner.findCandidateComponents(basePackage)) + } + return beanDefinitions + } + + /** + * 获取指定接口的类型过滤器 + * + * @param interfaces 需要过滤的父接口类型 + * @param onlyInterface 是否只获取接口类型 + * @return 类型过滤器 + */ + protected fun interfaceFilter(interfaces: Array>, onlyInterface: Boolean = false): TypeFilter { + return TypeFilter { metadataReader: MetadataReader, _: MetadataReaderFactory? -> + // 如果只获取接口类型且当前类型非接口 直接返回 + if (onlyInterface && !metadataReader.annotationMetadata.isInterface) + return@TypeFilter false + + var matched = false + val interfaceNames = metadataReader.classMetadata.interfaceNames + // 如果当前类型继承接口有任一需要过滤的接口则说明复合条件 + for (interfaceName in interfaceNames) { + matched = interfaces.any { clazz -> clazz.name == interfaceName } + } + matched + } + } + + override fun setResourceLoader(resourceLoader: ResourceLoader) { + this._resourceLoader = resourceLoader + } + + override fun setBeanClassLoader(classLoader: ClassLoader) { + this._classLoader = classLoader + } + + override fun setEnvironment(environment: Environment) { + this._environment = environment + } + + @Throws(BeansException::class) + override fun setBeanFactory(beanFactory: BeanFactory) { + this._beanFactory = beanFactory + } +} \ No newline at end of file diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/IRepository.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/IRepository.kt index 67d4ea2..99c411a 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/IRepository.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/IRepository.kt @@ -6,22 +6,29 @@ import com.synebula.gaea.domain.model.IAggregateRoot * 定义了提供增删改的仓储接口。 * 本接口泛型放置到方法上,并需要显式提供聚合根的class对象 */ -interface IRepository { +interface IRepository, ID> { + + /** + * 仓储的对象类 + */ + var clazz: Class + /** * 插入单个对象。 * * @param obj 需要插入的对象。 * @return 返回原对象,如果对象ID为自增,则补充自增ID。 */ - fun , ID> add(obj: TAggregateRoot, clazz: Class) + fun add(obj: TAggregateRoot) /** * 插入多个个对象。 * - * @param obj 需要插入的对象。 + * @param list 需要插入的对象。 * @return 返回原对象,如果对象ID为自增,则补充自增ID。 */ - fun , ID> add(obj: List, clazz: Class) + fun add(list: List) + /** * 更新对象。 @@ -29,24 +36,30 @@ interface IRepository { * @param obj 需要更新的对象。 * @return */ - fun , ID> update(obj: TAggregateRoot, clazz: Class) + fun update(obj: TAggregateRoot) + + /** + * 更新多个个对象。 + * + * @param list 需要新的对象。 + */ + fun update(list: List) /** * 通过id删除该条数据 * - * @param id id - * @param clazz 操作数据的类型 + * @param id 对象ID。 + * @return */ - fun , ID> remove(id: ID, clazz: Class) + fun remove(id: ID) /** * 根据ID获取对象。 * - * @param id id - * @param clazz 操作数据的类型 - * @return 聚合根 + * @param id 对象ID。 + * @return */ - fun , ID> get(id: ID, clazz: Class): TAggregateRoot? + fun get(id: ID): TAggregateRoot? /** @@ -55,5 +68,7 @@ interface IRepository { * @param params 查询条件。 * @return int */ - fun count(params: Map?, clazz: Class): Int + fun count(params: Map?): Int + } + diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/ISpecificRepository.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/ISpecificRepository.kt deleted file mode 100644 index e9501c0..0000000 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/ISpecificRepository.kt +++ /dev/null @@ -1,61 +0,0 @@ -package com.synebula.gaea.domain.repository - -import com.synebula.gaea.domain.model.IAggregateRoot - -/** - * 继承本接口表示对象为仓储类。 - * 定义了提供增删改的仓储接口。 - * 本接口泛型定义在类上,方法中不需要显式提供聚合根的class对象,class对象作为类的成员变量声明。 - * - * @param TAggregateRoot 聚合根类型 - * @author alex - */ -interface ISpecificRepository, ID> { - - /** - * 仓储的对象类 - */ - var clazz: Class? - - /** - * 插入单个对象。 - * - * @param obj 需要插入的对象。 - * @return 返回原对象,如果对象ID为自增,则补充自增ID。 - */ - fun add(obj: TAggregateRoot) - - /** - * 更新对象。 - * - * @param obj 需要更新的对象。 - * @return - */ - fun update(obj: TAggregateRoot) - - /** - * 通过id删除该条数据 - * - * @param id 对象ID。 - * @return - */ - fun remove(id: ID) - - /** - * 根据ID获取对象。 - * - * @param id 对象ID。 - * @return - */ - fun get(id: ID): TAggregateRoot - - - /** - * 根据条件查询符合条件记录的数量 - * - * @param params 查询条件。 - * @return int - */ - fun count(params: Map?): Int - -} diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/IUniversalRepository.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/IUniversalRepository.kt new file mode 100644 index 0000000..8eaca7e --- /dev/null +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/IUniversalRepository.kt @@ -0,0 +1,65 @@ +package com.synebula.gaea.domain.repository + +import com.synebula.gaea.domain.model.IAggregateRoot + +/** + * 定义了提供增删改的仓储接口。 + * 本接口泛型放置到方法上,并需要显式提供聚合根的class对象 + */ +interface IUniversalRepository { + /** + * 插入单个对象。 + * + * @param root 需要插入的对象。 + * @return 返回原对象,如果对象ID为自增,则补充自增ID。 + */ + fun , ID> add(root: TAggregateRoot, clazz: Class) + + /** + * 插入多个个对象。 + * + * @param roots 需要插入的对象。 + */ + fun , ID> add(roots: List, clazz: Class) + + /** + * 更新对象。 + * + * @param root 需要更新的对象。 + * @return + */ + fun , ID> update(root: TAggregateRoot, clazz: Class) + + /** + * 更新多个个对象。 + * + * @param roots 需要更新的对象。 + */ + fun , ID> update(roots: List, clazz: Class) + + /** + * 通过id删除该条数据 + * + * @param id id + * @param clazz 操作数据的类型 + */ + fun , ID> remove(id: ID, clazz: Class) + + /** + * 根据ID获取对象。 + * + * @param id id + * @param clazz 操作数据的类型 + * @return 聚合根 + */ + fun , ID> get(id: ID, clazz: Class): TAggregateRoot? + + + /** + * 根据条件查询符合条件记录的数量 + * + * @param params 查询条件。 + * @return int + */ + fun count(params: Map?, clazz: Class): Int +} diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/IService.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/IService.kt index 6cabe08..82f26d6 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/IService.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/IService.kt @@ -1,8 +1,6 @@ package com.synebula.gaea.domain.service import com.synebula.gaea.data.message.DataMessage -import com.synebula.gaea.data.message.StatusMessage -import com.synebula.gaea.log.ILogger /** @@ -12,27 +10,39 @@ import com.synebula.gaea.log.ILogger * @since 2016年9月18日 下午2:23:15 */ interface IService { - /** - * 日志组件。 - */ - var logger: ILogger + /** + * 增加对象 + * + * @param command 增加对象命令 + */ fun add(command: ICommand): DataMessage + /** + * 增加对象 + * + * @param commands 增加对象命令列表 + */ + fun add(commands: List) + + /** + * 更新对象 + * + * @param id 对象ID + * @param command 更新对象命令 + */ fun update(id: ID, command: ICommand) + /** + * 批量更新对象 + * + * @param commands 更新对象命令列表 + */ + fun update(commands: List) + + /** + * 增加对象 + * @param id 对象ID + */ fun remove(id: ID) - - /** - * 添加一个删除对象前执行监听器。 - * @param key 监听器标志。 - * @param func 监听方法。 - */ - fun addBeforeRemoveListener(key: String, func: (id: ID) -> StatusMessage) - - /** - * 移除一个删除对象前执行监听器。 - * @param key 监听器标志。 - */ - fun removeBeforeRemoveListener(key: String) } diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/ISimpleService.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/ISimpleService.kt index 6d8fbff..ad7b5bc 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/ISimpleService.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/ISimpleService.kt @@ -1,7 +1,6 @@ package com.synebula.gaea.domain.service import com.synebula.gaea.data.message.DataMessage -import com.synebula.gaea.data.message.StatusMessage import com.synebula.gaea.domain.model.IAggregateRoot import com.synebula.gaea.log.ILogger @@ -18,22 +17,38 @@ interface ISimpleService, ID> { */ var logger: ILogger + /** + * 增加对象 + * + * @param root 增加对象命令 + */ fun add(root: TAggregateRoot): DataMessage + /** + * 增加对象 + * + * @param roots 增加对象命令列表 + */ + fun add(roots: List) + + /** + * 更新对象 + * + * @param id 对象ID + * @param root 更新对象命令 + */ fun update(id: ID, root: TAggregateRoot) + /** + * 批量更新对象 + * + * @param roots 更新对象命令列表 + */ + fun update(roots: List) + + /** + * 增加对象 + * @param id 对象ID + */ fun remove(id: ID) - - /** - * 添加一个删除对象前执行监听器。 - * @param key 监听器标志。 - * @param func 监听方法。 - */ - fun addBeforeRemoveListener(key: String, func: (id: ID) -> StatusMessage) - - /** - * 移除一个删除对象前执行监听器。 - * @param key 监听器标志。 - */ - fun removeBeforeRemoveListener(key: String) } diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/Service.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/Service.kt index eee85ec..264a258 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/Service.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/Service.kt @@ -1,78 +1,80 @@ package com.synebula.gaea.domain.service import com.synebula.gaea.data.message.DataMessage -import com.synebula.gaea.data.message.StatusMessage import com.synebula.gaea.data.serialization.IObjectMapper import com.synebula.gaea.domain.model.IAggregateRoot import com.synebula.gaea.domain.repository.IRepository -import com.synebula.gaea.log.ILogger /** - * 依赖了IRepository仓储借口的服务实现类 Service - * 该类依赖仓储接口 @see IRepository, 需要显式提供聚合根的class对象 + * 依赖了IRepository仓储借口的服务实现类 GenericsService + * 该类依赖仓储接口 @see IGenericsRepository, 需要显式提供聚合根的class对象 * - * @param repository 仓储对象 * @param clazz 聚合根类对象 - * @param deserializer 对象转换组件 - * @param logger 日志组件 + * @param repo 仓储对象 + * @param mapper 对象转换组件 * @author alex * @version 0.1 * @since 2020-05-17 */ -open class Service, ID>( - protected open var clazz: Class, - protected open var repository: IRepository, - protected open var deserializer: IObjectMapper, - override var logger: ILogger, +open class Service, ID>( + protected open var clazz: Class, + protected open var repo: IRepository, + protected open var mapper: IObjectMapper, ) : IService { - /** - * 删除对象前执行监听器。 - */ - protected val beforeRemoveListeners = mutableMapOf StatusMessage>() /** - * 添加一个删除对象前执行监听器。 - * @param key 监听器标志。 - * @param func 监听方法。 + * 增加对象 + * + * @param command 增加对象命令 */ - override fun addBeforeRemoveListener(key: String, func: (id: ID) -> StatusMessage) { - this.beforeRemoveListeners[key] = func - } - - /** - * 移除一个删除对象前执行监听器。 - * @param key 监听器标志。 - */ - override fun removeBeforeRemoveListener(key: String) { - this.beforeRemoveListeners.remove(key) - } - override fun add(command: ICommand): DataMessage { val msg = DataMessage() - val root = this.deserialize(command) - this.repository.add(root, this.clazz) + val root = this.map(command) + this.repo.add(root) msg.data = root.id return msg } - override fun update(id: ID, command: ICommand) { - val root = this.deserialize(command) - root.id = id - this.repository.update(root, this.clazz) + /** + * 增加对象 + * + * @param commands 增加对象命令列表 + */ + override fun add(commands: List) { + val roots = commands.map { this.map(it) } + this.repo.add(roots) } + /** + * 更新对象 + * + * @param id 对象ID + * @param command 更新对象命令 + */ + override fun update(id: ID, command: ICommand) { + val root = this.map(command) + root.id = id + this.repo.update(root) + } + + /** + * 批量更新对象 + * + * @param commands 更新对象命令列表 + */ + override fun update(commands: List) { + val roots = commands.map { this.map(it) } + this.repo.update(roots) + } + + /** + * 增加对象 + * @param id 对象ID + */ override fun remove(id: ID) { - val functions = this.beforeRemoveListeners.values - var msg: StatusMessage - for (func in functions) { - msg = func(id) - if (!msg.success()) { - throw IllegalStateException(msg.message) - } - } - this.repository.remove(id, this.clazz) + this.repo.remove(id) } /** @@ -81,9 +83,9 @@ open class Service, ID>( * @param command 需要转换的命令 * @return 聚合根 */ - protected open fun deserialize(command: ICommand): TAggregateRoot { + protected open fun map(command: ICommand): TRoot { try { - return deserializer.deserialize(command, this.clazz) + return mapper.deserialize(command, this.clazz) } catch (ex: Exception) { throw RuntimeException("command not match aggregate root", ex) } diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/ServiceDependency.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/ServiceDependency.kt new file mode 100644 index 0000000..42e0c2b --- /dev/null +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/ServiceDependency.kt @@ -0,0 +1,16 @@ +package com.synebula.gaea.domain.service + +import com.synebula.gaea.domain.model.IAggregateRoot +import com.synebula.gaea.domain.repository.IRepository +import kotlin.reflect.KClass + +/** + * 声明服务的依赖项,若服务没有实现类则可以根据依赖项自动组装服务。 + * + * @param clazz 依赖的聚合根类型 + * @param repo 依赖的[IRepository]类型 + */ +annotation class ServiceDependency( + val clazz: KClass>, + val repo: KClass>, +) diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/SimpleService.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/SimpleService.kt index 1a216bc..3c31c8e 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/SimpleService.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/SimpleService.kt @@ -1,15 +1,14 @@ package com.synebula.gaea.domain.service import com.synebula.gaea.data.message.DataMessage -import com.synebula.gaea.data.message.StatusMessage import com.synebula.gaea.domain.model.IAggregateRoot import com.synebula.gaea.domain.repository.IRepository import com.synebula.gaea.log.ILogger /** - * 依赖了IRepository仓储借口的服务实现类 Service - * 该类依赖仓储接口 @see IRepository, 需要显式提供聚合根的class对象 + * 依赖了IRepository仓储借口的服务实现类 GenericsService + * 该类依赖仓储接口 @see IGenericsRepository, 需要显式提供聚合根的class对象 * * @param repository 仓储对象 * @param clazz 聚合根类对象 @@ -20,53 +19,41 @@ import com.synebula.gaea.log.ILogger */ open class SimpleService, ID>( protected open var clazz: Class, - protected open var repository: IRepository, + protected open var repository: IRepository, override var logger: ILogger, ) : ISimpleService { - /** - * 删除对象前执行监听器。 - */ - protected val beforeRemoveListeners = mutableMapOf StatusMessage>() - - /** - * 添加一个删除对象前执行监听器。 - * @param key 监听器标志。 - * @param func 监听方法。 - */ - override fun addBeforeRemoveListener(key: String, func: (id: ID) -> StatusMessage) { - this.beforeRemoveListeners[key] = func - } - - /** - * 移除一个删除对象前执行监听器。 - * @param key 监听器标志。 - */ - override fun removeBeforeRemoveListener(key: String) { - this.beforeRemoveListeners.remove(key) - } - override fun add(root: TAggregateRoot): DataMessage { val msg = DataMessage() - this.repository.add(root, this.clazz) + this.repository.add(root) msg.data = root.id return msg } override fun update(id: ID, root: TAggregateRoot) { root.id = id - this.repository.update(root, this.clazz) + this.repository.update(root) } override fun remove(id: ID) { - val functions = this.beforeRemoveListeners.values - var msg: StatusMessage - for (func in functions) { - msg = func(id) - if (!msg.success()) { - throw IllegalStateException(msg.message) - } - } - this.repository.remove(id, this.clazz) + this.repository.remove(id) + } + + /** + * 增加对象 + * + * @param roots 增加对象命令列表 + */ + override fun add(roots: List) { + this.repository.add(roots) + } + + /** + * 批量更新对象 + * + * @param roots 更新对象命令列表 + */ + override fun update(roots: List) { + this.repository.update(roots) } } diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/query/IQuery.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/query/IQuery.kt index adce2a8..1f2aa50 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/query/IQuery.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/query/IQuery.kt @@ -5,22 +5,27 @@ package com.synebula.gaea.query * * @author alex */ -interface IQuery { +interface IQuery { + /** + * 仓储的视图类 + */ + var clazz: Class + /** * 根据Key获取对象。 * * @param id 对象Key。 * @return 视图结果 */ - fun get(id: ID, clazz: Class): TView? + fun get(id: ID): TView? /** * 根据实体类条件查询所有符合条件记录 - * + *` * @param params 查询条件。 * @return 视图列表 */ - fun list(params: Map?, clazz: Class): List + fun list(params: Map?): List /** * 根据条件查询符合条件记录的数量 @@ -28,7 +33,7 @@ interface IQuery { * @param params 查询条件。 * @return 数量 */ - fun count(params: Map?, clazz: Class): Int + fun count(params: Map?): Int /** * 根据实体类条件查询所有符合条件记录(分页查询) @@ -36,7 +41,7 @@ interface IQuery { * @param params 分页条件 * @return 分页数据 */ - fun paging(params: Params, clazz: Class): Page + fun paging(params: Params): Page /** * 查询条件范围内数据。 @@ -45,5 +50,5 @@ interface IQuery { * * @return 视图列表 */ - fun range(field: String, params: List, clazz: Class): List + fun range(field: String, params: List): List } diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/query/ISpecificQuery.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/query/IUniversalQuery.kt similarity index 61% rename from src/gaea/src/main/kotlin/com/synebula/gaea/query/ISpecificQuery.kt rename to src/gaea/src/main/kotlin/com/synebula/gaea/query/IUniversalQuery.kt index fbe4c77..05929ab 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/query/ISpecificQuery.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/query/IUniversalQuery.kt @@ -1,18 +1,18 @@ package com.synebula.gaea.query /** - * 查询基接口。 - * 本接口泛型定义在类上,方法中不需要显式提供聚合根的class对象,class对象作为类的成员变量声明。 + * 查询基接口, 其中方法都指定了查询的视图类型。 + * * @author alex */ -interface ISpecificQuery { +interface IUniversalQuery { /** * 根据Key获取对象。 * * @param id 对象Key。 * @return 视图结果 */ - fun get(id: ID): TView? + fun get(id: ID, clazz: Class): TView? /** * 根据实体类条件查询所有符合条件记录 @@ -20,7 +20,7 @@ interface ISpecificQuery { * @param params 查询条件。 * @return 视图列表 */ - fun list(params: Map?): List + fun list(params: Map?, clazz: Class): List /** * 根据条件查询符合条件记录的数量 @@ -28,7 +28,7 @@ interface ISpecificQuery { * @param params 查询条件。 * @return 数量 */ - fun count(params: Map?): Int + fun count(params: Map?, clazz: Class): Int /** * 根据实体类条件查询所有符合条件记录(分页查询) @@ -36,7 +36,7 @@ interface ISpecificQuery { * @param params 分页条件 * @return 分页数据 */ - fun paging(params: Params): Page + fun paging(params: Params, clazz: Class): Page /** * 查询条件范围内数据。 @@ -45,5 +45,5 @@ interface ISpecificQuery { * * @return 视图列表 */ - fun range(field: String, params: List): List + fun range(field: String, params: List, clazz: Class): List } diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/query/type/Operator.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/query/Operator.kt similarity index 92% rename from src/gaea/src/main/kotlin/com/synebula/gaea/query/type/Operator.kt rename to src/gaea/src/main/kotlin/com/synebula/gaea/query/Operator.kt index e3ece94..523cf30 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/query/type/Operator.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/query/Operator.kt @@ -1,4 +1,4 @@ -package com.synebula.gaea.query.type +package com.synebula.gaea.query enum class Operator { /** diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/query/type/Order.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/query/Order.kt similarity index 84% rename from src/gaea/src/main/kotlin/com/synebula/gaea/query/type/Order.kt rename to src/gaea/src/main/kotlin/com/synebula/gaea/query/Order.kt index 35cd05f..8fdeba1 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/query/type/Order.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/query/Order.kt @@ -1,4 +1,4 @@ -package com.synebula.gaea.query.type +package com.synebula.gaea.query /** * class OrderType diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/query/Params.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/query/Params.kt index 0362126..ed6ed3b 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/query/Params.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/query/Params.kt @@ -1,7 +1,5 @@ package com.synebula.gaea.query -import com.synebula.gaea.query.type.Order - /** * class 分页参数信息 * diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/query/annotation/Table.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/query/Table.kt similarity index 51% rename from src/gaea/src/main/kotlin/com/synebula/gaea/query/annotation/Table.kt rename to src/gaea/src/main/kotlin/com/synebula/gaea/query/Table.kt index 00d7922..59431c1 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/query/annotation/Table.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/query/Table.kt @@ -1,3 +1,3 @@ -package com.synebula.gaea.query.annotation +package com.synebula.gaea.query annotation class Table(val name: String = "") \ No newline at end of file diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/query/annotation/Where.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/query/Where.kt similarity index 83% rename from src/gaea/src/main/kotlin/com/synebula/gaea/query/annotation/Where.kt rename to src/gaea/src/main/kotlin/com/synebula/gaea/query/Where.kt index 8170cf3..1e06df3 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/query/annotation/Where.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/query/Where.kt @@ -1,6 +1,4 @@ -package com.synebula.gaea.query.annotation - -import com.synebula.gaea.query.type.Operator +package com.synebula.gaea.query /** * 字段注解,规定字段的查询方式 diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/reflect/Types.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/reflect/Types.kt index 75ac061..28a137e 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/reflect/Types.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/reflect/Types.kt @@ -1,7 +1,5 @@ package com.synebula.gaea.reflect -import com.synebula.gaea.bus.SubscriberRegistry - object Types { /** * 获取类的所有父类型。 @@ -9,15 +7,15 @@ object Types { fun supertypes(clazz: Class<*>): Set> { val supertypes = mutableSetOf>() supertypes.add(clazz) - if (clazz.superclass != null) - supertypes.addAll(SubscriberRegistry.flattenHierarchy(clazz.superclass)) if (clazz.interfaces.isNotEmpty()) { - supertypes.addAll(clazz.interfaces.map { SubscriberRegistry.flattenHierarchy(it) }.reduce { r, c -> + supertypes.addAll(clazz.interfaces.map { supertypes(it) }.reduce { r, c -> val all = r.toMutableSet() all.addAll(c) all }) } + if (clazz.superclass != null) + supertypes.addAll(supertypes(clazz.superclass)) return supertypes } } \ No newline at end of file From b09e0c0f03d093d6241a2312f7ab6a7e491523e3 Mon Sep 17 00:00:00 2001 From: alex Date: Thu, 18 Aug 2022 15:15:48 +0800 Subject: [PATCH 09/14] 1.1.1 move aop to package gaea.spring --- src/gaea.app/build.gradle | 1 - .../com/synebula/gaea/app/cmd/ICommandApp.kt | 2 +- .../gaea/app/cmd/ISimpleCommandApp.kt | 2 +- .../com/synebula/gaea/app/query/IQueryApp.kt | 2 +- .../mongodb/autoconfig/MongodbRepoProxy.kt | 2 +- src/gaea.spring/build.gradle | 2 ++ .../synebula/gaea/spring}/aop/AppAspect.kt | 27 ++++++++----------- .../gaea/spring}/aop/annotation/AccessLog.kt | 4 +-- .../gaea/spring}/aop/annotation/Handler.kt | 4 +-- .../gaea/spring}/aop/annotation/Method.kt | 2 +- .../gaea/spring}/aop/annotation/Module.kt | 2 +- .../spring}/aop/handler/AccessLogHandler.kt | 2 +- .../spring}/aop/handler/AnnotationHandler.kt | 2 +- 13 files changed, 25 insertions(+), 29 deletions(-) rename src/{gaea.app/src/main/kotlin/com/synebula/gaea/app/component => gaea.spring/src/main/kotlin/com/synebula/gaea/spring}/aop/AppAspect.kt (73%) rename src/{gaea.app/src/main/kotlin/com/synebula/gaea/app/component => gaea.spring/src/main/kotlin/com/synebula/gaea/spring}/aop/annotation/AccessLog.kt (52%) rename src/{gaea.app/src/main/kotlin/com/synebula/gaea/app/component => gaea.spring/src/main/kotlin/com/synebula/gaea/spring}/aop/annotation/Handler.kt (68%) rename src/{gaea.app/src/main/kotlin/com/synebula/gaea/app/component => gaea.spring/src/main/kotlin/com/synebula/gaea/spring}/aop/annotation/Method.kt (83%) rename src/{gaea.app/src/main/kotlin/com/synebula/gaea/app/component => gaea.spring/src/main/kotlin/com/synebula/gaea/spring}/aop/annotation/Module.kt (76%) rename src/{gaea.app/src/main/kotlin/com/synebula/gaea/app/component => gaea.spring/src/main/kotlin/com/synebula/gaea/spring}/aop/handler/AccessLogHandler.kt (95%) rename src/{gaea.app/src/main/kotlin/com/synebula/gaea/app/component => gaea.spring/src/main/kotlin/com/synebula/gaea/spring}/aop/handler/AnnotationHandler.kt (75%) diff --git a/src/gaea.app/build.gradle b/src/gaea.app/build.gradle index 9af631c..e137186 100644 --- a/src/gaea.app/build.gradle +++ b/src/gaea.app/build.gradle @@ -11,7 +11,6 @@ dependencies { api project(":src:gaea.spring") api("org.springframework.boot:spring-boot-starter-web:$spring_version") - api("org.springframework.boot:spring-boot-starter-aop:$spring_version") api("org.springframework.boot:spring-boot-starter-mail:$spring_version") api("org.springframework.boot:spring-boot-starter-security:$spring_version") api group: 'net.sf.dozer', name: 'dozer', version: '5.5.1' diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/ICommandApp.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/ICommandApp.kt index 8ac4982..b95d292 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/ICommandApp.kt +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/ICommandApp.kt @@ -1,12 +1,12 @@ package com.synebula.gaea.app.cmd import com.synebula.gaea.app.IApplication -import com.synebula.gaea.app.component.aop.annotation.Method import com.synebula.gaea.app.struct.HttpMessage import com.synebula.gaea.data.message.Status import com.synebula.gaea.data.serialization.json.IJsonSerializer import com.synebula.gaea.domain.service.ICommand import com.synebula.gaea.domain.service.IService +import com.synebula.gaea.spring.aop.annotation.Method import org.springframework.web.bind.annotation.* /** diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/ISimpleCommandApp.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/ISimpleCommandApp.kt index 6c7b89c..fa7344c 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/ISimpleCommandApp.kt +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/ISimpleCommandApp.kt @@ -1,12 +1,12 @@ package com.synebula.gaea.app.cmd import com.synebula.gaea.app.IApplication -import com.synebula.gaea.app.component.aop.annotation.Method import com.synebula.gaea.app.struct.HttpMessage import com.synebula.gaea.data.message.Status import com.synebula.gaea.data.serialization.json.IJsonSerializer import com.synebula.gaea.domain.model.IAggregateRoot import com.synebula.gaea.domain.service.ISimpleService +import com.synebula.gaea.spring.aop.annotation.Method import org.springframework.web.bind.annotation.* /** diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/query/IQueryApp.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/query/IQueryApp.kt index e06f38f..7557c9c 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/query/IQueryApp.kt +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/query/IQueryApp.kt @@ -1,10 +1,10 @@ package com.synebula.gaea.app.query import com.synebula.gaea.app.IApplication -import com.synebula.gaea.app.component.aop.annotation.Method import com.synebula.gaea.app.struct.HttpMessage import com.synebula.gaea.query.IQuery import com.synebula.gaea.query.Params +import com.synebula.gaea.spring.aop.annotation.Method import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.RequestParam diff --git a/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/autoconfig/MongodbRepoProxy.kt b/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/autoconfig/MongodbRepoProxy.kt index b4eb4a8..e1c64a3 100644 --- a/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/autoconfig/MongodbRepoProxy.kt +++ b/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/autoconfig/MongodbRepoProxy.kt @@ -71,7 +71,7 @@ class MongodbRepoProxy( } else if (this.query != null) { this.query!!.javaClass } else - throw InvalidClassException("class ${this.supertype.name} property repo and query are both null") + throw InvalidClassException("class [${this.supertype.name}] proxy object property [repo] and [query] are both null") try { val proxyMethod: Method = proxyClazz.getDeclaredMethod(method.name, *method.parameterTypes) diff --git a/src/gaea.spring/build.gradle b/src/gaea.spring/build.gradle index 95e297c..d283485 100644 --- a/src/gaea.spring/build.gradle +++ b/src/gaea.spring/build.gradle @@ -10,6 +10,8 @@ dependencies { implementation project(":src:gaea") implementation("org.springframework.boot:spring-boot-starter-web:$spring_version") implementation group: 'com.google.code.gson', name: 'gson', version: '2.8.6' + + api("org.springframework.boot:spring-boot-starter-aop:$spring_version") } publishing { diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/aop/AppAspect.kt b/src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/aop/AppAspect.kt similarity index 73% rename from src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/aop/AppAspect.kt rename to src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/aop/AppAspect.kt index 1c696d8..ace1148 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/aop/AppAspect.kt +++ b/src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/aop/AppAspect.kt @@ -1,14 +1,13 @@ -package com.synebula.gaea.app.component.aop +package com.synebula.gaea.spring.aop import com.google.gson.Gson -import com.synebula.gaea.app.IApplication -import com.synebula.gaea.app.component.aop.annotation.Handler -import com.synebula.gaea.app.component.aop.annotation.Method -import com.synebula.gaea.app.component.aop.annotation.Module -import com.synebula.gaea.app.struct.HttpMessage +import com.synebula.gaea.data.message.DataMessage import com.synebula.gaea.data.message.Status import com.synebula.gaea.exception.NoticeUserException import com.synebula.gaea.log.ILogger +import com.synebula.gaea.spring.aop.annotation.Handler +import com.synebula.gaea.spring.aop.annotation.Method +import com.synebula.gaea.spring.aop.annotation.Module import org.aspectj.lang.ProceedingJoinPoint import org.aspectj.lang.annotation.Around import org.springframework.beans.factory.annotation.Autowired @@ -16,7 +15,7 @@ import org.springframework.context.ApplicationContext import org.springframework.core.DefaultParameterNameDiscoverer abstract class AppAspect { - private var paramDiscover = DefaultParameterNameDiscoverer() + private var parameterNameDiscoverer = DefaultParameterNameDiscoverer() private val gson = Gson() @@ -63,13 +62,9 @@ abstract class AppAspect { } catch (ex: Throwable) { //找到类的模块名称,否则使用类名 var moduleName = clazz.name - if (IApplication::class.java.isAssignableFrom(clazz)) { - moduleName = (point.`this` as IApplication).name - } else { - val name = clazz.annotations.find { it is Module } - if (name != null && name is Module) { - moduleName = name.name - } + val module = clazz.annotations.find { it is Module } + if (module != null && module is Module) { + moduleName = module.name } var message = "$moduleName - $funcName 异常" message = if (ex is NoticeUserException) { @@ -80,12 +75,12 @@ abstract class AppAspect { logger.error( ex, "$message。Method args ${ - paramDiscover.getParameterNames(func)?.contentToString() + parameterNameDiscoverer.getParameterNames(func)?.contentToString() } values is ${ gson.toJson(point.args) }" ) - return HttpMessage(Status.Error, message) + return gson.toJson(DataMessage(Status.Error, message)) } } } \ No newline at end of file diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/aop/annotation/AccessLog.kt b/src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/aop/annotation/AccessLog.kt similarity index 52% rename from src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/aop/annotation/AccessLog.kt rename to src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/aop/annotation/AccessLog.kt index 28015c6..8f87125 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/aop/annotation/AccessLog.kt +++ b/src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/aop/annotation/AccessLog.kt @@ -1,6 +1,6 @@ -package com.synebula.gaea.app.component.aop.annotation +package com.synebula.gaea.spring.aop.annotation -import com.synebula.gaea.app.component.aop.handler.AccessLogHandler +import com.synebula.gaea.spring.aop.handler.AccessLogHandler @Target(AnnotationTarget.FUNCTION) @Handler(AccessLogHandler::class) diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/aop/annotation/Handler.kt b/src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/aop/annotation/Handler.kt similarity index 68% rename from src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/aop/annotation/Handler.kt rename to src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/aop/annotation/Handler.kt index ff159f9..ea92224 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/aop/annotation/Handler.kt +++ b/src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/aop/annotation/Handler.kt @@ -1,6 +1,6 @@ -package com.synebula.gaea.app.component.aop.annotation +package com.synebula.gaea.spring.aop.annotation -import com.synebula.gaea.app.component.aop.handler.AnnotationHandler +import com.synebula.gaea.spring.aop.handler.AnnotationHandler import kotlin.reflect.KClass /** diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/aop/annotation/Method.kt b/src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/aop/annotation/Method.kt similarity index 83% rename from src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/aop/annotation/Method.kt rename to src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/aop/annotation/Method.kt index 3c198a3..aa3cb55 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/aop/annotation/Method.kt +++ b/src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/aop/annotation/Method.kt @@ -1,4 +1,4 @@ -package com.synebula.gaea.app.component.aop.annotation +package com.synebula.gaea.spring.aop.annotation import java.lang.annotation.Inherited diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/aop/annotation/Module.kt b/src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/aop/annotation/Module.kt similarity index 76% rename from src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/aop/annotation/Module.kt rename to src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/aop/annotation/Module.kt index 03ec88b..7202fbd 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/aop/annotation/Module.kt +++ b/src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/aop/annotation/Module.kt @@ -1,4 +1,4 @@ -package com.synebula.gaea.app.component.aop.annotation +package com.synebula.gaea.spring.aop.annotation /** * 模块的业务名称 diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/aop/handler/AccessLogHandler.kt b/src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/aop/handler/AccessLogHandler.kt similarity index 95% rename from src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/aop/handler/AccessLogHandler.kt rename to src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/aop/handler/AccessLogHandler.kt index 1898eb3..c2f70da 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/aop/handler/AccessLogHandler.kt +++ b/src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/aop/handler/AccessLogHandler.kt @@ -1,4 +1,4 @@ -package com.synebula.gaea.app.component.aop.handler +package com.synebula.gaea.spring.aop.handler import com.fasterxml.jackson.databind.ObjectMapper import com.synebula.gaea.log.ILogger diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/aop/handler/AnnotationHandler.kt b/src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/aop/handler/AnnotationHandler.kt similarity index 75% rename from src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/aop/handler/AnnotationHandler.kt rename to src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/aop/handler/AnnotationHandler.kt index fbd2a37..5f98788 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/aop/handler/AnnotationHandler.kt +++ b/src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/aop/handler/AnnotationHandler.kt @@ -1,4 +1,4 @@ -package com.synebula.gaea.app.component.aop.handler +package com.synebula.gaea.spring.aop.handler import java.lang.reflect.Method From 3c23c26a64044c8ba87ba6640ec13638d4aa47eb Mon Sep 17 00:00:00 2001 From: alex Date: Fri, 19 Aug 2022 17:00:09 +0800 Subject: [PATCH 10/14] =?UTF-8?q?1.1.2=20=E4=BC=98=E5=8C=96=E4=BB=A3?= =?UTF-8?q?=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- build.gradle | 2 +- .../app/autoconfig/service/ServiceProxy.kt | 2 +- .../mongodb/autoconfig/MongodbRepoProxy.kt | 69 ++++++------------- .../gaea/mongodb/query/MongodbQuery.kt | 16 ++--- .../mongodb/query/MongodbUniversalQuery.kt | 18 ++--- .../synebula/gaea/bus/SubscriberRegistry.kt | 4 +- .../synebula/gaea/domain/service/Service.kt | 15 ++-- .../kotlin/com/synebula/gaea/reflect/Types.kt | 43 +++++++----- 8 files changed, 68 insertions(+), 101 deletions(-) diff --git a/build.gradle b/build.gradle index 1b16f91..00cd1c5 100644 --- a/build.gradle +++ b/build.gradle @@ -17,7 +17,7 @@ buildscript { subprojects { group 'com.synebula' - version '1.1.0' + version '1.1.2' buildscript { repositories { diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/autoconfig/service/ServiceProxy.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/autoconfig/service/ServiceProxy.kt index 5aa6bce..3920630 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/autoconfig/service/ServiceProxy.kt +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/autoconfig/service/ServiceProxy.kt @@ -47,7 +47,7 @@ class ServiceProxy( */ override fun exec(proxy: Any, method: Method, args: Array): Any? { try { - val proxyMethod = this.service.javaClass.getDeclaredMethod(method.name, *method.parameterTypes) + val proxyMethod = this.service.javaClass.getMethod(method.name, *method.parameterTypes) return proxyMethod.invoke(this.service, *args) } catch (ex: NoSuchMethodException) { throw NoSuchMethodException("method [${method.toGenericString()}] not implements in class [${this.service::class.java}], you must implements interface [${this.supertype.name}] ") diff --git a/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/autoconfig/MongodbRepoProxy.kt b/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/autoconfig/MongodbRepoProxy.kt index e1c64a3..30e926b 100644 --- a/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/autoconfig/MongodbRepoProxy.kt +++ b/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/autoconfig/MongodbRepoProxy.kt @@ -1,59 +1,41 @@ package com.synebula.gaea.mongodb.autoconfig import com.synebula.gaea.domain.repository.IRepository -import com.synebula.gaea.log.ILogger import com.synebula.gaea.mongodb.query.MongodbQuery import com.synebula.gaea.mongodb.repository.MongodbRepository import com.synebula.gaea.query.IQuery +import com.synebula.gaea.reflect.getGenericInterface import com.synebula.gaea.spring.autoconfig.Proxy import org.springframework.beans.factory.BeanFactory import org.springframework.data.mongodb.core.MongoTemplate -import java.io.InvalidClassException import java.lang.reflect.Method -import java.lang.reflect.ParameterizedType class MongodbRepoProxy( private var supertype: Class<*>, private var beanFactory: BeanFactory, implementBeanNames: Array = arrayOf() ) : Proxy() { - private var repo: IRepository<*, *>? = null - - private var query: IQuery<*, *>? = null + private var mongodbRepo: Any init { + // 判断接口类型 + val clazz: Class<*> // 代理服务类型 + val interfaceClazz: Class<*> // 代理服务接口 if (this.supertype.interfaces.any { it == IRepository::class.java }) { - // 如果是IRepository子接口 - if (implementBeanNames.isEmpty()) { - val genericInterfaces = this.supertype.genericInterfaces.find { - it.typeName.startsWith(IRepository::class.java.typeName) - }!! - val constructor = MongodbRepository::class.java.getConstructor( - Class::class.java, MongoTemplate::class.java - ) - this.repo = constructor.newInstance( - (genericInterfaces as ParameterizedType).actualTypeArguments[0], - this.beanFactory.getBean(MongoTemplate::class.java) - ) - } else { - this.repo = this.beanFactory.getBean(implementBeanNames[0]) as IRepository<*, *> - } + clazz = MongodbRepository::class.java + interfaceClazz = IRepository::class.java } else { - // 否则是IQuery子接口 - if (implementBeanNames.isEmpty()) { - val genericInterfaces = this.supertype.genericInterfaces.find { - it.typeName.startsWith(IQuery::class.java.typeName) - }!! - val constructor = MongodbQuery::class.java.getConstructor( - Class::class.java, MongoTemplate::class.java, ILogger::class.java - ) - this.query = constructor.newInstance( - (genericInterfaces as ParameterizedType).actualTypeArguments[0], - this.beanFactory.getBean(MongoTemplate::class.java), - this.beanFactory.getBean(ILogger::class.java), - ) - } else { - this.query = this.beanFactory.getBean(implementBeanNames[0]) as IQuery<*, *> - } + clazz = MongodbQuery::class.java + interfaceClazz = IQuery::class.java + } + + if (implementBeanNames.isEmpty()) { + val constructor = clazz.getConstructor(Class::class.java, MongoTemplate::class.java) + this.mongodbRepo = constructor.newInstance( + this.supertype.getGenericInterface(interfaceClazz)!!.actualTypeArguments[0], + this.beanFactory.getBean(MongoTemplate::class.java) + ) + } else { + this.mongodbRepo = this.beanFactory.getBean(implementBeanNames[0]) } } @@ -66,18 +48,11 @@ class MongodbRepoProxy( * @return 方法执行结果 */ override fun exec(proxy: Any, method: Method, args: Array): Any? { - val proxyClazz = if (this.repo != null) { - this.repo!!.javaClass - } else if (this.query != null) { - this.query!!.javaClass - } else - throw InvalidClassException("class [${this.supertype.name}] proxy object property [repo] and [query] are both null") - try { - val proxyMethod: Method = proxyClazz.getDeclaredMethod(method.name, *method.parameterTypes) - return proxyMethod.invoke(this.repo, *args) + val proxyMethod: Method = this.mongodbRepo.javaClass.getMethod(method.name, *method.parameterTypes) + return proxyMethod.invoke(this.mongodbRepo, *args) } catch (ex: NoSuchMethodException) { - throw NoSuchMethodException("method [${method.toGenericString()}] not implements in class [${proxyClazz}], you must implements interface [${this.supertype.name}] ") + throw NoSuchMethodException("method [${method.toGenericString()}] not implements in class [${this.mongodbRepo.javaClass}], you must implements interface [${this.supertype.name}] ") } } diff --git a/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/query/MongodbQuery.kt b/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/query/MongodbQuery.kt index 93bff5b..27cabbf 100644 --- a/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/query/MongodbQuery.kt +++ b/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/query/MongodbQuery.kt @@ -2,7 +2,6 @@ package com.synebula.gaea.mongodb.query import com.synebula.gaea.ext.fieldNames import com.synebula.gaea.ext.firstCharLowerCase -import com.synebula.gaea.log.ILogger import com.synebula.gaea.mongodb.order import com.synebula.gaea.mongodb.select import com.synebula.gaea.mongodb.where @@ -20,7 +19,7 @@ import org.springframework.data.mongodb.core.query.Query * @param template MongodbRepo对象 */ -open class MongodbQuery(override var clazz: Class, var template: MongoTemplate, var logger: ILogger) : +open class MongodbQuery(override var clazz: Class, var template: MongoTemplate) : IQuery { /** @@ -85,18 +84,13 @@ open class MongodbQuery(override var clazz: Class, var templat /** * 获取collection */ - protected fun collection(clazz: Class): String { - val table: Table? = clazz.getDeclaredAnnotation( - Table::class.java - ) - return if (table != null) return table.name + fun collection(clazz: Class): String { + val table = clazz.getDeclaredAnnotation(Table::class.java) + return if (table != null) table.name else { - this.logger.info(this, "视图类没有标记[Collection]注解,无法获取Collection名称。尝试使用View<${clazz.name}>名称解析集合") val name = clazz.simpleName.removeSuffix("View").firstCharLowerCase() if (!validViewCollection || this.template.collectionExists(name)) name - else { - throw RuntimeException("找不到名为[${clazz.name}]的集合") - } + else throw RuntimeException("找不到名为[${clazz.name}]的集合") } } } diff --git a/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/query/MongodbUniversalQuery.kt b/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/query/MongodbUniversalQuery.kt index f88dfbc..823963e 100644 --- a/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/query/MongodbUniversalQuery.kt +++ b/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/query/MongodbUniversalQuery.kt @@ -3,7 +3,6 @@ package com.synebula.gaea.mongodb.query import com.synebula.gaea.ext.fieldNames import com.synebula.gaea.ext.firstCharLowerCase -import com.synebula.gaea.log.ILogger import com.synebula.gaea.mongodb.order import com.synebula.gaea.mongodb.select import com.synebula.gaea.mongodb.where @@ -20,7 +19,7 @@ import org.springframework.data.mongodb.core.query.Query * 实现IQuery的Mongodb查询类 * @param template MongodbRepo对象 */ -open class MongodbUniversalQuery(var template: MongoTemplate, var logger: ILogger) : IUniversalQuery { +open class MongodbUniversalQuery(var template: MongoTemplate) : IUniversalQuery { /** * 使用View解析是collection时是否校验存在,默认不校验 @@ -85,19 +84,12 @@ open class MongodbUniversalQuery(var template: MongoTemplate, var logger: ILogge * 获取collection */ fun collection(clazz: Class): String { - val table: Table? = clazz.getDeclaredAnnotation( - Table::class.java - ) - return if (table != null) - return table.name + val table = clazz.getDeclaredAnnotation(Table::class.java) + return if (table != null) table.name else { - this.logger.info(this, "视图类没有标记[Collection]注解,无法获取Collection名称。尝试使用View<${clazz.name}>名称解析集合") val name = clazz.simpleName.removeSuffix("View").firstCharLowerCase() - if (!validViewCollection || this.template.collectionExists(name)) - name - else { - throw RuntimeException("找不到名为[${clazz.name}]的集合") - } + if (!validViewCollection || this.template.collectionExists(name)) name + else throw RuntimeException("找不到名为[${clazz.name}]的集合") } } } diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/bus/SubscriberRegistry.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/SubscriberRegistry.kt index 05138f0..00b7244 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/bus/SubscriberRegistry.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/SubscriberRegistry.kt @@ -13,7 +13,7 @@ */ package com.synebula.gaea.bus -import com.synebula.gaea.reflect.Types +import com.synebula.gaea.reflect.supertypes import java.lang.reflect.Method import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.CopyOnWriteArraySet @@ -184,7 +184,7 @@ open class SubscriberRegistry(private val bus: IBus) { fun flattenHierarchy(clazz: Class<*>): Set> { var supertypes = flattenHierarchyCache[clazz] if (supertypes == null) { - supertypes = Types.supertypes(clazz) + supertypes = clazz.supertypes() flattenHierarchyCache[clazz] = supertypes } return supertypes diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/Service.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/Service.kt index 264a258..1856b12 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/Service.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/Service.kt @@ -11,7 +11,7 @@ import com.synebula.gaea.domain.repository.IRepository * 该类依赖仓储接口 @see IGenericsRepository, 需要显式提供聚合根的class对象 * * @param clazz 聚合根类对象 - * @param repo 仓储对象 + * @param repository 仓储对象 * @param mapper 对象转换组件 * @author alex * @version 0.1 @@ -19,11 +19,10 @@ import com.synebula.gaea.domain.repository.IRepository */ open class Service, ID>( protected open var clazz: Class, - protected open var repo: IRepository, + protected open var repository: IRepository, protected open var mapper: IObjectMapper, ) : IService { - /** * 增加对象 * @@ -32,7 +31,7 @@ open class Service, ID>( override fun add(command: ICommand): DataMessage { val msg = DataMessage() val root = this.map(command) - this.repo.add(root) + this.repository.add(root) msg.data = root.id return msg } @@ -44,7 +43,7 @@ open class Service, ID>( */ override fun add(commands: List) { val roots = commands.map { this.map(it) } - this.repo.add(roots) + this.repository.add(roots) } /** @@ -56,7 +55,7 @@ open class Service, ID>( override fun update(id: ID, command: ICommand) { val root = this.map(command) root.id = id - this.repo.update(root) + this.repository.update(root) } /** @@ -66,7 +65,7 @@ open class Service, ID>( */ override fun update(commands: List) { val roots = commands.map { this.map(it) } - this.repo.update(roots) + this.repository.update(roots) } /** @@ -74,7 +73,7 @@ open class Service, ID>( * @param id 对象ID */ override fun remove(id: ID) { - this.repo.remove(id) + this.repository.remove(id) } /** diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/reflect/Types.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/reflect/Types.kt index 28a137e..95e1dce 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/reflect/Types.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/reflect/Types.kt @@ -1,21 +1,28 @@ package com.synebula.gaea.reflect -object Types { - /** - * 获取类的所有父类型。 - */ - fun supertypes(clazz: Class<*>): Set> { - val supertypes = mutableSetOf>() - supertypes.add(clazz) - if (clazz.interfaces.isNotEmpty()) { - supertypes.addAll(clazz.interfaces.map { supertypes(it) }.reduce { r, c -> - val all = r.toMutableSet() - all.addAll(c) - all - }) - } - if (clazz.superclass != null) - supertypes.addAll(supertypes(clazz.superclass)) - return supertypes +import java.lang.reflect.ParameterizedType + +/** + * 获取类的所有父类型。 + */ +fun Class<*>.supertypes(): Set> { + val supertypes = mutableSetOf>() + supertypes.add(this) + if (this.interfaces.isNotEmpty()) { + supertypes.addAll(this.interfaces.map { it.supertypes() }.reduce { r, c -> + val all = r.toMutableSet() + all.addAll(c) + all + }) } -} \ No newline at end of file + if (this.superclass != null) + supertypes.addAll(this.superclass.supertypes()) + return supertypes +} + +fun Class<*>.getGenericInterface(interfaceClazz: Class<*>): ParameterizedType? { + val type = this.genericInterfaces.find { it.typeName.startsWith(interfaceClazz.typeName) } + return if (type == null) null + else type as ParameterizedType + +} From 53709b6fc3041fcf853da71b513f562c9f948492 Mon Sep 17 00:00:00 2001 From: alex Date: Mon, 22 Aug 2022 15:16:41 +0800 Subject: [PATCH 11/14] =?UTF-8?q?1.2.0=20=E5=A2=9E=E5=8A=A0=20IRepository?= =?UTF-8?q?=20IQuery=E7=9A=84=E5=B7=A5=E5=8E=82=E6=96=B9=E6=B3=95=EF=BC=8C?= =?UTF-8?q?=E9=81=BF=E5=85=8D=E6=97=A0=E7=94=A8=E7=9A=84=E7=A9=BA=E7=99=BD?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3=E7=BC=96=E5=86=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- build.gradle | 2 +- .../app/autoconfig/service/ServiceProxy.kt | 24 +++++++++++++------ .../mongodb/autoconfig/MongodbRepoRegister.kt | 12 ++++++++++ .../gaea/mongodb/query/MongodbQueryFactory.kt | 23 ++++++++++++++++++ .../repository/MongodbRepositoryFactory.kt | 24 +++++++++++++++++++ .../domain/repository/IRepositoryFactory.kt | 19 +++++++++++++++ .../synebula/gaea/domain/service/Domain.kt | 13 ++++++++++ .../gaea/domain/service/ServiceDependency.kt | 16 ------------- .../com/synebula/gaea/query/IQueryFactory.kt | 18 ++++++++++++++ 9 files changed, 127 insertions(+), 24 deletions(-) create mode 100644 src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/query/MongodbQueryFactory.kt create mode 100644 src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/repository/MongodbRepositoryFactory.kt create mode 100644 src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/IRepositoryFactory.kt create mode 100644 src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/Domain.kt delete mode 100644 src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/ServiceDependency.kt create mode 100644 src/gaea/src/main/kotlin/com/synebula/gaea/query/IQueryFactory.kt diff --git a/build.gradle b/build.gradle index 00cd1c5..128548a 100644 --- a/build.gradle +++ b/build.gradle @@ -17,7 +17,7 @@ buildscript { subprojects { group 'com.synebula' - version '1.1.2' + version '1.2.0' buildscript { repositories { diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/autoconfig/service/ServiceProxy.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/autoconfig/service/ServiceProxy.kt index 3920630..05ec640 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/autoconfig/service/ServiceProxy.kt +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/autoconfig/service/ServiceProxy.kt @@ -2,16 +2,18 @@ package com.synebula.gaea.app.autoconfig.service import com.synebula.gaea.data.serialization.IObjectMapper import com.synebula.gaea.domain.repository.IRepository +import com.synebula.gaea.domain.repository.IRepositoryFactory +import com.synebula.gaea.domain.service.Domain import com.synebula.gaea.domain.service.IService import com.synebula.gaea.domain.service.Service -import com.synebula.gaea.domain.service.ServiceDependency import com.synebula.gaea.spring.autoconfig.Proxy import org.springframework.beans.factory.BeanFactory import java.io.InvalidClassException import java.lang.reflect.Method class ServiceProxy( - private var supertype: Class<*>, private var beanFactory: BeanFactory, implementBeanNames: Array = arrayOf() + private var supertype: Class<*>, + private var beanFactory: BeanFactory, implementBeanNames: Array = arrayOf() ) : Proxy() { private var service: IService<*> @@ -20,18 +22,26 @@ class ServiceProxy( // 如果没有实现类, 使用Service类代理 if (implementBeanNames.isEmpty()) { // 如果没有实现类并且没有ServiceDependency注解, 则抛出异常 - if (!this.supertype.declaredAnnotations.any { it.annotationClass == ServiceDependency::class }) { + if (!this.supertype.declaredAnnotations.any { it.annotationClass == Domain::class }) { throw InvalidClassException( - "interface ${this.supertype.name} must has implementation class or annotation by ${ServiceDependency::class.qualifiedName}" + "interface ${this.supertype.name} must has implementation class or annotation by ${Domain::class.qualifiedName}" ) } - val serviceDependency = this.supertype.getDeclaredAnnotation(ServiceDependency::class.java) - val repo = this.beanFactory.getBean(serviceDependency.repo.java) + val domain = this.supertype.getDeclaredAnnotation(Domain::class.java) + + // repository工厂对象 + val defaultRepositoryFactory = this.beanFactory.getBean(IRepositoryFactory::class.java) val mapper = this.beanFactory.getBean(IObjectMapper::class.java) + val constructor = Service::class.java.getConstructor( Class::class.java, IRepository::class.java, IObjectMapper::class.java ) - this.service = constructor.newInstance(serviceDependency.clazz.java, repo, mapper) + this.service = + constructor.newInstance( + domain.clazz.java, + defaultRepositoryFactory.createRawRepository(domain.clazz.java), + mapper + ) } else { this.service = this.beanFactory.getBean(implementBeanNames[0]) as IService<*> } diff --git a/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/autoconfig/MongodbRepoRegister.kt b/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/autoconfig/MongodbRepoRegister.kt index f62cf4c..55d6bda 100644 --- a/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/autoconfig/MongodbRepoRegister.kt +++ b/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/autoconfig/MongodbRepoRegister.kt @@ -51,4 +51,16 @@ class MongodbRepoRegister : Register() { } return result } + + private fun addDefaultProxyBean(result: MutableMap) { + // IRepository proxy + val builder = BeanDefinitionBuilder.genericBeanDefinition(IRepository::class.java) + builder.addConstructorArgValue(IRepository::class.java) + builder.addConstructorArgValue(this._beanFactory) + builder.addConstructorArgValue(emptyArray()) + val definition = builder.rawBeanDefinition as GenericBeanDefinition + definition.beanClass = MongodbRepoFactory::class.java + definition.autowireMode = GenericBeanDefinition.AUTOWIRE_BY_TYPE + result[IRepository::class.java.name] = definition + } } \ No newline at end of file diff --git a/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/query/MongodbQueryFactory.kt b/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/query/MongodbQueryFactory.kt new file mode 100644 index 0000000..ca4c351 --- /dev/null +++ b/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/query/MongodbQueryFactory.kt @@ -0,0 +1,23 @@ +package com.synebula.gaea.mongodb.query + +import com.synebula.gaea.query.IQuery +import com.synebula.gaea.query.IQueryFactory +import org.springframework.data.mongodb.core.MongoTemplate + +class MongodbQueryFactory(var template: MongoTemplate) : IQueryFactory { + + /** + * 创建IQuery接口类型 + */ + override fun createRawQuery(clazz: Class<*>): IQuery<*, *> { + val constructor = MongodbQuery::class.java.getConstructor(Class::class.java, MongoTemplate::class.java) + return constructor.newInstance(clazz, this.template) + } + + /** + * 创建IQuery接口类型 + */ + override fun createQuery(clazz: Class): IQuery { + return MongodbQuery(clazz, template) + } +} \ No newline at end of file diff --git a/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/repository/MongodbRepositoryFactory.kt b/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/repository/MongodbRepositoryFactory.kt new file mode 100644 index 0000000..012db8f --- /dev/null +++ b/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/repository/MongodbRepositoryFactory.kt @@ -0,0 +1,24 @@ +package com.synebula.gaea.mongodb.repository + +import com.synebula.gaea.domain.model.IAggregateRoot +import com.synebula.gaea.domain.repository.IRepository +import com.synebula.gaea.domain.repository.IRepositoryFactory +import org.springframework.data.mongodb.core.MongoTemplate + +class MongodbRepositoryFactory(var template: MongoTemplate) : IRepositoryFactory { + + /** + * 创建IRepository接口类型 + */ + override fun createRawRepository(clazz: Class<*>): IRepository<*, *> { + val constructor = MongodbRepository::class.java.getConstructor(Class::class.java, MongoTemplate::class.java) + return constructor.newInstance(clazz, this.template) + } + + /** + * 创建IRepository接口类型 + */ + override fun , I> createRepository(clazz: Class): IRepository { + return MongodbRepository(clazz, template) + } +} \ No newline at end of file diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/IRepositoryFactory.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/IRepositoryFactory.kt new file mode 100644 index 0000000..20fb622 --- /dev/null +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/IRepositoryFactory.kt @@ -0,0 +1,19 @@ +package com.synebula.gaea.domain.repository + +import com.synebula.gaea.domain.model.IAggregateRoot + +/** + * Repository 工厂接口。 定义了Repository的创建方法。 + */ +interface IRepositoryFactory { + + /** + * 创建原始类型的IRepository接口类型 + */ + fun createRawRepository(clazz: Class<*>): IRepository<*, *> + + /** + * 创建指定类型的IRepository接口类型 + */ + fun , I> createRepository(clazz: Class): IRepository +} \ No newline at end of file diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/Domain.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/Domain.kt new file mode 100644 index 0000000..16f787c --- /dev/null +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/Domain.kt @@ -0,0 +1,13 @@ +package com.synebula.gaea.domain.service + +import com.synebula.gaea.domain.model.IAggregateRoot +import kotlin.reflect.KClass + +/** + * 声明服务依赖的聚合根,若服务没有实现类则可以根据依赖项自动组装服务。 + * + * @param clazz 依赖的聚合根类型 + */ +@Target(AnnotationTarget.CLASS) +@Retention(AnnotationRetention.RUNTIME) +annotation class Domain(val clazz: KClass>) diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/ServiceDependency.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/ServiceDependency.kt deleted file mode 100644 index 42e0c2b..0000000 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/ServiceDependency.kt +++ /dev/null @@ -1,16 +0,0 @@ -package com.synebula.gaea.domain.service - -import com.synebula.gaea.domain.model.IAggregateRoot -import com.synebula.gaea.domain.repository.IRepository -import kotlin.reflect.KClass - -/** - * 声明服务的依赖项,若服务没有实现类则可以根据依赖项自动组装服务。 - * - * @param clazz 依赖的聚合根类型 - * @param repo 依赖的[IRepository]类型 - */ -annotation class ServiceDependency( - val clazz: KClass>, - val repo: KClass>, -) diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/query/IQueryFactory.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/query/IQueryFactory.kt new file mode 100644 index 0000000..f89d856 --- /dev/null +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/query/IQueryFactory.kt @@ -0,0 +1,18 @@ +package com.synebula.gaea.query + + +/** + * Query 工厂接口。 定义了Query的创建方法。 + */ +interface IQueryFactory { + + /** + * 创建原始类型的IQuery接口类型 + */ + fun createRawQuery(clazz: Class<*>): IQuery<*, *> + + /** + * 创建指定类型的IQuery接口类型 + */ + fun createQuery(clazz: Class): IQuery +} \ No newline at end of file From 58402a6400a697f9715f6e6aa96878470570894d Mon Sep 17 00:00:00 2001 From: alex Date: Tue, 23 Aug 2022 15:47:22 +0800 Subject: [PATCH 12/14] =?UTF-8?q?1.3.0=20=E7=AE=80=E5=8C=96bus=E4=BD=BF?= =?UTF-8?q?=E7=94=A8=EF=BC=8C=E5=A2=9E=E5=8A=A0remove=E5=89=8D=E5=90=8E?= =?UTF-8?q?=E4=BA=8B=E4=BB=B6=EF=BC=8C=E7=AE=80=E5=8C=96auto=20config?= =?UTF-8?q?=E6=B3=A8=E5=86=8C=E6=96=B9=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- build.gradle | 2 +- .../app/autoconfig/service/ServiceFactory.kt | 3 +- .../app/autoconfig/service/ServiceProxy.kt | 61 ++-- .../app/autoconfig/service/ServiceRegister.kt | 26 +- .../gaea/app/component/bus/EventBus.kt | 2 +- .../bus/EventBusSubscriberProcessor.kt | 9 +- .../mongodb/autoconfig/MongodbRepoFactory.kt | 3 +- .../mongodb/autoconfig/MongodbRepoProxy.kt | 16 +- .../mongodb/autoconfig/MongodbRepoRegister.kt | 26 +- .../mongodb/repository/MongodbRepository.kt | 2 +- .../com/synebula/gaea/spring/aop/AppAspect.kt | 4 +- .../gaea/bus/AllowConcurrentSubscribe.kt | 2 +- .../kotlin/com/synebula/gaea/bus/AsyncBus.kt | 68 ----- .../main/kotlin/com/synebula/gaea/bus/Bus.kt | 154 +++++++--- .../com/synebula/gaea/bus/DeadMessage.kt | 2 +- .../com/synebula/gaea/bus/Dispatcher.kt | 39 +-- .../main/kotlin/com/synebula/gaea/bus/IBus.kt | 43 +++ .../com/synebula/gaea/bus/Subscriber.kt | 12 +- .../synebula/gaea/bus/SubscriberRegistry.kt | 110 +++++-- .../gaea/bus/messagebus/AsyncMessageBus.kt | 71 ----- .../gaea/bus/messagebus/IMessageBus.kt | 39 --- .../gaea/bus/messagebus/MessageBus.kt | 280 ------------------ .../bus/messagebus/TopicSubscriberRegistry.kt | 184 ------------ .../gaea/domain/event/AfterRemoveEvent.kt | 5 + .../gaea/domain/event/BeforeRemoveEvent.kt | 5 + .../gaea/domain/repository/IRepository.kt | 2 +- .../synebula/gaea/domain/service/Service.kt | 17 ++ .../kotlin/com/synebula/gaea/bus/BusTest.kt | 27 +- 28 files changed, 391 insertions(+), 823 deletions(-) delete mode 100644 src/gaea/src/main/kotlin/com/synebula/gaea/bus/AsyncBus.kt delete mode 100644 src/gaea/src/main/kotlin/com/synebula/gaea/bus/messagebus/AsyncMessageBus.kt delete mode 100644 src/gaea/src/main/kotlin/com/synebula/gaea/bus/messagebus/IMessageBus.kt delete mode 100644 src/gaea/src/main/kotlin/com/synebula/gaea/bus/messagebus/MessageBus.kt delete mode 100644 src/gaea/src/main/kotlin/com/synebula/gaea/bus/messagebus/TopicSubscriberRegistry.kt create mode 100644 src/gaea/src/main/kotlin/com/synebula/gaea/domain/event/AfterRemoveEvent.kt create mode 100644 src/gaea/src/main/kotlin/com/synebula/gaea/domain/event/BeforeRemoveEvent.kt diff --git a/build.gradle b/build.gradle index 128548a..345a5bc 100644 --- a/build.gradle +++ b/build.gradle @@ -17,7 +17,7 @@ buildscript { subprojects { group 'com.synebula' - version '1.2.0' + version '1.3.0' buildscript { repositories { diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/autoconfig/service/ServiceFactory.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/autoconfig/service/ServiceFactory.kt index e3447dd..c3e33a2 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/autoconfig/service/ServiceFactory.kt +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/autoconfig/service/ServiceFactory.kt @@ -7,9 +7,8 @@ import org.springframework.beans.factory.BeanFactory class ServiceFactory( supertype: Class<*>, var beanFactory: BeanFactory, - var implementBeanNames: Array = arrayOf() ) : Factory(supertype) { override fun createProxy(): Proxy { - return ServiceProxy(supertype, this.beanFactory, this.implementBeanNames) + return ServiceProxy(supertype, this.beanFactory) } } \ No newline at end of file diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/autoconfig/service/ServiceProxy.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/autoconfig/service/ServiceProxy.kt index 05ec640..15519fe 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/autoconfig/service/ServiceProxy.kt +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/autoconfig/service/ServiceProxy.kt @@ -1,49 +1,57 @@ package com.synebula.gaea.app.autoconfig.service +import com.synebula.gaea.bus.IBus import com.synebula.gaea.data.serialization.IObjectMapper import com.synebula.gaea.domain.repository.IRepository import com.synebula.gaea.domain.repository.IRepositoryFactory import com.synebula.gaea.domain.service.Domain import com.synebula.gaea.domain.service.IService import com.synebula.gaea.domain.service.Service +import com.synebula.gaea.exception.NoticeUserException import com.synebula.gaea.spring.autoconfig.Proxy import org.springframework.beans.factory.BeanFactory +import org.springframework.core.ResolvableType import java.io.InvalidClassException +import java.lang.reflect.InvocationTargetException import java.lang.reflect.Method class ServiceProxy( private var supertype: Class<*>, - private var beanFactory: BeanFactory, implementBeanNames: Array = arrayOf() + private var beanFactory: BeanFactory ) : Proxy() { private var service: IService<*> init { // 如果没有实现类, 使用Service类代理 - if (implementBeanNames.isEmpty()) { - // 如果没有实现类并且没有ServiceDependency注解, 则抛出异常 - if (!this.supertype.declaredAnnotations.any { it.annotationClass == Domain::class }) { - throw InvalidClassException( - "interface ${this.supertype.name} must has implementation class or annotation by ${Domain::class.qualifiedName}" - ) - } - val domain = this.supertype.getDeclaredAnnotation(Domain::class.java) - - // repository工厂对象 - val defaultRepositoryFactory = this.beanFactory.getBean(IRepositoryFactory::class.java) - val mapper = this.beanFactory.getBean(IObjectMapper::class.java) - - val constructor = Service::class.java.getConstructor( - Class::class.java, IRepository::class.java, IObjectMapper::class.java + // 如果没有实现类并且没有ServiceDependency注解, 则抛出异常 + if (!this.supertype.declaredAnnotations.any { it.annotationClass == Domain::class }) { + throw InvalidClassException( + "interface ${this.supertype.name} must has implementation class or annotation by ${Domain::class.qualifiedName}" ) - this.service = - constructor.newInstance( - domain.clazz.java, - defaultRepositoryFactory.createRawRepository(domain.clazz.java), - mapper - ) - } else { - this.service = this.beanFactory.getBean(implementBeanNames[0]) as IService<*> + } + val domain = this.supertype.getDeclaredAnnotation(Domain::class.java) + + // repository工厂对象 + val defaultRepositoryFactory = this.beanFactory.getBean(IRepositoryFactory::class.java) + val mapper = this.beanFactory.getBean(IObjectMapper::class.java) + + val constructor = Service::class.java.getConstructor( + Class::class.java, IRepository::class.java, IObjectMapper::class.java + ) + this.service = + constructor.newInstance( + domain.clazz.java, + defaultRepositoryFactory.createRawRepository(domain.clazz.java), + mapper + ) + + // 尝试注入IBus对象 + val bus = Service::class.java.getDeclaredField("bus") + val iBusObjectProvider = this.beanFactory.getBeanProvider>(ResolvableType.forField(bus)) + iBusObjectProvider.ifAvailable { busBean -> + bus.isAccessible = true + bus.set(this.service, busBean) } } @@ -61,6 +69,11 @@ class ServiceProxy( return proxyMethod.invoke(this.service, *args) } catch (ex: NoSuchMethodException) { throw NoSuchMethodException("method [${method.toGenericString()}] not implements in class [${this.service::class.java}], you must implements interface [${this.supertype.name}] ") + } catch (ex: InvocationTargetException) { + if (ex.cause is Error || ex.cause is NoticeUserException) { + throw ex.targetException!! + } + throw ex } } } \ No newline at end of file diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/autoconfig/service/ServiceRegister.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/autoconfig/service/ServiceRegister.kt index d62878b..0dd1f0a 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/autoconfig/service/ServiceRegister.kt +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/autoconfig/service/ServiceRegister.kt @@ -30,20 +30,20 @@ class ServiceRegister : Register() { // 尝试获取实际继承类型 val implBeanDefinitions = this.doScan(basePackages, arrayOf(this.interfaceFilter(arrayOf(beanClazz)))) - implBeanDefinitions.forEach { - it.isAutowireCandidate = false - result[it.beanClassName!!] = it + if (implBeanDefinitions.isNotEmpty()) { + implBeanDefinitions.forEach { + result[it.beanClassName!!] = it + } + } else { + // 构造BeanDefinition + val builder = BeanDefinitionBuilder.genericBeanDefinition(beanClazz) + builder.addConstructorArgValue(beanClazz) + builder.addConstructorArgValue(this._beanFactory) + val definition = builder.rawBeanDefinition as GenericBeanDefinition + definition.beanClass = ServiceFactory::class.java + definition.autowireMode = GenericBeanDefinition.AUTOWIRE_BY_TYPE + result[beanClazz.name] = definition } - - // 构造BeanDefinition - val builder = BeanDefinitionBuilder.genericBeanDefinition(beanClazz) - builder.addConstructorArgValue(beanClazz) - builder.addConstructorArgValue(this._beanFactory) - builder.addConstructorArgValue(implBeanDefinitions.map { it.beanClassName }) - val definition = builder.rawBeanDefinition as GenericBeanDefinition - definition.beanClass = ServiceFactory::class.java - definition.autowireMode = GenericBeanDefinition.AUTOWIRE_BY_TYPE - result[beanClazz.name] = definition } return result } diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/bus/EventBus.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/bus/EventBus.kt index acd6c29..87f6c0c 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/bus/EventBus.kt +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/bus/EventBus.kt @@ -4,5 +4,5 @@ import com.synebula.gaea.bus.Bus import org.springframework.stereotype.Component @Component -class EventBus : Bus() +class EventBus : Bus() diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/bus/EventBusSubscriberProcessor.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/bus/EventBusSubscriberProcessor.kt index 2a00a4d..f87bbd6 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/bus/EventBusSubscriberProcessor.kt +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/bus/EventBusSubscriberProcessor.kt @@ -14,7 +14,7 @@ class EventBusSubscriberProcessor : BeanPostProcessor { // 事件总线bean由Spring IoC容器负责创建,这里只需要通过@Autowired注解注入该bean即可使用事件总线 @Autowired - var messageBus: IBus? = null + var bus: IBus? = null @Throws(BeansException::class) override fun postProcessBeforeInitialization(bean: Any, beanName: String): Any { @@ -34,12 +34,15 @@ class EventBusSubscriberProcessor : BeanPostProcessor { if (annotation.annotationClass == Subscribe::class) { // 如果这是一个Guava @Subscribe注解的事件监听器方法,说明所在bean实例 // 对应一个Guava事件监听器类,将该bean实例注册到Guava事件总线 - messageBus?.register(bean) + val subscribe = annotation as Subscribe + if (subscribe.topics.isEmpty()) + bus?.register(bean, method) + else + bus?.register(subscribe.topics, bean, method) return bean } } } return bean } - } \ No newline at end of file diff --git a/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/autoconfig/MongodbRepoFactory.kt b/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/autoconfig/MongodbRepoFactory.kt index dbdeacf..f654626 100644 --- a/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/autoconfig/MongodbRepoFactory.kt +++ b/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/autoconfig/MongodbRepoFactory.kt @@ -7,9 +7,8 @@ import org.springframework.beans.factory.BeanFactory class MongodbRepoFactory( supertype: Class<*>, var beanFactory: BeanFactory, - var implementBeanNames: Array = arrayOf() ) : Factory(supertype) { override fun createProxy(): Proxy { - return MongodbRepoProxy(supertype, this.beanFactory, this.implementBeanNames) + return MongodbRepoProxy(supertype, this.beanFactory) } } \ No newline at end of file diff --git a/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/autoconfig/MongodbRepoProxy.kt b/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/autoconfig/MongodbRepoProxy.kt index 30e926b..5fa6459 100644 --- a/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/autoconfig/MongodbRepoProxy.kt +++ b/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/autoconfig/MongodbRepoProxy.kt @@ -11,7 +11,7 @@ import org.springframework.data.mongodb.core.MongoTemplate import java.lang.reflect.Method class MongodbRepoProxy( - private var supertype: Class<*>, private var beanFactory: BeanFactory, implementBeanNames: Array = arrayOf() + private var supertype: Class<*>, private var beanFactory: BeanFactory ) : Proxy() { private var mongodbRepo: Any @@ -28,15 +28,11 @@ class MongodbRepoProxy( interfaceClazz = IQuery::class.java } - if (implementBeanNames.isEmpty()) { - val constructor = clazz.getConstructor(Class::class.java, MongoTemplate::class.java) - this.mongodbRepo = constructor.newInstance( - this.supertype.getGenericInterface(interfaceClazz)!!.actualTypeArguments[0], - this.beanFactory.getBean(MongoTemplate::class.java) - ) - } else { - this.mongodbRepo = this.beanFactory.getBean(implementBeanNames[0]) - } + val constructor = clazz.getConstructor(Class::class.java, MongoTemplate::class.java) + this.mongodbRepo = constructor.newInstance( + this.supertype.getGenericInterface(interfaceClazz)!!.actualTypeArguments[0], + this.beanFactory.getBean(MongoTemplate::class.java) + ) } /** diff --git a/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/autoconfig/MongodbRepoRegister.kt b/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/autoconfig/MongodbRepoRegister.kt index 55d6bda..85d4fee 100644 --- a/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/autoconfig/MongodbRepoRegister.kt +++ b/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/autoconfig/MongodbRepoRegister.kt @@ -34,20 +34,20 @@ class MongodbRepoRegister : Register() { // 尝试获取实际继承类型 val implBeanDefinitions = this.doScan(basePackages, arrayOf(this.interfaceFilter(arrayOf(beanClazz)))) - implBeanDefinitions.forEach { - it.isAutowireCandidate = false - result[it.beanClassName!!] = it - } - // 构造BeanDefinition - val builder = BeanDefinitionBuilder.genericBeanDefinition(beanClazz) - builder.addConstructorArgValue(beanClazz) - builder.addConstructorArgValue(this._beanFactory) - builder.addConstructorArgValue(implBeanDefinitions.map { it.beanClassName }) - val definition = builder.rawBeanDefinition as GenericBeanDefinition - definition.beanClass = MongodbRepoFactory::class.java - definition.autowireMode = GenericBeanDefinition.AUTOWIRE_BY_TYPE - result[beanClazz.name] = definition + if (implBeanDefinitions.isNotEmpty()) { + implBeanDefinitions.forEach { + result[it.beanClassName!!] = it + } + } else { // 构造BeanDefinition + val builder = BeanDefinitionBuilder.genericBeanDefinition(beanClazz) + builder.addConstructorArgValue(beanClazz) + builder.addConstructorArgValue(this._beanFactory) + val definition = builder.rawBeanDefinition as GenericBeanDefinition + definition.beanClass = MongodbRepoFactory::class.java + definition.autowireMode = GenericBeanDefinition.AUTOWIRE_BY_TYPE + result[beanClazz.name] = definition + } } return result } diff --git a/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/repository/MongodbRepository.kt b/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/repository/MongodbRepository.kt index 8c3a348..02ba374 100644 --- a/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/repository/MongodbRepository.kt +++ b/src/gaea.mongodb/src/main/kotlin/com/synebula/gaea/mongodb/repository/MongodbRepository.kt @@ -40,7 +40,7 @@ open class MongodbRepository, ID>( this.repo.save(list) } - override fun count(params: Map?): Int { + override fun count(params: Map?): Int { val query = Query() return this.repo.count(query.where(params, clazz), clazz).toInt() } diff --git a/src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/aop/AppAspect.kt b/src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/aop/AppAspect.kt index ace1148..5a305db 100644 --- a/src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/aop/AppAspect.kt +++ b/src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/aop/AppAspect.kt @@ -61,13 +61,13 @@ abstract class AppAspect { point.proceed() } catch (ex: Throwable) { //找到类的模块名称,否则使用类名 - var moduleName = clazz.name + var moduleName = clazz.simpleName val module = clazz.annotations.find { it is Module } if (module != null && module is Module) { moduleName = module.name } var message = "$moduleName - $funcName 异常" - message = if (ex is NoticeUserException) { + message = if (ex is NoticeUserException || ex is Error) { "$message: ${ex.message}" } else { "$message。" diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/bus/AllowConcurrentSubscribe.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/AllowConcurrentSubscribe.kt index 1fe2f13..77687ee 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/bus/AllowConcurrentSubscribe.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/AllowConcurrentSubscribe.kt @@ -14,7 +14,7 @@ package com.synebula.gaea.bus /** - * Marks an message subscriber method as being thread-safe. This annotation indicates that MessageBus + * Marks a message subscriber method as being thread-safe. This annotation indicates that MessageBus * may invoke the message subscriber simultaneously from multiple threads. * * diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/bus/AsyncBus.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/AsyncBus.kt deleted file mode 100644 index 1da1f56..0000000 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/bus/AsyncBus.kt +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (C) 2007 The Guava Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package com.synebula.gaea.bus - -import java.util.concurrent.Executor - -/** - * An [Bus] that takes the Executor of your choice and uses it to dispatch messages, - * allowing dispatch to occur asynchronously. - * - * @author Cliff - * @since 10.0 - */ -class AsyncBus : Bus { - /** - * Creates a new AsyncMessageBus that will use `executor` to dispatch messages. Assigns `identifier` as the bus's name for logging purposes. - * - * @param identifier short name for the bus, for logging purposes. - * @param executor Executor to use to dispatch messages. It is the caller's responsibility to shut - * down the executor after the last message has been posted to this message bus. - */ - constructor(identifier: String, executor: Executor) : super( - identifier, - executor, - Dispatcher.legacyAsync(), - LoggingHandler() - ) - - /** - * Creates a new AsyncMessageBus that will use `executor` to dispatch messages. - * - * @param executor Executor to use to dispatch messages. It is the caller's responsibility to shut - * down the executor after the last message has been posted to this message bus. - * @param subscriberExceptionHandler Handler used to handle exceptions thrown from subscribers. - * See [SubscriberExceptionHandler] for more information. - * @since 16.0 - */ - constructor(executor: Executor, subscriberExceptionHandler: SubscriberExceptionHandler) : super( - "default", - executor, - Dispatcher.legacyAsync(), - subscriberExceptionHandler - ) - - /** - * Creates a new AsyncMessageBus that will use `executor` to dispatch messages. - * - * @param executor Executor to use to dispatch messages. It is the caller's responsibility to shut - * down the executor after the last message has been posted to this message bus. - */ - constructor(executor: Executor) : super( - "default", - executor, - Dispatcher.legacyAsync(), - LoggingHandler() - ) -} \ No newline at end of file diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/bus/Bus.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/Bus.kt index bf36e15..e4c2952 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/bus/Bus.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/Bus.kt @@ -37,7 +37,7 @@ import java.util.logging.Logger * * To react to messages, we recommend a reactive-streams framework like [RxJava](https://github.com/ReactiveX/RxJava/wiki) (supplemented with its [RxAndroid](https://github.com/ReactiveX/RxAndroid) extension if you are building for * Android) or [Project Reactor](https://projectreactor.io/). (For the basics of - * translating code from using an message bus to using a reactive-streams framework, see these two + * translating code from using a message bus to using a reactive-streams framework, see these two * guides: [1](https://blog.jkl.gg/implementing-an-message-bus-with-rxjava-rxbus/), [2](https://lorentzos.com/rxjava-as-message-bus-the-right-way-10a36bdd49ba).) Some usages * of MessageBus may be better written using [Kotlin coroutines](https://kotlinlang.org/docs/coroutines-guide.html), including [Flow](https://kotlinlang.org/docs/flow.html) and [Channels](https://kotlinlang.org/docs/channels.html). Yet other usages are better served * by individual libraries that provide specialized support for particular use cases. @@ -60,12 +60,10 @@ import java.util.logging.Logger * * It doesn't propagate exceptions, so apps don't have a way to react to them. * * It doesn't interoperate well with RxJava, coroutines, and other more commonly used * alternatives. - * * It imposes requirements on the lifecycle of its subscribers. For example, if an message + * * It imposes requirements on the lifecycle of its subscribers. For example, if a message * occurs between when one subscriber is removed and the next subscriber is added, the message * is dropped. * * Its performance is suboptimal, especially under Android. - * * It [doesn't support parameterized - * types](https://github.com/google/guava/issues/1431). * * With the introduction of lambdas in Java 8, MessageBus went from less verbose than listeners * to [more verbose](https://github.com/google/guava/issues/3311). * @@ -94,19 +92,15 @@ import java.util.logging.Logger *

Posting Messages

* * - * To post an message, simply provide the message object to the [.post] method. The + * To post a message, simply provide the message object to the [.post] method. The * MessageBus instance will determine the type of message and route it to all registered listeners. * * - * Messages are routed based on their type an message will be delivered to any subscriber for + * Messages are routed based on their type a message will be delivered to any subscriber for * any type to which the message is *assignable.* This includes implemented interfaces, all - * superclasses, and all interfaces implemented by superclasses. + * thisclasses, and all interfaces implemented by thisclasses. * * - * When `post` is called, all registered subscribers for an message are run in sequence, so - * subscribers should be reasonably quick. If an message may trigger an extended process (such as a - * database load), spawn a thread or queue it for later. (For a convenient way to do this, use an - * [AsyncBus].) * *

Subscriber Methods

* @@ -126,12 +120,12 @@ import java.util.logging.Logger *

Dead Messages

* * - * If an message is posted, but no registered subscribers can accept it, it is considered "dead." + * If a message is posted, but no registered subscribers can accept it, it is considered "dead." * To give the system a second chance to handle dead messages, they are wrapped in an instance of * [DeadMessage] and reposted. * * - * If a subscriber for a supertype of all messages (such as Object) is registered, no message will + * If a subscriber for this type of all messages (such as Object) is registered, no message will * ever be considered dead, and no DeadMessages will be generated. Accordingly, while DeadMessage * extends [Object], a subscriber registered to receive any Object will never receive a * DeadMessage. @@ -140,8 +134,6 @@ import java.util.logging.Logger * This class is safe for concurrent use. * * - * See the Guava User Guide article on [`MessageBus`](https://github.com/google/guava/wiki/MessageBusExplained). - * * @author Cliff * @since 10.0 * @param identifier a brief name for this bus, for logging purposes. Should/home/alex/privacy/project/myths/gaea be a valid Java @@ -149,14 +141,16 @@ import java.util.logging.Logger * @param dispatcher message dispatcher. * @param exceptionHandler Handler for subscriber exceptions. */ -open class Bus( +open class Bus( override val identifier: String, override val executor: Executor, - val dispatcher: Dispatcher, - val exceptionHandler: SubscriberExceptionHandler, -) : IBus { + val dispatcher: Dispatcher, + val exceptionHandler: SubscriberExceptionHandler, +) : IBus { - private val subscribers: SubscriberRegistry = SubscriberRegistry(this) + val DEAD_TOPIC = "DEAD_TOPIC" + + private val subscribers: SubscriberRegistry = SubscriberRegistry(this) /** * Creates a new MessageBus with the given `identifier`. @@ -178,18 +172,76 @@ open class Bus( * @param exceptionHandler Handler for subscriber exceptions. * @since 16.0 */ - constructor(exceptionHandler: SubscriberExceptionHandler) : this( + constructor(exceptionHandler: SubscriberExceptionHandler) : this( "default", Executor { it.run() }, Dispatcher.perThreadDispatchQueue(), exceptionHandler ) + /** + * Creates a new AsyncMessageBus that will use `executor` to dispatch messages. Assigns `identifier` as the bus's name for logging purposes. + * + * @param identifier short name for the bus, for logging purposes. + * @param executor Executor to use to dispatch messages. It is the caller's responsibility to shut + * down the executor after the last message has been posted to this message bus. + */ + constructor(identifier: String, executor: Executor) : this( + identifier, + executor, + Dispatcher.legacyAsync(), + LoggingHandler() + ) + + /** + * Creates a new AsyncMessageBus that will use `executor` to dispatch messages. + * + * @param executor Executor to use to dispatch messages. It is the caller's responsibility to shut + * down the executor after the last message has been posted to this message bus. + * @param subscriberExceptionHandler Handler used to handle exceptions thrown from subscribers. + * See [SubscriberExceptionHandler] for more information. + * @since 16.0 + */ + constructor(executor: Executor, subscriberExceptionHandler: SubscriberExceptionHandler) : this( + "default", + executor, + Dispatcher.legacyAsync(), + subscriberExceptionHandler + ) + + /** + * Creates a new AsyncMessageBus that will use `executor` to dispatch messages. + * + * @param executor Executor to use to dispatch messages. It is the caller's responsibility to shut + * down the executor after the last message has been posted to this message bus. + */ + constructor(executor: Executor) : this( + "default", + executor, + Dispatcher.legacyAsync(), + LoggingHandler() + ) + + override fun register(topics: Array, subscriber: Any) { + subscribers.register(topics, subscriber) + } + + /** + * Registers subscriber method on `object` to receive messages. + * + * @param topics method subscribe topic. + * @param subscriber subscriber method declare object. + * @param method subscriber method should be registered. + */ + override fun register(topics: Array, subscriber: Any, method: Method) { + subscribers.register(topics, subscriber, method) + } + /** * Registers all subscriber methods on `object` to receive messages. * - * @param subscriber object whose subscriber methods should be registered. + * @param subscriber object whose subscriber methods should be registered. */ override fun register(subscriber: Any) { subscribers.register(subscriber) @@ -202,37 +254,73 @@ open class Bus( /** * Unregisters all subscriber methods on a registered `object`. * - * @param subscriber object whose subscriber methods should be unregistered. + * @param subscriber object whose subscriber methods should be unregistered. * @throws IllegalArgumentException if the object was not previously registered. */ override fun unregister(subscriber: Any) { subscribers.unregister(subscriber) } + override fun unregister(topic: String, subscriber: Any) { + subscribers.unregister(topic, subscriber) + } + /** - * Posts an message to all registered subscribers. This method will return successfully after the + * Posts a message to all registered subscribers. This method will return successfully after the * message has been posted to all subscribers, and regardless of any exceptions thrown by * subscribers. * - * - * If no subscribers have been subscribed for `message`'s class, and `message` is not - * already a [DeadMessage], it will be wrapped in a DeadMessage and reposted. - * * @param message message to post. */ - override fun publish(message: Any) { - val messageSubscribers = subscribers.getSubscribers(message) + override fun publish(message: T) { + val messageSubscribers = subscribers.getSubscribers(message::class.java.name) if (messageSubscribers.hasNext()) { dispatcher.dispatch(message, messageSubscribers) - } else if (message !is DeadMessage) { + } else { // the message had no subscribers and was not itself a DeadMessage - publish(DeadMessage(this, message)) + publish(DEAD_TOPIC, message) } } + /** + * Posts a message to all registered subscribers. This method will return successfully after the + * message has been posted to all subscribers, and regardless of any exceptions thrown by + * subscribers. + * + * @param message message to post. + */ + override fun publishAsync(message: T) { + val messageSubscribers = subscribers.getSubscribers(message::class.java.name) + if (messageSubscribers.hasNext()) { + dispatcher.dispatchAsync(message, messageSubscribers) + } else { + // the message had no subscribers and was not itself a DeadMessage + publishAsync(DEAD_TOPIC, message) + } + } + + override fun publish(topic: String, message: T) { + val messageSubscribers = subscribers.getSubscribers(topic) + if (messageSubscribers.hasNext()) { + dispatcher.dispatch(message, messageSubscribers) + } else if (topic != DEAD_TOPIC) { + // the message had no subscribers and was not itself a DeadMessage + publish(DEAD_TOPIC, message) + } + } + + override fun publishAsync(topic: String, message: T) { + val messageSubscribers = subscribers.getSubscribers(topic) + if (messageSubscribers.hasNext()) { + dispatcher.dispatchAsync(message, messageSubscribers) + } else if (topic != DEAD_TOPIC) { + // the message had no subscribers and was not itself a DeadMessage + publishAsync(DEAD_TOPIC, message) + } + } /** Handles the given exception thrown by a subscriber with the given context. */ - override fun handleException(cause: Throwable?, context: SubscriberExceptionContext) { + override fun handleException(cause: Throwable?, context: SubscriberExceptionContext) { try { exceptionHandler.handleException(cause, context) } catch (e2: Throwable) { diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/bus/DeadMessage.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/DeadMessage.kt index 1c044ac..6255b78 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/bus/DeadMessage.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/DeadMessage.kt @@ -14,7 +14,7 @@ package com.synebula.gaea.bus /** - * Wraps an message that was posted, but which had no subscribers and thus could not be delivered. + * Wraps a message that was posted, but which had no subscribers and thus could not be delivered. * * * Registering a DeadMessage subscriber is useful for debugging or logging, as it can detect diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/bus/Dispatcher.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/Dispatcher.kt index daab5f6..091519f 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/bus/Dispatcher.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/Dispatcher.kt @@ -23,13 +23,20 @@ import java.util.concurrent.ConcurrentLinkedQueue * * **Note:** The dispatcher is orthogonal to the subscriber's `Executor`. The dispatcher * controls the order in which messages are dispatched, while the executor controls how (i.e. on which - * thread) the subscriber is actually called when an message is dispatched to it. + * thread) the subscriber is actually called when a message is dispatched to it. * * @author Colin Decker */ abstract class Dispatcher { /** Dispatches the given `message` to the given `subscribers`. */ - abstract fun dispatch(message: T, subscribers: Iterator>?) + fun dispatch(message: T, subscribers: Iterator>?) { + while (subscribers!!.hasNext()) { + subscribers.next().dispatch(message) + } + } + + /** Dispatches the given `message` to the given `subscribers`. */ + abstract fun dispatchAsync(message: T, subscribers: Iterator>?) /** Implementation of a [.perThreadDispatchQueue] dispatcher. */ private class PerThreadQueuedDispatcher : Dispatcher() { @@ -48,7 +55,7 @@ abstract class Dispatcher { } } - override fun dispatch(message: T, subscribers: Iterator>?) { + override fun dispatchAsync(message: T, subscribers: Iterator>?) { val queueForThread = queue.get() queueForThread.offer(Message(message, subscribers)) if (!dispatching.get()) { @@ -57,7 +64,7 @@ abstract class Dispatcher { var nextMessage: Message? while (queueForThread.poll().also { nextMessage = it } != null) { while (nextMessage!!.subscribers!!.hasNext()) { - nextMessage!!.subscribers!!.next().dispatchMessage(nextMessage!!.message) + nextMessage!!.subscribers!!.next().dispatchAsync(nextMessage!!.message) } } } finally { @@ -91,32 +98,23 @@ abstract class Dispatcher { // in some cases. /** Global message queue. */ private val queue = ConcurrentLinkedQueue>() - override fun dispatch(message: T, subscribers: Iterator>?) { + override fun dispatchAsync(message: T, subscribers: Iterator>?) { while (subscribers!!.hasNext()) { queue.add(MessageWithSubscriber(message, subscribers.next())) } var e: MessageWithSubscriber? while (queue.poll().also { e = it } != null) { - e!!.subscriber!!.dispatchMessage(e!!.message) + e!!.subscriber!!.dispatchAsync(e!!.message) } } private class MessageWithSubscriber(val message: T, val subscriber: Subscriber?) } - /** Implementation of [.immediate]. */ - private class ImmediateDispatcher : Dispatcher() { - override fun dispatch(message: T, subscribers: Iterator>?) { - while (subscribers!!.hasNext()) { - subscribers.next().dispatchMessage(message) - } - } - } - companion object { /** * Returns a dispatcher that queues messages that are posted reentrantly on a thread that is already - * dispatching an message, guaranteeing that all messages posted on a single thread are dispatched to + * dispatching a message, guaranteeing that all messages posted on a single thread are dispatched to * all subscribers in the order they are posted. * * @@ -138,14 +136,5 @@ abstract class Dispatcher { fun legacyAsync(): Dispatcher { return LegacyAsyncDispatcher() } - - /** - * Returns a dispatcher that dispatches messages to subscribers immediately as they're posted - * without using an intermediate queue to change the dispatch order. This is effectively a - * depth-first dispatch order, vs. breadth-first when using a queue. - */ - fun immediate(): Dispatcher { - return ImmediateDispatcher() - } } } \ No newline at end of file diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/bus/IBus.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/IBus.kt index 207b5e3..d0ee938 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/bus/IBus.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/IBus.kt @@ -33,6 +33,49 @@ interface IBus { */ fun publish(message: T) + /** + * 异步发布事件 + * @param message 事件 + */ + fun publishAsync(message: T) + + /** + * 注册事件Listener + * @param topics 主题 + * @param subscriber subscriber对象 + */ + fun register(topics: Array, subscriber: Any) + + /** + * 注册事件Listener + * @param topics 主题 + * @param subscriber subscriber对象 + * @param method Listener方法 + */ + fun register(topics: Array, subscriber: Any, method: Method) + + + /** + * 取消注册事件Listener + * @param topic 主题 + * @param subscriber subscriber对象 + */ + fun unregister(topic: String, subscriber: Any) + + + /** + * 同步发布事件 + * @param topic 主题 + * @param message 事件 + */ + fun publish(topic: String, message: T) + + /** + * 异步发布事件 + * @param topic 主题 + * @param message 事件 + */ + fun publishAsync(topic: String, message: T) /** * 异常处理 diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/bus/Subscriber.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/Subscriber.kt index c66d422..bd0484d 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/bus/Subscriber.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/Subscriber.kt @@ -13,6 +13,7 @@ */ package com.synebula.gaea.bus +import com.synebula.gaea.exception.NoticeUserException import java.lang.reflect.InvocationTargetException import java.lang.reflect.Method import java.util.concurrent.Executor @@ -44,8 +45,13 @@ open class Subscriber private constructor( executor = bus.executor } + /** Dispatches `message` to this subscriber . */ + fun dispatch(message: Any) { + invokeSubscriberMethod(message) + } + /** Dispatches `message` to this subscriber using the proper executor. */ - fun dispatchMessage(message: Any) { + fun dispatchAsync(message: Any) { executor!!.execute { try { invokeSubscriberMethod(message) @@ -68,8 +74,8 @@ open class Subscriber private constructor( } catch (e: IllegalAccessException) { throw Error("Method became inaccessible: $message", e) } catch (e: InvocationTargetException) { - if (e.cause is Error) { - throw (e.cause as Error?)!! + if (e.cause is Error || e.cause is NoticeUserException) { + throw e.cause!! } throw e } diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/bus/SubscriberRegistry.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/SubscriberRegistry.kt index 00b7244..cd713d8 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/bus/SubscriberRegistry.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/SubscriberRegistry.kt @@ -31,50 +31,75 @@ open class SubscriberRegistry(private val bus: IBus) { * The [CopyOnWriteArraySet] values make it easy and relatively lightweight to get an * immutable snapshot of all current subscribers to a message without any locking. */ - private val subscribers = ConcurrentHashMap, CopyOnWriteArraySet>>() + private val subscribers = ConcurrentHashMap>>() - - /** Registers all subscriber methods on the given subscriber object. */ - open fun register(subscriber: Any) { + open fun register(topics: Array, subscriber: Any) { val listenerMethods = findAllSubscribers(subscriber) - for ((eventType, messageMethodsInListener) in listenerMethods) { - var messageSubscribers = subscribers[eventType] + for (topic in topics) { + for ((_, messageMethodsInListener) in listenerMethods) { + var messageSubscribers = subscribers[topic] + if (messageSubscribers == null) { + val newSet = CopyOnWriteArraySet>() + messageSubscribers = subscribers.putIfAbsent(topic, newSet) ?: newSet + } + messageSubscribers.addAll(messageMethodsInListener) + } + } + } + + open fun register(topics: Array, subscriber: Any, method: Method) { + for (topic in topics) { + var messageSubscribers = subscribers[topic] if (messageSubscribers == null) { val newSet = CopyOnWriteArraySet>() - messageSubscribers = subscribers.putIfAbsent(eventType, newSet) ?: newSet + messageSubscribers = subscribers.putIfAbsent(topic, newSet) ?: newSet + } + messageSubscribers.add(Subscriber.create(this.bus, subscriber, method)) + } + } + + /** Registers all subscriber methods on the given subscriber object. */ + fun register(subscriber: Any) { + val listenerMethods = findAllSubscribers(subscriber) + for ((topic, messageMethodsInListener) in listenerMethods) { + var messageSubscribers = subscribers[topic] + if (messageSubscribers == null) { + val newSet = CopyOnWriteArraySet>() + messageSubscribers = subscribers.putIfAbsent(topic, newSet) ?: newSet } messageSubscribers.addAll(messageMethodsInListener) } } /** Registers subscriber method on the given subscriber object. */ - open fun register(subscriber: Any, method: Method) { + fun register(subscriber: Any, method: Method) { val parameterTypes = method.parameterTypes - val eventType = parameterTypes[0] check(parameterTypes.size == 1) { "Method $method has @SubscribeTopic annotation but has ${parameterTypes.size} parameters. Subscriber methods must have exactly 1 parameter." } check(!parameterTypes[0].isPrimitive) { "@SubscribeTopic method $method's parameter is ${parameterTypes[0].name}. Subscriber methods cannot accept primitives. " } - var messageSubscribers = subscribers[eventType] + + val eventType = parameterTypes[0] + val topic = eventType.name + var messageSubscribers = subscribers[topic] if (messageSubscribers == null) { val newSet = CopyOnWriteArraySet>() - messageSubscribers = subscribers.putIfAbsent(eventType, newSet) ?: newSet + messageSubscribers = subscribers.putIfAbsent(topic, newSet) ?: newSet } messageSubscribers.add(Subscriber.create(bus, subscriber, method)) } - - /** Unregisters all subscribers on the given subscriber object. */ - open fun unregister(subscriber: Any) { + /** Unregisters all subscribers on the given subscriber object. */ + fun unregister(subscriber: Any) { val listenerMethods = findAllSubscribers(subscriber) - for ((eventType, listenerMethodsForType) in listenerMethods) { - val currentSubscribers = subscribers[eventType] + for ((topic, listenerMethodsForType) in listenerMethods) { + val currentSubscribers = subscribers[topic] require(!(currentSubscribers == null || !currentSubscribers.removeAll(listenerMethodsForType.toSet()))) { // if removeAll returns true, all we really know is that at least one subscriber was // removed... however, barring something very strange we can assume that if at least one - // subscriber was removed, all subscribers on subscriber for that message type were... after + // subscriber was removed, all subscribers on subscriber for that message type were... after // all, the definition of subscribers on a particular class is totally static "missing message subscriber for an annotated method. Is $subscriber registered?" } @@ -84,30 +109,55 @@ open class SubscriberRegistry(private val bus: IBus) { } } + /** Unregisters all subscribers by topic on the given subscriber object. */ + open fun unregister(topic: String, subscriber: Any) { + val listenerMethods = findAllSubscribers(subscriber) + if (listenerMethods[topic] == null) return //不包含topic则推出 + val currentSubscribers = subscribers[topic] + require(!(currentSubscribers == null || !currentSubscribers.removeAll(listenerMethods[topic]!!.toSet()))) { + // if removeAll returns true, all we really know is that at least one subscriber was + // removed... however, barring something very strange we can assume that if at least one + // subscriber was removed, all subscribers on subscriber for that message type were... after + // all, the definition of subscribers on a particular class is totally static + "missing message subscriber for an annotated method. Is $subscriber registered?" + } + + // don't try to remove the set if it's empty; that can't be done safely without a lock + // anyway, if the set is empty it'll just be wrapping an array of length 0 + } + + /** * Gets an iterator representing an immutable snapshot of all subscribers to the given message at * the time this method is called. */ - fun getSubscribers(eventType: Any): Iterator> { - val eventSubscribers: CopyOnWriteArraySet> = - subscribers[eventType.javaClass] ?: CopyOnWriteArraySet() - return eventSubscribers.iterator() + fun getSubscribers(topic: String): Iterator> { + val topicSubscribers: CopyOnWriteArraySet> = subscribers[topic] ?: CopyOnWriteArraySet() + return topicSubscribers.iterator() } /** - * Returns all subscribers for the given subscriber grouped by the type of message they subscribe to. + * Returns all subscribers for the given subscriber grouped by the type of message they subscribe to. */ - private fun findAllSubscribers(subscriber: Any): Map, List>> { - val methodsInListener = mutableMapOf, List>>() + private fun findAllSubscribers(subscriber: Any): Map>> { + val methodsInListener = mutableMapOf>>() val clazz: Class<*> = subscriber.javaClass for (method in getAnnotatedMethods(clazz)) { - val parameterTypes = method.parameterTypes - val eventType = parameterTypes[0] - val methods = methodsInListener[eventType]?.toMutableList() ?: mutableListOf() - methods.add(Subscriber.create(bus, subscriber, method)) - methodsInListener[eventType] = methods + var topics = method.getAnnotation(Subscribe::class.java).topics + + //如果没有定义topic,则使用消息类名称做topic + if (topics.isEmpty()) { + val parameterTypes = method.parameterTypes + val messageType = parameterTypes[0] + topics = arrayOf(messageType.name) + } + for (topic in topics) { + val listeners = methodsInListener.getOrDefault(topic, mutableListOf()) + listeners.add(Subscriber.create(bus, subscriber, method)) + methodsInListener[topic] = listeners + } } - return methodsInListener.toMap() + return methodsInListener } diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/bus/messagebus/AsyncMessageBus.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/messagebus/AsyncMessageBus.kt deleted file mode 100644 index 30cb8b5..0000000 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/bus/messagebus/AsyncMessageBus.kt +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (C) 2007 The Guava Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package com.synebula.gaea.bus.messagebus - -import com.synebula.gaea.bus.Dispatcher -import com.synebula.gaea.bus.LoggingHandler -import com.synebula.gaea.bus.SubscriberExceptionHandler -import java.util.concurrent.Executor - -/** - * An [MessageBus] that takes the Executor of your choice and uses it to dispatch events, - * allowing dispatch to occur asynchronously. - * - * @author Cliff - * @since 10.0 - */ -class AsyncMessageBus : MessageBus { - /** - * Creates a new AsyncEventBus that will use `executor` to dispatch events. Assigns `identifier` as the bus's name for logging purposes. - * - * @param identifier short name for the bus, for logging purposes. - * @param executor Executor to use to dispatch events. It is the caller's responsibility to shut - * down the executor after the last event has been posted to this event bus. - */ - constructor(identifier: String, executor: Executor) : super( - identifier, - executor, - Dispatcher.legacyAsync(), - LoggingHandler() - ) - - /** - * Creates a new AsyncEventBus that will use `executor` to dispatch events. - * - * @param executor Executor to use to dispatch events. It is the caller's responsibility to shut - * down the executor after the last event has been posted to this event bus. - * @param subscriberExceptionHandler Handler used to handle exceptions thrown from subscribers. - * See [SubscriberExceptionHandler] for more information. - * @since 16.0 - */ - constructor(executor: Executor, subscriberExceptionHandler: SubscriberExceptionHandler) : super( - "default", - executor, - Dispatcher.legacyAsync(), - subscriberExceptionHandler - ) - - /** - * Creates a new AsyncEventBus that will use `executor` to dispatch events. - * - * @param executor Executor to use to dispatch events. It is the caller's responsibility to shut - * down the executor after the last event has been posted to this event bus. - */ - constructor(executor: Executor) : super( - "default", - executor, - Dispatcher.legacyAsync(), - LoggingHandler() - ) -} \ No newline at end of file diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/bus/messagebus/IMessageBus.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/messagebus/IMessageBus.kt deleted file mode 100644 index da731fb..0000000 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/bus/messagebus/IMessageBus.kt +++ /dev/null @@ -1,39 +0,0 @@ -package com.synebula.gaea.bus.messagebus - -import com.synebula.gaea.bus.IBus -import java.lang.reflect.Method - -interface IMessageBus : IBus { - - /** - * 注册事件Listener - * @param topics 主题 - * @param subscriber subscriber对象 - */ - fun register(topics: Array, subscriber: Any) - - /** - * 注册事件Listener - * @param topics 主题 - * @param subscriber subscriber对象 - * @param method Listener方法 - */ - fun register(topics: Array, subscriber: Any, method: Method) - - - /** - * 取消注册事件Listener - * @param topic 主题 - * @param subscriber subscriber对象 - */ - fun unregister(topic: String, subscriber: Any) - - - /** - * 同步发布事件 - * @param topic 主题 - * @param message 事件 - */ - fun publish(topic: String, message: T) - -} \ No newline at end of file diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/bus/messagebus/MessageBus.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/messagebus/MessageBus.kt deleted file mode 100644 index db6a4aa..0000000 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/bus/messagebus/MessageBus.kt +++ /dev/null @@ -1,280 +0,0 @@ -/* - * Copyright (C) 2007 The Guava Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package com.synebula.gaea.bus.messagebus - -import com.synebula.gaea.bus.* -import java.lang.reflect.Method -import java.util.* -import java.util.concurrent.Executor -import java.util.logging.Level -import java.util.logging.Logger - -/** - * Dispatches events to listeners, and provides ways for listeners to register themselves. - * - *

Avoid EventBus

- * - * - * **We recommend against using EventBus.** It was designed many years ago, and newer - * libraries offer better ways to decouple components and react to events. - * - * - * To decouple components, we recommend a dependency-injection framework. For Android code, most - * apps use [Dagger](https://dagger.dev). For server code, common options include [Guice](https://github.com/google/guice/wiki/Motivation) and [Spring](https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-introduction). - * Frameworks typically offer a way to register multiple listeners independently and then request - * them together as a set ([Dagger](https://dagger.dev/dev-guide/multibindings), [Guice](https://github.com/google/guice/wiki/Multibindings), [Spring](https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-autowired-annotation)). - * - * - * To react to events, we recommend a reactive-streams framework like [RxJava](https://github.com/ReactiveX/RxJava/wiki) (supplemented with its [RxAndroid](https://github.com/ReactiveX/RxAndroid) extension if you are building for - * Android) or [Project Reactor](https://projectreactor.io/). (For the basics of - * translating code from using an event bus to using a reactive-streams framework, see these two - * guides: [1](https://blog.jkl.gg/implementing-an-event-bus-with-rxjava-rxbus/), [2](https://lorentzos.com/rxjava-as-event-bus-the-right-way-10a36bdd49ba).) Some usages - * of EventBus may be better written using [Kotlin coroutines](https://kotlinlang.org/docs/coroutines-guide.html), including [Flow](https://kotlinlang.org/docs/flow.html) and [Channels](https://kotlinlang.org/docs/channels.html). Yet other usages are better served - * by individual libraries that provide specialized support for particular use cases. - * - * - * Disadvantages of EventBus include: - * - * - * * It makes the cross-references between producer and subscriber harder to find. This can - * complicate debugging, lead to unintentional reentrant calls, and force apps to eagerly - * initialize all possible subscribers at startup time. - * * It uses reflection in ways that break when code is processed by optimizers/minimizer like - * [R8 and Proguard](https://developer.android.com/studio/build/shrink-code). - * * It doesn't offer a way to wait for multiple events before taking action. For example, it - * doesn't offer a way to wait for multiple producers to all report that they're "ready," nor - * does it offer a way to batch multiple events from a single producer together. - * * It doesn't support backpressure and other features needed for resilience. - * * It doesn't provide much control of threading. - * * It doesn't offer much monitoring. - * * It doesn't propagate exceptions, so apps don't have a way to react to them. - * * It doesn't interoperate well with RxJava, coroutines, and other more commonly used - * alternatives. - * * It imposes requirements on the lifecycle of its subscribers. For example, if an event - * occurs between when one subscriber is removed and the next subscriber is added, the event - * is dropped. - * * Its performance is suboptimal, especially under Android. - * * It [doesn't support parameterized - * types](https://github.com/google/guava/issues/1431). - * * With the introduction of lambdas in Java 8, EventBus went from less verbose than listeners - * to [more verbose](https://github.com/google/guava/issues/3311). - * - * - *

EventBus Summary

- * - * - * The EventBus allows publish-subscribe-style communication between components without requiring - * the components to explicitly register with one another (and thus be aware of each other). It is - * designed exclusively to replace traditional Java in-process event distribution using explicit - * registration. It is *not* a general-purpose publish-subscribe system, nor is it intended - * for interprocess communication. - * - *

Receiving Events

- * - * - * To receive events, an object should: - * - * - * 1. Expose a public method, known as the *event subscriber*, which accepts a single - * argument of the type of event desired; - * 1. Mark it with a [Subscribe] annotation; - * 1. Pass itself to an EventBus instance's [.register] method. - * - * - *

Posting Events

- * - * - * To post an event, simply provide the event object to the [.post] method. The - * EventBus instance will determine the type of event and route it to all registered listeners. - * - * - * Events are routed based on their type an event will be delivered to any subscriber for - * any type to which the event is *assignable.* This includes implemented interfaces, all - * superclasses, and all interfaces implemented by superclasses. - * - * - * When `post` is called, all registered subscribers for an event are run in sequence, so - * subscribers should be reasonably quick. If an event may trigger an extended process (such as a - * database load), spawn a thread or queue it for later. (For a convenient way to do this, use an - * [AsyncMessageBus].) - * - *

Subscriber Methods

- * - * - * Event subscriber methods must accept only one argument: the event. - * - * - * Subscribers should not, in general, throw. If they do, the EventBus will catch and log the - * exception. This is rarely the right solution for error handling and should not be relied upon; it - * is intended solely to help find problems during development. - * - * - * The EventBus guarantees that it will not call a subscriber method from multiple threads - * simultaneously, unless the method explicitly allows it by bearing the [ ] annotation. If this annotation is not present, subscriber methods need not - * worry about being reentrant, unless also called from outside the EventBus. - * - *

Dead Events

- * - * - * If an event is posted, but no registered subscribers can accept it, it is considered "dead." - * To give the system a second chance to handle dead events, they are wrapped in an instance of - * [DeadMessage] and reposted. - * - * - * If a subscriber for a supertype of all events (such as Object) is registered, no event will - * ever be considered dead, and no DeadEvents will be generated. Accordingly, while DeadMessage - * extends [Object], a subscriber registered to receive any Object will never receive a - * DeadMessage. - * - * - * This class is safe for concurrent use. - * - * - * See the Guava User Guide article on [`EventBus`](https://github.com/google/guava/wiki/EventBusExplained). - * - * @author Cliff - * @param identifier a brief name for this bus, for logging purposes. Should/home/alex/privacy/project/myths/gaea be a valid Java - * @param executor the default executor this event bus uses for dispatching events to subscribers. - * @param dispatcher message dispatcher. - * @param exceptionHandler Handler for subscriber exceptions. - */ -open class MessageBus internal constructor( - override val identifier: String, - override val executor: Executor, - val dispatcher: Dispatcher, - val exceptionHandler: SubscriberExceptionHandler, -) : IMessageBus { - val DEAD_TOPIC = "DEAD_TOPIC" - - val subscribers = TopicSubscriberRegistry(this) - - /** - * Creates a new EventBus with the given `identifier`. - * - * @param identifier a brief name for this bus, for logging purposes. Should/home/alex/privacy/project/myths/gaea be a valid Java - * identifier. - */ - @JvmOverloads - constructor(identifier: String = "default") : this( - identifier, - Executor { it.run() }, - Dispatcher.perThreadDispatchQueue(), - LoggingHandler() - ) - - /** - * Creates a new EventBus with the given [SubscriberExceptionHandler]. - * - * @param exceptionHandler Handler for subscriber exceptions. - * @since 16.0 - */ - constructor(exceptionHandler: SubscriberExceptionHandler) : this( - "default", - Executor { it.run() }, - Dispatcher.perThreadDispatchQueue(), - exceptionHandler - ) - - override fun register(topics: Array, subscriber: Any) { - subscribers.register(topics, subscriber) - } - - /** - * Registers subscriber method on `object` to receive messages. - * - * @param topics method subscribe topic. - * @param subscriber subscriber method declare object. - * @param method subscriber method should be registered. - */ - override fun register(topics: Array, subscriber: Any, method: Method) { - subscribers.register(topics, subscriber, method) - } - - - /** - * Registers all subscriber methods on `object` to receive messages. - * - * @param subscriber object whose subscriber methods should be registered. - */ - override fun register(subscriber: Any) { - subscribers.register(subscriber) - } - - override fun register(subscriber: Any, method: Method) { - subscribers.register(subscriber, method) - } - - /** - * Unregisters all subscriber methods on a registered `object`. - * - * @param subscriber object whose subscriber methods should be unregistered. - * @throws IllegalArgumentException if the object was not previously registered. - */ - override fun unregister(subscriber: Any) { - subscribers.unregister(subscriber) - } - - override fun unregister(topic: String, subscriber: Any) { - subscribers.unregister(topic, subscriber) - } - - /** - * Posts an message to all registered subscribers. This method will return successfully after the - * message has been posted to all subscribers, and regardless of any exceptions thrown by - * subscribers. - * - * @param message message to post. - */ - override fun publish(message: T) { - val messageSubscribers = subscribers.getSubscribers(message.javaClass.name) - if (messageSubscribers.hasNext()) { - dispatcher.dispatch(message, messageSubscribers) - } else { - // the message had no subscribers and was not itself a DeadMessage - publish(DEAD_TOPIC, message) - } - } - - override fun publish(topic: String, message: T) { - val messageSubscribers = subscribers.getSubscribers(topic) - if (messageSubscribers.hasNext()) { - dispatcher.dispatch(message, messageSubscribers) - } else if (topic != DEAD_TOPIC) { - // the message had no subscribers and was not itself a DeadMessage - publish(DEAD_TOPIC, message) - } - } - - - /** Handles the given exception thrown by a subscriber with the given context. */ - override fun handleException(cause: Throwable?, context: SubscriberExceptionContext) { - try { - exceptionHandler.handleException(cause, context) - } catch (e2: Throwable) { - // if the handler threw an exception... well, just log it - logger.log( - Level.SEVERE, String.format(Locale.ROOT, "Exception %s thrown while handling exception: %s", e2, cause), - e2 - ) - } - } - - override fun toString(): String { - return "MessageBus(identifier='$identifier', executor=$executor, dispatcher=$dispatcher, exceptionHandler=$exceptionHandler, subscribers=$subscribers)" - } - - companion object { - private val logger = Logger.getLogger(Bus::class.java.name) - } -} \ No newline at end of file diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/bus/messagebus/TopicSubscriberRegistry.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/bus/messagebus/TopicSubscriberRegistry.kt deleted file mode 100644 index 6c8d0f7..0000000 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/bus/messagebus/TopicSubscriberRegistry.kt +++ /dev/null @@ -1,184 +0,0 @@ -/* - * Copyright (C) 2014 The Guava Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package com.synebula.gaea.bus.messagebus - -import com.synebula.gaea.bus.Subscribe -import com.synebula.gaea.bus.Subscriber -import com.synebula.gaea.bus.SubscriberRegistry -import java.lang.reflect.Method -import java.util.concurrent.ConcurrentHashMap -import java.util.concurrent.CopyOnWriteArraySet - -/** - * Registry of subscribers to a single message bus. - * - * @author Colin Decker - */ -open class TopicSubscriberRegistry(private val bus: IMessageBus) : SubscriberRegistry(bus) { - /** - * All registered subscribers, indexed by message type. - * - * - * The [CopyOnWriteArraySet] values make it easy and relatively lightweight to get an - * immutable snapshot of all current subscribers to an message without any locking. - */ - private val subscribers = ConcurrentHashMap>>() - - open fun register(topics: Array, subscriber: Any) { - val listenerMethods = findAllSubscribers(subscriber) - for (topic in topics) { - for ((_, messageMethodsInListener) in listenerMethods) { - var messageSubscribers = subscribers[topic] - if (messageSubscribers == null) { - val newSet = CopyOnWriteArraySet>() - messageSubscribers = subscribers.putIfAbsent(topic, newSet) ?: newSet - } - messageSubscribers.addAll(messageMethodsInListener) - } - } - } - - open fun register(topics: Array, subscriber: Any, method: Method) { - for (topic in topics) { - var messageSubscribers = subscribers[topic] - if (messageSubscribers == null) { - val newSet = CopyOnWriteArraySet>() - messageSubscribers = subscribers.putIfAbsent(topic, newSet) ?: newSet - } - messageSubscribers.add(Subscriber.create(this.bus, subscriber, method)) - } - } - - /** Registers all subscriber methods on the given subscriber object. */ - override fun register(subscriber: Any) { - val listenerMethods = findAllSubscribers(subscriber) - for ((topic, messageMethodsInListener) in listenerMethods) { - var messageSubscribers = subscribers[topic] - if (messageSubscribers == null) { - val newSet = CopyOnWriteArraySet>() - messageSubscribers = subscribers.putIfAbsent(topic, newSet) ?: newSet - } - messageSubscribers.addAll(messageMethodsInListener) - } - } - - /** Registers subscriber method on the given subscriber object. */ - override fun register(subscriber: Any, method: Method) { - val parameterTypes = method.parameterTypes - check(parameterTypes.size == 1) { - "Method $method has @SubscribeTopic annotation but has ${parameterTypes.size} parameters. Subscriber methods must have exactly 1 parameter." - } - check(!parameterTypes[0].isPrimitive) { - "@SubscribeTopic method $method's parameter is ${parameterTypes[0].name}. Subscriber methods cannot accept primitives. " - } - - val eventType = parameterTypes[0] - val topic = eventType.name - var messageSubscribers = subscribers[topic] - if (messageSubscribers == null) { - val newSet = CopyOnWriteArraySet>() - messageSubscribers = subscribers.putIfAbsent(topic, newSet) ?: newSet - } - messageSubscribers.add(Subscriber.create(bus, subscriber, method)) - } - - /** Unregisters all subscribers on the given subscriber object. */ - override fun unregister(subscriber: Any) { - val listenerMethods = findAllSubscribers(subscriber) - for ((topic, listenerMethodsForType) in listenerMethods) { - val currentSubscribers = subscribers[topic] - require(!(currentSubscribers == null || !currentSubscribers.removeAll(listenerMethodsForType.toSet()))) { - // if removeAll returns true, all we really know is that at least one subscriber was - // removed... however, barring something very strange we can assume that if at least one - // subscriber was removed, all subscribers on subscriber for that message type were... after - // all, the definition of subscribers on a particular class is totally static - "missing message subscriber for an annotated method. Is $subscriber registered?" - } - - // don't try to remove the set if it's empty; that can't be done safely without a lock - // anyway, if the set is empty it'll just be wrapping an array of length 0 - } - } - - /** Unregisters all subscribers by topic on the given subscriber object. */ - open fun unregister(topic: String, subscriber: Any) { - val listenerMethods = findAllSubscribers(subscriber) - if (listenerMethods[topic] == null) return //不包含topic则推出 - val currentSubscribers = subscribers[topic] - require(!(currentSubscribers == null || !currentSubscribers.removeAll(listenerMethods[topic]!!.toSet()))) { - // if removeAll returns true, all we really know is that at least one subscriber was - // removed... however, barring something very strange we can assume that if at least one - // subscriber was removed, all subscribers on subscriber for that message type were... after - // all, the definition of subscribers on a particular class is totally static - "missing message subscriber for an annotated method. Is $subscriber registered?" - } - - // don't try to remove the set if it's empty; that can't be done safely without a lock - // anyway, if the set is empty it'll just be wrapping an array of length 0 - } - - - /** - * Gets an iterator representing an immutable snapshot of all subscribers to the given message at - * the time this method is called. - */ - fun getSubscribers(topic: String): Iterator> { - val topicSubscribers: CopyOnWriteArraySet> = subscribers[topic] ?: CopyOnWriteArraySet() - return topicSubscribers.iterator() - } - - /** - * Returns all subscribers for the given subscriber grouped by the type of message they subscribe to. - */ - private fun findAllSubscribers(subscriber: Any): Map>> { - val methodsInListener = mutableMapOf>>() - val clazz: Class<*> = subscriber.javaClass - for (method in getAnnotatedMethods(clazz)) { - var topics = method.getAnnotation(Subscribe::class.java).topics - - //如果没有定义topic,则使用消息类名称做topic - if (topics.isEmpty()) { - val parameterTypes = method.parameterTypes - val messageType = parameterTypes[0] - topics = arrayOf(messageType.name) - } - for (topic in topics) { - val listeners = methodsInListener.getOrDefault(topic, mutableListOf()) - listeners.add(Subscriber.create(bus, subscriber, method)) - methodsInListener[topic] = listeners - } - } - return methodsInListener - } - - - class MethodIdentifier(method: Method) { - private val name: String = method.name - private val parameterTypes: List> = listOf(*method.parameterTypes) - - override fun hashCode(): Int { - var result = name.hashCode() - for (element in parameterTypes) result = 31 * result + element.hashCode() - return result - } - - override fun equals(other: Any?): Boolean { - if (other is MethodIdentifier) { - return name == other.name && parameterTypes == other.parameterTypes - } - return false - } - } - -} \ No newline at end of file diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/event/AfterRemoveEvent.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/event/AfterRemoveEvent.kt new file mode 100644 index 0000000..6c3b076 --- /dev/null +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/event/AfterRemoveEvent.kt @@ -0,0 +1,5 @@ +package com.synebula.gaea.domain.event + +import com.synebula.gaea.domain.model.IAggregateRoot + +class AfterRemoveEvent, I>(var id: I? = null) \ No newline at end of file diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/event/BeforeRemoveEvent.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/event/BeforeRemoveEvent.kt new file mode 100644 index 0000000..21a9211 --- /dev/null +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/event/BeforeRemoveEvent.kt @@ -0,0 +1,5 @@ +package com.synebula.gaea.domain.event + +import com.synebula.gaea.domain.model.IAggregateRoot + +class BeforeRemoveEvent, I>(var id: I? = null) \ No newline at end of file diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/IRepository.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/IRepository.kt index 99c411a..e8fa6cd 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/IRepository.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/repository/IRepository.kt @@ -68,7 +68,7 @@ interface IRepository, ID> { * @param params 查询条件。 * @return int */ - fun count(params: Map?): Int + fun count(params: Map?): Int } diff --git a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/Service.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/Service.kt index 1856b12..27b8021 100644 --- a/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/Service.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/domain/service/Service.kt @@ -1,9 +1,14 @@ package com.synebula.gaea.domain.service +import com.synebula.gaea.bus.IBus import com.synebula.gaea.data.message.DataMessage import com.synebula.gaea.data.serialization.IObjectMapper +import com.synebula.gaea.domain.event.AfterRemoveEvent +import com.synebula.gaea.domain.event.BeforeRemoveEvent import com.synebula.gaea.domain.model.IAggregateRoot import com.synebula.gaea.domain.repository.IRepository +import com.synebula.gaea.ext.firstCharLowerCase +import javax.annotation.Resource /** @@ -22,6 +27,8 @@ open class Service, ID>( protected open var repository: IRepository, protected open var mapper: IObjectMapper, ) : IService { + @Resource + protected open var bus: IBus? = null /** * 增加对象 @@ -73,7 +80,17 @@ open class Service, ID>( * @param id 对象ID */ override fun remove(id: ID) { + val beforeRemoveEvent = BeforeRemoveEvent(id) + this.bus?.publish( + "${this.clazz.simpleName.firstCharLowerCase()}${BeforeRemoveEvent::class.java.simpleName}", + beforeRemoveEvent + ) this.repository.remove(id) + val afterRemoveEvent = AfterRemoveEvent(id) + this.bus?.publish( + "${this.clazz.simpleName.firstCharLowerCase()}${AfterRemoveEvent::class.java.simpleName}", + afterRemoveEvent + ) } /** diff --git a/src/gaea/src/test/kotlin/com/synebula/gaea/bus/BusTest.kt b/src/gaea/src/test/kotlin/com/synebula/gaea/bus/BusTest.kt index 0022320..da0a145 100644 --- a/src/gaea/src/test/kotlin/com/synebula/gaea/bus/BusTest.kt +++ b/src/gaea/src/test/kotlin/com/synebula/gaea/bus/BusTest.kt @@ -1,8 +1,5 @@ package com.synebula.gaea.bus -import com.synebula.gaea.bus.messagebus.AsyncMessageBus -import com.synebula.gaea.bus.messagebus.IMessageBus -import com.synebula.gaea.bus.messagebus.MessageBus import org.junit.Test import java.util.concurrent.Executors @@ -21,36 +18,36 @@ class BusTest { @Test fun testAsyncBus() { - val bus: IBus = AsyncBus(Executors.newFixedThreadPool(10)) + val bus: IBus = Bus(Executors.newFixedThreadPool(10)) val subscriber = TestSubscriber() bus.register(subscriber, subscriber.javaClass.declaredMethods[0]) bus.register(subscriber, subscriber.javaClass.declaredMethods[1]) - bus.publish("Hello world") - bus.publish(subscriber) + bus.publishAsync("Hello world") + bus.publishAsync(subscriber) } @Test - fun testMessageBus() { - val bus: IMessageBus = MessageBus() + fun testTopicBus() { + val bus: IBus = Bus() val subscriber = TestTopicSubscriber() bus.register(subscriber) bus.publish("hello", "Hello world") - bus.publish("whoami", subscriber) + bus.publishAsync("whoami", subscriber) } @Test - fun testMessageBus2() { - val bus: IMessageBus = AsyncMessageBus(Executors.newFixedThreadPool(10)) + fun testAsyncTopicBus() { + val bus: IBus = Bus(Executors.newFixedThreadPool(10)) val subscriber = TestTopicSubscriber() val subscriber2 = TestTopicSubscriber2() bus.register(subscriber) bus.register(subscriber2) - bus.publish("hello", "Hello world") - bus.publish("whoami", subscriber) + bus.publishAsync("hello", "Hello world") + bus.publishAsync("whoami", subscriber) bus.unregister(subscriber2) - bus.publish("hello", "Hello world") - bus.publish("whoami", subscriber) + bus.publishAsync("hello", "Hello world") + bus.publishAsync("whoami", subscriber) } internal class TestSubscriber { From 5d742df4661a8b930e9c1d8f02f782311aaef164 Mon Sep 17 00:00:00 2001 From: alex Date: Tue, 23 Aug 2022 16:34:16 +0800 Subject: [PATCH 13/14] change HttpMessage location --- .../com/synebula/gaea/app/IApplication.kt | 2 +- .../com/synebula/gaea/app/cmd/ICommandApp.kt | 2 +- .../gaea/app/cmd/ISimpleCommandApp.kt | 2 +- .../component/security/WebAuthorization.kt | 2 +- .../app/component/security/WebSecurity.kt | 2 +- .../com/synebula/gaea/app/query/IQueryApp.kt | 2 +- .../com/synebula/gaea/spring/aop/AppAspect.kt | 48 +++++++++---------- .../gaea/data/message}/HttpMessage.kt | 10 ++-- 8 files changed, 36 insertions(+), 34 deletions(-) rename src/{gaea.app/src/main/kotlin/com/synebula/gaea/app/struct => gaea/src/main/kotlin/com/synebula/gaea/data/message}/HttpMessage.kt (71%) diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/IApplication.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/IApplication.kt index d0b3dfe..e6429c9 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/IApplication.kt +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/IApplication.kt @@ -1,7 +1,7 @@ package com.synebula.gaea.app import com.google.gson.Gson -import com.synebula.gaea.app.struct.HttpMessage +import com.synebula.gaea.data.message.HttpMessage import com.synebula.gaea.data.message.Status import com.synebula.gaea.log.ILogger import org.springframework.security.core.context.SecurityContextHolder diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/ICommandApp.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/ICommandApp.kt index b95d292..aff4805 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/ICommandApp.kt +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/ICommandApp.kt @@ -1,7 +1,7 @@ package com.synebula.gaea.app.cmd import com.synebula.gaea.app.IApplication -import com.synebula.gaea.app.struct.HttpMessage +import com.synebula.gaea.data.message.HttpMessage import com.synebula.gaea.data.message.Status import com.synebula.gaea.data.serialization.json.IJsonSerializer import com.synebula.gaea.domain.service.ICommand diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/ISimpleCommandApp.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/ISimpleCommandApp.kt index fa7344c..98bd2ec 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/ISimpleCommandApp.kt +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/cmd/ISimpleCommandApp.kt @@ -1,7 +1,7 @@ package com.synebula.gaea.app.cmd import com.synebula.gaea.app.IApplication -import com.synebula.gaea.app.struct.HttpMessage +import com.synebula.gaea.data.message.HttpMessage import com.synebula.gaea.data.message.Status import com.synebula.gaea.data.serialization.json.IJsonSerializer import com.synebula.gaea.domain.model.IAggregateRoot diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/security/WebAuthorization.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/security/WebAuthorization.kt index 1d451d4..d82f6aa 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/security/WebAuthorization.kt +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/security/WebAuthorization.kt @@ -1,7 +1,7 @@ package com.synebula.gaea.app.component.security -import com.synebula.gaea.app.struct.HttpMessage import com.synebula.gaea.app.struct.exception.TokenCloseExpireException +import com.synebula.gaea.data.message.HttpMessage import com.synebula.gaea.data.message.Status import org.springframework.security.authentication.AuthenticationManager import org.springframework.security.authentication.UsernamePasswordAuthenticationToken diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/security/WebSecurity.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/security/WebSecurity.kt index fa6208f..1c0ea81 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/security/WebSecurity.kt +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/component/security/WebSecurity.kt @@ -1,6 +1,6 @@ package com.synebula.gaea.app.component.security -import com.synebula.gaea.app.struct.HttpMessage +import com.synebula.gaea.data.message.HttpMessage import com.synebula.gaea.data.message.Status import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.annotation.Bean diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/query/IQueryApp.kt b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/query/IQueryApp.kt index 7557c9c..b390ad8 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/query/IQueryApp.kt +++ b/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/query/IQueryApp.kt @@ -1,7 +1,7 @@ package com.synebula.gaea.app.query import com.synebula.gaea.app.IApplication -import com.synebula.gaea.app.struct.HttpMessage +import com.synebula.gaea.data.message.HttpMessage import com.synebula.gaea.query.IQuery import com.synebula.gaea.query.Params import com.synebula.gaea.spring.aop.annotation.Method diff --git a/src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/aop/AppAspect.kt b/src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/aop/AppAspect.kt index 5a305db..6033e30 100644 --- a/src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/aop/AppAspect.kt +++ b/src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/aop/AppAspect.kt @@ -1,7 +1,7 @@ package com.synebula.gaea.spring.aop import com.google.gson.Gson -import com.synebula.gaea.data.message.DataMessage +import com.synebula.gaea.data.message.HttpMessage import com.synebula.gaea.data.message.Status import com.synebula.gaea.exception.NoticeUserException import com.synebula.gaea.log.ILogger @@ -36,37 +36,37 @@ abstract class AppAspect { */ @Around("func()") fun around(point: ProceedingJoinPoint): Any? { - val clazz = point.`this`.javaClass //获取实际对象的类型避免获取到父类 - val func = point.signature.declaringType.methods.find { - it.name == point.signature.name - }!!//获取声明类型中的方法信息 - val funcAnnotations = func.annotations ?: arrayOf() - - var funcName = func.name - //遍历方法注解 - for (funcAnnotation in funcAnnotations) { - val annotations = funcAnnotation.annotationClass.annotations - - //尝试寻找方法注解的处理类 - val handler = annotations.find { it is Handler } - if (handler != null && handler is Handler) { - val handleClazz = applicationContext.getBean(handler.value.java) - handleClazz.handle(clazz, func, point.args) - } - if (funcAnnotation is Method) - funcName = funcAnnotation.name - } - return try { point.proceed() } catch (ex: Throwable) { + val clazz = point.`this`.javaClass //获取实际对象的类型避免获取到父类 + val func = point.signature.declaringType.methods.find { + it.name == point.signature.name + }!!//获取声明类型中的方法信息 + val funcAnnotations = func.annotations ?: arrayOf() + + var funcName = func.name + //遍历方法注解 + for (funcAnnotation in funcAnnotations) { + val annotations = funcAnnotation.annotationClass.annotations + + //尝试寻找方法注解的处理类 + val handler = annotations.find { it is Handler } + if (handler != null && handler is Handler) { + val handleClazz = applicationContext.getBean(handler.value.java) + handleClazz.handle(clazz, func, point.args) + } + if (funcAnnotation is Method) + funcName = funcAnnotation.name + } + //找到类的模块名称,否则使用类名 var moduleName = clazz.simpleName val module = clazz.annotations.find { it is Module } if (module != null && module is Module) { moduleName = module.name } - var message = "$moduleName - $funcName 异常" + var message = "$moduleName - ${funcName}异常" message = if (ex is NoticeUserException || ex is Error) { "$message: ${ex.message}" } else { @@ -80,7 +80,7 @@ abstract class AppAspect { gson.toJson(point.args) }" ) - return gson.toJson(DataMessage(Status.Error, message)) + return HttpMessage(Status.Error, message) } } } \ No newline at end of file diff --git a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/struct/HttpMessage.kt b/src/gaea/src/main/kotlin/com/synebula/gaea/data/message/HttpMessage.kt similarity index 71% rename from src/gaea.app/src/main/kotlin/com/synebula/gaea/app/struct/HttpMessage.kt rename to src/gaea/src/main/kotlin/com/synebula/gaea/data/message/HttpMessage.kt index 43e8236..345acb2 100644 --- a/src/gaea.app/src/main/kotlin/com/synebula/gaea/app/struct/HttpMessage.kt +++ b/src/gaea/src/main/kotlin/com/synebula/gaea/data/message/HttpMessage.kt @@ -1,10 +1,12 @@ -package com.synebula.gaea.app.struct +package com.synebula.gaea.data.message + +import com.synebula.gaea.data.serialization.json.IJsonSerializer -import com.google.gson.Gson -import com.synebula.gaea.data.message.DataMessage class HttpMessage() : DataMessage() { + var serializer: IJsonSerializer? = null + constructor(data: Any) : this() { this.data = data } @@ -25,6 +27,6 @@ class HttpMessage() : DataMessage() { } override fun toString(): String { - return Gson().toJson(this) + return serializer?.serialize(this) ?: super.toString() } } \ No newline at end of file From 39e6e60dbd6812d254c75d38c8619cfd53b4a7a2 Mon Sep 17 00:00:00 2001 From: alex Date: Tue, 23 Aug 2022 16:59:37 +0800 Subject: [PATCH 14/14] =?UTF-8?q?=E9=87=8D=E6=9E=84=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/synebula/gaea/spring/aop/AppAspect.kt | 68 +++++++++++-------- .../spring/aop/handler/AccessLogHandler.kt | 4 +- .../spring/aop/handler/AnnotationHandler.kt | 13 +++- 3 files changed, 55 insertions(+), 30 deletions(-) diff --git a/src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/aop/AppAspect.kt b/src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/aop/AppAspect.kt index 6033e30..44f1029 100644 --- a/src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/aop/AppAspect.kt +++ b/src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/aop/AppAspect.kt @@ -36,36 +36,30 @@ abstract class AppAspect { */ @Around("func()") fun around(point: ProceedingJoinPoint): Any? { + val func = point.signature.declaringType.methods.find { + it.name == point.signature.name + }!!//获取声明类型中的方法信息 + val funcAnnotations = func.annotations ?: arrayOf() + + var funcName = func.name + //遍历方法注解 + for (funcAnnotation in funcAnnotations) { + if (funcAnnotation is Method) + funcName = funcAnnotation.name + + val annotations = funcAnnotation.annotationClass.annotations + //尝试寻找方法注解的处理类 + val handler = annotations.find { it is Handler } + if (handler != null && handler is Handler) { + val handleClazz = applicationContext.getBean(handler.value.java) + handleClazz.handle(point.`this`, func, point.args) + } + } + return try { point.proceed() } catch (ex: Throwable) { - val clazz = point.`this`.javaClass //获取实际对象的类型避免获取到父类 - val func = point.signature.declaringType.methods.find { - it.name == point.signature.name - }!!//获取声明类型中的方法信息 - val funcAnnotations = func.annotations ?: arrayOf() - - var funcName = func.name - //遍历方法注解 - for (funcAnnotation in funcAnnotations) { - val annotations = funcAnnotation.annotationClass.annotations - - //尝试寻找方法注解的处理类 - val handler = annotations.find { it is Handler } - if (handler != null && handler is Handler) { - val handleClazz = applicationContext.getBean(handler.value.java) - handleClazz.handle(clazz, func, point.args) - } - if (funcAnnotation is Method) - funcName = funcAnnotation.name - } - - //找到类的模块名称,否则使用类名 - var moduleName = clazz.simpleName - val module = clazz.annotations.find { it is Module } - if (module != null && module is Module) { - moduleName = module.name - } + val moduleName = this.resolveModuleName(point.`this`) var message = "$moduleName - ${funcName}异常" message = if (ex is NoticeUserException || ex is Error) { "$message: ${ex.message}" @@ -83,4 +77,24 @@ abstract class AppAspect { return HttpMessage(Status.Error, message) } } + + /** + * 解析模块名 + */ + private fun resolveModuleName(obj: Any): String { + val clazz = obj.javaClass + // 1.默认使用类名作为模块名 + var moduleName = clazz.simpleName + // 2.找到类的模块注解解析名称 + val module = clazz.annotations.find { it is Module } + if (module != null && module is Module) { + moduleName = module.name + } + // 3.尝试找类的name字段作为模块名称 + val nameField = clazz.fields.find { it.name == "name" } + if (nameField != null) { + moduleName = nameField.get(obj).toString() + } + return moduleName + } } \ No newline at end of file diff --git a/src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/aop/handler/AccessLogHandler.kt b/src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/aop/handler/AccessLogHandler.kt index c2f70da..a6d679c 100644 --- a/src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/aop/handler/AccessLogHandler.kt +++ b/src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/aop/handler/AccessLogHandler.kt @@ -15,11 +15,11 @@ class AccessLogHandler : AnnotationHandler { @Autowired lateinit var logger: ILogger - override fun handle(clazz: Class, func: Method, args: Array, exception: Exception?) { + override fun handle(obj: Any, func: Method, args: Array, exception: Exception?) { val attributes = RequestContextHolder.getRequestAttributes() as ServletRequestAttributes val request = attributes.request logger.info( - "${request.method} ${request.requestURL} from ${request.remoteAddr}, call function ${clazz.name}.${func.name}, args: ${ + "${request.method} ${request.requestURL} from ${request.remoteAddr}, call function ${func.toGenericString()}, args: ${ mapper.writeValueAsString( args ) diff --git a/src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/aop/handler/AnnotationHandler.kt b/src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/aop/handler/AnnotationHandler.kt index 5f98788..335a0f5 100644 --- a/src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/aop/handler/AnnotationHandler.kt +++ b/src/gaea.spring/src/main/kotlin/com/synebula/gaea/spring/aop/handler/AnnotationHandler.kt @@ -2,6 +2,17 @@ package com.synebula.gaea.spring.aop.handler import java.lang.reflect.Method +/** + * 注解对应的方法处理对象接口 + */ interface AnnotationHandler { - fun handle(clazz: Class, func: Method, args: Array, exception: Exception? = null) + + /** + * 处理“被注解方法”的方法 + * @param obj 处理的类对象 + * @param func 处理的方法 + * @param args 处理的方法参数信息 + * @param exception 处理的异常信息 + */ + fun handle(obj: Any, func: Method, args: Array, exception: Exception? = null) } \ No newline at end of file