This is an automated email from the ASF dual-hosted git repository. sseifert pushed a commit to branch release/1.x in repository https://gitbox.apache.org/repos/asf/sling-org-apache-sling-testing-osgi-mock.git
commit b884265f34da72b15fd2f39429b1e83fb0b301ba Author: sseifert <sseif...@pro-vision.de> AuthorDate: Mon Nov 6 17:10:53 2017 +0100 import branch for 1.x from svn --- pom.xml | 137 +++----- .../sling/testing/mock/osgi/MapMergeUtil.java | 21 +- .../apache/sling/testing/mock/osgi/MapUtil.java | 4 +- .../sling/testing/mock/osgi/MatchAllFilter.java | 6 - .../apache/sling/testing/mock/osgi/MockBundle.java | 44 +-- .../sling/testing/mock/osgi/MockBundleContext.java | 143 ++++---- .../testing/mock/osgi/MockComponentContext.java | 4 +- .../sling/testing/mock/osgi/MockConfiguration.java | 7 +- .../sling/testing/mock/osgi/MockEventAdmin.java | 26 +- .../apache/sling/testing/mock/osgi/MockOsgi.java | 87 ++++- .../testing/mock/osgi/MockServiceReference.java | 16 +- .../testing/mock/osgi/MockServiceRegistration.java | 28 +- .../sling/testing/mock/osgi/OsgiMetadataUtil.java | 18 +- .../sling/testing/mock/osgi/OsgiServiceUtil.java | 370 +++++---------------- .../mock/osgi/context/AbstractContextPlugin.java | 2 +- .../testing/mock/osgi/context/ContextCallback.java | 2 +- .../testing/mock/osgi/context/ContextPlugin.java | 2 +- .../testing/mock/osgi/context/ContextPlugins.java | 6 +- .../testing/mock/osgi/context/OsgiContextImpl.java | 3 +- .../testing/mock/osgi/context/package-info.java | 2 +- .../sling/testing/mock/osgi/junit/OsgiContext.java | 3 +- .../mock/osgi/junit/OsgiContextBuilder.java | 7 +- .../mock/osgi/junit/OsgiContextCallback.java | 3 +- .../testing/mock/osgi/junit/package-info.java | 2 +- .../sling/testing/mock/osgi/package-info.java | 2 +- ...ckBundleContextDynamicReferencesOsgiR6Test.java | 188 ----------- ...ockBundleContextStaticGreedyReferencesTest.java | 2 +- .../testing/mock/osgi/MockBundleContextTest.java | 94 ++---- .../mock/osgi/MockComponentContextTest.java | 2 +- .../mock/osgi/MockServiceReferencesSortTest.java | 78 ++--- .../OsgiServiceUtilActivateDeactivateTest.java | 76 +---- .../testing/mock/osgi/OsgiServiceUtilTest.java | 121 ++----- .../mock/osgi/context/OsgiContextImplTest.java | 8 +- .../testing/mock/osgi/junit/OsgiContextTest.java | 1 + ....osgi.OsgiServiceUtilActivateDeactivateTest.xml | 3 - ...sling.testing.mock.osgi.OsgiServiceUtilTest.xml | 9 - 36 files changed, 446 insertions(+), 1081 deletions(-) diff --git a/pom.xml b/pom.xml index 2fa57e7..7dfef63 100644 --- a/pom.xml +++ b/pom.xml @@ -23,12 +23,12 @@ <parent> <groupId>org.apache.sling</groupId> <artifactId>sling</artifactId> - <version>30</version> + <version>26</version> <relativePath /> </parent> <artifactId>org.apache.sling.testing.osgi-mock</artifactId> - <version>2.3.5-SNAPSHOT</version> + <version>1.9.9-SNAPSHOT</version> <packaging>bundle</packaging> <name>Apache Sling Testing OSGi Mock</name> @@ -44,12 +44,26 @@ <dependency> <groupId>org.osgi</groupId> - <artifactId>osgi.core</artifactId> + <artifactId>org.osgi.core</artifactId> <scope>compile</scope> </dependency> <dependency> <groupId>org.osgi</groupId> - <artifactId>osgi.cmpn</artifactId> + <artifactId>org.osgi.compendium</artifactId> + <scope>compile</scope> + </dependency> + + <dependency> + <groupId>org.apache.sling</groupId> + <artifactId>org.apache.sling.commons.osgi</artifactId> + <version>2.2.0</version> + <scope>compile</scope> + </dependency> + + <dependency> + <groupId>org.apache.felix</groupId> + <artifactId>org.apache.felix.framework</artifactId> + <version>5.0.0</version> <scope>compile</scope> </dependency> @@ -78,7 +92,7 @@ <artifactId>slf4j-api</artifactId> <scope>compile</scope> </dependency> - + <dependency> <groupId>org.reflections</groupId> <artifactId>reflections</artifactId> @@ -110,28 +124,6 @@ </exclusions> </dependency> - <!-- Artifact is shaded and inlined, only some classes included (see below) --> - <dependency> - <groupId>org.apache.sling</groupId> - <artifactId>org.apache.sling.commons.osgi</artifactId> - <version>2.4.0</version> - <scope>compile</scope> - </dependency> - <!-- Artifact is shaded and inlined, only some classes included (see below) --> - <dependency> - <groupId>org.apache.felix</groupId> - <artifactId>org.apache.felix.framework</artifactId> - <version>5.0.0</version> - <scope>compile</scope> - </dependency> - <!-- Artifact is shaded and inlined, only some classes included (see below) --> - <dependency> - <groupId>org.apache.felix</groupId> - <artifactId>org.apache.felix.scr</artifactId> - <version>2.0.4</version> - <scope>compile</scope> - </dependency> - <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-all</artifactId> @@ -146,7 +138,7 @@ <dependency> <groupId>org.apache.sling</groupId> <artifactId>org.apache.sling.testing.logging-mock</artifactId> - <version>2.0.0</version> + <version>1.0.0</version> <scope>test</scope> </dependency> @@ -161,6 +153,11 @@ <extensions>true</extensions> </plugin> + <plugin> + <groupId>org.apache.felix</groupId> + <artifactId>maven-scr-plugin</artifactId> + </plugin> + <plugin> <groupId>org.apache.rat</groupId> <artifactId>apache-rat-plugin</artifactId> @@ -169,73 +166,31 @@ <exclude>src/test/resources/META-INF/test.txt</exclude> <exclude>src/test/resources/bundleData/nested/first.txt</exclude> <exclude>src/test/resources/bundleData/nested/second.txt</exclude> - <exclude>dependency-reduced-pom.xml</exclude> </excludes> </configuration> </plugin> - - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-shade-plugin</artifactId> - <version>2.4.3</version> - <executions> - <execution> - <phase>package</phase> - <goals> - <goal>shade</goal> - </goals> - <configuration> - <createSourcesJar>true</createSourcesJar> - <shadeSourcesContent>true</shadeSourcesContent> - <artifactSet> - <includes> - <include>org.apache.sling:org.apache.sling.commons.osgi</include> - <include>org.apache.felix:org.apache.felix.framework</include> - <include>org.apache.felix:org.apache.felix.scr</include> - </includes> - </artifactSet> - <relocations> - <relocation> - <pattern>org.apache.sling.commons.osgi</pattern> - <shadedPattern>osgimock.org.apache.sling.commons.osgi</shadedPattern> - </relocation> - <relocation> - <pattern>org.apache.felix.framework</pattern> - <shadedPattern>osgimock.org.apache.felix.framework</shadedPattern> - </relocation> - <relocation> - <pattern>org.apache.felix.scr.impl</pattern> - <shadedPattern>osgimock.org.apache.felix.scr.impl</shadedPattern> - </relocation> - </relocations> - <filters> - <filter> - <artifact>org.apache.sling:org.apache.sling.commons.osgi</artifact> - <includes> - <include>org/apache/sling/commons/osgi/ServiceUtil*</include> - <include>org/apache/sling/commons/osgi/Order*</include> - </includes> - </filter> - <filter> - <artifact>org.apache.felix:org.apache.felix.framework</artifact> - <includes> - <include>org/apache/felix/framework/**</include> - </includes> - </filter> - <filter> - <artifact>org.apache.felix:org.apache.felix.scr</artifact> - <includes> - <include>org/apache/felix/scr/impl/inject/Annotations*</include> - <include>org/apache/felix/scr/impl/helper/Coercions*</include> - </includes> - </filter> - </filters> - </configuration> - </execution> - </executions> - </plugin> - + </plugins> </build> + <profiles> + <profile> + <id>osgi-6</id> + <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>org.osgi.compendium</artifactId> + <version>5.0.0</version> + <scope>provided</scope> + </dependency> + </dependencies> + </profile> + </profiles> + </project> diff --git a/src/main/java/org/apache/sling/testing/mock/osgi/MapMergeUtil.java b/src/main/java/org/apache/sling/testing/mock/osgi/MapMergeUtil.java index d690752..4ac0341 100644 --- a/src/main/java/org/apache/sling/testing/mock/osgi/MapMergeUtil.java +++ b/src/main/java/org/apache/sling/testing/mock/osgi/MapMergeUtil.java @@ -31,25 +31,15 @@ import org.osgi.service.cm.Configuration; import org.osgi.service.cm.ConfigurationAdmin; /** - * Map util merge methods. + * Map merge util methods. */ final class MapMergeUtil { - + private MapMergeUtil() { // static methods only } - - /** - * Merge service properties from three sources (with this precedence): - * 1. Properties defined in calling unit test code - * 2. Properties from ConfigurationAdmin - * 3. Properties from OSGi SCR metadata - * @param target Target service - * @param configAdmin Configuration admin or null if none is registered - * @param properties Properties from unit test code or null if none where passed - * @return Merged properties - */ - static Dictionary<String, Object> propertiesMergeWithOsgiMetadata(Object target, + + public static Dictionary<String, Object> propertiesMergeWithOsgiMetadata(Object target, ConfigurationAdmin configAdmin, Dictionary<String, Object> properties) { return toDictionary(propertiesMergeWithOsgiMetadata(target, configAdmin, toMap(properties))); @@ -65,7 +55,8 @@ final class MapMergeUtil { * @param properties Properties from unit test code or null if none where passed * @return Merged properties */ - static Map<String, Object> propertiesMergeWithOsgiMetadata(Object target, + @SuppressWarnings("unchecked") + public static Map<String, Object> propertiesMergeWithOsgiMetadata(Object target, ConfigurationAdmin configAdmin, Map<String, Object> properties) { Map<String, Object> mergedProperties = new HashMap<String, Object>(); diff --git a/src/main/java/org/apache/sling/testing/mock/osgi/MapUtil.java b/src/main/java/org/apache/sling/testing/mock/osgi/MapUtil.java index 44aef63..1889087 100644 --- a/src/main/java/org/apache/sling/testing/mock/osgi/MapUtil.java +++ b/src/main/java/org/apache/sling/testing/mock/osgi/MapUtil.java @@ -46,7 +46,7 @@ public final class MapUtil { if (map == null) { return null; } - Hashtable<T, U> hashtable = new Hashtable<>(); + Hashtable<T, U> hashtable = new Hashtable<T, U>(); for (Map.Entry<T, U> entry : map.entrySet()) { if (entry.getKey() != null && entry.getValue() != null) { hashtable.put(entry.getKey(), entry.getValue()); @@ -105,7 +105,7 @@ public final class MapUtil { if (args.length % 2 != 0) { throw new IllegalArgumentException("args must be an even number of name/values:" + Arrays.asList(args)); } - final Map<String, Object> result = new HashMap<>(); + final Map<String, Object> result = new HashMap<String, Object>(); for (int i=0 ; i < args.length; i+=2) { Object key = args[i]; Object value = args[i+1]; diff --git a/src/main/java/org/apache/sling/testing/mock/osgi/MatchAllFilter.java b/src/main/java/org/apache/sling/testing/mock/osgi/MatchAllFilter.java index 3ef02df..0a7aaf3 100644 --- a/src/main/java/org/apache/sling/testing/mock/osgi/MatchAllFilter.java +++ b/src/main/java/org/apache/sling/testing/mock/osgi/MatchAllFilter.java @@ -19,7 +19,6 @@ package org.apache.sling.testing.mock.osgi; import java.util.Dictionary; -import java.util.Map; import org.osgi.framework.Filter; import org.osgi.framework.ServiceReference; @@ -44,9 +43,4 @@ class MatchAllFilter implements Filter { return true; } - @Override - public boolean matches(Map<String, ?> map) { - return true; - } - } diff --git a/src/main/java/org/apache/sling/testing/mock/osgi/MockBundle.java b/src/main/java/org/apache/sling/testing/mock/osgi/MockBundle.java index 89ad673..1a7a7c1 100644 --- a/src/main/java/org/apache/sling/testing/mock/osgi/MockBundle.java +++ b/src/main/java/org/apache/sling/testing/mock/osgi/MockBundle.java @@ -31,7 +31,6 @@ import java.util.Vector; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; -import org.osgi.framework.Constants; import org.osgi.framework.ServiceReference; import org.osgi.framework.Version; @@ -47,26 +46,16 @@ public final class MockBundle implements Bundle { private final long bundleId; private final BundleContext bundleContext; private Map<String, String> headers = ImmutableMap.<String, String>of(); - private String symbolicName; + private String symbolicName = "mock-bundle"; private long lastModified; /** * Constructor * @param bundleContext Bundle context - * @param bundleId Bundle ID - */ - MockBundle(BundleContext bundleContext, long bundleId) { - this.bundleId = bundleId; - this.bundleContext = bundleContext; - this.symbolicName = (bundleId == Constants.SYSTEM_BUNDLE_ID ? Constants.SYSTEM_BUNDLE_SYMBOLICNAME : "mock-bundle"); - } - - /** - * Constructor - * @param bundleContext Bundle context */ public MockBundle(BundleContext bundleContext) { - this(bundleContext, ++bundleCounter); + this.bundleId = ++bundleCounter; + this.bundleContext = bundleContext; } @Override @@ -185,24 +174,19 @@ public final class MockBundle implements Bundle { return queryPath; } + // --- unsupported operations --- @Override - public String getLocation() { - if (bundleId == Constants.SYSTEM_BUNDLE_ID) { - return Constants.SYSTEM_BUNDLE_LOCATION; - } - else { - return null; - } + public Enumeration<URL> findEntries(final String path, final String filePattern, final boolean recurse) { + throw new UnsupportedOperationException(); } - // --- unsupported operations --- @Override - public Enumeration<URL> findEntries(final String path, final String filePattern, final boolean recurse) { + public String getLocation() { throw new UnsupportedOperationException(); } @Override - public ServiceReference<?>[] getRegisteredServices() { + public ServiceReference[] getRegisteredServices() { throw new UnsupportedOperationException(); } @@ -217,7 +201,7 @@ public final class MockBundle implements Bundle { } @Override - public ServiceReference<?>[] getServicesInUse() { + public ServiceReference[] getServicesInUse() { throw new UnsupportedOperationException(); } @@ -266,27 +250,27 @@ public final class MockBundle implements Bundle { throw new UnsupportedOperationException(); } - @Override + // this is part of org.osgi 4.2.0 public Map<X509Certificate, List<X509Certificate>> getSignerCertificates(final int signersType) { throw new UnsupportedOperationException(); } - @Override + // this is part of org.osgi 4.2.0 public Version getVersion() { throw new UnsupportedOperationException(); } - @Override + // this is part of org.osgi.core 6.0.0 public int compareTo(Bundle o) { throw new UnsupportedOperationException(); } - @Override + // this is part of org.osgi.core 6.0.0 public <A> A adapt(Class<A> type) { throw new UnsupportedOperationException(); } - @Override + // this is part of org.osgi.core 6.0.0 public File getDataFile(String filename) { throw new UnsupportedOperationException(); } diff --git a/src/main/java/org/apache/sling/testing/mock/osgi/MockBundleContext.java b/src/main/java/org/apache/sling/testing/mock/osgi/MockBundleContext.java index 0340a55..1a6b768 100644 --- a/src/main/java/org/apache/sling/testing/mock/osgi/MockBundleContext.java +++ b/src/main/java/org/apache/sling/testing/mock/osgi/MockBundleContext.java @@ -44,14 +44,12 @@ import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleEvent; import org.osgi.framework.BundleListener; -import org.osgi.framework.Constants; import org.osgi.framework.Filter; import org.osgi.framework.FrameworkListener; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceEvent; import org.osgi.framework.ServiceFactory; import org.osgi.framework.ServiceListener; -import org.osgi.framework.ServiceObjects; import org.osgi.framework.ServiceReference; import org.osgi.framework.ServiceRegistration; import org.osgi.service.cm.ConfigurationAdmin; @@ -70,11 +68,8 @@ class MockBundleContext implements BundleContext { private final Queue<BundleListener> bundleListeners = new ConcurrentLinkedQueue<BundleListener>(); private final ConfigurationAdmin configAdmin = new MockConfigurationAdmin(); private File dataFileBaseDir; - - private final Bundle systemBundle; public MockBundleContext() { - this.systemBundle = new MockBundle(this, Constants.SYSTEM_BUNDLE_ID); this.bundle = new MockBundle(this); // register configuration admin by default @@ -96,7 +91,6 @@ class MockBundleContext implements BundleContext { } } - @SuppressWarnings("unchecked") @Override public ServiceRegistration registerService(final String clazz, final Object service, final Dictionary properties) { String[] clazzes; @@ -108,9 +102,8 @@ class MockBundleContext implements BundleContext { return registerService(clazzes, service, properties); } - @SuppressWarnings("unchecked") - @Override - public <S> ServiceRegistration<S> registerService(Class<S> clazz, S service, Dictionary<String, ?> properties) { + // this is part of org.osgi.core 6.0.0 + public <S> ServiceRegistration registerService(Class<S> clazz, S service, Dictionary<String, ?> properties) { return registerService(clazz.getName(), service, properties); } @@ -125,12 +118,6 @@ class MockBundleContext implements BundleContext { return registration; } - @SuppressWarnings("unchecked") - @Override - public <S> ServiceRegistration<S> registerService(Class<S> clazz, ServiceFactory<S> factory, Dictionary<String, ?> properties) { - return registerService(clazz.getName(), factory, properties); - } - /** * Check for already registered services that may be affected by the service registration - either * adding by additional optional references, or creating a conflict in the dependencies. @@ -142,20 +129,18 @@ class MockBundleContext implements BundleContext { List<ReferenceInfo> affectedDynamicReferences = OsgiServiceUtil.getMatchingDynamicReferences(registeredServices, registration); for (ReferenceInfo referenceInfo : affectedDynamicReferences) { Reference reference = referenceInfo.getReference(); - if (reference.matchesTargetFilter(registration.getReference())) { - switch (reference.getCardinality()) { - case MANDATORY_UNARY: - throw new ReferenceViolationException("Mandatory unary reference of type " + reference.getInterfaceType() + " already fulfilled " - + "for service " + reference.getServiceClass().getName() + ", registration of new service with this interface failed."); - case MANDATORY_MULTIPLE: - case OPTIONAL_MULTIPLE: - case OPTIONAL_UNARY: - OsgiServiceUtil.invokeBindMethod(reference, referenceInfo.getServiceRegistration().getService(), - new ServiceInfo(registration)); - break; - default: - throw new RuntimeException("Unepxected cardinality: " + reference.getCardinality()); - } + switch (reference.getCardinality()) { + case MANDATORY_UNARY: + throw new ReferenceViolationException("Mandatory unary reference of type " + reference.getInterfaceType() + " already fulfilled " + + "for service " + reference.getServiceClass().getName() + ", registration of new service with this interface failed."); + case MANDATORY_MULTIPLE: + case OPTIONAL_MULTIPLE: + case OPTIONAL_UNARY: + OsgiServiceUtil.invokeBindMethod(reference, referenceInfo.getServiceRegistration().getService(), + new ServiceInfo(registration)); + break; + default: + throw new RuntimeException("Unepxected cardinality: " + reference.getCardinality()); } } @@ -184,7 +169,6 @@ class MockBundleContext implements BundleContext { notifyServiceListeners(ServiceEvent.UNREGISTERING, registration.getReference()); } - @SuppressWarnings("unchecked") void restartService(MockServiceRegistration registration) { // get current service properties Class<?> serviceClass = registration.getService().getClass(); @@ -221,22 +205,20 @@ class MockBundleContext implements BundleContext { List<ReferenceInfo> affectedDynamicReferences = OsgiServiceUtil.getMatchingDynamicReferences(registeredServices, registration); for (ReferenceInfo referenceInfo : affectedDynamicReferences) { Reference reference = referenceInfo.getReference(); - if (reference.matchesTargetFilter(registration.getReference())) { - switch (reference.getCardinality()) { - case MANDATORY_UNARY: - throw new ReferenceViolationException("Reference of type " + reference.getInterfaceType() + " " - + "for service " + reference.getServiceClass().getName() + " is mandatory unary, " - + "unregistration of service with this interface failed."); - case MANDATORY_MULTIPLE: - case OPTIONAL_MULTIPLE: - case OPTIONAL_UNARY: - // it is currently not checked if for a MANDATORY_MULTIPLE reference the last reference is removed - OsgiServiceUtil.invokeUnbindMethod(reference, referenceInfo.getServiceRegistration().getService(), - new ServiceInfo(registration)); - break; - default: - throw new RuntimeException("Unepxected cardinality: " + reference.getCardinality()); - } + switch (reference.getCardinality()) { + case MANDATORY_UNARY: + throw new ReferenceViolationException("Reference of type " + reference.getInterfaceType() + " " + + "for service " + reference.getServiceClass().getName() + " is mandatory unary, " + + "unregistration of service with this interface failed."); + case MANDATORY_MULTIPLE: + case OPTIONAL_MULTIPLE: + case OPTIONAL_UNARY: + // it is currently not checked if for a MANDATORY_MULTIPLE reference the last reference is removed + OsgiServiceUtil.invokeUnbindMethod(reference, referenceInfo.getServiceRegistration().getService(), + new ServiceInfo(registration)); + break; + default: + throw new RuntimeException("Unepxected cardinality: " + reference.getCardinality()); } } @@ -260,7 +242,6 @@ class MockBundleContext implements BundleContext { } } - @SuppressWarnings("unchecked") @Override public ServiceReference getServiceReference(final String clazz) { try { @@ -275,13 +256,11 @@ class MockBundleContext implements BundleContext { return null; } - @SuppressWarnings("unchecked") - @Override - public <S> ServiceReference<S> getServiceReference(Class<S> clazz) { + // this is part of org.osgi.core 6.0.0 + public ServiceReference getServiceReference(Class clazz) { return getServiceReference(clazz.getName()); } - @SuppressWarnings("unchecked") @Override public ServiceReference[] getServiceReferences(final String clazz, final String filter) throws InvalidSyntaxException { Set<ServiceReference> result = new TreeSet<ServiceReference>(new Comparator<ServiceReference>() { @@ -303,19 +282,11 @@ class MockBundleContext implements BundleContext { } } - @SuppressWarnings("unchecked") - @Override - public <S> Collection<ServiceReference<S>> getServiceReferences(Class<S> clazz, String filter) throws InvalidSyntaxException { - ServiceReference<S>[] result = getServiceReferences(clazz.getName(), filter); - if (result == null) { - return ImmutableList.<ServiceReference<S>>of(); - } - else { - return ImmutableList.<ServiceReference<S>>copyOf(result); - } + // this is part of org.osgi.core 6.0.0 + public Collection<ServiceReference> getServiceReferences(Class clazz, String filter) throws InvalidSyntaxException { + return ImmutableList.<ServiceReference>copyOf(getServiceReferences(clazz.getName(), filter)); } - @SuppressWarnings("unchecked") @Override public ServiceReference[] getAllServiceReferences(final String clazz, final String filter) throws InvalidSyntaxException { // for now just do the same as getServiceReferences @@ -323,8 +294,8 @@ class MockBundleContext implements BundleContext { } @Override - public <S> S getService(final ServiceReference<S> serviceReference) { - return ((MockServiceReference<S>)serviceReference).getService(); + public Object getService(final ServiceReference serviceReference) { + return ((MockServiceReference)serviceReference).getService(); } @Override @@ -390,11 +361,10 @@ class MockBundleContext implements BundleContext { // accept method, but ignore it } - @SuppressWarnings("unchecked") - <S> S locateService(final String name, final ServiceReference<S> reference) { - for (MockServiceRegistration<?> serviceRegistration : this.registeredServices) { + Object locateService(final String name, final ServiceReference reference) { + for (MockServiceRegistration serviceRegistration : this.registeredServices) { if (serviceRegistration.getReference() == reference) { - return (S)serviceRegistration.getService(); + return serviceRegistration.getService(); } } return null; @@ -433,7 +403,7 @@ class MockBundleContext implements BundleContext { * Deactivates all bundles registered in this mocked bundle context. */ public void shutdown() { - for (MockServiceRegistration<?> serviceRegistration : ImmutableList.copyOf(registeredServices).reverse()) { + for (MockServiceRegistration serviceRegistration : ImmutableList.copyOf(registeredServices).reverse()) { try { MockOsgi.deactivate(serviceRegistration.getService(), this, serviceRegistration.getProperties()); } @@ -450,38 +420,37 @@ class MockBundleContext implements BundleContext { } } + // --- unsupported operations --- @Override - public Bundle getBundle(final long bundleId) { - if (bundleId == Constants.SYSTEM_BUNDLE_ID) { - return systemBundle; - } - // otherwise return null - no bundle found - return null; + public Bundle installBundle(final String s) { + throw new UnsupportedOperationException(); } @Override - public Bundle getBundle(String location) { - if (StringUtils.equals(location, Constants.SYSTEM_BUNDLE_LOCATION)) { - return systemBundle; - } - // otherwise return null - no bundle found - return null; + public Bundle installBundle(final String s, final InputStream inputStream) { + throw new UnsupportedOperationException(); } - // --- unsupported operations --- @Override - public Bundle installBundle(final String s) { + public Bundle getBundle(final long l) { throw new UnsupportedOperationException(); } - @Override - public Bundle installBundle(final String s, final InputStream inputStream) { + // this is part of org.osgi.core 6.0.0 + public Bundle getBundle(String location) { throw new UnsupportedOperationException(); } - @Override - public <S> ServiceObjects<S> getServiceObjects(ServiceReference<S> reference) { + // this is part of org.osgi.core 6.0.0 + public <S> ServiceRegistration registerService(Class<S> clazz, ServiceFactory factory, Dictionary<String, ?> properties) { + throw new UnsupportedOperationException(); + } + + // this is part of org.osgi.core 6.0.0 + /* class org.osgi.framework.ServiceObjects does not exist in older OSGi versions + public ServiceObjects getServiceObjects(ServiceReference reference) { throw new UnsupportedOperationException(); } + */ } diff --git a/src/main/java/org/apache/sling/testing/mock/osgi/MockComponentContext.java b/src/main/java/org/apache/sling/testing/mock/osgi/MockComponentContext.java index a00ec72..78154a5 100644 --- a/src/main/java/org/apache/sling/testing/mock/osgi/MockComponentContext.java +++ b/src/main/java/org/apache/sling/testing/mock/osgi/MockComponentContext.java @@ -48,7 +48,7 @@ class MockComponentContext implements ComponentContext { } @Override - public <S> S locateService(final String name, final ServiceReference<S> reference) { + public Object locateService(final String name, final ServiceReference reference) { return this.bundleContext.locateService(name, reference); } @@ -79,7 +79,7 @@ class MockComponentContext implements ComponentContext { } @Override - public ServiceReference<?> getServiceReference() { + public ServiceReference getServiceReference() { throw new UnsupportedOperationException(); } diff --git a/src/main/java/org/apache/sling/testing/mock/osgi/MockConfiguration.java b/src/main/java/org/apache/sling/testing/mock/osgi/MockConfiguration.java index 7bcac56..4959cb6 100644 --- a/src/main/java/org/apache/sling/testing/mock/osgi/MockConfiguration.java +++ b/src/main/java/org/apache/sling/testing/mock/osgi/MockConfiguration.java @@ -46,7 +46,7 @@ class MockConfiguration implements Configuration { } @Override - public Dictionary<String, Object> getProperties() { + public Dictionary getProperties() { // return copy of dictionary return new Hashtable<String,Object>(MapUtil.toMap(props)); } @@ -100,9 +100,4 @@ class MockConfiguration implements Configuration { throw new UnsupportedOperationException(); } - @Override - public long getChangeCount() { - throw new UnsupportedOperationException(); - } - } diff --git a/src/main/java/org/apache/sling/testing/mock/osgi/MockEventAdmin.java b/src/main/java/org/apache/sling/testing/mock/osgi/MockEventAdmin.java index fa16f44..d182d1f 100644 --- a/src/main/java/org/apache/sling/testing/mock/osgi/MockEventAdmin.java +++ b/src/main/java/org/apache/sling/testing/mock/osgi/MockEventAdmin.java @@ -26,15 +26,15 @@ import java.util.concurrent.RejectedExecutionException; import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.apache.sling.commons.osgi.Order; +import org.apache.felix.scr.annotations.Activate; +import org.apache.felix.scr.annotations.Component; +import org.apache.felix.scr.annotations.Deactivate; +import org.apache.felix.scr.annotations.Reference; +import org.apache.felix.scr.annotations.ReferenceCardinality; +import org.apache.felix.scr.annotations.ReferencePolicy; +import org.apache.felix.scr.annotations.Service; import org.apache.sling.commons.osgi.ServiceUtil; import org.osgi.service.component.ComponentContext; -import org.osgi.service.component.annotations.Activate; -import org.osgi.service.component.annotations.Component; -import org.osgi.service.component.annotations.Deactivate; -import org.osgi.service.component.annotations.Reference; -import org.osgi.service.component.annotations.ReferenceCardinality; -import org.osgi.service.component.annotations.ReferencePolicy; import org.osgi.service.event.Event; import org.osgi.service.event.EventAdmin; import org.osgi.service.event.EventConstants; @@ -46,12 +46,12 @@ import org.slf4j.LoggerFactory; * Mock implementation of {@link EventAdmin}. * From {@link EventConstants} currently only {@link EventConstants#EVENT_TOPIC} is supported. */ -@Component(immediate = true, service = EventAdmin.class) +@Component(immediate = true) +@Service(value = EventAdmin.class) public final class MockEventAdmin implements EventAdmin { - @Reference(name="eventHandler", service=EventHandler.class, - cardinality=ReferenceCardinality.MULTIPLE, policy=ReferencePolicy.DYNAMIC, - bind="bindEventHandler", unbind="unbindEventHandler") + @Reference(name="eventHandler", referenceInterface=EventHandler.class, + cardinality=ReferenceCardinality.OPTIONAL_MULTIPLE, policy=ReferencePolicy.DYNAMIC) private final Map<Object, EventHandlerItem> eventHandlers = new TreeMap<Object, EventHandlerItem>(); private ExecutorService asyncHandler; @@ -106,13 +106,13 @@ public final class MockEventAdmin implements EventAdmin { protected void bindEventHandler(EventHandler eventHandler, Map<String, Object> props) { synchronized (eventHandlers) { - eventHandlers.put(ServiceUtil.getComparableForServiceRanking(props, Order.DESCENDING), new EventHandlerItem(eventHandler, props)); + eventHandlers.put(ServiceUtil.getComparableForServiceRanking(props), new EventHandlerItem(eventHandler, props)); } } protected void unbindEventHandler(EventHandler eventHandler, Map<String, Object> props) { synchronized (eventHandlers) { - eventHandlers.remove(ServiceUtil.getComparableForServiceRanking(props, Order.DESCENDING)); + eventHandlers.remove(ServiceUtil.getComparableForServiceRanking(props)); } } diff --git a/src/main/java/org/apache/sling/testing/mock/osgi/MockOsgi.java b/src/main/java/org/apache/sling/testing/mock/osgi/MockOsgi.java index 7c07578..ccf2ed8 100644 --- a/src/main/java/org/apache/sling/testing/mock/osgi/MockOsgi.java +++ b/src/main/java/org/apache/sling/testing/mock/osgi/MockOsgi.java @@ -151,6 +151,18 @@ public final class MockOsgi { /** * Simulate activation of service instance. Invokes the @Activate annotated method. * @param target Service instance. + * @return true if activation method was called. False if no activate method is defined. + * @deprecated Please use {@link #activate(Object, BundleContext)} + * and shutdown the bundle context after usage. + */ + @Deprecated + public static boolean activate(Object target) { + return MockOsgi.activate(target, (Dictionary<String, Object>)null); + } + + /** + * Simulate activation of service instance. Invokes the @Activate annotated method. + * @param target Service instance. * @param bundleContext Bundle context * @return true if activation method was called. False if no activate method is defined. */ @@ -161,6 +173,34 @@ public final class MockOsgi { /** * Simulate activation of service instance. Invokes the @Activate annotated method. * @param target Service instance. + * @param properties Properties + * @return true if activation method was called. False if no activate method is defined. + * @deprecated Please use {@link #activate(Object, BundleContext, Dictionary)} + * and shutdown the bundle context after usage. + */ + @Deprecated + public static boolean activate(Object target, Dictionary<String, Object> properties) { + Dictionary<String, Object> mergedProperties = propertiesMergeWithOsgiMetadata(target, null, properties); + ComponentContext componentContext = newComponentContext(mergedProperties); + return OsgiServiceUtil.activateDeactivate(target, componentContext, true); + } + + /** + * Simulate activation of service instance. Invokes the @Activate annotated method. + * @param target Service instance. + * @param properties Properties + * @return true if activation method was called. False if no activate method is defined. + * @deprecated Please use {@link #activate(Object, BundleContext, Map)} + * and shutdown the bundle context after usage. + */ + @Deprecated + public static boolean activate(Object target, Map<String, Object> properties) { + return activate(target, toDictionary(properties)); + } + + /** + * Simulate activation of service instance. Invokes the @Activate annotated method. + * @param target Service instance. * @param bundleContext Bundle context * @param properties Properties * @return true if activation method was called. False if no activate method is defined. @@ -196,6 +236,18 @@ public final class MockOsgi { /** * Simulate deactivation of service instance. Invokes the @Deactivate annotated method. * @param target Service instance. + * @return true if deactivation method was called. False if no deactivate method is defined. + * @deprecated Please use {@link #deactivate(Object, BundleContext)} + * and shutdown the bundle context after usage. + */ + @Deprecated + public static boolean deactivate(Object target) { + return MockOsgi.deactivate(target, (Dictionary<String, Object>)null); + } + + /** + * Simulate deactivation of service instance. Invokes the @Deactivate annotated method. + * @param target Service instance. * @param bundleContext Bundle context. * @return true if deactivation method was called. False if no deactivate method is defined. */ @@ -206,6 +258,34 @@ public final class MockOsgi { /** * Simulate deactivation of service instance. Invokes the @Deactivate annotated method. * @param target Service instance. + * @param properties Properties + * @return true if deactivation method was called. False if no deactivate method is defined. + * @deprecated Please use {@link #deactivate(Object, BundleContext, Dictionary)} + * and shutdown the bundle context after usage. + */ + @Deprecated + public static boolean deactivate(Object target, Dictionary<String, Object> properties) { + Dictionary<String, Object> mergedProperties = propertiesMergeWithOsgiMetadata(target, null, properties); + ComponentContext componentContext = newComponentContext(mergedProperties); + return OsgiServiceUtil.activateDeactivate(target, componentContext, false); + } + + /** + * Simulate deactivation of service instance. Invokes the @Deactivate annotated method. + * @param target Service instance. + * @param properties Properties + * @return true if deactivation method was called. False if no deactivate method is defined. + * @deprecated Please use {@link #deactivate(Object, BundleContext, Map)} + * and shutdown the bundle context after usage. + */ + @Deprecated + public static boolean deactivate(Object target, Map<String, Object> properties) { + return deactivate(target, toDictionary(properties)); + } + + /** + * Simulate deactivation of service instance. Invokes the @Deactivate annotated method. + * @param target Service instance. * @param bundleContext Bundle context * @param properties Properties * @return true if deactivation method was called. False if no deactivate method is defined. @@ -258,8 +338,7 @@ public final class MockOsgi { */ public static boolean modified(Object target, BundleContext bundleContext, Map<String, Object> properties) { Map<String, Object> mergedProperties = propertiesMergeWithOsgiMetadata(target, getConfigAdmin(bundleContext), properties); - ComponentContext componentContext = newComponentContext(bundleContext, mergedProperties); - return OsgiServiceUtil.modified(target, componentContext, mergedProperties); + return OsgiServiceUtil.modified(target, bundleContext, mergedProperties); } /** @@ -270,7 +349,7 @@ public final class MockOsgi { * @return true if modified method was called. False if no modified method is defined. */ public static boolean modified(Object target, BundleContext bundleContext, Object... properties) { - return modified(target, bundleContext, toDictionary(properties)); + return modified(target, bundleContext, toMap(properties)); } /** @@ -321,7 +400,7 @@ public final class MockOsgi { * @return Configuration admin or null if not registered. */ private static ConfigurationAdmin getConfigAdmin(BundleContext bundleContext) { - ServiceReference<?> ref = bundleContext.getServiceReference(ConfigurationAdmin.class.getName()); + ServiceReference ref = bundleContext.getServiceReference(ConfigurationAdmin.class.getName()); if (ref != null) { return (ConfigurationAdmin)bundleContext.getService(ref); } diff --git a/src/main/java/org/apache/sling/testing/mock/osgi/MockServiceReference.java b/src/main/java/org/apache/sling/testing/mock/osgi/MockServiceReference.java index ed01402..f210095 100644 --- a/src/main/java/org/apache/sling/testing/mock/osgi/MockServiceReference.java +++ b/src/main/java/org/apache/sling/testing/mock/osgi/MockServiceReference.java @@ -22,7 +22,6 @@ import java.util.Collections; import java.util.Dictionary; import java.util.Map; -import org.apache.sling.commons.osgi.Order; import org.apache.sling.commons.osgi.ServiceUtil; import org.osgi.framework.Bundle; import org.osgi.framework.Constants; @@ -31,24 +30,23 @@ import org.osgi.framework.ServiceReference; /** * Mock {@link ServiceReference} implementation. */ -class MockServiceReference<T> implements ServiceReference<T> { +class MockServiceReference implements ServiceReference { private final Bundle bundle; - private final MockServiceRegistration<T> serviceRegistration; + private final MockServiceRegistration serviceRegistration; private volatile Comparable<Object> comparable; - public MockServiceReference(final Bundle bundle, final MockServiceRegistration<T> serviceRegistration) { + public MockServiceReference(final Bundle bundle, final MockServiceRegistration serviceRegistration) { this.bundle = bundle; this.serviceRegistration = serviceRegistration; this.comparable = buildComparable(); } - + private Comparable<Object> buildComparable() { Map<String,Object> props = MapUtil.toMap(serviceRegistration.getProperties()); - // use ascending order as defined in ServiceReference#compareTo() - return ServiceUtil.getComparableForServiceRanking(props, Order.ASCENDING); + return ServiceUtil.getComparableForServiceRanking(props); } - + @Override public Bundle getBundle() { return this.bundle; @@ -114,7 +112,7 @@ class MockServiceReference<T> implements ServiceReference<T> { } } - T getService() { + Object getService() { return this.serviceRegistration.getService(); } diff --git a/src/main/java/org/apache/sling/testing/mock/osgi/MockServiceRegistration.java b/src/main/java/org/apache/sling/testing/mock/osgi/MockServiceRegistration.java index 7a2e87d..8ef25a4 100644 --- a/src/main/java/org/apache/sling/testing/mock/osgi/MockServiceRegistration.java +++ b/src/main/java/org/apache/sling/testing/mock/osgi/MockServiceRegistration.java @@ -38,25 +38,24 @@ import com.google.common.collect.ImmutableList; /** * Mock {@link ServiceRegistration} implementation. */ -class MockServiceRegistration<T> implements ServiceRegistration<T>, Comparable<MockServiceRegistration<T>> { +class MockServiceRegistration implements ServiceRegistration, Comparable<MockServiceRegistration> { private static volatile long serviceCounter; private final Long serviceId; private final Set<String> clazzes; - private final T service; + private final Object service; private Dictionary<String, Object> properties; - private final ServiceReference<T> serviceReference; + private final ServiceReference serviceReference; private final MockBundleContext bundleContext; - @SuppressWarnings("unchecked") - public MockServiceRegistration(final Bundle bundle, final String[] clazzes, final T service, + public MockServiceRegistration(final Bundle bundle, final String[] clazzes, final Object service, final Dictionary<String, Object> properties, MockBundleContext bundleContext) { this.serviceId = ++serviceCounter; this.clazzes = new HashSet<String>(ImmutableList.copyOf(clazzes)); if (service instanceof ServiceFactory) { - this.service = ((ServiceFactory<T>)service).getService(bundleContext.getBundle(), this); + this.service = ((ServiceFactory)service).getService(bundleContext.getBundle(), this); } else { this.service = service; @@ -65,14 +64,14 @@ class MockServiceRegistration<T> implements ServiceRegistration<T>, Comparable<M this.properties = properties != null ? properties : new Hashtable<String,Object>(); this.properties.put(Constants.SERVICE_ID, this.serviceId); this.properties.put(Constants.OBJECTCLASS, clazzes); - this.serviceReference = new MockServiceReference<T>(bundle, this); + this.serviceReference = new MockServiceReference(bundle, this); this.bundleContext = bundleContext; readOsgiMetadata(); } @Override - public ServiceReference<T> getReference() { + public ServiceReference getReference() { return this.serviceReference; } @@ -101,15 +100,8 @@ class MockServiceRegistration<T> implements ServiceRegistration<T>, Comparable<M return clazzes; } - @SuppressWarnings("unchecked") - T getService() { - if (this.service instanceof ServiceFactory) { - ServiceFactory<T> factory = (ServiceFactory<T>)this.service; - return factory.getService(this.bundleContext.getBundle(), this); - } - else { - return this.service; - } + Object getService() { + return this.service; } @Override @@ -126,7 +118,7 @@ class MockServiceRegistration<T> implements ServiceRegistration<T>, Comparable<M } @Override - public int compareTo(MockServiceRegistration<T> obj) { + public int compareTo(MockServiceRegistration obj) { return serviceId.compareTo(obj.serviceId); } diff --git a/src/main/java/org/apache/sling/testing/mock/osgi/OsgiMetadataUtil.java b/src/main/java/org/apache/sling/testing/mock/osgi/OsgiMetadataUtil.java index a4c5a4b..8306218 100644 --- a/src/main/java/org/apache/sling/testing/mock/osgi/OsgiMetadataUtil.java +++ b/src/main/java/org/apache/sling/testing/mock/osgi/OsgiMetadataUtil.java @@ -153,7 +153,7 @@ final class OsgiMetadataUtil { * @return Cache map */ private static Map<String,Document> initMetadataDocumentCache() { - Map<String,Document> cacheMap = new HashMap<>(); + Map<String,Document> cacheMap = new HashMap<String,Document>(); XPath xpath = XPATH_FACTORY.newXPath(); xpath.setNamespaceContext(NAMESPACE_CONTEXT); @@ -179,9 +179,21 @@ final class OsgiMetadataUtil { Enumeration<URL> resourceUrls = OsgiMetadataUtil.class.getClassLoader().getResources(resourcePath); while (resourceUrls.hasMoreElements()) { URL resourceUrl = resourceUrls.nextElement(); - try (InputStream fileStream = resourceUrl.openStream()) { + InputStream fileStream = null; + try { + fileStream = resourceUrl.openStream(); parseMetadataDocument(cacheMap, resourcePath, fileStream, xpathExpression); } + finally { + if (fileStream != null) { + try { + fileStream.close(); + } + catch (IOException e) { + // ignore + } + } + } } } catch (Exception ex) { @@ -545,7 +557,7 @@ final class OsgiMetadataUtil { return this.target; } - public boolean matchesTargetFilter(ServiceReference<?> serviceReference) { + public boolean matchesTargetFilter(ServiceReference serviceReference) { if (targetFilter == null) { return true; } diff --git a/src/main/java/org/apache/sling/testing/mock/osgi/OsgiServiceUtil.java b/src/main/java/org/apache/sling/testing/mock/osgi/OsgiServiceUtil.java index f95e72b..15340d4 100644 --- a/src/main/java/org/apache/sling/testing/mock/osgi/OsgiServiceUtil.java +++ b/src/main/java/org/apache/sling/testing/mock/osgi/OsgiServiceUtil.java @@ -18,22 +18,20 @@ */ package org.apache.sling.testing.mock.osgi; -import java.lang.annotation.Annotation; -import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; -import java.util.Collection; +import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.SortedSet; +import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; -import org.apache.felix.scr.impl.inject.Annotations; -import org.apache.sling.testing.mock.osgi.OsgiMetadataUtil.FieldCollectionType; import org.apache.sling.testing.mock.osgi.OsgiMetadataUtil.OsgiMetadata; import org.apache.sling.testing.mock.osgi.OsgiMetadataUtil.Reference; +import org.apache.sling.testing.mock.osgi.OsgiMetadataUtil.ReferenceCardinality; import org.apache.sling.testing.mock.osgi.OsgiMetadataUtil.ReferencePolicy; import org.apache.sling.testing.mock.osgi.OsgiMetadataUtil.ReferencePolicyOption; import org.osgi.framework.BundleContext; @@ -56,6 +54,7 @@ final class OsgiServiceUtil { * @param componentContext Component context * @return true if activation/deactivation method was called. False if it failed. */ + @SuppressWarnings("unchecked") public static boolean activateDeactivate(Object target, ComponentContext componentContext, boolean activate) { Class<?> targetClass = target.getClass(); @@ -81,61 +80,7 @@ final class OsgiServiceUtil { } // try to find matching activate/deactivate method and execute it - if (invokeLifecycleMethod(target, targetClass, methodName, !activate, - componentContext, MapUtil.toMap(componentContext.getProperties()))) { - return true; - } - if (fallbackDefaultName) { - return false; - } - - throw new RuntimeException("No matching " + (activate ? "activation" : "deactivation") + " method with name '" + methodName + "' " - + " found in class " + targetClass.getName()); - } - - /** - * Simulate modification of configuration of OSGi service instance. - * @param target Service instance. - * @param properties Updated configuration - * @return true if modified method was called. False if it failed. - */ - public static boolean modified(Object target, ComponentContext componentContext, Map<String,Object> properties) { - Class<?> targetClass = target.getClass(); - - // get method name for activation/deactivation from osgi metadata - OsgiMetadata metadata = OsgiMetadataUtil.getMetadata(targetClass); - if (metadata == null) { - throw new NoScrMetadataException(targetClass); - } - String methodName = metadata.getModifiedMethodName(); - if (StringUtils.isEmpty(methodName)) { - return false; - } - - // try to find matching modified method and execute it - if (invokeLifecycleMethod(target, targetClass, methodName, false, componentContext, properties)) { - return true; - } - - throw new RuntimeException("No matching modified method with name '" + methodName + "' " - + " found in class " + targetClass.getName()); - } - - /** - * Invokes a lifecycle method (activation, deactivation or modified) with variable method arguments. - * @param target Target object - * @param targetClass Target object class - * @param methodName Method name - * @param allowIntegerArgument Allow int or Integer as arguments (only decactivate) - * @param componentContext Component context - * @param properties Component properties - * @return true if a method was found and invoked - */ - private static boolean invokeLifecycleMethod(Object target, Class<?> targetClass, - String methodName, boolean allowIntegerArgument, - ComponentContext componentContext, Map<String,Object> properties) { - // 1. componentContext Method method = getMethod(targetClass, methodName, new Class<?>[] { ComponentContext.class }); if (method != null) { @@ -157,17 +102,8 @@ final class OsgiServiceUtil { return true; } - // 4. Component property type (annotation lass) - method = getMethod(targetClass, methodName, new Class<?>[] { Annotation.class }); - if (method != null) { - invokeMethod(target, method, new Object[] { Annotations.toObject(method.getParameterTypes()[0], - MapUtil.toMap(componentContext.getProperties()), - componentContext.getBundleContext().getBundle(), false) }); - return true; - } - - // 5. int (deactivation only) - if (allowIntegerArgument) { + // 4. int (deactivation only) + if (!activate) { method = getMethod(targetClass, methodName, new Class<?>[] { int.class }); if (method != null) { invokeMethod(target, method, new Object[] { 0 }); @@ -175,8 +111,8 @@ final class OsgiServiceUtil { } } - // 6. Integer (deactivation only) - if (allowIntegerArgument) { + // 5. Integer (deactivation only) + if (!activate) { method = getMethod(targetClass, methodName, new Class<?>[] { Integer.class }); if (method != null) { invokeMethod(target, method, new Object[] { 0 }); @@ -184,10 +120,9 @@ final class OsgiServiceUtil { } } - // 7. mixed arguments - Class<?>[] mixedArgsAllowed = allowIntegerArgument ? - new Class<?>[] { ComponentContext.class, BundleContext.class, Map.class, Annotation.class, int.class, Integer.class } - : new Class<?>[] { ComponentContext.class, BundleContext.class, Map.class, Annotation.class }; + // 6. mixed arguments of componentContext, bundleContext and map + Class<?>[] mixedArgsAllowed = activate ? new Class<?>[] { ComponentContext.class, BundleContext.class, Map.class } + : new Class<?>[] { ComponentContext.class, BundleContext.class, Map.class, int.class, Integer.class }; method = getMethodWithAnyCombinationArgs(targetClass, methodName, mixedArgsAllowed); if (method != null) { Object[] args = new Object[method.getParameterTypes().length]; @@ -201,11 +136,6 @@ final class OsgiServiceUtil { else if (method.getParameterTypes()[i] == Map.class) { args[i] = MapUtil.toMap(componentContext.getProperties()); } - else if (method.getParameterTypes()[i].isAnnotation()) { - args[i] = Annotations.toObject(method.getParameterTypes()[i], - MapUtil.toMap(componentContext.getProperties()), - componentContext.getBundleContext().getBundle(), false); - } else if (method.getParameterTypes()[i] == int.class || method.getParameterTypes()[i] == Integer.class) { args[i] = 0; } @@ -214,31 +144,56 @@ final class OsgiServiceUtil { return true; } - // 8. noargs + // 7. noargs method = getMethod(targetClass, methodName, new Class<?>[0]); if (method != null) { invokeMethod(target, method, new Object[0]); return true; - } + } - return false; + if (fallbackDefaultName) { + return false; + } + throw new RuntimeException("No matching " + (activate ? "activation" : "deactivation") + " method with name '" + methodName + "' " + + " found in class " + targetClass.getName()); + } + + /** + * Simulate modification of configuration of OSGi service instance. + * @param target Service instance. + * @param properties Updated configuration + * @return true if modified method was called. False if it failed. + */ + public static boolean modified(Object target, BundleContext bundleContext, Map<String,Object> properties) { + Class<?> targetClass = target.getClass(); + + // get method name for activation/deactivation from osgi metadata + OsgiMetadata metadata = OsgiMetadataUtil.getMetadata(targetClass); + if (metadata == null) { + throw new NoScrMetadataException(targetClass); + } + String methodName = metadata.getModifiedMethodName(); + if (StringUtils.isEmpty(methodName)) { + return false; + } + + // try to find matching modified method and execute it + Method method = getMethod(targetClass, methodName, new Class<?>[] { Map.class }); + if (method != null) { + invokeMethod(target, method, new Object[] { properties }); + return true; + } + + throw new RuntimeException("No matching modified method with name '" + methodName + "' " + + " found in class " + targetClass.getName()); } private static Method getMethod(Class clazz, String methodName, Class<?>[] types) { Method[] methods = clazz.getDeclaredMethods(); for (Method method : methods) { - if (StringUtils.equals(method.getName(), methodName) && method.getParameterTypes().length==types.length) { - boolean foundMismatch = false; - for (int i=0; i<types.length; i++) { - if (!((method.getParameterTypes()[i]==types[i]) - || (types[i]==Annotation.class && method.getParameterTypes()[i].isAnnotation()))) { - foundMismatch = true; - break; - } - } - if (!foundMismatch) { - return method; - } + if (StringUtils.equals(method.getName(), methodName) + && Arrays.equals(method.getParameterTypes(), types)) { + return method; } } // not found? check super classes @@ -256,7 +211,7 @@ final class OsgiServiceUtil { boolean foundMismatch = false; for (int i=0; i<types.length; i++) { if (!method.getParameterTypes()[i].isAssignableFrom(types[i])) { - foundMismatch = true; + foundMismatch = false; break; } } @@ -277,24 +232,12 @@ final class OsgiServiceUtil { Method[] methods = clazz.getDeclaredMethods(); for (Method method : methods) { if (StringUtils.equals(method.getName(), methodName) && method.getParameterTypes().length > 1) { - boolean foundMismatch = false; for (Class<?> parameterType : method.getParameterTypes()) { - boolean foundAnyMatch = false; - for (int i=0; i<types.length; i++) { - if ((parameterType==types[i]) - || (types[i]==Annotation.class && parameterType.isAnnotation())) { - foundAnyMatch = true; - break; - } - } - if (!foundAnyMatch) { - foundMismatch = true; - break; + if (!ArrayUtils.contains(types, parameterType)) { + return null; } } - if (!foundMismatch) { - return method; - } + return method; } } // not found? check super classes @@ -321,49 +264,6 @@ final class OsgiServiceUtil { } } - private static Field getField(Class clazz, String fieldName, Class<?> type) { - Field[] fields = clazz.getDeclaredFields(); - for (Field field : fields) { - if (StringUtils.equals(field.getName(), fieldName) && field.getType().equals(type)) { - return field; - } - } - // not found? check super classes - Class<?> superClass = clazz.getSuperclass(); - if (superClass != null && superClass != Object.class) { - return getField(superClass, fieldName, type); - } - return null; - } - - private static Field getFieldWithAssignableType(Class clazz, String fieldName, Class<?> type) { - Field[] fields = clazz.getDeclaredFields(); - for (Field field : fields) { - if (StringUtils.equals(field.getName(), fieldName) && field.getType().isAssignableFrom(type)) { - return field; - } - } - // not found? check super classes - Class<?> superClass = clazz.getSuperclass(); - if (superClass != null && superClass != Object.class) { - return getFieldWithAssignableType(superClass, fieldName, type); - } - return null; - } - - private static void setField(Object target, Field field, Object value) { - try { - field.setAccessible(true); - field.set(target, value); - } catch (IllegalAccessException ex) { - throw new RuntimeException("Unable to set field '" + field.getName() + "' for class " - + target.getClass().getName(), ex); - } catch (IllegalArgumentException ex) { - throw new RuntimeException("Unable to set field '" + field.getName() + "' for class " - + target.getClass().getName(), ex); - } - } - /** * Simulate OSGi service dependency injection. Injects direct references and * multiple references. @@ -396,24 +296,28 @@ final class OsgiServiceUtil { Class<?> targetClass = target.getClass(); // get reference type - Class<?> type = reference.getInterfaceTypeAsClass(); + Class<?> type; + try { + type = Class.forName(reference.getInterfaceType()); + } catch (ClassNotFoundException ex) { + throw new RuntimeException("Unable to instantiate reference type: " + reference.getInterfaceType(), ex); + } // get matching service references - List<ServiceInfo> matchingServices = getMatchingServices(type, bundleContext, reference.getTarget()); + List<ServiceInfo> matchingServices = getMatchingServices(type, bundleContext); // no references found? check if reference was optional if (matchingServices.isEmpty()) { - if (!reference.isCardinalityOptional()) { + boolean isOptional = (reference.getCardinality() == ReferenceCardinality.OPTIONAL_UNARY || reference + .getCardinality() == ReferenceCardinality.OPTIONAL_MULTIPLE); + if (!isOptional) { throw new ReferenceViolationException("Unable to inject mandatory reference '" + reference.getName() + "' for class " + targetClass.getName() + " : no matching services were found."); } - if (reference.isCardinalityMultiple()) { - // make sure at least empty array is set - invokeBindUnbindMethod(reference, target, null, true); - } } // multiple references found? check if reference is not multiple - if (matchingServices.size() > 1 && !reference.isCardinalityMultiple()) { + if (matchingServices.size() > 1 + && (reference.getCardinality() == ReferenceCardinality.MANDATORY_UNARY || reference.getCardinality() == ReferenceCardinality.OPTIONAL_UNARY)) { throw new ReferenceViolationException("Multiple matches found for unary reference '" + reference.getName() + "' for class "+ targetClass.getName()); } @@ -428,14 +332,7 @@ final class OsgiServiceUtil { // try to invoke bind method String methodName = bind ? reference.getBind() : reference.getUnbind(); - String fieldName = reference.getField(); - - if (StringUtils.isEmpty(methodName) && StringUtils.isEmpty(fieldName)) { - throw new RuntimeException("No bind/unbind method name or file name defined " - + "for reference '" + reference.getName() + "' for class " + targetClass.getName()); - } - - if (StringUtils.isNotEmpty(methodName) && serviceInfo != null) { + if (StringUtils.isNotEmpty(methodName)) { // 1. ServiceReference Method method = getMethod(targetClass, methodName, new Class<?>[] { ServiceReference.class }); @@ -445,7 +342,12 @@ final class OsgiServiceUtil { } // 2. assignable from service instance - Class<?> interfaceType = reference.getInterfaceTypeAsClass(); + Class<?> interfaceType; + try { + interfaceType = Class.forName(reference.getInterfaceType()); + } catch (ClassNotFoundException e) { + throw new RuntimeException("Service reference type not found: " + reference.getInterfaceType()); + } method = getMethodWithAssignableTypes(targetClass, methodName, new Class<?>[] { interfaceType }); if (method != null) { invokeMethod(target, method, new Object[] { serviceInfo.getServiceInstance() }); @@ -458,119 +360,10 @@ final class OsgiServiceUtil { invokeMethod(target, method, new Object[] { serviceInfo.getServiceInstance(), serviceInfo.getServiceConfig() }); return; } - - throw new RuntimeException((bind ? "Bind" : "Unbind") + " method with name " + methodName + " not found " - + "for reference '" + reference.getName() + "' for class " + targetClass.getName()); } - - // in OSGi declarative services 1.3 there are no bind/unbind methods - modify the field directly - else if (StringUtils.isNotEmpty(fieldName)) { - - // check for field with list/collection reference - if (reference.isCardinalityMultiple()) { - switch (reference.getFieldCollectionType()) { - case SERVICE: - case REFERENCE: - Object item = null; - if (serviceInfo != null) { - item = serviceInfo.getServiceInstance(); - if (reference.getFieldCollectionType() == FieldCollectionType.REFERENCE) { - item = serviceInfo.getServiceReference(); - } - } - // 1. collection - Field field = getFieldWithAssignableType(targetClass, fieldName, Collection.class); - if (field != null) { - if (bind) { - addToCollection(target, field, item); - } - else { - removeFromCollection(target, field, item); - } - return; - } - - // 2. list - field = getField(targetClass, fieldName, List.class); - if (field != null) { - if (bind) { - addToCollection(target, field, item); - } - else { - removeFromCollection(target, field, item); - } - return; - } - break; - default: - throw new RuntimeException("Field collection type '" + reference.getFieldCollectionType() + "' not supported " - + "for reference '" + reference.getName() + "' for class " + targetClass.getName()); - } - } - - // check for single field reference - else { - // 1. assignable from service instance - Class<?> interfaceType = reference.getInterfaceTypeAsClass(); - Field field = getFieldWithAssignableType(targetClass, fieldName, interfaceType); - if (field != null) { - setField(target, field, bind && serviceInfo != null ? serviceInfo.getServiceInstance() : null); - return; - } - - // 2. ServiceReference - field = getField(targetClass, fieldName, ServiceReference.class); - if (field != null) { - setField(target, field, bind && serviceInfo != null ? serviceInfo.getServiceReference() : null); - return; - } - } - } - - } - - @SuppressWarnings("unchecked") - private static void addToCollection(Object target, Field field, Object item) { - try { - field.setAccessible(true); - Collection<Object> collection = (Collection<Object>)field.get(target); - if (collection == null) { - collection = new ArrayList<Object>(); - } - if (item != null) { - collection.add(item); - } - field.set(target, collection); - - } catch (IllegalAccessException ex) { - throw new RuntimeException("Unable to set field '" + field.getName() + "' for class " - + target.getClass().getName(), ex); - } catch (IllegalArgumentException ex) { - throw new RuntimeException("Unable to set field '" + field.getName() + "' for class " - + target.getClass().getName(), ex); - } - } - @SuppressWarnings("unchecked") - private static void removeFromCollection(Object target, Field field, Object item) { - try { - field.setAccessible(true); - Collection<Object> collection = (Collection<Object>)field.get(target); - if (collection == null) { - collection = new ArrayList<Object>(); - } - if (item != null) { - collection.remove(item); - } - field.set(target, collection); - - } catch (IllegalAccessException ex) { - throw new RuntimeException("Unable to set field '" + field.getName() + "' for class " - + target.getClass().getName(), ex); - } catch (IllegalArgumentException ex) { - throw new RuntimeException("Unable to set field '" + field.getName() + "' for class " - + target.getClass().getName(), ex); - } + throw new RuntimeException((bind ? "Bind" : "Unbind") + " method with name " + methodName + " not found " + + "for reference '" + reference.getName() + "' for class " + targetClass.getName()); } /** @@ -593,12 +386,12 @@ final class OsgiServiceUtil { invokeBindUnbindMethod(reference, target, serviceInfo, false); } - private static List<ServiceInfo> getMatchingServices(Class<?> type, BundleContext bundleContext, String filter) { + private static List<ServiceInfo> getMatchingServices(Class<?> type, BundleContext bundleContext) { List<ServiceInfo> matchingServices = new ArrayList<ServiceInfo>(); try { - ServiceReference[] references = bundleContext.getServiceReferences(type.getName(), filter); + ServiceReference[] references = bundleContext.getServiceReferences(type.getName(), null); if (references != null) { - for (ServiceReference<?> serviceReference : references) { + for (ServiceReference serviceReference : references) { Object serviceInstance = bundleContext.getService(serviceReference); Map<String, Object> serviceConfig = new HashMap<String, Object>(); String[] keys = serviceReference.getPropertyKeys(); @@ -622,7 +415,7 @@ final class OsgiServiceUtil { * @return List of references */ public static List<ReferenceInfo> getMatchingDynamicReferences(SortedSet<MockServiceRegistration> registeredServices, - MockServiceRegistration<?> registration) { + MockServiceRegistration registration) { List<ReferenceInfo> references = new ArrayList<ReferenceInfo>(); for (MockServiceRegistration existingRegistration : registeredServices) { OsgiMetadata metadata = OsgiMetadataUtil.getMetadata(existingRegistration.getService().getClass()); @@ -649,7 +442,7 @@ final class OsgiServiceUtil { * @return List of references */ public static List<ReferenceInfo> getMatchingStaticGreedyReferences(SortedSet<MockServiceRegistration> registeredServices, - MockServiceRegistration<?> registration) { + MockServiceRegistration registration) { List<ReferenceInfo> references = new ArrayList<ReferenceInfo>(); for (MockServiceRegistration existingRegistration : registeredServices) { OsgiMetadata metadata = OsgiMetadataUtil.getMetadata(existingRegistration.getService().getClass()); @@ -680,7 +473,6 @@ final class OsgiServiceUtil { this.serviceReference = serviceReference; } - @SuppressWarnings("unchecked") public ServiceInfo(MockServiceRegistration registration) { this.serviceInstance = registration.getService(); this.serviceConfig = MapUtil.toMap(registration.getProperties()); diff --git a/src/main/java/org/apache/sling/testing/mock/osgi/context/AbstractContextPlugin.java b/src/main/java/org/apache/sling/testing/mock/osgi/context/AbstractContextPlugin.java index 5d71c9c..594f05d 100644 --- a/src/main/java/org/apache/sling/testing/mock/osgi/context/AbstractContextPlugin.java +++ b/src/main/java/org/apache/sling/testing/mock/osgi/context/AbstractContextPlugin.java @@ -18,7 +18,7 @@ */ package org.apache.sling.testing.mock.osgi.context; -import org.osgi.annotation.versioning.ConsumerType; +import aQute.bnd.annotation.ConsumerType; /** * Default implementation of {@link ContextPlugin}. diff --git a/src/main/java/org/apache/sling/testing/mock/osgi/context/ContextCallback.java b/src/main/java/org/apache/sling/testing/mock/osgi/context/ContextCallback.java index aa2ed12..e50514d 100644 --- a/src/main/java/org/apache/sling/testing/mock/osgi/context/ContextCallback.java +++ b/src/main/java/org/apache/sling/testing/mock/osgi/context/ContextCallback.java @@ -18,7 +18,7 @@ */ package org.apache.sling.testing.mock.osgi.context; -import org.osgi.annotation.versioning.ConsumerType; +import aQute.bnd.annotation.ConsumerType; /** * Callback interface for application-specific setup and teardown operations to diff --git a/src/main/java/org/apache/sling/testing/mock/osgi/context/ContextPlugin.java b/src/main/java/org/apache/sling/testing/mock/osgi/context/ContextPlugin.java index 4fe3616..df7e458 100644 --- a/src/main/java/org/apache/sling/testing/mock/osgi/context/ContextPlugin.java +++ b/src/main/java/org/apache/sling/testing/mock/osgi/context/ContextPlugin.java @@ -18,7 +18,7 @@ */ package org.apache.sling.testing.mock.osgi.context; -import org.osgi.annotation.versioning.ConsumerType; +import aQute.bnd.annotation.ConsumerType; /** * Callback plugin for application-specific setup and teardown operations to diff --git a/src/main/java/org/apache/sling/testing/mock/osgi/context/ContextPlugins.java b/src/main/java/org/apache/sling/testing/mock/osgi/context/ContextPlugins.java index 503bf92..26a2b2a 100644 --- a/src/main/java/org/apache/sling/testing/mock/osgi/context/ContextPlugins.java +++ b/src/main/java/org/apache/sling/testing/mock/osgi/context/ContextPlugins.java @@ -22,7 +22,7 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; -import org.osgi.annotation.versioning.ProviderType; +import aQute.bnd.annotation.ProviderType; /** * Collects list of context plugins. @@ -30,7 +30,7 @@ import org.osgi.annotation.versioning.ProviderType; @ProviderType public final class ContextPlugins { - private List<ContextPlugin<? extends OsgiContextImpl>> plugins = new ArrayList<>(); + private List<ContextPlugin<? extends OsgiContextImpl>> plugins = new ArrayList<ContextPlugin<? extends OsgiContextImpl>>(); /** * Start with empty list. @@ -44,6 +44,7 @@ public final class ContextPlugins { * @param <T> context type * @param afterSetUpCallback Allows the application to register an own callback function that is called after the built-in setup rules are executed. */ + @SuppressWarnings("unchecked") public <T extends OsgiContextImpl> ContextPlugins(final ContextCallback<T> afterSetUpCallback) { addAfterSetUpCallback(afterSetUpCallback); } @@ -55,6 +56,7 @@ public final class ContextPlugins { * @param afterSetUpCallback Allows the application to register an own callback function that is called after the built-in setup rules are executed. * @param beforeTearDownCallback Allows the application to register an own callback function that is called before the built-in teardown rules are executed. */ + @SuppressWarnings("unchecked") public <U extends OsgiContextImpl, V extends OsgiContextImpl> ContextPlugins(final ContextCallback<U> afterSetUpCallback, final ContextCallback<V> beforeTearDownCallback) { addAfterSetUpCallback(afterSetUpCallback); addBeforeTearDownCallback(beforeTearDownCallback); diff --git a/src/main/java/org/apache/sling/testing/mock/osgi/context/OsgiContextImpl.java b/src/main/java/org/apache/sling/testing/mock/osgi/context/OsgiContextImpl.java index acb96e7..cfe02a2 100644 --- a/src/main/java/org/apache/sling/testing/mock/osgi/context/OsgiContextImpl.java +++ b/src/main/java/org/apache/sling/testing/mock/osgi/context/OsgiContextImpl.java @@ -25,12 +25,13 @@ import java.util.Map; import org.apache.sling.testing.mock.osgi.MapUtil; import org.apache.sling.testing.mock.osgi.MockEventAdmin; import org.apache.sling.testing.mock.osgi.MockOsgi; -import org.osgi.annotation.versioning.ConsumerType; import org.osgi.framework.BundleContext; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; import org.osgi.service.component.ComponentContext; +import aQute.bnd.annotation.ConsumerType; + /** * Defines OSGi context objects and helper methods. Should not be used directly * but via the {@link org.apache.sling.testing.mock.osgi.junit.OsgiContext} JUnit rule. diff --git a/src/main/java/org/apache/sling/testing/mock/osgi/context/package-info.java b/src/main/java/org/apache/sling/testing/mock/osgi/context/package-info.java index 6e57ffd..fbd1a7b 100644 --- a/src/main/java/org/apache/sling/testing/mock/osgi/context/package-info.java +++ b/src/main/java/org/apache/sling/testing/mock/osgi/context/package-info.java @@ -19,5 +19,5 @@ /** * OSGi context implementation for unit tests. */ -@org.osgi.annotation.versioning.Version("1.2") +@aQute.bnd.annotation.Version("1.2") package org.apache.sling.testing.mock.osgi.context; diff --git a/src/main/java/org/apache/sling/testing/mock/osgi/junit/OsgiContext.java b/src/main/java/org/apache/sling/testing/mock/osgi/junit/OsgiContext.java index 77e8ad5..f9718e3 100644 --- a/src/main/java/org/apache/sling/testing/mock/osgi/junit/OsgiContext.java +++ b/src/main/java/org/apache/sling/testing/mock/osgi/junit/OsgiContext.java @@ -25,7 +25,8 @@ import org.junit.rules.ExternalResource; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; -import org.osgi.annotation.versioning.ProviderType; + +import aQute.bnd.annotation.ProviderType; /** * JUnit rule for setting up and tearing down OSGi context for unit tests. diff --git a/src/main/java/org/apache/sling/testing/mock/osgi/junit/OsgiContextBuilder.java b/src/main/java/org/apache/sling/testing/mock/osgi/junit/OsgiContextBuilder.java index 9207e40..05d2220 100644 --- a/src/main/java/org/apache/sling/testing/mock/osgi/junit/OsgiContextBuilder.java +++ b/src/main/java/org/apache/sling/testing/mock/osgi/junit/OsgiContextBuilder.java @@ -18,11 +18,12 @@ */ package org.apache.sling.testing.mock.osgi.junit; -import org.apache.sling.testing.mock.osgi.context.ContextPlugins; -import org.apache.sling.testing.mock.osgi.context.OsgiContextImpl; import org.apache.sling.testing.mock.osgi.context.ContextCallback; import org.apache.sling.testing.mock.osgi.context.ContextPlugin; -import org.osgi.annotation.versioning.ProviderType; +import org.apache.sling.testing.mock.osgi.context.ContextPlugins; +import org.apache.sling.testing.mock.osgi.context.OsgiContextImpl; + +import aQute.bnd.annotation.ProviderType; /** * Builder class for creating {@link OsgiContext} instances with different sets of parameters. diff --git a/src/main/java/org/apache/sling/testing/mock/osgi/junit/OsgiContextCallback.java b/src/main/java/org/apache/sling/testing/mock/osgi/junit/OsgiContextCallback.java index 710b65d..946a9e0 100644 --- a/src/main/java/org/apache/sling/testing/mock/osgi/junit/OsgiContextCallback.java +++ b/src/main/java/org/apache/sling/testing/mock/osgi/junit/OsgiContextCallback.java @@ -19,7 +19,8 @@ package org.apache.sling.testing.mock.osgi.junit; import org.apache.sling.testing.mock.osgi.context.ContextCallback; -import org.osgi.annotation.versioning.ConsumerType; + +import aQute.bnd.annotation.ConsumerType; /** * Callback interface for application-specific setup and teardown operations to diff --git a/src/main/java/org/apache/sling/testing/mock/osgi/junit/package-info.java b/src/main/java/org/apache/sling/testing/mock/osgi/junit/package-info.java index 2295cbc..ca88e22 100644 --- a/src/main/java/org/apache/sling/testing/mock/osgi/junit/package-info.java +++ b/src/main/java/org/apache/sling/testing/mock/osgi/junit/package-info.java @@ -19,5 +19,5 @@ /** * Rule for providing easy access to OSGi context in JUnit tests. */ -@org.osgi.annotation.versioning.Version("2.0") +@aQute.bnd.annotation.Version("2.0") package org.apache.sling.testing.mock.osgi.junit; diff --git a/src/main/java/org/apache/sling/testing/mock/osgi/package-info.java b/src/main/java/org/apache/sling/testing/mock/osgi/package-info.java index d1f57fc..315ee5c 100644 --- a/src/main/java/org/apache/sling/testing/mock/osgi/package-info.java +++ b/src/main/java/org/apache/sling/testing/mock/osgi/package-info.java @@ -19,5 +19,5 @@ /** * Mock implementation of selected OSGi APIs. */ -@org.osgi.annotation.versioning.Version("3.3") +@aQute.bnd.annotation.Version("2.7") package org.apache.sling.testing.mock.osgi; diff --git a/src/test/java/org/apache/sling/testing/mock/osgi/MockBundleContextDynamicReferencesOsgiR6Test.java b/src/test/java/org/apache/sling/testing/mock/osgi/MockBundleContextDynamicReferencesOsgiR6Test.java deleted file mode 100644 index b7d022c..0000000 --- a/src/test/java/org/apache/sling/testing/mock/osgi/MockBundleContextDynamicReferencesOsgiR6Test.java +++ /dev/null @@ -1,188 +0,0 @@ -/* - * 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.sling.testing.mock.osgi; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; - -import org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest.Service3OsgiR6; -import org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest.ServiceInterface1; -import org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest.ServiceInterface1Optional; -import org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest.ServiceInterface2; -import org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest.ServiceInterface3; -import org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest.ServiceSuperInterface3; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceRegistration; - -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; - -@RunWith(MockitoJUnitRunner.class) -public class MockBundleContextDynamicReferencesOsgiR6Test { - - private BundleContext bundleContext; - private Service3OsgiR6 service; - private ServiceRegistration reg1a; - private ServiceRegistration reg2a; - - @Mock - private ServiceInterface1 dependency1a; - @Mock - private ServiceInterface1 dependency1b; - @Mock - private ServiceInterface1Optional dependency1aOptional; - @Mock - private ServiceInterface1Optional dependency1bOptional; - @Mock - private ServiceInterface2 dependency2a; - @Mock - private ServiceInterface2 dependency2b; - @Mock - private ServiceSuperInterface3 dependency3a; - @Mock - private ServiceSuperInterface3 dependency3b; - - @Before - public void setUp() { - bundleContext = MockOsgi.newBundleContext(); - - // setup service instance with only minimum mandatory references - reg1a = bundleContext.registerService(ServiceInterface1.class.getName(), dependency1a, null); - reg2a = bundleContext.registerService(ServiceInterface2.class.getName(), dependency2a, null); - - service = new Service3OsgiR6(); - MockOsgi.injectServices(service, bundleContext); - MockOsgi.activate(service, bundleContext); - bundleContext.registerService(Service3OsgiR6.class.getName(), service, null); - - assertDependency1(dependency1a); - assertDependency1Optional(null); - assertDependencies2(dependency2a); - assertDependencies3(); - } - - @Test - public void testAddRemoveOptionalUnaryService() { - ServiceRegistration reg1aOptional = bundleContext.registerService(ServiceInterface1Optional.class.getName(), dependency1aOptional, null); - assertDependency1Optional(dependency1aOptional); - - reg1aOptional.unregister(); - assertDependency1Optional(null); - } - - public void testAddOptionalUnaryService_TooMany() { - bundleContext.registerService(ServiceInterface1Optional.class.getName(), dependency1aOptional, null); - assertDependency1Optional(dependency1aOptional); - - // in real OSGi this should fail - but this is not covered by the current implementation. so test the real implementation here. - bundleContext.registerService(ServiceInterface1Optional.class.getName(), dependency1bOptional, null); - assertDependency1Optional(dependency1bOptional); - } - - @Test(expected = ReferenceViolationException.class) - public void testAddMandatoryUnaryService_TooMany() { - bundleContext.registerService(ServiceInterface1.class.getName(), dependency1b, null); - } - - @Test(expected = ReferenceViolationException.class) - public void testRemoveMandatoryUnaryService_TooMany() { - reg1a.unregister(); - } - - @Test - public void testAddRemoveOptionalMultipleService() { - ServiceRegistration reg3a = bundleContext.registerService(ServiceInterface3.class.getName(), dependency3a, null); - assertDependencies3(dependency3a); - - ServiceRegistration reg3b = bundleContext.registerService(ServiceInterface3.class.getName(), dependency3b, null); - assertDependencies3(dependency3a, dependency3b); - - reg3a.unregister(); - assertDependencies3(dependency3b); - - reg3b.unregister(); - assertDependencies3(); - } - - @Test - public void testAddRemoveMandatoryMultipleService() { - ServiceRegistration reg2b = bundleContext.registerService(ServiceInterface2.class.getName(), dependency2b, null); - assertDependencies2(dependency2a, dependency2b); - - reg2b.unregister(); - assertDependencies2(dependency2a); - - // in real OSGi this should fail - but this is not covered by the current implementation. so test the real implementation here. - reg2a.unregister(); - assertDependencies2(); - } - - @Test - public void testReferenceWithTargetFilter() { - assertDependencies3Filtered(); - - bundleContext.registerService(ServiceInterface3.class.getName(), dependency3a, - MapUtil.toDictionary(ImmutableMap.<String, Object>of("prop1", "abc"))); - - bundleContext.registerService(ServiceInterface3.class.getName(), dependency3b, - MapUtil.toDictionary(ImmutableMap.<String, Object>of("prop1", "def"))); - - assertDependencies3Filtered(dependency3a); - } - - private void assertDependency1(ServiceInterface1 instance) { - if (instance == null) { - assertNull(service.getReference1()); - } - else { - assertSame(instance, service.getReference1()); - } - } - - private void assertDependency1Optional(ServiceInterface1Optional instance) { - if (instance == null) { - assertNull(service.getReference1Optional()); - } - else { - assertSame(instance, service.getReference1Optional()); - } - } - - private void assertDependencies2(ServiceInterface2... instances) { - assertEquals(ImmutableSet.<ServiceInterface2>copyOf(instances), - ImmutableSet.<ServiceInterface2>copyOf(service.getReferences2())); - } - - private void assertDependencies3(ServiceSuperInterface3... instances) { - assertEquals(ImmutableSet.<ServiceSuperInterface3>copyOf(instances), - ImmutableSet.<ServiceSuperInterface3>copyOf(service.getReferences3())); - } - - private void assertDependencies3Filtered(ServiceSuperInterface3... instances) { - assertEquals(ImmutableSet.<ServiceSuperInterface3>copyOf(instances), - ImmutableSet.<ServiceSuperInterface3>copyOf(service.getReferences3Filtered())); - } - -} diff --git a/src/test/java/org/apache/sling/testing/mock/osgi/MockBundleContextStaticGreedyReferencesTest.java b/src/test/java/org/apache/sling/testing/mock/osgi/MockBundleContextStaticGreedyReferencesTest.java index f707222..98d31c3 100644 --- a/src/test/java/org/apache/sling/testing/mock/osgi/MockBundleContextStaticGreedyReferencesTest.java +++ b/src/test/java/org/apache/sling/testing/mock/osgi/MockBundleContextStaticGreedyReferencesTest.java @@ -179,7 +179,7 @@ public class MockBundleContextStaticGreedyReferencesTest { } private Service3StaticGreedy getService() { - ServiceReference<?> serviceRef = bundleContext.getServiceReference(Service3StaticGreedy.class.getName()); + ServiceReference serviceRef = bundleContext.getServiceReference(Service3StaticGreedy.class.getName()); return (Service3StaticGreedy)bundleContext.getService(serviceRef); } diff --git a/src/test/java/org/apache/sling/testing/mock/osgi/MockBundleContextTest.java b/src/test/java/org/apache/sling/testing/mock/osgi/MockBundleContextTest.java index 1760ced..e68f447 100644 --- a/src/test/java/org/apache/sling/testing/mock/osgi/MockBundleContextTest.java +++ b/src/test/java/org/apache/sling/testing/mock/osgi/MockBundleContextTest.java @@ -30,7 +30,6 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import java.io.File; -import java.util.Collection; import java.util.Dictionary; import java.util.Hashtable; @@ -39,7 +38,6 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; -import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleEvent; import org.osgi.framework.BundleListener; @@ -47,7 +45,6 @@ import org.osgi.framework.Constants; import org.osgi.framework.Filter; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceEvent; -import org.osgi.framework.ServiceFactory; import org.osgi.framework.ServiceListener; import org.osgi.framework.ServiceReference; import org.osgi.framework.ServiceRegistration; @@ -91,27 +88,27 @@ public class MockBundleContextTest { ServiceRegistration reg3 = bundleContext.registerService(clazz3, service3, properties3); // test get service references - ServiceReference<?> refString = bundleContext.getServiceReference(String.class.getName()); + ServiceReference refString = bundleContext.getServiceReference(String.class.getName()); assertSame(reg1.getReference(), refString); - ServiceReference<?> refInteger = bundleContext.getServiceReference(Integer.class.getName()); + ServiceReference refInteger = bundleContext.getServiceReference(Integer.class.getName()); assertSame(reg1.getReference(), refInteger); - ServiceReference<?>[] refsString = bundleContext.getServiceReferences(String.class.getName(), null); + ServiceReference[] refsString = bundleContext.getServiceReferences(String.class.getName(), null); assertEquals(2, refsString.length); assertSame(reg1.getReference(), refsString[0]); assertSame(reg2.getReference(), refsString[1]); - Collection<ServiceReference<String>> refColString = bundleContext.getServiceReferences(String.class, null); - assertEquals(2, refColString.size()); - assertSame(reg1.getReference(), refColString.iterator().next()); + ServiceReference[] refColString = bundleContext.getServiceReferences(String.class.getName(), null); + assertEquals(2, refColString.length); + assertSame(reg1.getReference(), refColString[0]); - ServiceReference<?>[] refsInteger = bundleContext.getServiceReferences(Integer.class.getName(), null); + ServiceReference[] refsInteger = bundleContext.getServiceReferences(Integer.class.getName(), null); assertEquals(2, refsInteger.length); assertSame(reg1.getReference(), refsInteger[0]); assertSame(reg3.getReference(), refsInteger[1]); - ServiceReference<?>[] allRefsString = bundleContext.getAllServiceReferences(String.class.getName(), null); + ServiceReference[] allRefsString = bundleContext.getAllServiceReferences(String.class.getName(), null); assertArrayEquals(refsString, allRefsString); // test get services @@ -126,45 +123,11 @@ public class MockBundleContextTest { } @Test - public void testServiceFactoryRegistration() throws InvalidSyntaxException { - // prepare test services - Class<String> clazz = String.class; - final String service = "abc"; - Dictionary<String, Object> properties1 = ranking(null); - ServiceRegistration reg = bundleContext.registerService(clazz, new ServiceFactory<String>() { - @Override - public String getService(Bundle bundle, ServiceRegistration<String> registration) { - return service; - } - @Override - public void ungetService(Bundle bundle, ServiceRegistration<String> registration, String service) { - // do nothing - } - }, properties1); - - ServiceReference<String> ref = bundleContext.getServiceReference(clazz); - assertNotNull(ref); - assertSame(reg.getReference(), ref); - assertSame(service, bundleContext.getService(ref)); - bundleContext.ungetService(ref); - } - - @Test - public void testNoServiceReferences() throws InvalidSyntaxException { - ServiceReference<?>[] refs = bundleContext.getServiceReferences(String.class.getName(), null); - assertNull(refs); - - Collection<ServiceReference<String>> refCol = bundleContext.getServiceReferences(String.class, null); - assertNotNull(refCol); - assertTrue(refCol.isEmpty()); - } - - @Test public void testServiceUnregistration() { // prepare test services String clazz1 = String.class.getName(); Object service1 = new Object(); - Dictionary<String, Object> properties1 = ranking(null); + Dictionary properties1 = ranking(null); ServiceRegistration reg1 = bundleContext.registerService(clazz1, service1, properties1); assertNotNull(bundleContext.getServiceReference(clazz1)); @@ -174,7 +137,6 @@ public class MockBundleContextTest { assertNull(bundleContext.getServiceReference(clazz1)); } - @Test public void testGetBundles() throws Exception { assertEquals(0, bundleContext.getBundles().length); @@ -253,32 +215,14 @@ public class MockBundleContextTest { } @Test - public void testSystemBundleById() { - Bundle systemBundle = bundleContext.getBundle(Constants.SYSTEM_BUNDLE_ID); - assertNotNull(systemBundle); - assertEquals(Constants.SYSTEM_BUNDLE_ID, systemBundle.getBundleId()); - assertEquals(Constants.SYSTEM_BUNDLE_SYMBOLICNAME, systemBundle.getSymbolicName()); - assertEquals(Constants.SYSTEM_BUNDLE_LOCATION, systemBundle.getLocation()); - } - - @Test - public void testSystemBundleByLocation() { - Bundle systemBundle = bundleContext.getBundle(Constants.SYSTEM_BUNDLE_LOCATION); - assertNotNull(systemBundle); - assertEquals(Constants.SYSTEM_BUNDLE_ID, systemBundle.getBundleId()); - assertEquals(Constants.SYSTEM_BUNDLE_SYMBOLICNAME, systemBundle.getSymbolicName()); - assertEquals(Constants.SYSTEM_BUNDLE_LOCATION, systemBundle.getLocation()); - } - - @Test public void testGetServiceOrderWithRanking() { - bundleContext.registerService(String.class, "service1", ranking(10)); - bundleContext.registerService(String.class, "service2", ranking(20)); - bundleContext.registerService(String.class, "service3", ranking(5)); + bundleContext.registerService(String.class.getName(), "service1", ranking(10)); + bundleContext.registerService(String.class.getName(), "service2", ranking(20)); + bundleContext.registerService(String.class.getName(), "service3", ranking(5)); // should return service with highest ranking - ServiceReference<String> ref = bundleContext.getServiceReference(String.class); - String service = bundleContext.getService(ref); + ServiceReference ref = bundleContext.getServiceReference(String.class.getName()); + String service = (String)bundleContext.getService(ref); assertEquals("service2", service); bundleContext.ungetService(ref); @@ -286,13 +230,13 @@ public class MockBundleContextTest { @Test public void testGetServiceOrderWithoutRanking() { - bundleContext.registerService(String.class, "service1", ranking(null)); - bundleContext.registerService(String.class, "service2", ranking(null)); - bundleContext.registerService(String.class, "service3", ranking(null)); + bundleContext.registerService(String.class.getName(), "service1", ranking(null)); + bundleContext.registerService(String.class.getName(), "service2", ranking(null)); + bundleContext.registerService(String.class.getName(), "service3", ranking(null)); // should return service with lowest service id = which was registered first - ServiceReference<String> ref = bundleContext.getServiceReference(String.class); - String service = bundleContext.getService(ref); + ServiceReference ref = bundleContext.getServiceReference(String.class.getName()); + String service = (String)bundleContext.getService(ref); assertEquals("service1", service); bundleContext.ungetService(ref); diff --git a/src/test/java/org/apache/sling/testing/mock/osgi/MockComponentContextTest.java b/src/test/java/org/apache/sling/testing/mock/osgi/MockComponentContextTest.java index aab327e..b4497eb 100644 --- a/src/test/java/org/apache/sling/testing/mock/osgi/MockComponentContextTest.java +++ b/src/test/java/org/apache/sling/testing/mock/osgi/MockComponentContextTest.java @@ -71,7 +71,7 @@ public class MockComponentContextTest { String clazz = String.class.getName(); Object service = new Object(); underTest.getBundleContext().registerService(clazz, service, null); - ServiceReference<?> ref = underTest.getBundleContext().getServiceReference(clazz); + ServiceReference ref = underTest.getBundleContext().getServiceReference(clazz); // test locate service Object locatedService = underTest.locateService(null, ref); diff --git a/src/test/java/org/apache/sling/testing/mock/osgi/MockServiceReferencesSortTest.java b/src/test/java/org/apache/sling/testing/mock/osgi/MockServiceReferencesSortTest.java index 2c83bcf..daf1268 100644 --- a/src/test/java/org/apache/sling/testing/mock/osgi/MockServiceReferencesSortTest.java +++ b/src/test/java/org/apache/sling/testing/mock/osgi/MockServiceReferencesSortTest.java @@ -22,8 +22,10 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; +import java.util.ArrayList; import java.util.Arrays; import java.util.Hashtable; +import java.util.List; import org.junit.After; import org.junit.Before; @@ -34,9 +36,7 @@ import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; import org.osgi.framework.ServiceRegistration; -/** - * Test the service-ranking based sorting of mock service references - */ +/** Test the service-ranking based sorting of mock service references */ public class MockServiceReferencesSortTest { private BundleContext bundleContext; @@ -52,73 +52,49 @@ public class MockServiceReferencesSortTest { } @Test - public void testAllWithRanking() { - registerStringServiceWithRanking("A", 3); - registerStringServiceWithRanking("B", 5); - registerStringServiceWithRanking("C", 4); - registerStringServiceWithRanking("D", 1); - registerStringServiceWithRanking("E", 2); - - assertEquals("DEACB", getSortedServicesString()); - assertEquals("B", bundleContext.getService(bundleContext.getServiceReference(String.class))); + public void testServicesOrder() { + assertEquals("12345", getSortedServicesString(bundleContext)); } - @Test - public void testAllWithoutRanking() { - registerStringServiceWithoutRanking("A"); - registerStringServiceWithoutRanking("B"); - registerStringServiceWithoutRanking("C"); - registerStringServiceWithoutRanking("D"); - registerStringServiceWithoutRanking("E"); - - assertEquals("EDCBA", getSortedServicesString()); - assertEquals("A", bundleContext.getService(bundleContext.getServiceReference(String.class))); - } - - @Test - public void testMixed() { - registerStringServiceWithoutRanking("A"); - registerStringServiceWithRanking("B", 5); - registerStringServiceWithoutRanking("C"); - registerStringServiceWithRanking("D", 10); - registerStringServiceWithoutRanking("E"); - - assertEquals("ECABD", getSortedServicesString()); - assertEquals("D", bundleContext.getService(bundleContext.getServiceReference(String.class))); - } - - private ServiceRegistration<?> registerStringServiceWithoutRanking(String serviceValue) { - return bundleContext.registerService(String.class, serviceValue, new Hashtable<String, Object>()); - } - - private ServiceRegistration<?> registerStringServiceWithRanking(String serviceValue, int index) { + private static ServiceRegistration registerStringService(BundleContext ctx, int index) { final Hashtable<String, Object> props = new Hashtable<String, Object>(); props.put(Constants.SERVICE_RANKING, new Integer(index)); - return bundleContext.registerService(String.class, serviceValue, props); + return ctx.registerService(String.class.getName(), String.valueOf(index), props); } /** Register services with a specific ranking, sort their references and * return their concatenated toString() values. * Use to test service references sorting. */ - private String getSortedServicesString() { - ServiceReference<?>[] refs = null; + private static String getSortedServicesString(BundleContext ctx) { + final List<ServiceRegistration> toCleanup = new ArrayList<ServiceRegistration>(); + + toCleanup.add(registerStringService(ctx, 3)); + toCleanup.add(registerStringService(ctx, 5)); + toCleanup.add(registerStringService(ctx, 4)); + toCleanup.add(registerStringService(ctx, 1)); + toCleanup.add(registerStringService(ctx, 2)); + + ServiceReference [] refs = null; try { - refs = bundleContext.getServiceReferences(String.class.getName(), null); - } - catch (InvalidSyntaxException ise) { + refs = ctx.getServiceReferences(String.class.getName(), null); + } catch(InvalidSyntaxException ise) { fail("Unexpected InvalidSyntaxException"); } assertNotNull("Expecting our service references", refs); Arrays.sort(refs); final StringBuilder sb = new StringBuilder(); - for(ServiceReference<?> ref : refs) { - sb.append(bundleContext.getService(ref).toString()); - bundleContext.ungetService(ref); + for(ServiceReference ref : refs) { + sb.append(ctx.getService(ref).toString()); + ctx.ungetService(ref); + } + + for(ServiceRegistration reg : toCleanup) { + reg.unregister(); } return sb.toString(); } -} +} \ No newline at end of file diff --git a/src/test/java/org/apache/sling/testing/mock/osgi/OsgiServiceUtilActivateDeactivateTest.java b/src/test/java/org/apache/sling/testing/mock/osgi/OsgiServiceUtilActivateDeactivateTest.java index 60358a4..8c91aac 100644 --- a/src/test/java/org/apache/sling/testing/mock/osgi/OsgiServiceUtilActivateDeactivateTest.java +++ b/src/test/java/org/apache/sling/testing/mock/osgi/OsgiServiceUtilActivateDeactivateTest.java @@ -25,12 +25,12 @@ import static org.junit.Assert.assertTrue; import java.util.Map; +import org.apache.felix.scr.annotations.Activate; +import org.apache.felix.scr.annotations.Component; +import org.apache.felix.scr.annotations.Deactivate; import org.junit.Test; import org.osgi.framework.BundleContext; import org.osgi.service.component.ComponentContext; -import org.osgi.service.component.annotations.Activate; -import org.osgi.service.component.annotations.Component; -import org.osgi.service.component.annotations.Deactivate; import com.google.common.collect.ImmutableMap; @@ -84,7 +84,6 @@ public class OsgiServiceUtilActivateDeactivateTest { assertTrue(MockOsgi.activate(service, bundleContext, map)); assertTrue(service.isActivated()); - assertEquals(map, ImmutableMap.copyOf(service.getMap())); assertTrue(MockOsgi.deactivate(service, bundleContext, map)); assertFalse(service.isActivated()); @@ -114,25 +113,6 @@ public class OsgiServiceUtilActivateDeactivateTest { assertTrue(MockOsgi.deactivate(service, bundleContext, map)); assertFalse(service.isActivated()); } - - @Test - public void testService7() { - Service7 service = new Service7(); - - assertTrue(MockOsgi.activate(service, bundleContext, map)); - assertTrue(service.isActivated()); - assertSame(bundleContext, service.getComponentContext().getBundleContext()); - assertSame(bundleContext, service.getBundleContext()); - assertEquals(map, ImmutableMap.copyOf(service.getMap())); - - assertTrue(MockOsgi.deactivate(service, bundleContext, map)); - assertFalse(service.isActivated()); - } - - - public @interface ServiceConfig { - String prop1(); - } @Component public static class Service1 { @@ -222,12 +202,10 @@ public class OsgiServiceUtilActivateDeactivateTest { public static class Service4 { private boolean activated; - private Map<String, Object> map; @Activate - private void activate(ServiceConfig config) { + private void activate() { this.activated = true; - map = ImmutableMap.<String, Object>of("prop1", config.prop1()); } @Deactivate @@ -239,10 +217,6 @@ public class OsgiServiceUtilActivateDeactivateTest { return activated; } - public Map<String, Object> getMap() { - return map; - } - } @Component @@ -308,46 +282,4 @@ public class OsgiServiceUtilActivateDeactivateTest { } - @Component - public static class Service7 { - - private boolean activated; - private ComponentContext componentContext; - private BundleContext bundleContext; - private Map<String,Object> map; - - @Activate - private void activate(ComponentContext componentContext, ServiceConfig config, BundleContext bundleContext) { - this.activated = true; - this.componentContext = componentContext; - this.bundleContext = bundleContext; - this.map = ImmutableMap.<String, Object>of("prop1", config.prop1());; - } - - @Deactivate - private void deactivate() { - this.activated = false; - this.componentContext = null; - this.bundleContext = null; - this.map = null; - } - - public boolean isActivated() { - return activated; - } - - public ComponentContext getComponentContext() { - return componentContext; - } - - public BundleContext getBundleContext() { - return bundleContext; - } - - public Map<String, Object> getMap() { - return map; - } - - } - } diff --git a/src/test/java/org/apache/sling/testing/mock/osgi/OsgiServiceUtilTest.java b/src/test/java/org/apache/sling/testing/mock/osgi/OsgiServiceUtilTest.java index 1f92fa7..988cf26 100644 --- a/src/test/java/org/apache/sling/testing/mock/osgi/OsgiServiceUtilTest.java +++ b/src/test/java/org/apache/sling/testing/mock/osgi/OsgiServiceUtilTest.java @@ -31,6 +31,14 @@ import java.util.Hashtable; import java.util.List; import java.util.Map; +import org.apache.felix.scr.annotations.Activate; +import org.apache.felix.scr.annotations.Component; +import org.apache.felix.scr.annotations.Deactivate; +import org.apache.felix.scr.annotations.Property; +import org.apache.felix.scr.annotations.Reference; +import org.apache.felix.scr.annotations.ReferenceCardinality; +import org.apache.felix.scr.annotations.References; +import org.apache.felix.scr.annotations.Service; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -42,12 +50,7 @@ import org.osgi.framework.ServiceFactory; import org.osgi.framework.ServiceReference; import org.osgi.framework.ServiceRegistration; import org.osgi.service.component.ComponentContext; -import org.osgi.service.component.annotations.Activate; -import org.osgi.service.component.annotations.Component; -import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Modified; -import org.osgi.service.component.annotations.Reference; -import org.osgi.service.component.annotations.ReferenceCardinality; import com.google.common.collect.ImmutableMap; @@ -219,37 +222,39 @@ public class OsgiServiceUtilTest { // no methods } - @Component(service = ServiceInterface1.class, - property = Constants.SERVICE_RANKING + ":Integer=100") + @Component + @Service(ServiceInterface1.class) + @Property(name = Constants.SERVICE_RANKING, intValue = 100) public static class Service1 implements ServiceInterface1 { // dummy interface } - @Component(service = { ServiceInterface2.class, ServiceInterface3.class }, - property = Constants.SERVICE_RANKING + ":Integer=200") + @Component + @Service({ ServiceInterface2.class, ServiceInterface3.class }) + @Property(name = Constants.SERVICE_RANKING, intValue = 200) public static class Service2 implements ServiceInterface2, ServiceInterface3 { // dummy interface } - @Component(reference = { @Reference(name = "reference2", service = ServiceInterface2.class, cardinality = ReferenceCardinality.AT_LEAST_ONE, - bind="bindReference2", unbind="unbindReference2") }) + @Component + @References({ @Reference(name = "reference2", referenceInterface = ServiceInterface2.class, cardinality = ReferenceCardinality.MANDATORY_MULTIPLE) }) public static class Service3 { - @Reference(bind="bindReference1", unbind="unbindReference1") + @Reference private ServiceInterface1 reference1; - @Reference(cardinality = ReferenceCardinality.OPTIONAL, bind="bindReference1Optional", unbind="unbindReference1Optional") + @Reference(cardinality = ReferenceCardinality.OPTIONAL_UNARY) private ServiceInterface1Optional reference1Optional; private List<ServiceReference> references2 = new ArrayList<ServiceReference>(); - @Reference(name = "reference3", service = ServiceInterface3.class, cardinality = ReferenceCardinality.MULTIPLE, - bind="bindReference3", unbind="unbindReference3") + @Reference(name = "reference3", referenceInterface = ServiceInterface3.class, cardinality = ReferenceCardinality.OPTIONAL_MULTIPLE) private List<ServiceSuperInterface3> references3 = new ArrayList<ServiceSuperInterface3>(); private List<Map<String, Object>> reference3Configs = new ArrayList<Map<String, Object>>(); private ComponentContext componentContext; private Map<String, Object> config; + @SuppressWarnings("unchecked") @Activate private void activate(ComponentContext ctx) { this.componentContext = ctx; @@ -276,7 +281,7 @@ public class OsgiServiceUtilTest { public List<ServiceInterface2> getReferences2() { List<ServiceInterface2> services = new ArrayList<ServiceInterface2>(); - for (ServiceReference<?> serviceReference : references2) { + for (ServiceReference serviceReference : references2) { services.add((ServiceInterface2)componentContext.getBundleContext().getService(serviceReference)); } return services; @@ -334,86 +339,25 @@ public class OsgiServiceUtilTest { } - public static class Service3OsgiR6 { - - private ServiceInterface1 reference1; - private ServiceInterface1Optional reference1Optional; - private List<ServiceReference> references2; - private List<ServiceSuperInterface3> references3; - private List<ServiceSuperInterface3> references3Filtered; - - private ComponentContext componentContext; - private Map<String, Object> config; - - @Activate - private void activate(ComponentContext ctx) { - this.componentContext = ctx; - this.config = MapUtil.toMap(ctx.getProperties()); - } - - @Deactivate - private void deactivate(ComponentContext ctx) { - this.componentContext = null; - } - - @Modified - private void modified(Map<String,Object> newConfig) { - this.config = newConfig; - } - - public ServiceInterface1 getReference1() { - return this.reference1; - } - - public ServiceInterface1Optional getReference1Optional() { - return this.reference1Optional; - } - - public List<ServiceInterface2> getReferences2() { - List<ServiceInterface2> services = new ArrayList<ServiceInterface2>(); - for (ServiceReference<?> serviceReference : references2) { - services.add((ServiceInterface2)componentContext.getBundleContext().getService(serviceReference)); - } - return services; - } - - public List<ServiceSuperInterface3> getReferences3() { - return this.references3; - } - - public List<ServiceSuperInterface3> getReferences3Filtered() { - return this.references3Filtered; - } - - public ComponentContext getComponentContext() { - return this.componentContext; - } - - public Map<String, Object> getConfig() { - return config; - } - - } - - @Component(reference = { @Reference(name = "reference2", service = ServiceInterface2.class, cardinality = ReferenceCardinality.AT_LEAST_ONE, - bind="bindReference2", unbind="unbindReference2") }) + @Component + @References({ @Reference(name = "reference2", referenceInterface = ServiceInterface2.class, cardinality = ReferenceCardinality.MANDATORY_MULTIPLE) }) public static class Service3StaticGreedy { - @Reference(bind="bindReference1", unbind="unbindReference1") + @Reference private ServiceInterface1 reference1; - @Reference(cardinality = ReferenceCardinality.OPTIONAL, bind="bindReference1Optional", unbind="unbindReference1Optional") + @Reference(cardinality = ReferenceCardinality.OPTIONAL_UNARY) private ServiceInterface1Optional reference1Optional; private List<ServiceReference> references2 = new ArrayList<ServiceReference>(); - @Reference(name = "reference3", service = ServiceInterface3.class, cardinality = ReferenceCardinality.MULTIPLE, - bind="bindReference3", unbind="unbindReference3") + @Reference(name = "reference3", referenceInterface = ServiceInterface3.class, cardinality = ReferenceCardinality.OPTIONAL_MULTIPLE) private List<ServiceSuperInterface3> references3 = new ArrayList<ServiceSuperInterface3>(); private List<Map<String, Object>> reference3Configs = new ArrayList<Map<String, Object>>(); private ComponentContext componentContext; private Map<String, Object> config; + @SuppressWarnings("unchecked") @Activate private void activate(ComponentContext ctx) { this.componentContext = ctx; @@ -440,7 +384,7 @@ public class OsgiServiceUtilTest { public List<ServiceInterface2> getReferences2() { List<ServiceInterface2> services = new ArrayList<ServiceInterface2>(); - for (ServiceReference<?> serviceReference : references2) { + for (ServiceReference serviceReference : references2) { services.add((ServiceInterface2)componentContext.getBundleContext().getService(serviceReference)); } return services; @@ -498,7 +442,8 @@ public class OsgiServiceUtilTest { } - @Component(reference = @Reference(service = ServiceInterface1.class, name = "customName", bind = "customBind", unbind = "customUnbind")) + @Component + @Reference(referenceInterface = ServiceInterface1.class, name = "customName", bind = "customBind", unbind = "customUnbind") public static class Service4 { private ServiceInterface1 reference1; @@ -517,7 +462,8 @@ public class OsgiServiceUtilTest { } - @Component(service = { ServiceInterface5.class }) + @Component + @Service({ ServiceInterface5.class }) public static class Service5 implements ServiceInterface5 { @Override @@ -532,7 +478,8 @@ public class OsgiServiceUtilTest { } - @Component(service = ServiceFactory1.class, servicefactory = true) + @Component + @Service(value=ServiceFactory1.class, serviceFactory=true) public static class ServiceFactory1 { } diff --git a/src/test/java/org/apache/sling/testing/mock/osgi/context/OsgiContextImplTest.java b/src/test/java/org/apache/sling/testing/mock/osgi/context/OsgiContextImplTest.java index 36fd122..ea2e5df 100644 --- a/src/test/java/org/apache/sling/testing/mock/osgi/context/OsgiContextImplTest.java +++ b/src/test/java/org/apache/sling/testing/mock/osgi/context/OsgiContextImplTest.java @@ -75,7 +75,7 @@ public class OsgiContextImplTest { Set<String> myService = new HashSet<String>(); context.registerService(Set.class, myService, props); - ServiceReference<?> serviceReference = context.bundleContext().getServiceReference(Set.class.getName()); + ServiceReference serviceReference = context.bundleContext().getServiceReference(Set.class.getName()); Object serviceResult = context.bundleContext().getService(serviceReference); assertSame(myService, serviceResult); assertEquals("value1", serviceReference.getProperty("prop1")); @@ -86,7 +86,7 @@ public class OsgiContextImplTest { Set<String> myService = new HashSet<String>(); context.registerService(Set.class, myService, "prop1", "value1"); - ServiceReference<?> serviceReference = context.bundleContext().getServiceReference(Set.class.getName()); + ServiceReference serviceReference = context.bundleContext().getServiceReference(Set.class.getName()); Object serviceResult = context.bundleContext().getService(serviceReference); assertSame(myService, serviceResult); assertEquals("value1", serviceReference.getProperty("prop1")); @@ -101,8 +101,6 @@ public class OsgiContextImplTest { context.registerService(Set.class, myService1); Set<String> myService2 = new HashSet<String>(); context.registerService(Set.class, myService2); - - assertSame(myService1, context.getService(Set.class)); // expected: ascending order because ordering ascending by service ID serviceResults = context.getServices(Set.class, null); @@ -142,7 +140,7 @@ public class OsgiContextImplTest { public void testRegisterInjectActivateWithPropertyMapNulls() { context.registerService(ServiceInterface1.class, mock(ServiceInterface1.class)); context.registerService(ServiceInterface2.class, mock(ServiceInterface2.class)); - Map<String,Object> props = new HashMap<>(); + Map<String,Object> props = new HashMap<String,Object>(); props.put("prop1", "value3"); props.put("prop2", null); props.put(null, "value4"); diff --git a/src/test/java/org/apache/sling/testing/mock/osgi/junit/OsgiContextTest.java b/src/test/java/org/apache/sling/testing/mock/osgi/junit/OsgiContextTest.java index 840e951..f361345 100644 --- a/src/test/java/org/apache/sling/testing/mock/osgi/junit/OsgiContextTest.java +++ b/src/test/java/org/apache/sling/testing/mock/osgi/junit/OsgiContextTest.java @@ -37,6 +37,7 @@ public class OsgiContextTest { private final OsgiContextCallback contextAfterTeardown = mock(OsgiContextCallback.class); // Run all unit tests for each resource resolver types listed here + @SuppressWarnings("unchecked") @Rule public OsgiContext context = new OsgiContextBuilder() .beforeSetUp(contextBeforeSetup) diff --git a/src/test/resources/OSGI-INF/org.apache.sling.testing.mock.osgi.OsgiServiceUtilActivateDeactivateTest.xml b/src/test/resources/OSGI-INF/org.apache.sling.testing.mock.osgi.OsgiServiceUtilActivateDeactivateTest.xml index a869506..61b4bc6 100644 --- a/src/test/resources/OSGI-INF/org.apache.sling.testing.mock.osgi.OsgiServiceUtilActivateDeactivateTest.xml +++ b/src/test/resources/OSGI-INF/org.apache.sling.testing.mock.osgi.OsgiServiceUtilActivateDeactivateTest.xml @@ -36,7 +36,4 @@ <scr:component name="org.apache.sling.testing.mock.osgi.OsgiServiceUtilActivateDeactivateTest$Service6" activate="activate" deactivate="deactivate"> <implementation class="org.apache.sling.testing.mock.osgi.OsgiServiceUtilActivateDeactivateTest$Service6"/> </scr:component> - <scr:component name="org.apache.sling.testing.mock.osgi.OsgiServiceUtilActivateDeactivateTest$Service7" activate="activate" deactivate="deactivate"> - <implementation class="org.apache.sling.testing.mock.osgi.OsgiServiceUtilActivateDeactivateTest$Service7"/> - </scr:component> </components> diff --git a/src/test/resources/OSGI-INF/org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest.xml b/src/test/resources/OSGI-INF/org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest.xml index 0229572..bf88df7 100644 --- a/src/test/resources/OSGI-INF/org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest.xml +++ b/src/test/resources/OSGI-INF/org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest.xml @@ -43,15 +43,6 @@ <reference name="reference2" interface="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$ServiceInterface2" cardinality="1..n" policy="dynamic" bind="bindReference2" unbind="unbindReference2"/> <reference name="reference3" interface="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$ServiceInterface3" cardinality="0..n" policy="dynamic" bind="bindReference3" unbind="unbindReference3"/> </scr:component> - <scr:component name="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$Service3OsgiR6" activate="activate" deactivate="deactivate" modified="modified"> - <implementation class="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$Service3OsgiR6"/> - <property name="service.pid" value="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$Service3OsgiR6"/> - <reference name="reference1" interface="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$ServiceInterface1" cardinality="1..1" policy="dynamic" field="reference1"/> - <reference name="reference1Optional" interface="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$ServiceInterface1Optional" cardinality="0..1" policy="dynamic" field="reference1Optional"/> - <reference name="reference2" interface="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$ServiceInterface2" cardinality="1..n" policy="dynamic" field="references2" field-collection-type="reference"/> - <reference name="reference3" interface="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$ServiceInterface3" cardinality="0..n" policy="dynamic" field="references3" field-collection-type="service"/> - <reference name="references3Filtered" interface="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$ServiceInterface3" cardinality="0..n" policy="dynamic" field="references3Filtered" field-collection-type="service" target="(prop1=abc)"/> - </scr:component> <scr:component name="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$Service3StaticGreedy" activate="activate" deactivate="deactivate" modified="modified"> <implementation class="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$Service3StaticGreedy"/> <property name="service.pid" value="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$Service3StaticGreedy"/> -- To stop receiving notification emails like this one, please contact "commits@sling.apache.org" <commits@sling.apache.org>.