You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@aries.apache.org by ti...@apache.org on 2020/09/11 17:09:52 UTC
[aries-typedevent] 01/01: Initial contribution of a minimal Typed
Event Service
This is an automated email from the ASF dual-hosted git repository.
timothyjward pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/aries-typedevent.git
commit e7a191c94c7b51e519297f92e13e53b361bcef95
Author: Tim Ward <ti...@apache.org>
AuthorDate: Fri Sep 11 17:59:15 2020 +0100
Initial contribution of a minimal Typed Event Service
This contribution is based on code originally written as part of the BRAIN-IoT project (http://www.brain-iot.eu). The BRAIN-IoT project has received funding from the European Union’s Horizon 2020 research and innovation programme under grant agreement No 780089.
---
.gitignore | 15 +
LICENSE | 202 ++++++++++
org.apache.aries.typedevent.bus/pom.xml | 71 ++++
.../aries/typedevent/bus/impl/EventConverter.java | 237 ++++++++++++
.../aries/typedevent/bus/impl/EventTask.java | 22 ++
.../typedevent/bus/impl/MonitorEventTask.java | 44 +++
.../bus/impl/TypedEventBusActivator.java | 226 ++++++++++++
.../typedevent/bus/impl/TypedEventBusImpl.java | 381 +++++++++++++++++++
.../typedevent/bus/impl/TypedEventMonitorImpl.java | 165 +++++++++
.../aries/typedevent/bus/impl/TypedEventTask.java | 46 +++
.../typedevent/bus/impl/UnhandledEventTask.java | 45 +++
.../typedevent/bus/impl/UntypedEventTask.java | 45 +++
.../typedevent/bus/impl/EventConverterTest.java | 188 ++++++++++
.../typedevent/bus/impl/TypedEventBusImplTest.java | 405 +++++++++++++++++++++
pom.xml | 203 +++++++++++
15 files changed, 2295 insertions(+)
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..7081da0
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,15 @@
+.project
+.settings
+.idea
+*.iml
+.classpath
+.project
+.settings/
+*/bin/
+**/build/
+**/generated/
+**/personal.bnd
+**/target/
+*/*.jar
+*/cnf/
+*/TEST-*.xml
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..d645695
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ 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.
diff --git a/org.apache.aries.typedevent.bus/pom.xml b/org.apache.aries.typedevent.bus/pom.xml
new file mode 100644
index 0000000..db237cf
--- /dev/null
+++ b/org.apache.aries.typedevent.bus/pom.xml
@@ -0,0 +1,71 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor
+ license agreements. See the NOTICE file distributed with this work for additional
+ information regarding copyright ownership. The ASF licenses this file to
+ you under the Apache License, Version 2.0 (the "License"); you may not use
+ this file except in compliance with the License. You may obtain a copy of
+ the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required
+ by applicable law or agreed to in writing, software distributed under the
+ License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
+ OF ANY KIND, either express or implied. See the License for the specific
+ language governing permissions and limitations under the License. -->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>org.apache.aries.typedevent</groupId>
+ <artifactId>typedevent-parent</artifactId>
+ <version>0.0.1-SNAPSHOT</version>
+ <relativePath>../</relativePath>
+ </parent>
+
+ <artifactId>org.apache.aries.typedevent.bus</artifactId>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.osgi</groupId>
+ <artifactId>org.osgi.core</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.osgi</groupId>
+ <artifactId>org.osgi.service.typedevent</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.osgi</groupId>
+ <artifactId>osgi.annotation</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.osgi</groupId>
+ <artifactId>org.osgi.annotation.bundle</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.osgi</groupId>
+ <artifactId>org.osgi.namespace.service</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.aries.component-dsl</groupId>
+ <artifactId>org.apache.aries.component-dsl.component-dsl</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>org.apache.felix.converter</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-core</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-junit-jupiter</artifactId>
+ </dependency>
+ </dependencies>
+</project>
\ No newline at end of file
diff --git a/org.apache.aries.typedevent.bus/src/main/java/org/apache/aries/typedevent/bus/impl/EventConverter.java b/org.apache.aries.typedevent.bus/src/main/java/org/apache/aries/typedevent/bus/impl/EventConverter.java
new file mode 100644
index 0000000..93d0d6f
--- /dev/null
+++ b/org.apache.aries.typedevent.bus/src/main/java/org/apache/aries/typedevent/bus/impl/EventConverter.java
@@ -0,0 +1,237 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.aries.typedevent.bus.impl;
+
+import static java.lang.ThreadLocal.withInitial;
+import static java.util.Collections.newSetFromMap;
+
+import java.lang.reflect.Array;
+import java.lang.reflect.Type;
+import java.time.Duration;
+import java.time.Instant;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.LocalTime;
+import java.time.MonthDay;
+import java.time.OffsetDateTime;
+import java.time.OffsetTime;
+import java.time.Year;
+import java.time.YearMonth;
+import java.time.ZonedDateTime;
+import java.util.Calendar;
+import java.util.Collection;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.IdentityHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+
+import org.osgi.framework.Filter;
+import org.osgi.util.converter.Converter;
+import org.osgi.util.converter.ConverterFunction;
+import org.osgi.util.converter.Converters;
+import org.osgi.util.converter.TypeReference;
+
+/**
+ * This class is responsible for converting events to and from their "flattened"
+ * representations. A "flattened" event uses Maps rather than DTOs and Strings
+ * rather than enums. This makes a flattened event readable by anyone, even if
+ * they don't have access to the necessary API types
+ */
+public class EventConverter {
+
+ private static final TypeReference<List<Object>> LIST_OF_OBJECTS = new TypeReference<List<Object>>() {
+ };
+ private static final TypeReference<Set<Object>> SET_OF_OBJECTS = new TypeReference<Set<Object>>() {
+ };
+ private static final TypeReference<Map<String, Object>> MAP_WITH_STRING_KEYS = new TypeReference<Map<String, Object>>() {
+ };
+ private static final TypeReference<Map<Object, Object>> MAP_OF_OBJECT_TO_OBJECT = new TypeReference<Map<Object, Object>>() {
+ };
+
+ private static final Converter eventConverter;
+ private static final Set<Class<?>> safeClasses;
+ private static final Set<Class<?>> specialClasses;
+ private static final ThreadLocal<Set<Object>> errorsBeingHandled = withInitial(
+ () -> newSetFromMap(new IdentityHashMap<>()));
+
+ static {
+ safeClasses = new HashSet<>();
+ safeClasses.add(String.class);
+ safeClasses.add(Boolean.class);
+ safeClasses.add(Byte.class);
+ safeClasses.add(Short.class);
+ safeClasses.add(Character.class);
+ safeClasses.add(Integer.class);
+ safeClasses.add(Long.class);
+ safeClasses.add(Float.class);
+ safeClasses.add(Double.class);
+
+ specialClasses = new HashSet<Class<?>>();
+ specialClasses.add(Date.class);
+ specialClasses.add(Calendar.class);
+ specialClasses.add(Duration.class);
+ specialClasses.add(Instant.class);
+ specialClasses.add(LocalDate.class);
+ specialClasses.add(LocalDateTime.class);
+ specialClasses.add(LocalTime.class);
+ specialClasses.add(MonthDay.class);
+ specialClasses.add(OffsetTime.class);
+ specialClasses.add(OffsetDateTime.class);
+ specialClasses.add(Year.class);
+ specialClasses.add(YearMonth.class);
+ specialClasses.add(ZonedDateTime.class);
+ specialClasses.add(UUID.class);
+
+ eventConverter = Converters.standardConverter().newConverterBuilder().rule(EventConverter::convert)
+ .errorHandler(EventConverter::attemptRecovery).build();
+ }
+
+ static Object convert(Object o, Type target) {
+
+ if (target != Object.class || o == null) {
+ return ConverterFunction.CANNOT_HANDLE;
+ }
+
+ Class<? extends Object> sourceClass = o.getClass();
+
+ // "Safe" classes use an identity transform
+ if (safeClasses.contains(sourceClass)) {
+ return o;
+ }
+
+ // "Special" types and Enums map to strings
+ if (specialClasses.contains(sourceClass) || sourceClass.isEnum()) {
+ return eventConverter.convert(o).sourceAs(Object.class).to(String.class);
+ }
+
+ // Collections get remapped using the same converter to
+ // the relevant collection type containing objects, this
+ // ensures we pick up any embedded lists of DTOs or enums
+ if (o instanceof Collection) {
+ if (o instanceof Set) {
+ return eventConverter.convert(o).to(SET_OF_OBJECTS);
+ } else {
+ return eventConverter.convert(o).to(LIST_OF_OBJECTS);
+ }
+ }
+
+ // As with collections we remap nested maps to clean up any
+ // undesirable types in the keys or values
+ if (o instanceof Map) {
+ return eventConverter.convert(o).to(MAP_OF_OBJECT_TO_OBJECT);
+ }
+
+ if (sourceClass.isArray()) {
+ int depth = 1;
+ Class<?> arrayComponentType = sourceClass.getComponentType();
+ Class<?> actualComponentType = sourceClass.getComponentType();
+ while (actualComponentType.isArray()) {
+ depth++;
+ actualComponentType = actualComponentType.getComponentType();
+ }
+ if (safeClasses.contains(actualComponentType) || actualComponentType.isPrimitive()) {
+ return o;
+ } else if (actualComponentType.isEnum()) {
+ // This becomes an n dimensional String array
+ Class<?> stringArrayType = Array.newInstance(String.class, new int[depth]).getClass();
+ return eventConverter.convert(o).to(stringArrayType);
+ } else {
+ // This is an array of something complicated, recursively turn it into a
+ // list of something, then make it into an array of the right type
+ List<Object> oList = eventConverter.convert(o).to(LIST_OF_OBJECTS);
+ return oList.toArray((Object[]) Array.newInstance(arrayComponentType, 0));
+ }
+ }
+
+ // If we get here then treat the type as a DTO
+ return eventConverter.convert(o).sourceAsDTO().to(MAP_WITH_STRING_KEYS);
+ }
+
+ static Object attemptRecovery(Object o, Type target) {
+ if (o instanceof Map) {
+ Set<Object> errors = errorsBeingHandled.get();
+
+ if (errors.contains(o)) {
+ // TODO log the warning in a big way
+ return ConverterFunction.CANNOT_HANDLE;
+ }
+
+ try {
+ errors.add(o);
+
+ // TODO log the warning in a big way
+
+ return eventConverter.convert(o).targetAsDTO().to(target);
+ } finally {
+ errors.remove(o);
+ }
+ }
+ return ConverterFunction.CANNOT_HANDLE;
+ }
+
+ private final Object originalEvent;
+
+ private Map<String, ?> untypedEventDataForFiltering;
+
+ private EventConverter(Object event) {
+ this.originalEvent = event;
+ }
+
+ private EventConverter(Map<String, ?> untypedEvent) {
+ this.originalEvent = untypedEvent;
+ this.untypedEventDataForFiltering = untypedEvent;
+ }
+
+ public static EventConverter forTypedEvent(Object event) {
+ return new EventConverter(event);
+ }
+
+ public static EventConverter forUntypedEvent(Map<String, ?> event) {
+ return new EventConverter(event);
+ }
+
+ public boolean applyFilter(Filter f) {
+ Map<String, ?> toTest;
+ if (untypedEventDataForFiltering == null) {
+ toTest = toUntypedEvent();
+ } else {
+ toTest = untypedEventDataForFiltering;
+ }
+
+ return f.matches(toTest);
+ }
+
+ public Map<String, ?> toUntypedEvent() {
+ if (untypedEventDataForFiltering == null) {
+ untypedEventDataForFiltering = eventConverter.convert(originalEvent).sourceAsDTO().to(MAP_WITH_STRING_KEYS);
+ }
+ return untypedEventDataForFiltering;
+ }
+
+ public <T> T toTypedEvent(Class<T> clazz) {
+ if (clazz.isInstance(originalEvent)) {
+ return clazz.cast(originalEvent);
+ } else {
+ return eventConverter.convert(originalEvent).targetAsDTO().to(clazz);
+ }
+ }
+
+}
\ No newline at end of file
diff --git a/org.apache.aries.typedevent.bus/src/main/java/org/apache/aries/typedevent/bus/impl/EventTask.java b/org.apache.aries.typedevent.bus/src/main/java/org/apache/aries/typedevent/bus/impl/EventTask.java
new file mode 100644
index 0000000..67b77fb
--- /dev/null
+++ b/org.apache.aries.typedevent.bus/src/main/java/org/apache/aries/typedevent/bus/impl/EventTask.java
@@ -0,0 +1,22 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.aries.typedevent.bus.impl;
+
+abstract class EventTask {
+ public abstract void notifyListener();
+}
\ No newline at end of file
diff --git a/org.apache.aries.typedevent.bus/src/main/java/org/apache/aries/typedevent/bus/impl/MonitorEventTask.java b/org.apache.aries.typedevent.bus/src/main/java/org/apache/aries/typedevent/bus/impl/MonitorEventTask.java
new file mode 100644
index 0000000..1336cb5
--- /dev/null
+++ b/org.apache.aries.typedevent.bus/src/main/java/org/apache/aries/typedevent/bus/impl/MonitorEventTask.java
@@ -0,0 +1,44 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.aries.typedevent.bus.impl;
+
+import java.util.Map;
+
+class MonitorEventTask extends EventTask {
+
+ private final String eventType;
+ private final EventConverter eventData;
+ private final TypedEventMonitorImpl monitorImpl;
+
+ public MonitorEventTask(String eventType, EventConverter eventData, TypedEventMonitorImpl monitorImpl) {
+ super();
+ this.eventType = eventType;
+ this.eventData = eventData;
+ this.monitorImpl = monitorImpl;
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public void notifyListener() {
+ try {
+ monitorImpl.event(eventType, (Map<String, Object>) eventData.toUntypedEvent());
+ } catch (Exception e) {
+ // TODO log this, also blacklist?
+ }
+ }
+}
\ No newline at end of file
diff --git a/org.apache.aries.typedevent.bus/src/main/java/org/apache/aries/typedevent/bus/impl/TypedEventBusActivator.java b/org.apache.aries.typedevent.bus/src/main/java/org/apache/aries/typedevent/bus/impl/TypedEventBusActivator.java
new file mode 100644
index 0000000..af61b3f
--- /dev/null
+++ b/org.apache.aries.typedevent.bus/src/main/java/org/apache/aries/typedevent/bus/impl/TypedEventBusActivator.java
@@ -0,0 +1,226 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.aries.typedevent.bus.impl;
+
+import static java.util.function.Function.identity;
+
+import java.util.Arrays;
+import java.util.Dictionary;
+import java.util.HashMap;
+import java.util.Hashtable;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.stream.Collectors;
+
+import org.osgi.annotation.bundle.Header;
+import org.osgi.framework.BundleActivator;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.Constants;
+import org.osgi.framework.ServiceReference;
+import org.osgi.framework.ServiceRegistration;
+import org.osgi.service.typedevent.TypedEventBus;
+import org.osgi.service.typedevent.TypedEventHandler;
+import org.osgi.service.typedevent.UnhandledEventHandler;
+import org.osgi.service.typedevent.UntypedEventHandler;
+import org.osgi.service.typedevent.monitor.TypedEventMonitor;
+import org.osgi.util.tracker.ServiceTracker;
+import org.osgi.util.tracker.ServiceTrackerCustomizer;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Header(name = Constants.BUNDLE_ACTIVATOR, value = "${@class}")
+public class TypedEventBusActivator implements BundleActivator {
+
+ private static final Logger _log = LoggerFactory.getLogger(TypedEventBusActivator.class);
+
+ private TypedEventMonitorImpl monitorImpl;
+ private ServiceRegistration<TypedEventMonitor> monitorReg;
+
+ private TypedEventBusImpl busImpl;
+ private ServiceRegistration<TypedEventBus> busReg;
+
+ private ServiceTracker<TypedEventHandler<?>, TypedEventHandler<?>> typedTracker;
+ private ServiceTracker<UntypedEventHandler, UntypedEventHandler> untypedTracker;
+ private ServiceTracker<UnhandledEventHandler, UnhandledEventHandler> unhandledTracker;
+
+ @Override
+ public void start(BundleContext bundleContext) throws Exception {
+ if (_log.isDebugEnabled()) {
+ _log.debug("Aries Typed Event Bus Starting");
+ }
+
+ // TODO use Config Admin
+
+ Map<String, Object> map = new HashMap<String, Object>();
+
+ createEventBus(bundleContext, map);
+
+ if (_log.isDebugEnabled()) {
+ _log.debug("Aries Typed Event Bus Started");
+ }
+ }
+
+ private void createEventBus(BundleContext bundleContext, Map<String, ?> configuration) throws Exception {
+
+ Dictionary<String, Object> serviceProps = toServiceProps(configuration);
+
+ monitorImpl = new TypedEventMonitorImpl(configuration);
+ busImpl = new TypedEventBusImpl(monitorImpl, configuration);
+
+ untypedTracker = new ServiceTracker<>(bundleContext, UntypedEventHandler.class,
+ new ServiceTrackerCustomizer<UntypedEventHandler, UntypedEventHandler>() {
+
+ @Override
+ public UntypedEventHandler addingService(ServiceReference<UntypedEventHandler> reference) {
+ UntypedEventHandler service = bundleContext.getService(reference);
+ busImpl.addUntypedEventHandler(service, getServiceProps(reference));
+ return service;
+ }
+
+ @Override
+ public void modifiedService(ServiceReference<UntypedEventHandler> reference,
+ UntypedEventHandler service) {
+ busImpl.updatedUntypedEventHandler(service, getServiceProps(reference));
+ }
+
+ @Override
+ public void removedService(ServiceReference<UntypedEventHandler> reference,
+ UntypedEventHandler service) {
+ busImpl.removeUntypedEventHandler(service, getServiceProps(reference));
+ }
+ });
+
+ untypedTracker = new ServiceTracker<>(bundleContext, UntypedEventHandler.class,
+ new ServiceTrackerCustomizer<UntypedEventHandler, UntypedEventHandler>() {
+
+ @Override
+ public UntypedEventHandler addingService(ServiceReference<UntypedEventHandler> reference) {
+ UntypedEventHandler service = bundleContext.getService(reference);
+ busImpl.addUntypedEventHandler(service, getServiceProps(reference));
+ return service;
+ }
+
+ @Override
+ public void modifiedService(ServiceReference<UntypedEventHandler> reference,
+ UntypedEventHandler service) {
+ busImpl.updatedUntypedEventHandler(service, getServiceProps(reference));
+ }
+
+ @Override
+ public void removedService(ServiceReference<UntypedEventHandler> reference,
+ UntypedEventHandler service) {
+ busImpl.removeUntypedEventHandler(service, getServiceProps(reference));
+ }
+ });
+
+ unhandledTracker = new ServiceTracker<>(bundleContext, UnhandledEventHandler.class,
+ new ServiceTrackerCustomizer<UnhandledEventHandler, UnhandledEventHandler>() {
+
+ @Override
+ public UnhandledEventHandler addingService(ServiceReference<UnhandledEventHandler> reference) {
+ UnhandledEventHandler service = bundleContext.getService(reference);
+ busImpl.addUnhandledEventHandler(service, getServiceProps(reference));
+ return service;
+ }
+
+ @Override
+ public void modifiedService(ServiceReference<UnhandledEventHandler> reference,
+ UnhandledEventHandler service) {
+ }
+
+ @Override
+ public void removedService(ServiceReference<UnhandledEventHandler> reference,
+ UnhandledEventHandler service) {
+ busImpl.removeUnhandledEventHandler(service, getServiceProps(reference));
+ }
+ });
+
+ try {
+ busImpl.start();
+
+ monitorReg = bundleContext.registerService(TypedEventMonitor.class, monitorImpl, serviceProps);
+
+ typedTracker.open();
+ untypedTracker.open();
+ unhandledTracker.open();
+
+ busReg = bundleContext.registerService(TypedEventBus.class, busImpl, serviceProps);
+
+ } catch (Exception e) {
+ stop(bundleContext);
+ }
+
+ }
+
+ private void safeUnregister(ServiceRegistration<?> reg) {
+ try {
+ reg.unregister();
+ } catch (IllegalStateException ise) {
+ // no op
+ // TODO LOG this
+ }
+
+ }
+
+ private Dictionary<String, Object> toServiceProps(Map<String, ?> config) {
+ return config.entrySet().stream().filter(e -> e.getKey() != null && e.getKey().startsWith("."))
+ .collect(Collectors.toMap(Entry::getKey, Entry::getValue, (a, b) -> {
+ throw new IllegalArgumentException("Duplicate key ");
+ }, Hashtable::new));
+ }
+
+ private Map<String, Object> getServiceProps(ServiceReference<?> ref) {
+ return Arrays.stream(ref.getPropertyKeys()).collect(Collectors.toMap(identity(), ref::getProperty));
+ }
+
+ @Override
+ public void stop(BundleContext context) throws Exception {
+ if (_log.isDebugEnabled()) {
+ _log.debug("Aries Typed Event Bus Stopping");
+ }
+
+ // Order matters here
+ if (busReg != null) {
+ safeUnregister(busReg);
+ }
+
+ if (busImpl != null) {
+ busImpl.stop();
+ }
+
+ if (typedTracker != null) {
+ typedTracker.close();
+ }
+ if (untypedTracker != null) {
+ untypedTracker.close();
+ }
+ if (unhandledTracker != null) {
+ unhandledTracker.close();
+ }
+
+ if (monitorReg != null) {
+ safeUnregister(monitorReg);
+ }
+
+ monitorImpl.destroy();
+
+ if (_log.isDebugEnabled()) {
+ _log.debug("Aries Typed Event Bus Stopped");
+ }
+ }
+}
\ No newline at end of file
diff --git a/org.apache.aries.typedevent.bus/src/main/java/org/apache/aries/typedevent/bus/impl/TypedEventBusImpl.java b/org.apache.aries.typedevent.bus/src/main/java/org/apache/aries/typedevent/bus/impl/TypedEventBusImpl.java
new file mode 100644
index 0000000..b23df64
--- /dev/null
+++ b/org.apache.aries.typedevent.bus/src/main/java/org/apache/aries/typedevent/bus/impl/TypedEventBusImpl.java
@@ -0,0 +1,381 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.aries.typedevent.bus.impl;
+
+import static java.util.Collections.emptyMap;
+import static java.util.stream.Collectors.toList;
+import static org.osgi.util.converter.Converters.standardConverter;
+
+import java.lang.reflect.ParameterizedType;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Function;
+import java.util.stream.Stream;
+
+import org.osgi.framework.Constants;
+import org.osgi.framework.Filter;
+import org.osgi.framework.FrameworkUtil;
+import org.osgi.framework.InvalidSyntaxException;
+import org.osgi.service.typedevent.TypedEventBus;
+import org.osgi.service.typedevent.TypedEventConstants;
+import org.osgi.service.typedevent.TypedEventHandler;
+import org.osgi.service.typedevent.UnhandledEventHandler;
+import org.osgi.service.typedevent.UntypedEventHandler;
+import org.osgi.util.converter.TypeReference;
+
+public class TypedEventBusImpl implements TypedEventBus {
+
+ private static final TypeReference<List<String>> LIST_OF_STRINGS = new TypeReference<List<String>>() {
+ };
+
+ private final Object lock = new Object();
+
+ private final TypedEventMonitorImpl monitorImpl;
+
+ /**
+ * Map access and mutation must be synchronized on {@link #lock}. Values from
+ * the map should be copied as the contents are not thread safe.
+ */
+ private final Map<String, Map<TypedEventHandler<?>, Filter>> topicsToTypedHandlers = new HashMap<>();
+
+ /**
+ * Map access and mutation must be synchronized on {@link #lock}. Values from
+ * the map should be copied as the contents are not thread safe.
+ */
+ private final Map<TypedEventHandler<?>, Class<?>> typedHandlersToTargetClasses = new HashMap<>();
+
+ /**
+ * Map access and mutation must be synchronized on {@link #lock}. Values from
+ * the map should be copied as the contents are not thread safe.
+ */
+ private final Map<String, Map<UntypedEventHandler, Filter>> topicsToUntypedHandlers = new HashMap<>();
+
+ /**
+ * List access and mutation must be synchronized on {@link #lock}.
+ */
+ private final List<UnhandledEventHandler> unhandledEventHandlers = new ArrayList<>();
+
+ /**
+ * Map access and mutation must be synchronized on {@link #lock}. Values from
+ * the map should be copied as the contents are not thread safe.
+ */
+ private final Map<Long, List<String>> knownHandlers = new HashMap<>();
+
+ private final BlockingQueue<EventTask> queue = new LinkedBlockingQueue<>();
+
+ /**
+ *
+ * Field access must be synchronized on {@link #threadLock}
+ */
+ private EventThread thread;
+
+ private final Object threadLock = new Object();
+
+ public TypedEventBusImpl(TypedEventMonitorImpl monitorImpl, Map<String, ?> config) {
+ this.monitorImpl = monitorImpl;
+ }
+
+ void addTypedEventHandler(TypedEventHandler<?> handler, Map<String, Object> properties) {
+ // TODO try to extract topic name reflectively
+ String defaultTopic = null;
+
+ Object type = properties.get(TypedEventConstants.TYPED_EVENT_TYPE);
+ if (type != null) {
+ defaultTopic = String.valueOf(type).replace(".", "/");
+ try {
+ Class<?> clazz = handler.getClass().getClassLoader().loadClass(String.valueOf(type));
+
+ synchronized (lock) {
+ typedHandlersToTargetClasses.put(handler, clazz);
+ }
+ } catch (ClassNotFoundException e) {
+ // TODO Blow up
+ e.printStackTrace();
+ }
+ } else {
+ Class<?> clazz = Arrays.stream(handler.getClass().getGenericInterfaces())
+ .filter(ParameterizedType.class::isInstance).map(ParameterizedType.class::cast)
+ .filter(t -> TypedEventHandler.class.equals(t.getRawType())).map(t -> t.getActualTypeArguments()[0])
+ .findFirst().map(Class.class::cast).orElse(null);
+
+ if (clazz != null) {
+ defaultTopic = String.valueOf(type).replace(".", "/");
+ synchronized (lock) {
+ typedHandlersToTargetClasses.put(handler, clazz);
+ }
+ } else {
+ // TODO Blow Up
+ }
+ }
+
+ doAddEventHandler(topicsToTypedHandlers, handler, defaultTopic, properties);
+ }
+
+ void addUntypedEventHandler(UntypedEventHandler handler, Map<String, Object> properties) {
+ doAddEventHandler(topicsToUntypedHandlers, handler, null, properties);
+ }
+
+ private <T> void doAddEventHandler(Map<String, Map<T, Filter>> map, T handler, String defaultTopic,
+ Map<String, Object> properties) {
+
+ Object prop = properties.get(TypedEventConstants.TYPED_EVENT_TOPICS);
+
+ List<String> topicList;
+ if (prop == null) {
+ if (defaultTopic == null) {
+ // TODO log a broken handler
+ return;
+ } else {
+ topicList = Collections.singletonList(defaultTopic);
+ }
+ } else {
+ topicList = standardConverter().convert(prop).to(LIST_OF_STRINGS);
+ }
+
+ Long serviceId = getServiceId(properties);
+
+ Filter f;
+ try {
+ f = getFilter(serviceId, properties);
+ } catch (IllegalArgumentException e) {
+ // TODO Log a broken handler
+ e.printStackTrace();
+ return;
+ }
+
+ doAddToMap(map, handler, x -> f, topicList, serviceId);
+ }
+
+ private <T, U> void doAddToMap(Map<String, Map<T, U>> map, T handler, Function<String, U> valueSupplier,
+ List<String> list, Long serviceId) {
+ synchronized (lock) {
+ knownHandlers.put(serviceId, list);
+
+ list.forEach(s -> {
+ Map<T, U> handlers = map.computeIfAbsent(s, x -> new HashMap<>());
+ handlers.put(handler, valueSupplier.apply(s));
+ });
+ }
+ }
+
+ void removeTypedEventHandler(TypedEventHandler<?> handler, Map<String, Object> properties) {
+
+ Long serviceId = getServiceId(properties);
+
+ doRemoveEventHandler(topicsToTypedHandlers, handler, serviceId);
+
+ synchronized (lock) {
+ typedHandlersToTargetClasses.remove(handler);
+ }
+ }
+
+ void removeUntypedEventHandler(UntypedEventHandler handler, Map<String, Object> properties) {
+
+ Long serviceId = getServiceId(properties);
+
+ doRemoveEventHandler(topicsToUntypedHandlers, handler, serviceId);
+ }
+
+ private Long getServiceId(Map<String, Object> properties) {
+ return standardConverter().convert(properties.get(Constants.SERVICE_ID)).to(Long.class);
+ }
+
+ private Filter getFilter(Long serviceId, Map<String, Object> properties) throws IllegalArgumentException {
+ String key = "event.filter";
+ return getFilter(serviceId, key, properties.get(key));
+ }
+
+ private Filter getFilter(Long serviceId, String key, Object o) throws IllegalArgumentException {
+ if (o == null || "".equals(o)) {
+ return null;
+ } else {
+ try {
+ return FrameworkUtil.createFilter(String.valueOf(o));
+ } catch (InvalidSyntaxException ise) {
+ throw new IllegalArgumentException("The filter associated with property " + key + "for service with id "
+ + serviceId + " is invalid", ise);
+ }
+ }
+ }
+
+ private <T, U> void doRemoveEventHandler(Map<String, Map<T, U>> map, T handler, Long serviceId) {
+ synchronized (lock) {
+ List<String> consumed = knownHandlers.remove(serviceId);
+ if (consumed != null) {
+ consumed.forEach(s -> {
+ Map<T, ?> handlers = map.get(s);
+ if (handlers != null) {
+ handlers.remove(handler);
+ if (handlers.isEmpty()) {
+ map.remove(s);
+ }
+ }
+ });
+ }
+ }
+ }
+
+ void updatedTypedEventHandler(TypedEventHandler<?> handler, Map<String, Object> properties) {
+ // TODO try to extract topic name reflectively
+ String defaultTopic = null;
+ doUpdatedEventHandler(topicsToTypedHandlers, handler, defaultTopic, properties);
+ }
+
+ void updatedUntypedEventHandler(UntypedEventHandler handler, Map<String, Object> properties) {
+ doUpdatedEventHandler(topicsToUntypedHandlers, handler, null, properties);
+ }
+
+ private <T> void doUpdatedEventHandler(Map<String, Map<T, Filter>> map, T handler, String defaultTopic,
+ Map<String, Object> properties) {
+ Long serviceId = getServiceId(properties);
+
+ synchronized (lock) {
+ doRemoveEventHandler(map, handler, serviceId);
+ doAddEventHandler(map, handler, defaultTopic, properties);
+ }
+ }
+
+ void addUnhandledEventHandler(UnhandledEventHandler handler, Map<String, Object> properties) {
+ synchronized (lock) {
+ unhandledEventHandlers.add(handler);
+ }
+ }
+
+ void removeUnhandledEventHandler(UnhandledEventHandler handler, Map<String, Object> properties) {
+ synchronized (lock) {
+ unhandledEventHandlers.remove(handler);
+ }
+ }
+
+ void start() {
+
+ EventThread thread = new EventThread();
+
+ synchronized (threadLock) {
+ this.thread = thread;
+ }
+
+ thread.start();
+ }
+
+ void stop() {
+ EventThread thread;
+
+ synchronized (threadLock) {
+ thread = this.thread;
+ this.thread = null;
+ }
+
+ thread.shutdown();
+
+ try {
+ thread.join(2000);
+ } catch (InterruptedException e) {
+ // This is not an error, it just means that we should stop
+ // waiting and let the interrupt propagate
+ Thread.currentThread().interrupt();
+ }
+ monitorImpl.destroy();
+ }
+
+ @Override
+ public void deliver(Object event) {
+ String topicName = event.getClass().getName().replace('.', '/');
+ deliver(topicName, event);
+ }
+
+ @Override
+ public void deliver(String topic, Object event) {
+ deliver(topic, EventConverter.forTypedEvent(event));
+ }
+
+ @Override
+ public void deliverUntyped(String topic, Map<String, ?> eventData) {
+ deliver(topic, EventConverter.forUntypedEvent(eventData));
+ }
+
+ private void deliver(String topic, EventConverter convertibleEventData) {
+
+ List<? extends EventTask> deliveryTasks;
+
+ synchronized (lock) {
+ Stream<EventTask> typedDeliveries = topicsToTypedHandlers.getOrDefault(topic, emptyMap()).entrySet()
+ .stream().filter(e -> e.getValue() == null || convertibleEventData.applyFilter(e.getValue()))
+ .map(Entry::getKey).map(handler -> new TypedEventTask(topic, convertibleEventData, handler,
+ typedHandlersToTargetClasses.get(handler)));
+
+ Stream<EventTask> untypedDeliveries = topicsToUntypedHandlers.getOrDefault(topic, emptyMap()).entrySet()
+ .stream().filter(e -> e.getValue() == null || convertibleEventData.applyFilter(e.getValue()))
+ .map(Entry::getKey).map(handler -> new UntypedEventTask(topic, convertibleEventData, handler));
+
+ deliveryTasks = Stream.concat(typedDeliveries, untypedDeliveries).collect(toList());
+
+ if (deliveryTasks.isEmpty()) {
+ // TODO log properly
+ System.out.println("Unhandled Event Handlers are being used for event sent to topic" + topic);
+ deliveryTasks = unhandledEventHandlers.stream()
+ .map(handler -> new UnhandledEventTask(topic, convertibleEventData, handler)).collect(toList());
+ }
+ }
+
+ queue.add(new MonitorEventTask(topic, convertibleEventData, monitorImpl));
+
+ queue.addAll(deliveryTasks);
+ }
+
+ private class EventThread extends Thread {
+
+ private final AtomicBoolean running = new AtomicBoolean(true);
+
+ public EventThread() {
+ super("BRAIN-IoT EventBus Delivery Thread");
+ }
+
+ public void shutdown() {
+ running.set(false);
+ interrupt();
+ }
+
+ public void run() {
+
+ while (running.get()) {
+
+ EventTask take;
+ try {
+ take = queue.take();
+ } catch (InterruptedException e) {
+ // TODO log the interrupt and continue
+ e.printStackTrace();
+ continue;
+ }
+
+ take.notifyListener();
+ }
+
+ }
+
+ }
+}
diff --git a/org.apache.aries.typedevent.bus/src/main/java/org/apache/aries/typedevent/bus/impl/TypedEventMonitorImpl.java b/org.apache.aries.typedevent.bus/src/main/java/org/apache/aries/typedevent/bus/impl/TypedEventMonitorImpl.java
new file mode 100644
index 0000000..309f384
--- /dev/null
+++ b/org.apache.aries.typedevent.bus/src/main/java/org/apache/aries/typedevent/bus/impl/TypedEventMonitorImpl.java
@@ -0,0 +1,165 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.aries.typedevent.bus.impl;
+
+import java.time.Instant;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.ListIterator;
+import java.util.Map;
+import java.util.concurrent.ArrayBlockingQueue;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+import org.osgi.annotation.bundle.Capability;
+import org.osgi.namespace.service.ServiceNamespace;
+import org.osgi.service.typedevent.monitor.MonitorEvent;
+import org.osgi.service.typedevent.monitor.TypedEventMonitor;
+import org.osgi.util.pushstream.PushEvent;
+import org.osgi.util.pushstream.PushEventSource;
+import org.osgi.util.pushstream.PushStream;
+import org.osgi.util.pushstream.PushStreamProvider;
+import org.osgi.util.pushstream.PushbackPolicyOption;
+import org.osgi.util.pushstream.QueuePolicyOption;
+import org.osgi.util.pushstream.SimplePushEventSource;
+
+@Capability(namespace = ServiceNamespace.SERVICE_NAMESPACE, attribute = "objectClass:List<String>=org.osgi.service.typedevent.monitor.TypedEventMonitor", uses = TypedEventMonitor.class)
+public class TypedEventMonitorImpl implements TypedEventMonitor {
+
+ private final LinkedList<MonitorEvent> historicEvents = new LinkedList<MonitorEvent>();
+
+ private final ExecutorService monitoringWorker;
+
+ private final Object lock = new Object();
+
+ private final PushStreamProvider psp;
+
+ private final SimplePushEventSource<MonitorEvent> source;
+
+ private final int historySize = 1024;
+
+ public TypedEventMonitorImpl(Map<String, ?> props) {
+
+ monitoringWorker = Executors.newCachedThreadPool();
+
+ psp = new PushStreamProvider();
+ source = psp.buildSimpleEventSource(MonitorEvent.class).withExecutor(monitoringWorker)
+ .withQueuePolicy(QueuePolicyOption.BLOCK).build();
+ }
+
+ public void destroy() {
+ source.close();
+ monitoringWorker.shutdown();
+ }
+
+ public void event(String topic, Map<String, Object> eventData) {
+ MonitorEvent me = new MonitorEvent();
+ me.eventData = eventData;
+ me.topic = topic;
+ me.publicationTime = Instant.now();
+
+ synchronized (lock) {
+ historicEvents.add(me);
+ int toRemove = historicEvents.size() - historySize;
+ for (; toRemove > 0; toRemove--) {
+ historicEvents.poll();
+ }
+ source.publish(me);
+ }
+ }
+
+ @Override
+ public PushStream<MonitorEvent> monitorEvents() {
+ return monitorEvents(0);
+ }
+
+ @Override
+ public PushStream<MonitorEvent> monitorEvents(int history) {
+ return psp.buildStream(eventSource(history))
+ .withBuffer(new ArrayBlockingQueue<>(Math.max(historySize, history)))
+ .withPushbackPolicy(PushbackPolicyOption.FIXED, 0).withQueuePolicy(QueuePolicyOption.FAIL)
+ .withExecutor(monitoringWorker).build();
+ }
+
+ @Override
+ public PushStream<MonitorEvent> monitorEvents(Instant history) {
+ return psp.buildStream(eventSource(history)).withBuffer(new ArrayBlockingQueue<>(1024))
+ .withPushbackPolicy(PushbackPolicyOption.FIXED, 0).withQueuePolicy(QueuePolicyOption.FAIL)
+ .withExecutor(monitoringWorker).build();
+ }
+
+ PushEventSource<MonitorEvent> eventSource(int events) {
+
+ return pec -> {
+ synchronized (lock) {
+
+ int size = historicEvents.size();
+ int start = Math.max(0, size - events);
+
+ List<MonitorEvent> list = historicEvents.subList(start, size);
+
+ for (MonitorEvent me : list) {
+ try {
+ if (pec.accept(PushEvent.data(me)) < 0) {
+ return () -> {
+ };
+ }
+ } catch (Exception e) {
+ return () -> {
+ };
+ }
+ }
+ return source.open(pec);
+ }
+
+ };
+ }
+
+ PushEventSource<MonitorEvent> eventSource(Instant since) {
+
+ return pec -> {
+ synchronized (lock) {
+
+ ListIterator<MonitorEvent> it = historicEvents.listIterator();
+
+ while (it.hasNext()) {
+ MonitorEvent next = it.next();
+ if (next.publicationTime.isAfter(since)) {
+ it.previous();
+ break;
+ }
+ }
+
+ while (it.hasNext()) {
+ try {
+ if (pec.accept(PushEvent.data(it.next())) < 0) {
+ return () -> {
+ };
+ }
+ } catch (Exception e) {
+ return () -> {
+ };
+ }
+ }
+ return source.open(pec);
+ }
+
+ };
+ }
+
+}
diff --git a/org.apache.aries.typedevent.bus/src/main/java/org/apache/aries/typedevent/bus/impl/TypedEventTask.java b/org.apache.aries.typedevent.bus/src/main/java/org/apache/aries/typedevent/bus/impl/TypedEventTask.java
new file mode 100644
index 0000000..e5a2459
--- /dev/null
+++ b/org.apache.aries.typedevent.bus/src/main/java/org/apache/aries/typedevent/bus/impl/TypedEventTask.java
@@ -0,0 +1,46 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.aries.typedevent.bus.impl;
+
+import org.osgi.service.typedevent.TypedEventHandler;
+
+class TypedEventTask extends EventTask {
+ private final String topic;
+ private final Class<?> targetEventClass;
+ private final EventConverter eventData;
+ private final TypedEventHandler<Object> eventProcessor;
+
+ @SuppressWarnings("unchecked")
+ public TypedEventTask(String topic, EventConverter eventData, TypedEventHandler<?> eventProcessor,
+ Class<?> targetEventClass) {
+ super();
+ this.topic = topic;
+ this.targetEventClass = targetEventClass;
+ this.eventData = eventData;
+ this.eventProcessor = (TypedEventHandler<Object>) eventProcessor;
+ }
+
+ @Override
+ public void notifyListener() {
+ try {
+ eventProcessor.notify(topic, eventData.toTypedEvent(targetEventClass));
+ } catch (Exception e) {
+ // TODO log this, also blacklist?
+ }
+ }
+}
\ No newline at end of file
diff --git a/org.apache.aries.typedevent.bus/src/main/java/org/apache/aries/typedevent/bus/impl/UnhandledEventTask.java b/org.apache.aries.typedevent.bus/src/main/java/org/apache/aries/typedevent/bus/impl/UnhandledEventTask.java
new file mode 100644
index 0000000..df2f495
--- /dev/null
+++ b/org.apache.aries.typedevent.bus/src/main/java/org/apache/aries/typedevent/bus/impl/UnhandledEventTask.java
@@ -0,0 +1,45 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.aries.typedevent.bus.impl;
+
+import java.util.Map;
+
+import org.osgi.service.typedevent.UnhandledEventHandler;
+
+class UnhandledEventTask extends EventTask {
+ private final String topic;
+ private final EventConverter eventData;
+ private final UnhandledEventHandler eventProcessor;
+
+ public UnhandledEventTask(String topic, EventConverter eventData, UnhandledEventHandler eventProcessor) {
+ super();
+ this.topic = topic;
+ this.eventData = eventData;
+ this.eventProcessor = eventProcessor;
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public void notifyListener() {
+ try {
+ eventProcessor.notifyUnhandled(topic, (Map<String, Object>) eventData.toUntypedEvent());
+ } catch (Exception e) {
+ // TODO log this, also blacklist?
+ }
+ }
+}
\ No newline at end of file
diff --git a/org.apache.aries.typedevent.bus/src/main/java/org/apache/aries/typedevent/bus/impl/UntypedEventTask.java b/org.apache.aries.typedevent.bus/src/main/java/org/apache/aries/typedevent/bus/impl/UntypedEventTask.java
new file mode 100644
index 0000000..884e4be
--- /dev/null
+++ b/org.apache.aries.typedevent.bus/src/main/java/org/apache/aries/typedevent/bus/impl/UntypedEventTask.java
@@ -0,0 +1,45 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.aries.typedevent.bus.impl;
+
+import java.util.Map;
+
+import org.osgi.service.typedevent.UntypedEventHandler;
+
+class UntypedEventTask extends EventTask {
+ private final String topic;
+ private final EventConverter eventData;
+ private final UntypedEventHandler eventProcessor;
+
+ public UntypedEventTask(String topic, EventConverter eventData, UntypedEventHandler eventProcessor) {
+ super();
+ this.topic = topic;
+ this.eventData = eventData;
+ this.eventProcessor = eventProcessor;
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public void notifyListener() {
+ try {
+ eventProcessor.notifyUntyped(topic, (Map<String, Object>) eventData.toUntypedEvent());
+ } catch (Exception e) {
+ // TODO log this, also blacklist?
+ }
+ }
+}
\ No newline at end of file
diff --git a/org.apache.aries.typedevent.bus/src/test/java/org/apache/aries/typedevent/bus/impl/EventConverterTest.java b/org.apache.aries.typedevent.bus/src/test/java/org/apache/aries/typedevent/bus/impl/EventConverterTest.java
new file mode 100644
index 0000000..98b4d19
--- /dev/null
+++ b/org.apache.aries.typedevent.bus/src/test/java/org/apache/aries/typedevent/bus/impl/EventConverterTest.java
@@ -0,0 +1,188 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.aries.typedevent.bus.impl;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+
+import java.util.Map;
+
+import org.junit.jupiter.api.Test;
+import org.osgi.util.converter.ConversionException;
+
+public class EventConverterTest {
+
+ public static class TestEvent {
+ public String message;
+ }
+
+ public static class NestedEventHolder {
+ public TestEvent event;
+ }
+
+ static class DefaultVisibilityNestedEventHolder {
+ public TestEvent event;
+ }
+
+ public static class NestedEventHolderNotAProperDTO {
+ public TestEvent event;
+
+ public static NestedEventHolderNotAProperDTO factory(TestEvent event) {
+ NestedEventHolderNotAProperDTO holder = new NestedEventHolderNotAProperDTO();
+ holder.event = event;
+ return holder;
+ }
+ }
+
+ public static class DoublyNestedEventHolderWithIssues {
+ public NestedEventHolderNotAProperDTO event;
+ }
+
+ @Test
+ public void testSimpleFlattenAndReconstitute() {
+
+ TestEvent te = new TestEvent();
+ te.message = "FOO";
+
+ Map<String, ?> map = EventConverter.forTypedEvent(te).toUntypedEvent();
+
+ assertEquals("FOO", map.get("message"));
+
+ TestEvent testEvent = EventConverter.forUntypedEvent(map).toTypedEvent(TestEvent.class);
+
+ assertEquals(te.message, testEvent.message);
+
+ }
+
+ @Test
+ public void testNestedFlattenAndReconstitute() {
+
+ TestEvent te = new TestEvent();
+ te.message = "FOO";
+
+ NestedEventHolder holder = new NestedEventHolder();
+ holder.event = te;
+
+ Map<String, ?> map = EventConverter.forTypedEvent(holder).toUntypedEvent();
+
+ @SuppressWarnings({ "unchecked" })
+ Map<String, Object> nested = (Map<String, Object>) map.get("event");
+ assertEquals("FOO", nested.get("message"));
+
+ NestedEventHolder testEvent = EventConverter.forUntypedEvent(map).toTypedEvent(NestedEventHolder.class);
+
+ assertEquals(te.message, testEvent.event.message);
+
+ }
+
+ @Test
+ public void testDefaultVisibiltyNestedFlattenAndReconstitute() {
+
+ TestEvent te = new TestEvent();
+ te.message = "FOO";
+
+ NestedEventHolder holder = new NestedEventHolder();
+ holder.event = te;
+
+ Map<String, ?> map = EventConverter.forTypedEvent(holder).toUntypedEvent();
+
+ @SuppressWarnings("unchecked")
+ Map<String, Object> nested = (Map<String, Object>) map.get("event");
+ assertEquals("FOO", nested.get("message"));
+
+ try {
+ EventConverter.forUntypedEvent(map).toTypedEvent(DefaultVisibilityNestedEventHolder.class);
+ fail("Should not succeed in creating a Default Visibility type");
+ } catch (ConversionException ce) {
+ assertEquals(IllegalAccessException.class, ce.getCause().getClass());
+ }
+ }
+
+ @Test
+ public void testNestedFlattenAndReconstituteNotAProperDTO() {
+
+ TestEvent te = new TestEvent();
+ te.message = "FOO";
+
+ NestedEventHolderNotAProperDTO holder = new NestedEventHolderNotAProperDTO();
+ holder.event = te;
+
+ Map<String, ?> map = EventConverter.forTypedEvent(holder).toUntypedEvent();
+
+ @SuppressWarnings("unchecked")
+ Map<String, Object> nested = (Map<String, Object>) map.get("event");
+ assertEquals("FOO", nested.get("message"));
+
+ NestedEventHolderNotAProperDTO testEvent = EventConverter.forUntypedEvent(map)
+ .toTypedEvent(NestedEventHolderNotAProperDTO.class);
+
+ assertEquals(te.message, testEvent.event.message);
+
+ }
+
+ @SuppressWarnings("unchecked")
+ @Test
+ public void testDoublyNestedFlattenAndReconstitute() {
+
+ TestEvent te = new TestEvent();
+ te.message = "FOO";
+
+ NestedEventHolderNotAProperDTO holder = new NestedEventHolderNotAProperDTO();
+ holder.event = te;
+
+ DoublyNestedEventHolderWithIssues doubleHolder = new DoublyNestedEventHolderWithIssues();
+ doubleHolder.event = holder;
+
+ Map<String, ?> map = EventConverter.forTypedEvent(doubleHolder).toUntypedEvent();
+
+ Map<String, Object> nested = (Map<String, Object>) map.get("event");
+ assertTrue(nested.containsKey("event"));
+ nested = (Map<String, Object>) nested.get("event");
+ assertEquals("FOO", nested.get("message"));
+
+ DoublyNestedEventHolderWithIssues testEvent = EventConverter.forUntypedEvent(map)
+ .toTypedEvent(DoublyNestedEventHolderWithIssues.class);
+
+ assertEquals(te.message, testEvent.event.event.message);
+
+ }
+
+ @Test
+ public void testNestedFlattenAndReconstituteIntoADifferentType() {
+
+ TestEvent te = new TestEvent();
+ te.message = "FOO";
+
+ NestedEventHolder holder = new NestedEventHolder();
+ holder.event = te;
+
+ Map<String, ?> map = EventConverter.forTypedEvent(holder).toUntypedEvent();
+
+ @SuppressWarnings("unchecked")
+ Map<String, Object> nested = (Map<String, Object>) map.get("event");
+ assertEquals("FOO", nested.get("message"));
+
+ NestedEventHolderNotAProperDTO testEvent = EventConverter.forUntypedEvent(map)
+ .toTypedEvent(NestedEventHolderNotAProperDTO.class);
+
+ assertEquals(te.message, testEvent.event.message);
+
+ }
+
+}
diff --git a/org.apache.aries.typedevent.bus/src/test/java/org/apache/aries/typedevent/bus/impl/TypedEventBusImplTest.java b/org.apache.aries.typedevent.bus/src/test/java/org/apache/aries/typedevent/bus/impl/TypedEventBusImplTest.java
new file mode 100644
index 0000000..6b8c67f
--- /dev/null
+++ b/org.apache.aries.typedevent.bus/src/test/java/org/apache/aries/typedevent/bus/impl/TypedEventBusImplTest.java
@@ -0,0 +1,405 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.aries.typedevent.bus.impl;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.quality.Strictness.LENIENT;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.Semaphore;
+import java.util.concurrent.TimeUnit;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.ArgumentMatcher;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.mockito.junit.jupiter.MockitoSettings;
+import org.osgi.framework.Constants;
+import org.osgi.service.typedevent.TypedEventConstants;
+import org.osgi.service.typedevent.TypedEventHandler;
+import org.osgi.service.typedevent.UnhandledEventHandler;
+import org.osgi.service.typedevent.UntypedEventHandler;
+import org.osgi.util.converter.Converters;
+
+@ExtendWith(MockitoExtension.class)
+@MockitoSettings(strictness = LENIENT)
+public class TypedEventBusImplTest {
+
+ public static class TestEvent {
+ public String message;
+ }
+
+ public static class TestEvent2 {
+ public int count;
+ }
+
+ @Mock
+ TypedEventHandler<Object> handlerA, handlerB;
+
+ @Mock
+ UntypedEventHandler untypedHandlerA, untypedHandlerB;
+
+ @Mock
+ UnhandledEventHandler unhandledHandler;
+
+ Semaphore semA = new Semaphore(0), semB = new Semaphore(0), untypedSemA = new Semaphore(0),
+ untypedSemB = new Semaphore(0), unhandledSem = new Semaphore(0);
+
+ TypedEventBusImpl impl;
+ TypedEventMonitorImpl monitorImpl;
+
+ @BeforeEach
+ public void start() {
+
+ Mockito.doAnswer(i -> {
+ semA.release();
+ return null;
+ }).when(handlerA).notify(Mockito.anyString(), Mockito.any());
+
+ Mockito.doAnswer(i -> {
+ semB.release();
+ return null;
+ }).when(handlerB).notify(Mockito.anyString(), Mockito.any());
+
+ Mockito.doAnswer(i -> {
+ untypedSemA.release();
+ return null;
+ }).when(untypedHandlerA).notifyUntyped(Mockito.anyString(), Mockito.any());
+
+ Mockito.doAnswer(i -> {
+ untypedSemB.release();
+ return null;
+ }).when(untypedHandlerB).notifyUntyped(Mockito.anyString(), Mockito.any());
+
+ Mockito.doAnswer(i -> {
+ unhandledSem.release();
+ return null;
+ }).when(unhandledHandler).notifyUnhandled(Mockito.anyString(), Mockito.any());
+
+ monitorImpl = new TypedEventMonitorImpl(new HashMap<String, Object>());
+
+ impl = new TypedEventBusImpl(monitorImpl, new HashMap<String, Object>());
+ impl.start();
+ }
+
+ @AfterEach
+ public void stop() {
+ impl.stop();
+ monitorImpl.destroy();
+ }
+
+ /**
+ * Tests that events are delivered to Smart Behaviours based on type
+ *
+ * @throws InterruptedException
+ */
+ @Test
+ public void testEventSending() throws InterruptedException {
+
+ TestEvent event = new TestEvent();
+ event.message = "boo";
+
+ Map<String, Object> serviceProperties = new HashMap<>();
+
+ serviceProperties.put(TypedEventConstants.TYPED_EVENT_TOPICS, TestEvent.class.getName().replace(".", "/"));
+ serviceProperties.put(TypedEventConstants.TYPED_EVENT_TYPE, TestEvent.class.getName());
+ serviceProperties.put(Constants.SERVICE_ID, 42L);
+
+ impl.addTypedEventHandler(handlerA, serviceProperties);
+
+ serviceProperties = new HashMap<>();
+
+ serviceProperties.put(TypedEventConstants.TYPED_EVENT_TOPICS, TestEvent2.class.getName().replace(".", "/"));
+ serviceProperties.put(TypedEventConstants.TYPED_EVENT_TYPE, TestEvent2.class.getName());
+ serviceProperties.put(Constants.SERVICE_ID, 43L);
+
+ impl.addTypedEventHandler(handlerB, serviceProperties);
+
+ serviceProperties = new HashMap<>();
+
+ serviceProperties.put(TypedEventConstants.TYPED_EVENT_TOPICS, TestEvent.class.getName().replace(".", "/"));
+ serviceProperties.put(Constants.SERVICE_ID, 44L);
+
+ impl.addUntypedEventHandler(untypedHandlerA, serviceProperties);
+
+ serviceProperties = new HashMap<>();
+
+ serviceProperties.put(TypedEventConstants.TYPED_EVENT_TOPICS, TestEvent2.class.getName().replace(".", "/"));
+ serviceProperties.put(Constants.SERVICE_ID, 45L);
+
+ impl.addUntypedEventHandler(untypedHandlerB, serviceProperties);
+
+ impl.deliver(event);
+
+ assertTrue(semA.tryAcquire(1, TimeUnit.SECONDS));
+
+ Mockito.verify(handlerA).notify(Mockito.eq(TestEvent.class.getName().replace('.', '/')),
+ Mockito.argThat(isTestEventWithMessage("boo")));
+
+ assertFalse(semB.tryAcquire(1, TimeUnit.SECONDS));
+
+ assertTrue(untypedSemA.tryAcquire(1, TimeUnit.SECONDS));
+
+ Mockito.verify(untypedHandlerA).notifyUntyped(Mockito.eq(TestEvent.class.getName().replace('.', '/')),
+ Mockito.argThat(isUntypedTestEventWithMessage("boo")));
+
+ assertFalse(untypedSemB.tryAcquire(1, TimeUnit.SECONDS));
+
+ }
+
+ /**
+ * Tests that events are delivered to Smart Behaviours based on type
+ *
+ * @throws InterruptedException
+ */
+ @Test
+ public void testUntypedEventSending() throws InterruptedException {
+
+ TestEvent event = new TestEvent();
+ event.message = "boo";
+
+ Map<String, Object> serviceProperties = new HashMap<>();
+
+ serviceProperties.put(TypedEventConstants.TYPED_EVENT_TOPICS, TestEvent.class.getName());
+ serviceProperties.put(TypedEventConstants.TYPED_EVENT_TYPE, TestEvent.class.getName());
+ serviceProperties.put(Constants.SERVICE_ID, 42L);
+
+ impl.addTypedEventHandler(handlerA, serviceProperties);
+
+ serviceProperties = new HashMap<>();
+
+ serviceProperties.put(TypedEventConstants.TYPED_EVENT_TOPICS, TestEvent2.class.getName());
+ serviceProperties.put(TypedEventConstants.TYPED_EVENT_TYPE, TestEvent2.class.getName());
+ serviceProperties.put(Constants.SERVICE_ID, 43L);
+
+ impl.addTypedEventHandler(handlerB, serviceProperties);
+
+ serviceProperties = new HashMap<>();
+
+ serviceProperties.put(TypedEventConstants.TYPED_EVENT_TOPICS, TestEvent.class.getName());
+ serviceProperties.put(Constants.SERVICE_ID, 44L);
+
+ impl.addUntypedEventHandler(untypedHandlerA, serviceProperties);
+
+ serviceProperties = new HashMap<>();
+
+ serviceProperties.put(TypedEventConstants.TYPED_EVENT_TOPICS, TestEvent2.class.getName());
+ serviceProperties.put(Constants.SERVICE_ID, 45L);
+
+ impl.addUntypedEventHandler(untypedHandlerB, serviceProperties);
+
+ impl.deliver(event.getClass().getName(), Converters.standardConverter().convert(event).to(Map.class));
+
+ assertTrue(semA.tryAcquire(1, TimeUnit.SECONDS));
+
+ Mockito.verify(handlerA).notify(Mockito.eq(TestEvent.class.getName()),
+ Mockito.argThat(isTestEventWithMessage("boo")));
+
+ assertFalse(semB.tryAcquire(1, TimeUnit.SECONDS));
+
+ assertTrue(untypedSemA.tryAcquire(1, TimeUnit.SECONDS));
+
+ Mockito.verify(untypedHandlerA).notifyUntyped(Mockito.eq(TestEvent.class.getName()),
+ Mockito.argThat(isUntypedTestEventWithMessage("boo")));
+
+ assertFalse(untypedSemB.tryAcquire(1, TimeUnit.SECONDS));
+
+ }
+
+ /**
+ * Tests that filtering is applied to message sending/receiving
+ *
+ * @throws InterruptedException
+ */
+ @Test
+ public void testEventFiltering() throws InterruptedException {
+
+ Map<String, Object> serviceProperties = new HashMap<>();
+
+ serviceProperties.put(TypedEventConstants.TYPED_EVENT_TOPICS, TestEvent.class.getName().replace(".", "/"));
+ serviceProperties.put(TypedEventConstants.TYPED_EVENT_TYPE, TestEvent.class.getName());
+ serviceProperties.put("event.filter", "(message=foo)");
+ serviceProperties.put(Constants.SERVICE_ID, 42L);
+
+ impl.addTypedEventHandler(handlerA, serviceProperties);
+
+ serviceProperties = new HashMap<>();
+
+ serviceProperties.put(TypedEventConstants.TYPED_EVENT_TOPICS, TestEvent.class.getName().replace(".", "/"));
+ serviceProperties.put(TypedEventConstants.TYPED_EVENT_TYPE, TestEvent.class.getName());
+ serviceProperties.put("event.filter", "(message=bar)");
+ serviceProperties.put(Constants.SERVICE_ID, 43L);
+
+ impl.addTypedEventHandler(handlerB, serviceProperties);
+
+ serviceProperties = new HashMap<>();
+
+ serviceProperties.put(TypedEventConstants.TYPED_EVENT_TOPICS, TestEvent.class.getName().replace(".", "/"));
+ serviceProperties.put("event.filter", "(message=foo)");
+ serviceProperties.put(Constants.SERVICE_ID, 44L);
+
+ impl.addUntypedEventHandler(untypedHandlerA, serviceProperties);
+
+ serviceProperties = new HashMap<>();
+
+ serviceProperties.put(TypedEventConstants.TYPED_EVENT_TOPICS, TestEvent.class.getName().replace(".", "/"));
+ serviceProperties.put("event.filter", "(message=bar)");
+ serviceProperties.put(Constants.SERVICE_ID, 45L);
+
+ impl.addUntypedEventHandler(untypedHandlerB, serviceProperties);
+
+ TestEvent event = new TestEvent();
+ event.message = "foo";
+
+ impl.deliver(event);
+
+ assertTrue(semA.tryAcquire(1, TimeUnit.SECONDS));
+
+ Mockito.verify(handlerA).notify(Mockito.eq(TestEvent.class.getName().replace('.', '/')),
+ Mockito.argThat(isTestEventWithMessage("foo")));
+
+ assertFalse(semB.tryAcquire(1, TimeUnit.SECONDS));
+
+ assertTrue(untypedSemA.tryAcquire(1, TimeUnit.SECONDS));
+
+ Mockito.verify(untypedHandlerA).notifyUntyped(Mockito.eq(TestEvent.class.getName().replace('.', '/')),
+ Mockito.argThat(isUntypedTestEventWithMessage("foo")));
+
+ assertFalse(untypedSemB.tryAcquire(1, TimeUnit.SECONDS));
+
+ event = new TestEvent();
+ event.message = "bar";
+
+ impl.deliver(event);
+
+ assertTrue(semB.tryAcquire(1, TimeUnit.SECONDS));
+
+ Mockito.verify(handlerB).notify(Mockito.eq(TestEvent.class.getName().replace('.', '/')),
+ Mockito.argThat(isTestEventWithMessage("bar")));
+
+ assertFalse(semA.tryAcquire(1, TimeUnit.SECONDS));
+
+ assertTrue(untypedSemB.tryAcquire(1, TimeUnit.SECONDS));
+
+ Mockito.verify(untypedHandlerB).notifyUntyped(Mockito.eq(TestEvent.class.getName().replace('.', '/')),
+ Mockito.argThat(isUntypedTestEventWithMessage("bar")));
+
+ assertFalse(untypedSemA.tryAcquire(1, TimeUnit.SECONDS));
+ }
+
+ /**
+ * Tests that filtering is applied to message sending/receiving
+ *
+ * @throws InterruptedException
+ */
+ @Test
+ public void testEventFilteringWithEmptyStringFilter() throws InterruptedException {
+
+ Map<String, Object> serviceProperties = new HashMap<>();
+
+ serviceProperties.put(TypedEventConstants.TYPED_EVENT_TOPICS, TestEvent.class.getName().replace(".", "/"));
+ serviceProperties.put(TypedEventConstants.TYPED_EVENT_TYPE, TestEvent.class.getName());
+ serviceProperties.put("event.filter", "");
+ serviceProperties.put(Constants.SERVICE_ID, 42L);
+
+ impl.addTypedEventHandler(handlerA, serviceProperties);
+
+ TestEvent event = new TestEvent();
+ event.message = "foo";
+
+ impl.deliver(event);
+
+ assertTrue(semA.tryAcquire(1, TimeUnit.SECONDS));
+ }
+
+ /**
+ * Tests that the consumer of last resort gets called appropriately
+ *
+ * @throws InterruptedException
+ */
+ @Test
+ public void testUnhandledEventHandlers() throws InterruptedException {
+
+ Map<String, Object> serviceProperties = new HashMap<>();
+
+ serviceProperties.put(TypedEventConstants.TYPED_EVENT_TOPICS, TestEvent.class.getName().replace(".", "/"));
+ serviceProperties.put(TypedEventConstants.TYPED_EVENT_TYPE, TestEvent.class.getName());
+ serviceProperties.put("event.filter", "(message=foo)");
+ serviceProperties.put(Constants.SERVICE_ID, 42L);
+
+ impl.addTypedEventHandler(handlerA, serviceProperties);
+
+ serviceProperties = new HashMap<>();
+
+ serviceProperties.put(Constants.SERVICE_ID, 45L);
+
+ impl.addUnhandledEventHandler(unhandledHandler, serviceProperties);
+
+ TestEvent event = new TestEvent();
+ event.message = "foo";
+
+ impl.deliver(event);
+
+ assertTrue(semA.tryAcquire(1, TimeUnit.SECONDS));
+
+ Mockito.verify(handlerA).notify(Mockito.eq(TestEvent.class.getName().replace('.', '/')),
+ Mockito.argThat(isTestEventWithMessage("foo")));
+
+ assertFalse(unhandledSem.tryAcquire(1, TimeUnit.SECONDS));
+
+ event = new TestEvent();
+ event.message = "bar";
+
+ impl.deliver(event);
+
+ assertTrue(unhandledSem.tryAcquire(1, TimeUnit.SECONDS));
+
+ Mockito.verify(unhandledHandler).notifyUnhandled(Mockito.eq(TestEvent.class.getName().replace('.', '/')),
+ Mockito.argThat(isUntypedTestEventWithMessage("bar")));
+
+ assertFalse(semA.tryAcquire(1, TimeUnit.SECONDS));
+
+ }
+
+ ArgumentMatcher<Object> isTestEventWithMessage(String message) {
+ return new ArgumentMatcher<Object>() {
+
+ @Override
+ public boolean matches(Object argument) {
+ return argument instanceof TestEvent && message.equals(((TestEvent) argument).message);
+ }
+ };
+ }
+
+ ArgumentMatcher<Map<String, Object>> isUntypedTestEventWithMessage(String message) {
+ return new ArgumentMatcher<Map<String, Object>>() {
+
+ @Override
+ public boolean matches(Map<String, Object> argument) {
+ return argument != null && message.equals(argument.get("message"));
+ }
+ };
+ }
+
+}
diff --git a/pom.xml b/pom.xml
new file mode 100644
index 0000000..9ccbbbe
--- /dev/null
+++ b/pom.xml
@@ -0,0 +1,203 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor
+ license agreements. See the NOTICE file distributed with this work for additional
+ information regarding copyright ownership. The ASF licenses this file to
+ you under the Apache License, Version 2.0 (the "License"); you may not use
+ this file except in compliance with the License. You may obtain a copy of
+ the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required
+ by applicable law or agreed to in writing, software distributed under the
+ License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
+ OF ANY KIND, either express or implied. See the License for the specific
+ language governing permissions and limitations under the License. -->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>org.apache</groupId>
+ <artifactId>apache</artifactId>
+ <version>23</version>
+ <relativePath />
+ </parent>
+
+ <groupId>org.apache.aries.typedevent</groupId>
+ <artifactId>typedevent-parent</artifactId>
+ <version>0.0.1-SNAPSHOT</version>
+ <packaging>pom</packaging>
+ <description>Apache Aries Typed Events Parent.</description>
+ <scm>
+ <connection>scm:git:http://gitbox.apache.org/repos/asf/aries-typedevent.git</connection>
+ <developerConnection>scm:git:https://gitbox.apache.org/repos/asf/aries-typedevent.git</developerConnection>
+ <url>https://gitbox.apache.org/repos/asf?p=aries-typedevent.git</url>
+ <tag>HEAD</tag>
+ </scm>
+
+ <repositories>
+ <repository>
+ <id>Apache-snapshots</id>
+ <url>https://repository.apache.org/content/groups/snapshots-group</url>
+ <snapshots>
+ <enabled>true</enabled>
+ <updatePolicy>daily</updatePolicy>
+ <checksumPolicy>ignore</checksumPolicy>
+ </snapshots>
+ <releases>
+ <enabled>false</enabled>
+ </releases>
+ </repository>
+ </repositories>
+
+ <properties>
+ <bnd.version>5.1.0</bnd.version>
+ <dsl.version>1.2.2</dsl.version>
+ <junit.version>5.6.2</junit.version>
+ <mockito.version>3.5.10</mockito.version>
+ </properties>
+
+ <dependencyManagement>
+ <dependencies>
+ <dependency>
+ <groupId>org.osgi</groupId>
+ <artifactId>org.osgi.core</artifactId>
+ <version>6.0.0</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.osgi</groupId>
+ <artifactId>osgi.annotation</artifactId>
+ <version>6.0.1</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.osgi</groupId>
+ <artifactId>org.osgi.annotation.bundle</artifactId>
+ <version>1.0.0</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.osgi</groupId>
+ <artifactId>org.osgi.namespace.service</artifactId>
+ <version>1.0.0</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.osgi</groupId>
+ <artifactId>org.osgi.service.cm</artifactId>
+ <version>1.5.0</version>
+ <scope>compile</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.osgi</groupId>
+ <artifactId>org.osgi.service.typedevent</artifactId>
+ <version>1.0.0-SNAPSHOT</version>
+ <scope>compile</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.osgi</groupId>
+ <artifactId>org.osgi.service.metatype.annotations</artifactId>
+ <version>1.3.0</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.aries.component-dsl</groupId>
+ <artifactId>org.apache.aries.component-dsl.component-dsl</artifactId>
+ <version>${dsl.version}</version>
+ <scope>compile</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>org.apache.felix.converter</artifactId>
+ <version>1.0.14</version>
+ <scope>compile</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
+ <version>1.7.0</version>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter</artifactId>
+ <version>${junit.version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-core</artifactId>
+ <version>${mockito.version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-junit-jupiter</artifactId>
+ <version>${mockito.version}</version>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+ </dependencyManagement>
+
+ <build>
+ <pluginManagement>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <version>3.8.1</version>
+ <configuration>
+ <source>1.8</source>
+ <target>1.8</target>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-jar-plugin</artifactId>
+ <version>3.2.0</version>
+ <configuration>
+ <archive>
+ <manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
+ </archive>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-javadoc-plugin</artifactId>
+ <version>3.2.0</version>
+ <configuration>
+ <source>1.8</source>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-surefire-plugin</artifactId>
+ <version>2.22.2</version>
+ <configuration>
+ <source>1.8</source>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>biz.aQute.bnd</groupId>
+ <artifactId>bnd-maven-plugin</artifactId>
+ <version>${bnd.version}</version>
+ <executions>
+ <execution>
+ <id>default-bnd-process</id>
+ <goals>
+ <goal>bnd-process</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </pluginManagement>
+
+ <plugins>
+ <plugin>
+ <groupId>biz.aQute.bnd</groupId>
+ <artifactId>bnd-maven-plugin</artifactId>
+ </plugin>
+ </plugins>
+ </build>
+ <modules>
+ <module>org.apache.aries.typedevent.bus</module>
+ </modules>
+</project>