You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@sling.apache.org by ro...@apache.org on 2017/11/07 10:18:46 UTC

[sling-org-apache-sling-testing-osgi-mock] annotated tag org.apache.sling.testing.osgi-mock-1.2.0 created (now b889f50)

This is an automated email from the ASF dual-hosted git repository.

rombert pushed a change to annotated tag org.apache.sling.testing.osgi-mock-1.2.0
in repository https://gitbox.apache.org/repos/asf/sling-org-apache-sling-testing-osgi-mock.git.


      at b889f50  (tag)
 tagging d47b2ce4c4d9b0eb4c9527120fe5c9b639bd06bd (commit)
      by Stefan Seifert
      on Sun Feb 22 20:15:44 2015 +0000

- Log -----------------------------------------------------------------
org.apache.sling.testing.osgi-mock-1.2.0
-----------------------------------------------------------------------

This annotated tag includes the following new commits:

     new e5ba840  SLING-4042 Donate sling-mock, jcr-mock, osgi-mock implementation
     new e1ee5ad  svn:ignore
     new 8d20817  SLING-4042 move all mock projects to mocks/ subdirectory
     new ad838b2  SLING-4042 add missing package-info files
     new 740687d  SLING-4042 make sure dependency injection is continued even if not all injections succeeded, and report root cause of invocation target exceptions
     new 7e5bc2d  SLING-4042 add README files
     new 21a5152  add/update SCM urls
     new 74be83a  [maven-release-plugin] prepare release org.apache.sling.testing.osgi-mock-1.0.0
     new d794a37  [maven-release-plugin] prepare for next development iteration
     new 0a80e0c  SLING-4090 Define package versions for Sling Mock, JCR Mock, OSGi Mock
     new 59f74f6  SLING-4142 MockOsgi: Activate/Deactivate method does not support different signatures
     new a822c76  SLING-4162 Introduce "OsgiContext" junit rule for OSGi and OsgiContextImpl
     new b30dd56  SLING-4162 fix javadoc
     new c40b2dd  SLING-4163 OSGi Mock: Reference bind/unbind method picking order
     new abe8b21  fix some javadoc copy&paste errors and formatting
     new 7c2b519  SLING-4166 OSGi Mock: Support for "modified" SCR lifecycle method
     new 4d131cd  SLING-4166 update package version
     new 907c7df  SLING-4165 OSGi Mock: Fail-fast when calling methods requiring SCR metadata and this is not present
     new 5538cda  SLING-4201 MockOsgi.activate()/deactivate()/modified() should fail fast if method is declared but can't be found
     new 50112aa  SLING-4202 OSGi Mock: Fail-fast when mandatory references cannot be injected
     new 70f5447  fix some javadoc errors/warnings
     new d7f336c  [maven-release-plugin] prepare release org.apache.sling.testing.osgi-mock-1.1.0
     new 5022c27  [maven-release-plugin] prepare for next development iteration
     new b910746  rename package-private class ReflectinServiceUtil to OsgiServiceUtil because it does not any longer use reflection to do it's job (no functional change)
     new 68de5d4  SLING-4435 OSGi Mock: Cache reading of OSGi SCR Metadata files
     new dc9866e  SLING-4439 add support for unregistering services and prepare dynamic service reference handling
     new e3e8bb1  SLING-4439 implement dynamic service registration
     new e6baa2c  SLING-4439 implement dynamic service registration
     new a980473  SLING-4439 implement dynamic service registration
     new e828e3d  SLING-4439 implement dynamic service registration - support string array properties in osgi metadata as well - merge properties from osgi metadata with those specified on activation/registration call - support "old-style" scr component metadata file as well (and test this case)
     new 5afcfc6  [maven-release-plugin] prepare release org.apache.sling.testing.osgi-mock-1.2.0
     new d47b2ce  [maven-release-plugin]  copy for tag org.apache.sling.testing.osgi-mock-1.2.0

The 32 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


-- 
To stop receiving notification emails like this one, please contact
['"commits@sling.apache.org" <co...@sling.apache.org>'].

[sling-org-apache-sling-testing-osgi-mock] 09/10: [maven-release-plugin] prepare release org.apache.sling.testing.osgi-mock-1.2.0

Posted by ro...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rombert pushed a commit to annotated tag org.apache.sling.testing.osgi-mock-1.2.0
in repository https://gitbox.apache.org/repos/asf/sling-org-apache-sling-testing-osgi-mock.git

commit 5afcfc6d8671f69a34239465b4014d09432a9bbb
Author: Stefan Seifert <ss...@apache.org>
AuthorDate: Sun Feb 22 20:15:26 2015 +0000

    [maven-release-plugin] prepare release org.apache.sling.testing.osgi-mock-1.2.0
    
    git-svn-id: https://svn.apache.org/repos/asf/sling/trunk/testing/mocks/osgi-mock@1661542 13f79535-47bb-0310-9956-ffa450edef68
---
 pom.xml | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/pom.xml b/pom.xml
index 3c036fc..680652c 100644
--- a/pom.xml
+++ b/pom.xml
@@ -28,7 +28,7 @@
     </parent>
 
     <artifactId>org.apache.sling.testing.osgi-mock</artifactId>
-    <version>1.1.1-SNAPSHOT</version>
+    <version>1.2.0</version>
     <packaging>bundle</packaging>
 
     <name>Apache Sling Testing OSGi Mock</name>
@@ -39,9 +39,9 @@
     </properties>
 
     <scm>
-        <connection>scm:svn:http://svn.apache.org/repos/asf/sling/trunk/testing/mocks/osgi-mock</connection>
-        <developerConnection>scm:svn:https://svn.apache.org/repos/asf/sling/trunk/testing/mocks/osgi-mock</developerConnection>
-        <url>http://svn.apache.org/viewvc/sling/trunk/testing/mocks/osgi-mock</url>
+        <connection>scm:svn:http://svn.apache.org/repos/asf/sling/tags/org.apache.sling.testing.osgi-mock-1.2.0</connection>
+        <developerConnection>scm:svn:https://svn.apache.org/repos/asf/sling/tags/org.apache.sling.testing.osgi-mock-1.2.0</developerConnection>
+        <url>http://svn.apache.org/viewvc/sling/tags/org.apache.sling.testing.osgi-mock-1.2.0</url>
     </scm>
 
     <dependencies>

-- 
To stop receiving notification emails like this one, please contact
"commits@sling.apache.org" <co...@sling.apache.org>.

[sling-org-apache-sling-testing-osgi-mock] 07/10: SLING-4439 implement dynamic service registration

Posted by ro...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rombert pushed a commit to annotated tag org.apache.sling.testing.osgi-mock-1.2.0
in repository https://gitbox.apache.org/repos/asf/sling-org-apache-sling-testing-osgi-mock.git

commit a9804736b3437fb5cff74fee9ad2f909a0ac85e3
Author: Stefan Seifert <ss...@apache.org>
AuthorDate: Thu Feb 19 22:54:45 2015 +0000

    SLING-4439 implement dynamic service registration
    
    git-svn-id: https://svn.apache.org/repos/asf/sling/trunk/testing/mocks/osgi-mock@1661030 13f79535-47bb-0310-9956-ffa450edef68
---
 .../sling/testing/mock/osgi/MockBundleContext.java |   4 +-
 .../sling/testing/mock/osgi/OsgiMetadataUtil.java  | 108 ++++++++++++++++-----
 .../sling/testing/mock/osgi/OsgiServiceUtil.java   |  22 ++++-
 .../testing/mock/osgi/OsgiMetadataUtilTest.java    |   8 +-
 ...sling.testing.mock.osgi.OsgiServiceUtilTest.xml |   8 +-
 ...iMetadataUtilTest.xml => serviceComponents.xml} |   1 +
 6 files changed, 108 insertions(+), 43 deletions(-)

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 fddb3c2..075df65 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
@@ -94,7 +94,7 @@ class MockBundleContext implements BundleContext {
      * @param registration
      */
     private void handleRefsUpdateOnRegister(MockServiceRegistration registration) {
-        List<ReferenceInfo> affectedReferences = OsgiServiceUtil.getMatchingReferences(registeredServices, registration);
+        List<ReferenceInfo> affectedReferences = OsgiServiceUtil.getMatchingDynamicReferences(registeredServices, registration);
         for (ReferenceInfo referenceInfo : affectedReferences) {
             Reference reference = referenceInfo.getReference();
             switch (reference.getCardinality()) {
@@ -125,7 +125,7 @@ class MockBundleContext implements BundleContext {
      * @param registration
      */
     private void handleRefsUpdateOnUnregister(MockServiceRegistration registration) {
-        List<ReferenceInfo> affectedReferences = OsgiServiceUtil.getMatchingReferences(registeredServices, registration);
+        List<ReferenceInfo> affectedReferences = OsgiServiceUtil.getMatchingDynamicReferences(registeredServices, registration);
         for (ReferenceInfo referenceInfo : affectedReferences) {
             Reference reference = referenceInfo.getReference();
             switch (reference.getCardinality()) {
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 b64cd39..359ac5b 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
@@ -20,7 +20,9 @@ package org.apache.sling.testing.mock.osgi;
 
 import java.io.IOException;
 import java.io.InputStream;
+import java.net.URL;
 import java.util.ArrayList;
+import java.util.Enumeration;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.Iterator;
@@ -40,6 +42,7 @@ import javax.xml.xpath.XPathFactory;
 
 import org.apache.commons.lang3.StringUtils;
 import org.apache.felix.scr.annotations.ReferenceCardinality;
+import org.apache.felix.scr.annotations.ReferencePolicy;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.w3c.dom.Document;
@@ -52,6 +55,7 @@ import com.google.common.cache.CacheLoader;
 import com.google.common.cache.LoadingCache;
 import com.google.common.collect.BiMap;
 import com.google.common.collect.HashBiMap;
+import com.google.common.collect.ImmutableList;
 
 /**
  * Helper methods to parse OSGi metadata.
@@ -82,13 +86,15 @@ final class OsgiMetadataUtil {
     private static final LoadingCache<Class, OsgiMetadata> METADATA_CACHE = CacheBuilder.newBuilder().build(new CacheLoader<Class, OsgiMetadata>() {
         @Override
         public OsgiMetadata load(Class clazz) throws Exception {
-            Document metadataDocument = OsgiMetadataUtil.getMetadataDocument(clazz);
-            if (metadataDocument == null) {
-                return NULL_METADATA;
-            }
-            else {
-                return new OsgiMetadata(clazz, metadataDocument);
+            List<Document> metadataDocuments = OsgiMetadataUtil.getMetadataDocument(clazz);
+            if (metadataDocuments != null) {
+                for (Document metadataDocument : metadataDocuments) {
+                    if (matchesService(clazz, metadataDocument)) {
+                        return new OsgiMetadata(clazz, metadataDocument);
+                    }
+                }
             }
+            return NULL_METADATA;
         }
     });
 
@@ -114,7 +120,11 @@ final class OsgiMetadataUtil {
     };
     
     public static String getMetadataPath(Class clazz) {
-        return "/OSGI-INF/" + StringUtils.substringBefore(clazz.getName(), "$") + ".xml";
+        return "OSGI-INF/" + StringUtils.substringBefore(clazz.getName(), "$") + ".xml";
+    }
+
+    public static String getOldMetadataMultiPath() {
+        return "OSGI-INF/serviceComponents.xml";
     }
 
     /**
@@ -138,32 +148,63 @@ final class OsgiMetadataUtil {
         }
     }
 
-    private static Document getMetadataDocument(Class clazz) {
+    private static List<Document> getMetadataDocument(Class clazz) {
         String metadataPath = getMetadataPath(clazz);
-        InputStream metadataStream = clazz.getResourceAsStream(metadataPath);
-        if (metadataStream == null) {
-            log.debug("No OSGi metadata found at {}", metadataPath);
-            return null;
+        InputStream metadataStream = OsgiMetadataUtil.class.getClassLoader().getResourceAsStream(metadataPath);
+        if (metadataStream == null) {            
+            String oldMetadataPath = getOldMetadataMultiPath();
+            log.debug("No OSGi metadata found at {}, try to fallback to {}", metadataPath, oldMetadataPath);
+
+            try {
+                Enumeration<URL> metadataUrls = OsgiMetadataUtil.class.getClassLoader().getResources(oldMetadataPath);
+                List<Document> docs = new ArrayList<Document>();
+                while (metadataUrls.hasMoreElements()) {
+                    URL metadataUrl = metadataUrls.nextElement();
+                    metadataStream = metadataUrl.openStream();
+                    docs.add(toXmlDocument(metadataStream, oldMetadataPath));
+                }
+                if (docs.size() == 0) {
+                    return null;
+                }
+                else {
+                    return docs;
+                }
+            }
+            catch (IOException ex) {
+                throw new RuntimeException("Unable to read classpath resource: " + oldMetadataPath, ex);
+            }
+        }
+        else {
+            return ImmutableList.of(toXmlDocument(metadataStream, metadataPath));
         }
+    }
+    
+    private static Document toXmlDocument(InputStream inputStream, String path) {
         try {
             DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
             DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
-            return documentBuilder.parse(metadataStream);
+            return documentBuilder.parse(inputStream);
         } catch (ParserConfigurationException ex) {
-            throw new RuntimeException("Unable to read classpath resource: " + metadataPath, ex);
+            throw new RuntimeException("Unable to read classpath resource: " + path, ex);
         } catch (SAXException ex) {
-            throw new RuntimeException("Unable to read classpath resource: " + metadataPath, ex);
+            throw new RuntimeException("Unable to read classpath resource: " + path, ex);
         } catch (IOException ex) {
-            throw new RuntimeException("Unable to read classpath resource: " + metadataPath, ex);
+            throw new RuntimeException("Unable to read classpath resource: " + path, ex);
         } finally {
             try {
-                metadataStream.close();
+                inputStream.close();
             } catch (IOException ex) {
                 // ignore
             }
         }
     }
 
+    private static boolean matchesService(Class clazz, Document metadata) {
+        String query = "/components/component[@name='" + clazz.getName() + "']";
+        NodeList nodes = queryNodes(metadata, query);
+        return nodes != null && nodes.getLength() > 0;
+    }
+    
     private static Set<String> getServiceInterfaces(Class clazz, Document metadata) {
         Set<String> serviceInterfaces = new HashSet<String>();
         String query = "/components/component[@name='" + clazz.getName() + "']/service/provide[@interface!='']";
@@ -317,6 +358,7 @@ final class OsgiMetadataUtil {
         private final String name;
         private final String interfaceType;
         private final ReferenceCardinality cardinality;
+        private final ReferencePolicy policy;
         private final String bind;
         private final String unbind;
 
@@ -325,6 +367,7 @@ final class OsgiMetadataUtil {
             this.name = getAttributeValue(node, "name");
             this.interfaceType = getAttributeValue(node, "interface");
             this.cardinality = toCardinality(getAttributeValue(node, "cardinality"));
+            this.policy = toPolicy(getAttributeValue(node, "policy"));
             this.bind = getAttributeValue(node, "bind");
             this.unbind = getAttributeValue(node, "unbind");
         }
@@ -333,15 +376,6 @@ final class OsgiMetadataUtil {
             return clazz;
         }
 
-        private ReferenceCardinality toCardinality(String value) {
-            for (ReferenceCardinality item : ReferenceCardinality.values()) {
-                if (StringUtils.equals(item.getCardinalityString(), value)) {
-                    return item;
-                }
-            }
-            return ReferenceCardinality.MANDATORY_UNARY;
-        }
-
         public String getName() {
             return this.name;
         }
@@ -353,6 +387,10 @@ final class OsgiMetadataUtil {
         public ReferenceCardinality getCardinality() {
             return this.cardinality;
         }
+        
+        public ReferencePolicy getPolicy() {
+            return policy;
+        }
 
         public String getBind() {
             return this.bind;
@@ -362,6 +400,24 @@ final class OsgiMetadataUtil {
             return this.unbind;
         }
 
+        private static ReferenceCardinality toCardinality(String value) {
+            for (ReferenceCardinality item : ReferenceCardinality.values()) {
+                if (StringUtils.equals(item.getCardinalityString(), value)) {
+                    return item;
+                }
+            }
+            return ReferenceCardinality.MANDATORY_UNARY;
+        }
+
+        private static ReferencePolicy toPolicy(String value) {
+            for (ReferencePolicy item : ReferencePolicy.values()) {
+                if (StringUtils.equalsIgnoreCase(item.name(), value)) {
+                    return item;
+                }
+            }
+            return ReferencePolicy.STATIC;
+        }
+
     }
 
 }
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 1960d0d..82c722c 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
@@ -30,6 +30,7 @@ import java.util.SortedSet;
 import org.apache.commons.lang3.ArrayUtils;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.felix.scr.annotations.ReferenceCardinality;
+import org.apache.felix.scr.annotations.ReferencePolicy;
 import org.apache.sling.testing.mock.osgi.OsgiMetadataUtil.OsgiMetadata;
 import org.apache.sling.testing.mock.osgi.OsgiMetadataUtil.Reference;
 import org.osgi.framework.BundleContext;
@@ -67,8 +68,14 @@ final class OsgiServiceUtil {
         } else {
             methodName = metadata.getDeactivateMethodName();
         }
+        boolean fallbackDefaultName = false;
         if (StringUtils.isEmpty(methodName)) {
-            return false;
+            fallbackDefaultName = true;
+            if (activate) {
+                methodName = "activate";
+            } else {
+                methodName = "deactivate";
+            }
         }
 
         // try to find matching activate/deactivate method and execute it
@@ -143,6 +150,9 @@ final class OsgiServiceUtil {
             return true;
         }
         
+        if (fallbackDefaultName) {
+            return false;
+        }
         throw new RuntimeException("No matching " + (activate ? "activation" : "deactivation") + " method with name '" + methodName + "' "
                 + " found in class " + targetClass.getName());
     }
@@ -402,16 +412,18 @@ final class OsgiServiceUtil {
      * @param registration Service registration
      * @return List of references
      */
-    public static List<ReferenceInfo> getMatchingReferences(SortedSet<MockServiceRegistration> registeredServices,
+    public static List<ReferenceInfo> getMatchingDynamicReferences(SortedSet<MockServiceRegistration> registeredServices,
             MockServiceRegistration registration) {
         List<ReferenceInfo> references = new ArrayList<ReferenceInfo>();
         for (MockServiceRegistration existingRegistration : registeredServices) {
             OsgiMetadata metadata = OsgiMetadataUtil.getMetadata(existingRegistration.getService().getClass());
             if (metadata != null) {
                 for (Reference reference : metadata.getReferences()) {
-                    for (String serviceInterface : registration.getClasses()) {
-                        if (StringUtils.equals(serviceInterface, reference.getInterfaceType())) {
-                            references.add(new ReferenceInfo(existingRegistration, reference));
+                    if (reference.getPolicy() == ReferencePolicy.DYNAMIC) {
+                        for (String serviceInterface : registration.getClasses()) {
+                            if (StringUtils.equals(serviceInterface, reference.getInterfaceType())) {
+                                references.add(new ReferenceInfo(existingRegistration, reference));
+                            }
                         }
                     }
                 }
diff --git a/src/test/java/org/apache/sling/testing/mock/osgi/OsgiMetadataUtilTest.java b/src/test/java/org/apache/sling/testing/mock/osgi/OsgiMetadataUtilTest.java
index 4611d25..ebd671e 100644
--- a/src/test/java/org/apache/sling/testing/mock/osgi/OsgiMetadataUtilTest.java
+++ b/src/test/java/org/apache/sling/testing/mock/osgi/OsgiMetadataUtilTest.java
@@ -19,6 +19,7 @@
 package org.apache.sling.testing.mock.osgi;
 
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
 
 import java.util.List;
@@ -53,12 +54,7 @@ public class OsgiMetadataUtilTest {
     @Test
     public void testNoMetadata() {
         OsgiMetadata metadata = OsgiMetadataUtil.getMetadata(ServiceWithoutMetadata.class);
-
-        Set<String> serviceInterfaces = metadata.getServiceInterfaces();
-        assertEquals(0, serviceInterfaces.size());
-
-        Map<String, Object> props = metadata.getProperties();
-        assertEquals(0, props.size());
+        assertNull(metadata);
     }
 
     @Test
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 ab82616..a1cd7a4 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
@@ -20,10 +20,10 @@
   <scr:component name="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$Service3" activate="activate" deactivate="deactivate" modified="modified">
     <implementation class="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$Service3"/>
     <property name="service.pid" value="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$Service3"/>
-    <reference name="reference1" interface="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$ServiceInterface1" cardinality="1..1" policy="static" bind="bindReference1" unbind="unbindReference1"/>
-    <reference name="reference1Optional" interface="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$ServiceInterface1Optional" cardinality="0..1" policy="static" bind="bindReference1Optional" unbind="unbindReference1Optional"/>
-    <reference name="reference2" interface="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$ServiceInterface2" cardinality="1..n" policy="static" bind="bindReference2" unbind="unbindReference2"/>
-    <reference name="reference3" interface="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$ServiceInterface3" cardinality="0..n" policy="static" bind="bindReference3" unbind="unbindReference3"/>
+    <reference name="reference1" interface="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$ServiceInterface1" cardinality="1..1" policy="dynamic" bind="bindReference1" unbind="unbindReference1"/>
+    <reference name="reference1Optional" interface="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$ServiceInterface1Optional" cardinality="0..1" policy="dynamic" bind="bindReference1Optional" unbind="unbindReference1Optional"/>
+    <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$Service4">
     <implementation class="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$Service4"/>
diff --git a/src/test/resources/OSGI-INF/org.apache.sling.testing.mock.osgi.OsgiMetadataUtilTest.xml b/src/test/resources/OSGI-INF/serviceComponents.xml
similarity index 90%
rename from src/test/resources/OSGI-INF/org.apache.sling.testing.mock.osgi.OsgiMetadataUtilTest.xml
rename to src/test/resources/OSGI-INF/serviceComponents.xml
index 95ac503..064f0fc 100644
--- a/src/test/resources/OSGI-INF/org.apache.sling.testing.mock.osgi.OsgiMetadataUtilTest.xml
+++ b/src/test/resources/OSGI-INF/serviceComponents.xml
@@ -1,4 +1,5 @@
 <?xml version="1.0" encoding="UTF-8"?>
+<!-- This file follows the old SCR convention using a fixed name "serviceComponents.xml" -->
 <components xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0">
   <scr:component name="org.apache.sling.testing.mock.osgi.OsgiMetadataUtilTest$ServiceWithMetadata" activate="activate">
     <implementation class="org.apache.sling.testing.mock.osgi.OsgiMetadataUtilTest$ServiceWithMetadata"/>

-- 
To stop receiving notification emails like this one, please contact
"commits@sling.apache.org" <co...@sling.apache.org>.

[sling-org-apache-sling-testing-osgi-mock] 06/10: SLING-4439 implement dynamic service registration

Posted by ro...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rombert pushed a commit to annotated tag org.apache.sling.testing.osgi-mock-1.2.0
in repository https://gitbox.apache.org/repos/asf/sling-org-apache-sling-testing-osgi-mock.git

commit e6baa2cfef3edcbb95b1e9b2ad419dd400648c0b
Author: Stefan Seifert <ss...@apache.org>
AuthorDate: Thu Feb 19 17:15:13 2015 +0000

    SLING-4439 implement dynamic service registration
    
    git-svn-id: https://svn.apache.org/repos/asf/sling/trunk/testing/mocks/osgi-mock@1660943 13f79535-47bb-0310-9956-ffa450edef68
---
 .../sling/testing/mock/osgi/MockBundleContext.java |   8 +-
 .../sling/testing/mock/osgi/OsgiServiceUtil.java   |  10 +-
 .../MockBundleContextDynamicReferncesTest.java     | 169 +++++++++++++++++++++
 .../testing/mock/osgi/OsgiMetadataUtilTest.java    |   4 +-
 .../testing/mock/osgi/OsgiServiceUtilTest.java     |  18 +++
 ...sling.testing.mock.osgi.OsgiServiceUtilTest.xml |   3 +-
 6 files changed, 200 insertions(+), 12 deletions(-)

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 9ae85bc..fddb3c2 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
@@ -104,8 +104,8 @@ class MockBundleContext implements BundleContext {
             case MANDATORY_MULTIPLE:
             case OPTIONAL_MULTIPLE:
             case OPTIONAL_UNARY:
-                OsgiServiceUtil.invokeBindMethod(reference, registration.getService(),
-                        new ServiceInfo(referenceInfo.getServiceRegistration()));
+                OsgiServiceUtil.invokeBindMethod(reference, referenceInfo.getServiceRegistration().getService(),
+                        new ServiceInfo(registration));
                 break;
             default:
                 throw new RuntimeException("Unepxected cardinality: " + reference.getCardinality());
@@ -137,8 +137,8 @@ class MockBundleContext implements BundleContext {
             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, registration.getService(),
-                        new ServiceInfo(referenceInfo.getServiceRegistration()));
+                OsgiServiceUtil.invokeUnbindMethod(reference, referenceInfo.getServiceRegistration().getService(),
+                        new ServiceInfo(registration));
                 break;
             default:
                 throw new RuntimeException("Unepxected cardinality: " + reference.getCardinality());
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 152379f..1960d0d 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
@@ -242,13 +242,13 @@ final class OsgiServiceUtil {
             method.setAccessible(true);
             method.invoke(target, args);
         } catch (IllegalAccessException ex) {
-            throw new RuntimeException("Unable to invoke activate/deactivate method for class "
+            throw new RuntimeException("Unable to invoke method '" + method.getName() + "' for class "
                     + target.getClass().getName(), ex);
         } catch (IllegalArgumentException ex) {
-            throw new RuntimeException("Unable to invoke activate/deactivate method for class "
+            throw new RuntimeException("Unable to invoke method '" + method.getName() + "' for class "
                     + target.getClass().getName(), ex);
         } catch (InvocationTargetException ex) {
-            throw new RuntimeException("Unable to invoke activate/deactivate method for class "
+            throw new RuntimeException("Unable to invoke method '" + method.getName() + "' for class "
                     + target.getClass().getName(), ex.getCause());
         }
     }
@@ -351,8 +351,8 @@ final class OsgiServiceUtil {
             }
         }
 
-        throw new RuntimeException((bind ? "Bind" : "Unbind") + "method with name " + methodName + " not found "
-                + "for reference '" + reference.getName() + "' for class {}" +  targetClass.getName());
+        throw new RuntimeException((bind ? "Bind" : "Unbind") + " method with name " + methodName + " not found "
+                + "for reference '" + reference.getName() + "' for class " +  targetClass.getName());
     }
 
     /**
diff --git a/src/test/java/org/apache/sling/testing/mock/osgi/MockBundleContextDynamicReferncesTest.java b/src/test/java/org/apache/sling/testing/mock/osgi/MockBundleContextDynamicReferncesTest.java
new file mode 100644
index 0000000..9900f01
--- /dev/null
+++ b/src/test/java/org/apache/sling/testing/mock/osgi/MockBundleContextDynamicReferncesTest.java
@@ -0,0 +1,169 @@
+/*
+ * 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.Service3;
+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.ImmutableSet;
+
+@RunWith(MockitoJUnitRunner.class)
+public class MockBundleContextDynamicReferncesTest {
+
+    private BundleContext bundleContext;
+    private Service3 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 Service3();
+        MockOsgi.injectServices(service, bundleContext);
+        MockOsgi.activate(service);
+        bundleContext.registerService(Service3.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();
+    }
+    
+    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()));
+    }
+    
+}
diff --git a/src/test/java/org/apache/sling/testing/mock/osgi/OsgiMetadataUtilTest.java b/src/test/java/org/apache/sling/testing/mock/osgi/OsgiMetadataUtilTest.java
index 9db1197..4611d25 100644
--- a/src/test/java/org/apache/sling/testing/mock/osgi/OsgiMetadataUtilTest.java
+++ b/src/test/java/org/apache/sling/testing/mock/osgi/OsgiMetadataUtilTest.java
@@ -65,9 +65,9 @@ public class OsgiMetadataUtilTest {
     public void testReferences() {
         OsgiMetadata metadata = OsgiMetadataUtil.getMetadata(OsgiServiceUtilTest.Service3.class);
         List<Reference> references = metadata.getReferences();
-        assertEquals(3, references.size());
+        assertEquals(4, references.size());
 
-        Reference ref1 = references.get(0);
+        Reference ref1 = references.get(2);
         assertEquals("reference2", ref1.getName());
         assertEquals("org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$ServiceInterface2", ref1.getInterfaceType());
         assertEquals(ReferenceCardinality.MANDATORY_MULTIPLE, ref1.getCardinality());
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 f71ed38..abed04a 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
@@ -147,6 +147,10 @@ public class OsgiServiceUtilTest {
         // no methods
     }
 
+    public interface ServiceInterface1Optional {
+        // no methods
+    }
+
     public interface ServiceInterface2 {
         // no methods
     }
@@ -179,6 +183,8 @@ public class OsgiServiceUtilTest {
 
         @Reference
         private ServiceInterface1 reference1;
+        @Reference(cardinality = ReferenceCardinality.OPTIONAL_UNARY)
+        private ServiceInterface1Optional reference1Optional;
 
         private List<ServiceReference> references2 = new ArrayList<ServiceReference>();
 
@@ -210,6 +216,10 @@ public class OsgiServiceUtilTest {
             return this.reference1;
         }
 
+        public ServiceInterface1Optional getReference1Optional() {
+            return this.reference1Optional;
+        }
+
         public List<ServiceInterface2> getReferences2() {
             List<ServiceInterface2> services = new ArrayList<ServiceInterface2>();
             for (ServiceReference serviceReference : references2) {
@@ -234,6 +244,14 @@ public class OsgiServiceUtilTest {
             return config;
         }
 
+        protected void bindReference1Optional(ServiceInterface1Optional service) {
+            reference1Optional = service;
+        }
+
+        protected void unbindReference1Optional(ServiceInterface1Optional service) {
+            reference1Optional = null;
+        }
+
         protected void bindReference1(ServiceInterface1 service) {
             reference1 = service;
         }
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 d678f77..ab82616 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
@@ -20,8 +20,9 @@
   <scr:component name="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$Service3" activate="activate" deactivate="deactivate" modified="modified">
     <implementation class="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$Service3"/>
     <property name="service.pid" value="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$Service3"/>
-    <reference name="reference2" interface="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$ServiceInterface2" cardinality="1..n" policy="static" bind="bindReference2" unbind="unbindReference2"/>
     <reference name="reference1" interface="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$ServiceInterface1" cardinality="1..1" policy="static" bind="bindReference1" unbind="unbindReference1"/>
+    <reference name="reference1Optional" interface="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$ServiceInterface1Optional" cardinality="0..1" policy="static" bind="bindReference1Optional" unbind="unbindReference1Optional"/>
+    <reference name="reference2" interface="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$ServiceInterface2" cardinality="1..n" policy="static" bind="bindReference2" unbind="unbindReference2"/>
     <reference name="reference3" interface="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$ServiceInterface3" cardinality="0..n" policy="static" bind="bindReference3" unbind="unbindReference3"/>
   </scr:component>
   <scr:component name="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$Service4">

-- 
To stop receiving notification emails like this one, please contact
"commits@sling.apache.org" <co...@sling.apache.org>.

[sling-org-apache-sling-testing-osgi-mock] 10/10: [maven-release-plugin] copy for tag org.apache.sling.testing.osgi-mock-1.2.0

Posted by ro...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rombert pushed a commit to annotated tag org.apache.sling.testing.osgi-mock-1.2.0
in repository https://gitbox.apache.org/repos/asf/sling-org-apache-sling-testing-osgi-mock.git

commit d47b2ce4c4d9b0eb4c9527120fe5c9b639bd06bd
Author: Stefan Seifert <ss...@apache.org>
AuthorDate: Sun Feb 22 20:15:44 2015 +0000

    [maven-release-plugin]  copy for tag org.apache.sling.testing.osgi-mock-1.2.0
    
    git-svn-id: https://svn.apache.org/repos/asf/sling/tags/org.apache.sling.testing.osgi-mock-1.2.0@1661543 13f79535-47bb-0310-9956-ffa450edef68

-- 
To stop receiving notification emails like this one, please contact
"commits@sling.apache.org" <co...@sling.apache.org>.

[sling-org-apache-sling-testing-osgi-mock] 08/10: SLING-4439 implement dynamic service registration - support string array properties in osgi metadata as well - merge properties from osgi metadata with those specified on activation/registration call - support "old-style" scr component metadata file as well (and test this case)

Posted by ro...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rombert pushed a commit to annotated tag org.apache.sling.testing.osgi-mock-1.2.0
in repository https://gitbox.apache.org/repos/asf/sling-org-apache-sling-testing-osgi-mock.git

commit e828e3dc4859d39c502958586134e991c5251c53
Author: Stefan Seifert <ss...@apache.org>
AuthorDate: Fri Feb 20 00:17:52 2015 +0000

    SLING-4439 implement dynamic service registration
    - support string array properties in osgi metadata as well
    - merge properties from osgi metadata with those specified on activation/registration call
    - support "old-style" scr component metadata file as well (and test this case)
    
    git-svn-id: https://svn.apache.org/repos/asf/sling/trunk/testing/mocks/osgi-mock@1661038 13f79535-47bb-0310-9956-ffa450edef68
---
 .../apache/sling/testing/mock/osgi/MapUtil.java    | 38 +++++++++++++++++++++
 .../sling/testing/mock/osgi/MockBundleContext.java |  3 +-
 .../apache/sling/testing/mock/osgi/MockOsgi.java   | 39 +++++++++++++---------
 .../sling/testing/mock/osgi/OsgiMetadataUtil.java  | 13 ++++++++
 .../testing/mock/osgi/OsgiMetadataUtilTest.java    |  5 ++-
 .../testing/mock/osgi/OsgiServiceUtilTest.java     |  8 ++---
 src/test/resources/OSGI-INF/serviceComponents.xml  |  4 +++
 7 files changed, 88 insertions(+), 22 deletions(-)

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 e819beb..17aad75 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
@@ -24,6 +24,8 @@ import java.util.HashMap;
 import java.util.Hashtable;
 import java.util.Map;
 
+import org.apache.sling.testing.mock.osgi.OsgiMetadataUtil.OsgiMetadata;
+
 /**
  * Map util methods.
  */
@@ -49,4 +51,40 @@ final class MapUtil {
         return map;
     }
 
+    public static Dictionary<String, Object> propertiesMergeWithOsgiMetadata(Object target, Dictionary<String, Object> properties) {
+        Dictionary<String, Object> mergedProperties = new Hashtable<String, Object>();
+        
+        OsgiMetadata metadata = OsgiMetadataUtil.getMetadata(target.getClass());
+        if (metadata != null && metadata.getProperties() != null) {
+            for (Map.Entry<String, Object> entry : metadata.getProperties().entrySet()) {
+                mergedProperties.put(entry.getKey(), entry.getValue());
+            }
+        }
+        
+        if (properties != null) {
+            Enumeration<String> keys = properties.keys();
+            while (keys.hasMoreElements()) {
+                String key = keys.nextElement();
+                mergedProperties.put(key, properties.get(key));
+            }
+        }
+        
+        return mergedProperties;
+    }
+    
+    public static Map<String, Object> propertiesMergeWithOsgiMetadata(Object target, Map<String, Object> properties) {
+        Map<String, Object> mergedProperties = new HashMap<String, Object>();
+        
+        OsgiMetadata metadata = OsgiMetadataUtil.getMetadata(target.getClass());
+        if (metadata != null && metadata.getProperties() != null) {
+            mergedProperties.putAll(metadata.getProperties());
+        }
+        
+        if (properties != null) {
+            mergedProperties.putAll(properties);
+        }
+        
+        return mergedProperties;
+    }
+    
 }
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 075df65..a7337ed 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
@@ -81,7 +81,8 @@ class MockBundleContext implements BundleContext {
     @SuppressWarnings("unchecked")
     @Override
     public ServiceRegistration registerService(final String[] clazzes, final Object service, final Dictionary properties) {
-        MockServiceRegistration registration = new MockServiceRegistration(this.bundle, clazzes, service, properties, this);
+        Dictionary<String, Object> mergedPropertes = MapUtil.propertiesMergeWithOsgiMetadata(service, properties);
+        MockServiceRegistration registration = new MockServiceRegistration(this.bundle, clazzes, service, mergedPropertes, this);
         handleRefsUpdateOnRegister(registration);
         this.registeredServices.add(registration);
         notifyServiceListeners(ServiceEvent.REGISTERED, registration.getReference());
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 9cbcf8d..dfba00e 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
@@ -18,6 +18,10 @@
  */
 package org.apache.sling.testing.mock.osgi;
 
+import static org.apache.sling.testing.mock.osgi.MapUtil.propertiesMergeWithOsgiMetadata;
+import static org.apache.sling.testing.mock.osgi.MapUtil.toDictionary;
+import static org.apache.sling.testing.mock.osgi.MapUtil.toMap;
+
 import java.util.Dictionary;
 import java.util.Map;
 
@@ -72,7 +76,7 @@ public final class MockOsgi {
      * @return Mocked {@link ComponentContext} instance
      */
     public static ComponentContext newComponentContext(Map<String, Object> properties) {
-        return newComponentContext(MapUtil.toDictionary(properties));
+        return newComponentContext(toDictionary(properties));
     }
 
     /**
@@ -91,7 +95,7 @@ public final class MockOsgi {
      * @return Mocked {@link ComponentContext} instance
      */
     public static ComponentContext newComponentContext(BundleContext bundleContext, Map<String, Object> properties) {
-        return newComponentContext(bundleContext, MapUtil.toDictionary(properties));
+        return newComponentContext(bundleContext, toDictionary(properties));
     }
 
     /**
@@ -120,8 +124,7 @@ public final class MockOsgi {
      * @return true if activation method was called. False if no activate method is defined.
      */
     public static boolean activate(Object target) {
-        ComponentContext componentContext = newComponentContext();
-        return OsgiServiceUtil.activateDeactivate(target, componentContext, true);
+        return MockOsgi.activate(target, (Dictionary<String, Object>)null);
     }
 
     /**
@@ -131,7 +134,8 @@ public final class MockOsgi {
      * @return true if activation method was called. False if no activate method is defined.
      */
     public static boolean activate(Object target, Dictionary<String, Object> properties) {
-        ComponentContext componentContext = newComponentContext(properties);
+        Dictionary<String, Object> mergedProperties = propertiesMergeWithOsgiMetadata(target, properties);
+        ComponentContext componentContext = newComponentContext(mergedProperties);
         return OsgiServiceUtil.activateDeactivate(target, componentContext, true);
     }
 
@@ -142,7 +146,7 @@ public final class MockOsgi {
      * @return true if activation method was called. False if no activate method is defined.
      */
     public static boolean activate(Object target, Map<String, Object> properties) {
-        return activate(target, MapUtil.toDictionary(properties));
+        return activate(target, toDictionary(properties));
     }
 
     /**
@@ -153,7 +157,8 @@ public final class MockOsgi {
      * @return true if activation method was called. False if no activate method is defined.
      */
     public static boolean activate(Object target, BundleContext bundleContext, Dictionary<String, Object> properties) {
-        ComponentContext componentContext = newComponentContext(bundleContext, properties);
+        Dictionary<String, Object> mergedProperties = propertiesMergeWithOsgiMetadata(target, properties);
+        ComponentContext componentContext = newComponentContext(bundleContext, mergedProperties);
         return OsgiServiceUtil.activateDeactivate(target, componentContext, true);
     }
 
@@ -165,7 +170,7 @@ public final class MockOsgi {
      * @return true if activation method was called. False if no activate method is defined.
      */
     public static boolean activate(Object target, BundleContext bundleContext, Map<String, Object> properties) {
-        return activate(target, bundleContext, MapUtil.toDictionary(properties));
+        return activate(target, bundleContext, toDictionary(properties));
     }
 
     /**
@@ -174,8 +179,7 @@ public final class MockOsgi {
      * @return true if deactivation method was called. False if no deactivate method is defined.
      */
     public static boolean deactivate(Object target) {
-        ComponentContext componentContext = newComponentContext();
-        return OsgiServiceUtil.activateDeactivate(target, componentContext, false);
+        return MockOsgi.deactivate(target, (Dictionary<String, Object>)null);
     }
 
     /**
@@ -185,7 +189,8 @@ public final class MockOsgi {
      * @return true if deactivation method was called. False if no deactivate method is defined.
      */
     public static boolean deactivate(Object target, Dictionary<String, Object> properties) {
-        ComponentContext componentContext = newComponentContext(properties);
+        Dictionary<String, Object> mergedProperties = propertiesMergeWithOsgiMetadata(target, properties);
+        ComponentContext componentContext = newComponentContext(mergedProperties);
         return OsgiServiceUtil.activateDeactivate(target, componentContext, false);
     }
 
@@ -196,7 +201,7 @@ public final class MockOsgi {
      * @return true if deactivation method was called. False if no deactivate method is defined.
      */
     public static boolean deactivate(Object target, Map<String, Object> properties) {
-        return deactivate(target, MapUtil.toDictionary(properties));
+        return deactivate(target, toDictionary(properties));
     }
 
     /**
@@ -207,7 +212,8 @@ public final class MockOsgi {
      * @return true if deactivation method was called. False if no deactivate method is defined.
      */
     public static boolean deactivate(Object target, BundleContext bundleContext, Dictionary<String, Object> properties) {
-        ComponentContext componentContext = newComponentContext(bundleContext, properties);
+        Dictionary<String, Object> mergedProperties = propertiesMergeWithOsgiMetadata(target, properties);
+        ComponentContext componentContext = newComponentContext(bundleContext, mergedProperties);
         return OsgiServiceUtil.activateDeactivate(target, componentContext, false);
     }
 
@@ -219,7 +225,7 @@ public final class MockOsgi {
      * @return true if deactivation method was called. False if no deactivate method is defined.
      */
     public static boolean deactivate(Object target, BundleContext bundleContext, Map<String, Object> properties) {
-        return deactivate(target, bundleContext, MapUtil.toDictionary(properties));
+        return deactivate(target, bundleContext, toDictionary(properties));
     }
 
     /**
@@ -230,7 +236,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, Dictionary<String, Object> properties) {
-        return modified(target, bundleContext, MapUtil.toMap(properties));
+        return modified(target, bundleContext, toMap(properties));
     }
 
     /**
@@ -241,7 +247,8 @@ 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, Map<String, Object> properties) {
-        return OsgiServiceUtil.modified(target, bundleContext, properties);
+        Map<String, Object> mergedProperties = propertiesMergeWithOsgiMetadata(target, properties);
+        return OsgiServiceUtil.modified(target, bundleContext, mergedProperties);
     }
     
 }
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 359ac5b..a216d5b 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
@@ -238,6 +238,19 @@ final class OsgiMetadataUtil {
                 }
             }
         }
+        query = "/components/component[@name='" + clazz.getName() + "']/property[@name!='' and text()!='']";
+        nodes = queryNodes(metadata, query);
+        if (nodes != null) {
+            for (int i = 0; i < nodes.getLength(); i++) {
+                Node node = nodes.item(i);
+                String name = getAttributeValue(node, "name");
+                String[] value = StringUtils.split(StringUtils.trim(node.getTextContent()), "\n\r");
+                for (int j = 0; j<value.length; j++) {
+                    value[j] = StringUtils.trim(value[j]);
+                }
+                props.put(name, value);
+            }
+        }
         return props;
     }
 
diff --git a/src/test/java/org/apache/sling/testing/mock/osgi/OsgiMetadataUtilTest.java b/src/test/java/org/apache/sling/testing/mock/osgi/OsgiMetadataUtilTest.java
index ebd671e..6663f81 100644
--- a/src/test/java/org/apache/sling/testing/mock/osgi/OsgiMetadataUtilTest.java
+++ b/src/test/java/org/apache/sling/testing/mock/osgi/OsgiMetadataUtilTest.java
@@ -18,6 +18,7 @@
  */
 package org.apache.sling.testing.mock.osgi;
 
+import static org.junit.Assert.assertArrayEquals;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
@@ -45,10 +46,12 @@ public class OsgiMetadataUtilTest {
         assertTrue(serviceInterfaces.contains("java.lang.Comparable"));
 
         Map<String, Object> props = metadata.getProperties();
-        assertEquals(3, props.size());
+        assertEquals(4, props.size());
         assertEquals(5000, props.get("service.ranking"));
         assertEquals("The Apache Software Foundation", props.get("service.vendor"));
         assertEquals("org.apache.sling.models.impl.injectors.OSGiServiceInjector", props.get("service.pid"));
+        assertArrayEquals(new String[] { "org.apache.sling.api.resource.Resource", "org.apache.sling.api.resource.ResourceResolver" },
+                (String[])props.get("adaptables"));
     }
 
     @Test
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 abed04a..1243116 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
@@ -73,7 +73,7 @@ public class OsgiServiceUtilTest {
         assertTrue(MockOsgi.activate(service3, bundleContext, service3Config));
 
         assertNotNull(service3.getComponentContext());
-        assertEquals(service3Config, service3.getComponentContext().getProperties());
+        assertEquals(service3Config.get("prop1"), service3.getComponentContext().getProperties().get("prop1"));
 
         assertSame(service1, service3.getReference1());
 
@@ -101,16 +101,16 @@ public class OsgiServiceUtilTest {
 
         Service3 service3 = new Service3();
         MockOsgi.activate(service3, bundleContext, initialProperites);
-        assertEquals(initialProperites, service3.getConfig());
+        assertEquals(initialProperites.get("prop1"), service3.getConfig().get("prop1"));
         
         Map<String,Object> newProperties = ImmutableMap.<String, Object>of("prop2", "value2");
         MockOsgi.modified(service3, bundleContext, newProperties);
-        assertEquals(newProperties, service3.getConfig());
+        assertEquals(newProperties.get("prop2"), service3.getConfig().get("prop2"));
 
         newProperties = ImmutableMap.<String, Object>of("prop3", "value3");
         Dictionary<String,Object> newPropertiesDictonary = new Hashtable<String,Object>(newProperties);
         MockOsgi.modified(service3, bundleContext, newPropertiesDictonary);
-        assertEquals(newProperties, service3.getConfig());
+        assertEquals(newProperties.get("prop3"), service3.getConfig().get("prop3"));
     }
     
     @Test
diff --git a/src/test/resources/OSGI-INF/serviceComponents.xml b/src/test/resources/OSGI-INF/serviceComponents.xml
index 064f0fc..ee6e662 100644
--- a/src/test/resources/OSGI-INF/serviceComponents.xml
+++ b/src/test/resources/OSGI-INF/serviceComponents.xml
@@ -11,5 +11,9 @@
     <property name="service.ranking" type="Integer" value="5000"/>
     <property name="service.vendor" value="The Apache Software Foundation"/>
     <property name="service.pid" value="org.apache.sling.models.impl.injectors.OSGiServiceInjector"/>
+    <property name="adaptables">
+       org.apache.sling.api.resource.Resource
+       org.apache.sling.api.resource.ResourceResolver
+    </property>
   </scr:component>
 </components>

-- 
To stop receiving notification emails like this one, please contact
"commits@sling.apache.org" <co...@sling.apache.org>.

[sling-org-apache-sling-testing-osgi-mock] 02/10: rename package-private class ReflectinServiceUtil to OsgiServiceUtil because it does not any longer use reflection to do it's job (no functional change)

Posted by ro...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rombert pushed a commit to annotated tag org.apache.sling.testing.osgi-mock-1.2.0
in repository https://gitbox.apache.org/repos/asf/sling-org-apache-sling-testing-osgi-mock.git

commit b910746382701553540a7f7fafa1faa39e6f06e4
Author: Stefan Seifert <ss...@apache.org>
AuthorDate: Thu Feb 19 09:31:49 2015 +0000

    rename package-private class ReflectinServiceUtil to OsgiServiceUtil because it does not any longer use reflection to do it's job
    (no functional change)
    
    git-svn-id: https://svn.apache.org/repos/asf/sling/trunk/testing/mocks/osgi-mock@1660817 13f79535-47bb-0310-9956-ffa450edef68
---
 .../apache/sling/testing/mock/osgi/MockOsgi.java   | 16 +++++------
 ...ectionServiceUtil.java => OsgiServiceUtil.java} |  6 ++--
 .../testing/mock/osgi/OsgiMetadataUtilTest.java    | 10 +++----
 ... => OsgiServiceUtilActivateDeactivateTest.java} |  2 +-
 ...rviceUtilTest.java => OsgiServiceUtilTest.java} |  2 +-
 .../mock/osgi/context/OsgiContextImplTest.java     | 10 +++----
 ....osgi.OsgiServiceUtilActivateDeactivateTest.xml | 21 ++++++++++++++
 ...sling.testing.mock.osgi.OsgiServiceUtilTest.xml | 32 ++++++++++++++++++++++
 ...ReflectionServiceUtilActivateDeactivateTest.xml | 21 --------------
 ...testing.mock.osgi.ReflectionServiceUtilTest.xml | 32 ----------------------
 10 files changed, 76 insertions(+), 76 deletions(-)

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 82448e4..9cbcf8d 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
@@ -111,7 +111,7 @@ public final class MockOsgi {
      * @return true if all dependencies could be injected, false if the service has no dependencies.
      */
     public static boolean injectServices(Object target, BundleContext bundleContext) {
-        return ReflectionServiceUtil.injectServices(target, bundleContext);
+        return OsgiServiceUtil.injectServices(target, bundleContext);
     }
 
     /**
@@ -121,7 +121,7 @@ public final class MockOsgi {
      */
     public static boolean activate(Object target) {
         ComponentContext componentContext = newComponentContext();
-        return ReflectionServiceUtil.activateDeactivate(target, componentContext, true);
+        return OsgiServiceUtil.activateDeactivate(target, componentContext, true);
     }
 
     /**
@@ -132,7 +132,7 @@ public final class MockOsgi {
      */
     public static boolean activate(Object target, Dictionary<String, Object> properties) {
         ComponentContext componentContext = newComponentContext(properties);
-        return ReflectionServiceUtil.activateDeactivate(target, componentContext, true);
+        return OsgiServiceUtil.activateDeactivate(target, componentContext, true);
     }
 
     /**
@@ -154,7 +154,7 @@ public final class MockOsgi {
      */
     public static boolean activate(Object target, BundleContext bundleContext, Dictionary<String, Object> properties) {
         ComponentContext componentContext = newComponentContext(bundleContext, properties);
-        return ReflectionServiceUtil.activateDeactivate(target, componentContext, true);
+        return OsgiServiceUtil.activateDeactivate(target, componentContext, true);
     }
 
     /**
@@ -175,7 +175,7 @@ public final class MockOsgi {
      */
     public static boolean deactivate(Object target) {
         ComponentContext componentContext = newComponentContext();
-        return ReflectionServiceUtil.activateDeactivate(target, componentContext, false);
+        return OsgiServiceUtil.activateDeactivate(target, componentContext, false);
     }
 
     /**
@@ -186,7 +186,7 @@ public final class MockOsgi {
      */
     public static boolean deactivate(Object target, Dictionary<String, Object> properties) {
         ComponentContext componentContext = newComponentContext(properties);
-        return ReflectionServiceUtil.activateDeactivate(target, componentContext, false);
+        return OsgiServiceUtil.activateDeactivate(target, componentContext, false);
     }
 
     /**
@@ -208,7 +208,7 @@ public final class MockOsgi {
      */
     public static boolean deactivate(Object target, BundleContext bundleContext, Dictionary<String, Object> properties) {
         ComponentContext componentContext = newComponentContext(bundleContext, properties);
-        return ReflectionServiceUtil.activateDeactivate(target, componentContext, false);
+        return OsgiServiceUtil.activateDeactivate(target, componentContext, false);
     }
 
     /**
@@ -241,7 +241,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, Map<String, Object> properties) {
-        return ReflectionServiceUtil.modified(target, bundleContext, properties);
+        return OsgiServiceUtil.modified(target, bundleContext, properties);
     }
     
 }
diff --git a/src/main/java/org/apache/sling/testing/mock/osgi/ReflectionServiceUtil.java b/src/main/java/org/apache/sling/testing/mock/osgi/OsgiServiceUtil.java
similarity index 99%
rename from src/main/java/org/apache/sling/testing/mock/osgi/ReflectionServiceUtil.java
rename to src/main/java/org/apache/sling/testing/mock/osgi/OsgiServiceUtil.java
index 77d5e08..7606d65 100644
--- a/src/main/java/org/apache/sling/testing/mock/osgi/ReflectionServiceUtil.java
+++ b/src/main/java/org/apache/sling/testing/mock/osgi/OsgiServiceUtil.java
@@ -37,11 +37,11 @@ import org.osgi.service.component.ComponentContext;
 import org.w3c.dom.Document;
 
 /**
- * Helper methods to inject dependencies and activate services via reflection.
+ * Helper methods to inject dependencies and activate services.
  */
-final class ReflectionServiceUtil {
+final class OsgiServiceUtil {
 
-    private ReflectionServiceUtil() {
+    private OsgiServiceUtil() {
         // static methods only
     }
 
diff --git a/src/test/java/org/apache/sling/testing/mock/osgi/OsgiMetadataUtilTest.java b/src/test/java/org/apache/sling/testing/mock/osgi/OsgiMetadataUtilTest.java
index 52f9011..280f955 100644
--- a/src/test/java/org/apache/sling/testing/mock/osgi/OsgiMetadataUtilTest.java
+++ b/src/test/java/org/apache/sling/testing/mock/osgi/OsgiMetadataUtilTest.java
@@ -63,13 +63,13 @@ public class OsgiMetadataUtilTest {
 
     @Test
     public void testReferences() {
-        Document doc = OsgiMetadataUtil.getMetadata(ReflectionServiceUtilTest.Service3.class);
-        List<Reference> references = OsgiMetadataUtil.getReferences(ReflectionServiceUtilTest.Service3.class, doc);
+        Document doc = OsgiMetadataUtil.getMetadata(OsgiServiceUtilTest.Service3.class);
+        List<Reference> references = OsgiMetadataUtil.getReferences(OsgiServiceUtilTest.Service3.class, doc);
         assertEquals(3, references.size());
 
         Reference ref1 = references.get(0);
         assertEquals("reference2", ref1.getName());
-        assertEquals("org.apache.sling.testing.mock.osgi.ReflectionServiceUtilTest$ServiceInterface2", ref1.getInterfaceType());
+        assertEquals("org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$ServiceInterface2", ref1.getInterfaceType());
         assertEquals(ReferenceCardinality.MANDATORY_MULTIPLE, ref1.getCardinality());
         assertEquals("bindReference2", ref1.getBind());
         assertEquals("unbindReference2", ref1.getUnbind());
@@ -77,8 +77,8 @@ public class OsgiMetadataUtilTest {
 
     @Test
     public void testActivateMethodName() {
-        Document doc = OsgiMetadataUtil.getMetadata(ReflectionServiceUtilTest.Service3.class);
-        String methodName = OsgiMetadataUtil.getActivateMethodName(ReflectionServiceUtilTest.Service3.class, doc);
+        Document doc = OsgiMetadataUtil.getMetadata(OsgiServiceUtilTest.Service3.class);
+        String methodName = OsgiMetadataUtil.getActivateMethodName(OsgiServiceUtilTest.Service3.class, doc);
         assertEquals("activate", methodName);
     }
 
diff --git a/src/test/java/org/apache/sling/testing/mock/osgi/ReflectionServiceUtilActivateDeactivateTest.java b/src/test/java/org/apache/sling/testing/mock/osgi/OsgiServiceUtilActivateDeactivateTest.java
similarity index 99%
rename from src/test/java/org/apache/sling/testing/mock/osgi/ReflectionServiceUtilActivateDeactivateTest.java
rename to src/test/java/org/apache/sling/testing/mock/osgi/OsgiServiceUtilActivateDeactivateTest.java
index 36cf88e..d848fe2 100644
--- a/src/test/java/org/apache/sling/testing/mock/osgi/ReflectionServiceUtilActivateDeactivateTest.java
+++ b/src/test/java/org/apache/sling/testing/mock/osgi/OsgiServiceUtilActivateDeactivateTest.java
@@ -37,7 +37,7 @@ import com.google.common.collect.ImmutableMap;
 /**
  * Test different variants of activate/deactivate methods with varying signatures.
  */
-public class ReflectionServiceUtilActivateDeactivateTest {
+public class OsgiServiceUtilActivateDeactivateTest {
 
     private Map<String,Object> map = ImmutableMap.<String, Object>of("prop1", "value1");
     private BundleContext bundleContext = MockOsgi.newBundleContext();
diff --git a/src/test/java/org/apache/sling/testing/mock/osgi/ReflectionServiceUtilTest.java b/src/test/java/org/apache/sling/testing/mock/osgi/OsgiServiceUtilTest.java
similarity index 99%
rename from src/test/java/org/apache/sling/testing/mock/osgi/ReflectionServiceUtilTest.java
rename to src/test/java/org/apache/sling/testing/mock/osgi/OsgiServiceUtilTest.java
index b8b8cea..f71ed38 100644
--- a/src/test/java/org/apache/sling/testing/mock/osgi/ReflectionServiceUtilTest.java
+++ b/src/test/java/org/apache/sling/testing/mock/osgi/OsgiServiceUtilTest.java
@@ -49,7 +49,7 @@ import org.osgi.service.component.annotations.Modified;
 
 import com.google.common.collect.ImmutableMap;
 
-public class ReflectionServiceUtilTest {
+public class OsgiServiceUtilTest {
 
     private BundleContext bundleContext = MockOsgi.newBundleContext();
     private Service1 service1;
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 35eecbb..60d5b0b 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
@@ -29,9 +29,9 @@ import java.util.Map;
 import java.util.Set;
 
 import org.apache.sling.testing.mock.osgi.NoScrMetadataException;
-import org.apache.sling.testing.mock.osgi.ReflectionServiceUtilTest;
-import org.apache.sling.testing.mock.osgi.ReflectionServiceUtilTest.ServiceInterface1;
-import org.apache.sling.testing.mock.osgi.ReflectionServiceUtilTest.ServiceInterface2;
+import org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest;
+import org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest.ServiceInterface1;
+import org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest.ServiceInterface2;
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
@@ -97,12 +97,12 @@ public class OsgiContextImplTest {
     public void testRegisterInjectActivate() {
         context.registerService(ServiceInterface1.class, mock(ServiceInterface1.class));
         context.registerService(ServiceInterface2.class, mock(ServiceInterface2.class));
-        context.registerInjectActivateService(new ReflectionServiceUtilTest.Service3());
+        context.registerInjectActivateService(new OsgiServiceUtilTest.Service3());
     }
 
     @Test(expected=RuntimeException.class)
     public void testRegisterInjectActivate_RefrenceMissing() {
-        context.registerInjectActivateService(new ReflectionServiceUtilTest.Service3());
+        context.registerInjectActivateService(new OsgiServiceUtilTest.Service3());
     }
 
     @Test(expected=NoScrMetadataException.class)
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
new file mode 100644
index 0000000..f0fccc9
--- /dev/null
+++ b/src/test/resources/OSGI-INF/org.apache.sling.testing.mock.osgi.OsgiServiceUtilActivateDeactivateTest.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<components xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0">
+  <scr:component name="org.apache.sling.testing.mock.osgi.OsgiServiceUtilActivateDeactivateTest$Service1" activate="activate" deactivate="deactivate">
+    <implementation class="org.apache.sling.testing.mock.osgi.OsgiServiceUtilActivateDeactivateTest$Service1"/>
+  </scr:component>
+  <scr:component name="org.apache.sling.testing.mock.osgi.OsgiServiceUtilActivateDeactivateTest$Service2" activate="activate" deactivate="deactivate">
+    <implementation class="org.apache.sling.testing.mock.osgi.OsgiServiceUtilActivateDeactivateTest$Service2"/>
+  </scr:component>
+  <scr:component name="org.apache.sling.testing.mock.osgi.OsgiServiceUtilActivateDeactivateTest$Service3" activate="activate" deactivate="deactivate">
+    <implementation class="org.apache.sling.testing.mock.osgi.OsgiServiceUtilActivateDeactivateTest$Service3"/>
+  </scr:component>
+  <scr:component name="org.apache.sling.testing.mock.osgi.OsgiServiceUtilActivateDeactivateTest$Service4" activate="activate" deactivate="deactivate">
+    <implementation class="org.apache.sling.testing.mock.osgi.OsgiServiceUtilActivateDeactivateTest$Service4"/>
+  </scr:component>
+  <scr:component name="org.apache.sling.testing.mock.osgi.OsgiServiceUtilActivateDeactivateTest$Service5" activate="activate" deactivate="deactivate">
+    <implementation class="org.apache.sling.testing.mock.osgi.OsgiServiceUtilActivateDeactivateTest$Service5"/>
+  </scr:component>
+  <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>
+</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
new file mode 100644
index 0000000..d678f77
--- /dev/null
+++ b/src/test/resources/OSGI-INF/org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest.xml
@@ -0,0 +1,32 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<components xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0">
+  <scr:component name="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$Service1">
+    <implementation class="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$Service1"/>
+    <service servicefactory="false">
+      <provide interface="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$ServiceInterface1"/>
+    </service>
+    <property name="service.ranking" type="Integer" value="100"/>
+    <property name="service.pid" value="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$Service1"/>
+  </scr:component>
+  <scr:component name="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$Service2">
+    <implementation class="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$Service2"/>
+    <service servicefactory="false">
+      <provide interface="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$ServiceInterface2"/>
+      <provide interface="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$ServiceInterface3"/>
+    </service>
+    <property name="service.ranking" type="Integer" value="200"/>
+    <property name="service.pid" value="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$Service2"/>
+  </scr:component>
+  <scr:component name="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$Service3" activate="activate" deactivate="deactivate" modified="modified">
+    <implementation class="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$Service3"/>
+    <property name="service.pid" value="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$Service3"/>
+    <reference name="reference2" interface="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$ServiceInterface2" cardinality="1..n" policy="static" bind="bindReference2" unbind="unbindReference2"/>
+    <reference name="reference1" interface="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$ServiceInterface1" cardinality="1..1" policy="static" bind="bindReference1" unbind="unbindReference1"/>
+    <reference name="reference3" interface="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$ServiceInterface3" cardinality="0..n" policy="static" bind="bindReference3" unbind="unbindReference3"/>
+  </scr:component>
+  <scr:component name="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$Service4">
+    <implementation class="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$Service4"/>
+    <property name="service.pid" value="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$Service4"/>
+    <reference name="customName" interface="org.apache.sling.testing.mock.osgi.OsgiServiceUtilTest$ServiceInterface1" cardinality="1..1" policy="static" bind="customBind" unbind="customUnbind"/>
+  </scr:component>
+</components>
diff --git a/src/test/resources/OSGI-INF/org.apache.sling.testing.mock.osgi.ReflectionServiceUtilActivateDeactivateTest.xml b/src/test/resources/OSGI-INF/org.apache.sling.testing.mock.osgi.ReflectionServiceUtilActivateDeactivateTest.xml
deleted file mode 100644
index 23c4585..0000000
--- a/src/test/resources/OSGI-INF/org.apache.sling.testing.mock.osgi.ReflectionServiceUtilActivateDeactivateTest.xml
+++ /dev/null
@@ -1,21 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<components xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0">
-  <scr:component name="org.apache.sling.testing.mock.osgi.ReflectionServiceUtilActivateDeactivateTest$Service1" activate="activate" deactivate="deactivate">
-    <implementation class="org.apache.sling.testing.mock.osgi.ReflectionServiceUtilActivateDeactivateTest$Service1"/>
-  </scr:component>
-  <scr:component name="org.apache.sling.testing.mock.osgi.ReflectionServiceUtilActivateDeactivateTest$Service2" activate="activate" deactivate="deactivate">
-    <implementation class="org.apache.sling.testing.mock.osgi.ReflectionServiceUtilActivateDeactivateTest$Service2"/>
-  </scr:component>
-  <scr:component name="org.apache.sling.testing.mock.osgi.ReflectionServiceUtilActivateDeactivateTest$Service3" activate="activate" deactivate="deactivate">
-    <implementation class="org.apache.sling.testing.mock.osgi.ReflectionServiceUtilActivateDeactivateTest$Service3"/>
-  </scr:component>
-  <scr:component name="org.apache.sling.testing.mock.osgi.ReflectionServiceUtilActivateDeactivateTest$Service4" activate="activate" deactivate="deactivate">
-    <implementation class="org.apache.sling.testing.mock.osgi.ReflectionServiceUtilActivateDeactivateTest$Service4"/>
-  </scr:component>
-  <scr:component name="org.apache.sling.testing.mock.osgi.ReflectionServiceUtilActivateDeactivateTest$Service5" activate="activate" deactivate="deactivate">
-    <implementation class="org.apache.sling.testing.mock.osgi.ReflectionServiceUtilActivateDeactivateTest$Service5"/>
-  </scr:component>
-  <scr:component name="org.apache.sling.testing.mock.osgi.ReflectionServiceUtilActivateDeactivateTest$Service6" activate="activate" deactivate="deactivate">
-    <implementation class="org.apache.sling.testing.mock.osgi.ReflectionServiceUtilActivateDeactivateTest$Service6"/>
-  </scr:component>
-</components>
diff --git a/src/test/resources/OSGI-INF/org.apache.sling.testing.mock.osgi.ReflectionServiceUtilTest.xml b/src/test/resources/OSGI-INF/org.apache.sling.testing.mock.osgi.ReflectionServiceUtilTest.xml
deleted file mode 100644
index 202dc40..0000000
--- a/src/test/resources/OSGI-INF/org.apache.sling.testing.mock.osgi.ReflectionServiceUtilTest.xml
+++ /dev/null
@@ -1,32 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<components xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0">
-  <scr:component name="org.apache.sling.testing.mock.osgi.ReflectionServiceUtilTest$Service1">
-    <implementation class="org.apache.sling.testing.mock.osgi.ReflectionServiceUtilTest$Service1"/>
-    <service servicefactory="false">
-      <provide interface="org.apache.sling.testing.mock.osgi.ReflectionServiceUtilTest$ServiceInterface1"/>
-    </service>
-    <property name="service.ranking" type="Integer" value="100"/>
-    <property name="service.pid" value="org.apache.sling.testing.mock.osgi.ReflectionServiceUtilTest$Service1"/>
-  </scr:component>
-  <scr:component name="org.apache.sling.testing.mock.osgi.ReflectionServiceUtilTest$Service2">
-    <implementation class="org.apache.sling.testing.mock.osgi.ReflectionServiceUtilTest$Service2"/>
-    <service servicefactory="false">
-      <provide interface="org.apache.sling.testing.mock.osgi.ReflectionServiceUtilTest$ServiceInterface2"/>
-      <provide interface="org.apache.sling.testing.mock.osgi.ReflectionServiceUtilTest$ServiceInterface3"/>
-    </service>
-    <property name="service.ranking" type="Integer" value="200"/>
-    <property name="service.pid" value="org.apache.sling.testing.mock.osgi.ReflectionServiceUtilTest$Service2"/>
-  </scr:component>
-  <scr:component name="org.apache.sling.testing.mock.osgi.ReflectionServiceUtilTest$Service3" activate="activate" deactivate="deactivate" modified="modified">
-    <implementation class="org.apache.sling.testing.mock.osgi.ReflectionServiceUtilTest$Service3"/>
-    <property name="service.pid" value="org.apache.sling.testing.mock.osgi.ReflectionServiceUtilTest$Service3"/>
-    <reference name="reference2" interface="org.apache.sling.testing.mock.osgi.ReflectionServiceUtilTest$ServiceInterface2" cardinality="1..n" policy="static" bind="bindReference2" unbind="unbindReference2"/>
-    <reference name="reference1" interface="org.apache.sling.testing.mock.osgi.ReflectionServiceUtilTest$ServiceInterface1" cardinality="1..1" policy="static" bind="bindReference1" unbind="unbindReference1"/>
-    <reference name="reference3" interface="org.apache.sling.testing.mock.osgi.ReflectionServiceUtilTest$ServiceInterface3" cardinality="0..n" policy="static" bind="bindReference3" unbind="unbindReference3"/>
-  </scr:component>
-  <scr:component name="org.apache.sling.testing.mock.osgi.ReflectionServiceUtilTest$Service4">
-    <implementation class="org.apache.sling.testing.mock.osgi.ReflectionServiceUtilTest$Service4"/>
-    <property name="service.pid" value="org.apache.sling.testing.mock.osgi.ReflectionServiceUtilTest$Service4"/>
-    <reference name="customName" interface="org.apache.sling.testing.mock.osgi.ReflectionServiceUtilTest$ServiceInterface1" cardinality="1..1" policy="static" bind="customBind" unbind="customUnbind"/>
-  </scr:component>
-</components>

-- 
To stop receiving notification emails like this one, please contact
"commits@sling.apache.org" <co...@sling.apache.org>.

[sling-org-apache-sling-testing-osgi-mock] 03/10: SLING-4435 OSGi Mock: Cache reading of OSGi SCR Metadata files

Posted by ro...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rombert pushed a commit to annotated tag org.apache.sling.testing.osgi-mock-1.2.0
in repository https://gitbox.apache.org/repos/asf/sling-org-apache-sling-testing-osgi-mock.git

commit 68de5d4e00c22c66636341be4f80dd14159d7b78
Author: Stefan Seifert <ss...@apache.org>
AuthorDate: Thu Feb 19 11:00:05 2015 +0000

    SLING-4435 OSGi Mock: Cache reading of OSGi SCR Metadata files
    
    git-svn-id: https://svn.apache.org/repos/asf/sling/trunk/testing/mocks/osgi-mock@1660841 13f79535-47bb-0310-9956-ffa450edef68
---
 .../testing/mock/osgi/MockServiceRegistration.java |  10 +-
 .../sling/testing/mock/osgi/OsgiMetadataUtil.java  | 121 +++++++++++++++++----
 .../sling/testing/mock/osgi/OsgiServiceUtil.java   |  22 ++--
 .../sling/testing/mock/osgi/package-info.java      |   2 +-
 .../testing/mock/osgi/OsgiMetadataUtilTest.java    |  23 ++--
 5 files changed, 128 insertions(+), 50 deletions(-)

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 1dc564b..f212b49 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
@@ -24,11 +24,11 @@ import java.util.Hashtable;
 import java.util.Map;
 import java.util.Set;
 
+import org.apache.sling.testing.mock.osgi.OsgiMetadataUtil.OsgiMetadata;
 import org.osgi.framework.Bundle;
 import org.osgi.framework.Constants;
 import org.osgi.framework.ServiceReference;
 import org.osgi.framework.ServiceRegistration;
-import org.w3c.dom.Document;
 
 import com.google.common.collect.ImmutableList;
 
@@ -89,16 +89,16 @@ class MockServiceRegistration implements ServiceRegistration {
      */
     private void readOsgiMetadata() {
         Class<?> serviceClass = service.getClass();
-        Document doc = OsgiMetadataUtil.getMetadata(serviceClass);
-        if (doc == null) {
+        OsgiMetadata metadata = OsgiMetadataUtil.getMetadata(serviceClass);
+        if (metadata == null) {
             return;
         }
 
         // add service interfaces from OSGi metadata
-        clazzes.addAll(OsgiMetadataUtil.getServiceInterfaces(serviceClass, doc));
+        clazzes.addAll(metadata.getServiceInterfaces());
 
         // add properties from OSGi metadata
-        Map<String, Object> props = OsgiMetadataUtil.getProperties(serviceClass, doc);
+        Map<String, Object> props = metadata.getProperties();
         for (Map.Entry<String, Object> entry : props.entrySet()) {
             properties.put(entry.getKey(), entry.getValue());
         }
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 41fc4b5..7cf7cfb 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
@@ -27,6 +27,7 @@ import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
+import java.util.concurrent.ExecutionException;
 
 import javax.xml.namespace.NamespaceContext;
 import javax.xml.parsers.DocumentBuilder;
@@ -46,6 +47,9 @@ import org.w3c.dom.Node;
 import org.w3c.dom.NodeList;
 import org.xml.sax.SAXException;
 
+import com.google.common.cache.CacheBuilder;
+import com.google.common.cache.CacheLoader;
+import com.google.common.cache.LoadingCache;
 import com.google.common.collect.BiMap;
 import com.google.common.collect.HashBiMap;
 
@@ -68,6 +72,25 @@ final class OsgiMetadataUtil {
     static {
         NAMESPACES.put("scr", "http://www.osgi.org/xmlns/scr/v1.1.0");
     }
+    
+    private static final OsgiMetadata NULL_METADATA = new OsgiMetadata();
+    
+    /*
+     * The OSGI metadata XML files do not change during the unit test runs because static part of classpath.
+     * So we can cache the parsing step if we need them multiple times.
+     */
+    private static final LoadingCache<Class, OsgiMetadata> METADATA_CACHE = CacheBuilder.newBuilder().build(new CacheLoader<Class, OsgiMetadata>() {
+        @Override
+        public OsgiMetadata load(Class clazz) throws Exception {
+            Document metadataDocument = OsgiMetadataUtil.getMetadataDocument(clazz);
+            if (metadataDocument == null) {
+                return NULL_METADATA;
+            }
+            else {
+                return new OsgiMetadata(clazz, metadataDocument);
+            }
+        }
+    });
 
     private OsgiMetadataUtil() {
         // static methods only
@@ -95,12 +118,27 @@ final class OsgiMetadataUtil {
     }
 
     /**
-     * Try to read OSGI-metadata from /OSGI-INF and read all implemented
-     * interfaces and service properties
+     * Try to read OSGI-metadata from /OSGI-INF and read all implemented interfaces and service properties.
+     * The metadata is cached after initial read, so it's no problem to call this method multiple time for the same class.
      * @param clazz OSGi service implementation class
-     * @return Metadata document or null
+     * @return Metadata object or null if no metadata present in classpath
      */
-    public static Document getMetadata(Class clazz) {
+    public static OsgiMetadata getMetadata(Class clazz) {
+        try {
+            OsgiMetadata metadata = METADATA_CACHE.get(clazz);
+            if (metadata == NULL_METADATA) {
+                return null;
+            }
+            else {
+                return metadata;
+            }
+        }
+        catch (ExecutionException ex) {
+            throw new RuntimeException("Error loading OSGi metadata from loader cache.", ex);
+        }
+    }
+
+    private static Document getMetadataDocument(Class clazz) {
         String metadataPath = getMetadataPath(clazz);
         InputStream metadataStream = clazz.getResourceAsStream(metadataPath);
         if (metadataStream == null) {
@@ -126,7 +164,7 @@ final class OsgiMetadataUtil {
         }
     }
 
-    public static Set<String> getServiceInterfaces(Class clazz, Document metadata) {
+    private static Set<String> getServiceInterfaces(Class clazz, Document metadata) {
         Set<String> serviceInterfaces = new HashSet<String>();
         String query = "/components/component[@name='" + clazz.getName() + "']/service/provide[@interface!='']";
         NodeList nodes = queryNodes(metadata, query);
@@ -142,7 +180,7 @@ final class OsgiMetadataUtil {
         return serviceInterfaces;
     }
 
-    public static Map<String, Object> getProperties(Class clazz, Document metadata) {
+    private static Map<String, Object> getProperties(Class clazz, Document metadata) {
         Map<String, Object> props = new HashMap<String, Object>();
         String query = "/components/component[@name='" + clazz.getName() + "']/property[@name!='' and @value!='']";
         NodeList nodes = queryNodes(metadata, query);
@@ -162,7 +200,7 @@ final class OsgiMetadataUtil {
         return props;
     }
 
-    public static List<Reference> getReferences(Class clazz, Document metadata) {
+    private static List<Reference> getReferences(Class clazz, Document metadata) {
         List<Reference> references = new ArrayList<Reference>();
         String query = "/components/component[@name='" + clazz.getName() + "']/reference[@name!='']";
         NodeList nodes = queryNodes(metadata, query);
@@ -175,18 +213,6 @@ final class OsgiMetadataUtil {
         return references;
     }
 
-    public static String getActivateMethodName(Class clazz, Document metadata) {
-        return getLifecycleMethodName(clazz, metadata, "activate");
-    }
-
-    public static String getDeactivateMethodName(Class clazz, Document metadata) {
-        return getLifecycleMethodName(clazz, metadata, "deactivate");
-    }
-
-    public static String getModifiedMethodName(Class clazz, Document metadata) {
-        return getLifecycleMethodName(clazz, metadata, "modified");
-    }
-
     private static String getLifecycleMethodName(Class clazz, Document metadata, String methodName) {
         String query = "/components/component[@name='" + clazz.getName() + "']";
         Node node = queryNode(metadata, query);
@@ -225,7 +251,60 @@ final class OsgiMetadataUtil {
         }
     }
 
-    public static class Reference {
+    static class OsgiMetadata {
+        
+        private final Set<String> serviceInterfaces;
+        private final Map<String, Object> properties;
+        private final List<Reference> references;
+        private final String activateMethodName;
+        private final String deactivateMethodName;
+        private final String modifiedMethodName;
+        
+        private OsgiMetadata(Class clazz, Document metadataDocument) {
+            this.serviceInterfaces = OsgiMetadataUtil.getServiceInterfaces(clazz, metadataDocument);
+            this.properties = OsgiMetadataUtil.getProperties(clazz, metadataDocument);
+            this.references = OsgiMetadataUtil.getReferences(clazz, metadataDocument);
+            this.activateMethodName = OsgiMetadataUtil.getLifecycleMethodName(clazz, metadataDocument, "activate");
+            this.deactivateMethodName = OsgiMetadataUtil.getLifecycleMethodName(clazz, metadataDocument, "deactivate");
+            this.modifiedMethodName = OsgiMetadataUtil.getLifecycleMethodName(clazz, metadataDocument, "modified");
+        }
+
+        private OsgiMetadata() {
+            this.serviceInterfaces = null;
+            this.properties = null;
+            this.references = null;
+            this.activateMethodName = null;
+            this.deactivateMethodName = null;
+            this.modifiedMethodName = null;
+        }
+        
+        public Set<String> getServiceInterfaces() {
+            return serviceInterfaces;
+        }
+
+        public Map<String, Object> getProperties() {
+            return properties;
+        }
+
+        public List<Reference> getReferences() {
+            return references;
+        }
+
+        public String getActivateMethodName() {
+            return activateMethodName;
+        }
+
+        public String getDeactivateMethodName() {
+            return deactivateMethodName;
+        }
+
+        public String getModifiedMethodName() {
+            return modifiedMethodName;
+        }
+        
+    }
+
+    static class Reference {
 
         private final String name;
         private final String interfaceType;
@@ -233,7 +312,7 @@ final class OsgiMetadataUtil {
         private final String bind;
         private final String unbind;
 
-        public Reference(Node node) {
+        private Reference(Node node) {
             this.name = getAttributeValue(node, "name");
             this.interfaceType = getAttributeValue(node, "interface");
             this.cardinality = toCardinality(getAttributeValue(node, "cardinality"));
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 7606d65..b340b29 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
@@ -29,12 +29,12 @@ import java.util.Map;
 import org.apache.commons.lang3.ArrayUtils;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.felix.scr.annotations.ReferenceCardinality;
+import org.apache.sling.testing.mock.osgi.OsgiMetadataUtil.OsgiMetadata;
 import org.apache.sling.testing.mock.osgi.OsgiMetadataUtil.Reference;
 import org.osgi.framework.BundleContext;
 import org.osgi.framework.InvalidSyntaxException;
 import org.osgi.framework.ServiceReference;
 import org.osgi.service.component.ComponentContext;
-import org.w3c.dom.Document;
 
 /**
  * Helper methods to inject dependencies and activate services.
@@ -56,15 +56,15 @@ final class OsgiServiceUtil {
         Class<?> targetClass = target.getClass();
 
         // get method name for activation/deactivation from osgi metadata
-        Document metadata = OsgiMetadataUtil.getMetadata(targetClass);
-        if (metadata==null) {
+        OsgiMetadata metadata = OsgiMetadataUtil.getMetadata(targetClass);
+        if (metadata == null) {
             throw new NoScrMetadataException(targetClass);
         }
         String methodName;
         if (activate) {
-            methodName = OsgiMetadataUtil.getActivateMethodName(targetClass, metadata);
+            methodName = metadata.getActivateMethodName();
         } else {
-            methodName = OsgiMetadataUtil.getDeactivateMethodName(targetClass, metadata);
+            methodName = metadata.getDeactivateMethodName();
         }
         if (StringUtils.isEmpty(methodName)) {
             return false;
@@ -156,11 +156,11 @@ final class OsgiServiceUtil {
         Class<?> targetClass = target.getClass();
 
         // get method name for activation/deactivation from osgi metadata
-        Document metadata = OsgiMetadataUtil.getMetadata(targetClass);
-        if (metadata==null) {
+        OsgiMetadata metadata = OsgiMetadataUtil.getMetadata(targetClass);
+        if (metadata == null) {
             throw new NoScrMetadataException(targetClass);
         }
-        String methodName = OsgiMetadataUtil.getModifiedMethodName(targetClass, metadata);
+        String methodName = metadata.getModifiedMethodName();
         if (StringUtils.isEmpty(methodName)) {
             return false;
         }
@@ -264,11 +264,11 @@ final class OsgiServiceUtil {
         // collect all declared reference annotations on class and field level
         Class<?> targetClass = target.getClass();
 
-        Document metadata = OsgiMetadataUtil.getMetadata(targetClass);
-        if (metadata==null) {
+        OsgiMetadata metadata = OsgiMetadataUtil.getMetadata(targetClass);
+        if (metadata == null) {
             throw new NoScrMetadataException(targetClass);
         }
-        List<Reference> references = OsgiMetadataUtil.getReferences(targetClass, metadata);
+        List<Reference> references = metadata.getReferences();
         if (references.isEmpty()) {
             return false;
         }
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 14b8744..6a6de3f 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.
  */
-@aQute.bnd.annotation.Version("1.1")
+@aQute.bnd.annotation.Version("2.0")
 package org.apache.sling.testing.mock.osgi;
diff --git a/src/test/java/org/apache/sling/testing/mock/osgi/OsgiMetadataUtilTest.java b/src/test/java/org/apache/sling/testing/mock/osgi/OsgiMetadataUtilTest.java
index 280f955..9db1197 100644
--- a/src/test/java/org/apache/sling/testing/mock/osgi/OsgiMetadataUtilTest.java
+++ b/src/test/java/org/apache/sling/testing/mock/osgi/OsgiMetadataUtilTest.java
@@ -26,24 +26,24 @@ import java.util.Map;
 import java.util.Set;
 
 import org.apache.felix.scr.annotations.ReferenceCardinality;
+import org.apache.sling.testing.mock.osgi.OsgiMetadataUtil.OsgiMetadata;
 import org.apache.sling.testing.mock.osgi.OsgiMetadataUtil.Reference;
 import org.junit.Test;
-import org.w3c.dom.Document;
 
 public class OsgiMetadataUtilTest {
 
     @Test
     public void testMetadata() {
-        Document doc = OsgiMetadataUtil.getMetadata(ServiceWithMetadata.class);
+        OsgiMetadata metadata = OsgiMetadataUtil.getMetadata(ServiceWithMetadata.class);
 
-        Set<String> serviceInterfaces = OsgiMetadataUtil.getServiceInterfaces(ServiceWithMetadata.class, doc);
+        Set<String> serviceInterfaces = metadata.getServiceInterfaces();
         assertEquals(3, serviceInterfaces.size());
         assertTrue(serviceInterfaces.contains("org.apache.sling.models.spi.Injector"));
         assertTrue(serviceInterfaces
                 .contains("org.apache.sling.models.spi.injectorspecific.InjectAnnotationProcessorFactory"));
         assertTrue(serviceInterfaces.contains("java.lang.Comparable"));
 
-        Map<String, Object> props = OsgiMetadataUtil.getProperties(ServiceWithMetadata.class, doc);
+        Map<String, Object> props = metadata.getProperties();
         assertEquals(3, props.size());
         assertEquals(5000, props.get("service.ranking"));
         assertEquals("The Apache Software Foundation", props.get("service.vendor"));
@@ -52,19 +52,19 @@ public class OsgiMetadataUtilTest {
 
     @Test
     public void testNoMetadata() {
-        Document doc = OsgiMetadataUtil.getMetadata(ServiceWithoutMetadata.class);
+        OsgiMetadata metadata = OsgiMetadataUtil.getMetadata(ServiceWithoutMetadata.class);
 
-        Set<String> serviceInterfaces = OsgiMetadataUtil.getServiceInterfaces(ServiceWithoutMetadata.class, doc);
+        Set<String> serviceInterfaces = metadata.getServiceInterfaces();
         assertEquals(0, serviceInterfaces.size());
 
-        Map<String, Object> props = OsgiMetadataUtil.getProperties(ServiceWithoutMetadata.class, doc);
+        Map<String, Object> props = metadata.getProperties();
         assertEquals(0, props.size());
     }
 
     @Test
     public void testReferences() {
-        Document doc = OsgiMetadataUtil.getMetadata(OsgiServiceUtilTest.Service3.class);
-        List<Reference> references = OsgiMetadataUtil.getReferences(OsgiServiceUtilTest.Service3.class, doc);
+        OsgiMetadata metadata = OsgiMetadataUtil.getMetadata(OsgiServiceUtilTest.Service3.class);
+        List<Reference> references = metadata.getReferences();
         assertEquals(3, references.size());
 
         Reference ref1 = references.get(0);
@@ -77,9 +77,8 @@ public class OsgiMetadataUtilTest {
 
     @Test
     public void testActivateMethodName() {
-        Document doc = OsgiMetadataUtil.getMetadata(OsgiServiceUtilTest.Service3.class);
-        String methodName = OsgiMetadataUtil.getActivateMethodName(OsgiServiceUtilTest.Service3.class, doc);
-        assertEquals("activate", methodName);
+        OsgiMetadata metadata = OsgiMetadataUtil.getMetadata(OsgiServiceUtilTest.Service3.class);
+        assertEquals("activate", metadata.getActivateMethodName());
     }
 
     static class ServiceWithMetadata {

-- 
To stop receiving notification emails like this one, please contact
"commits@sling.apache.org" <co...@sling.apache.org>.

[sling-org-apache-sling-testing-osgi-mock] 01/10: [maven-release-plugin] prepare for next development iteration

Posted by ro...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rombert pushed a commit to annotated tag org.apache.sling.testing.osgi-mock-1.2.0
in repository https://gitbox.apache.org/repos/asf/sling-org-apache-sling-testing-osgi-mock.git

commit 5022c27de87deda53a0e137065f9665cac84908e
Author: Stefan Seifert <ss...@apache.org>
AuthorDate: Tue Dec 9 23:02:17 2014 +0000

    [maven-release-plugin] prepare for next development iteration
    
    git-svn-id: https://svn.apache.org/repos/asf/sling/trunk/testing/mocks/osgi-mock@1644223 13f79535-47bb-0310-9956-ffa450edef68
---
 pom.xml | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/pom.xml b/pom.xml
index b37d460..3c036fc 100644
--- a/pom.xml
+++ b/pom.xml
@@ -28,7 +28,7 @@
     </parent>
 
     <artifactId>org.apache.sling.testing.osgi-mock</artifactId>
-    <version>1.1.0</version>
+    <version>1.1.1-SNAPSHOT</version>
     <packaging>bundle</packaging>
 
     <name>Apache Sling Testing OSGi Mock</name>
@@ -39,9 +39,9 @@
     </properties>
 
     <scm>
-        <connection>scm:svn:http://svn.apache.org/repos/asf/sling/tags/org.apache.sling.testing.osgi-mock-1.1.0</connection>
-        <developerConnection>scm:svn:https://svn.apache.org/repos/asf/sling/tags/org.apache.sling.testing.osgi-mock-1.1.0</developerConnection>
-        <url>http://svn.apache.org/viewvc/sling/tags/org.apache.sling.testing.osgi-mock-1.1.0</url>
+        <connection>scm:svn:http://svn.apache.org/repos/asf/sling/trunk/testing/mocks/osgi-mock</connection>
+        <developerConnection>scm:svn:https://svn.apache.org/repos/asf/sling/trunk/testing/mocks/osgi-mock</developerConnection>
+        <url>http://svn.apache.org/viewvc/sling/trunk/testing/mocks/osgi-mock</url>
     </scm>
 
     <dependencies>

-- 
To stop receiving notification emails like this one, please contact
"commits@sling.apache.org" <co...@sling.apache.org>.

[sling-org-apache-sling-testing-osgi-mock] 04/10: SLING-4439 add support for unregistering services and prepare dynamic service reference handling

Posted by ro...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rombert pushed a commit to annotated tag org.apache.sling.testing.osgi-mock-1.2.0
in repository https://gitbox.apache.org/repos/asf/sling-org-apache-sling-testing-osgi-mock.git

commit dc9866e557685680ee107ead6b7cb8b5665247e8
Author: Stefan Seifert <ss...@apache.org>
AuthorDate: Thu Feb 19 15:28:14 2015 +0000

    SLING-4439 add support for unregistering services and prepare dynamic service reference handling
    
    git-svn-id: https://svn.apache.org/repos/asf/sling/trunk/testing/mocks/osgi-mock@1660911 13f79535-47bb-0310-9956-ffa450edef68
---
 .../sling/testing/mock/osgi/MockBundleContext.java | 32 ++++++++++--
 .../testing/mock/osgi/MockServiceRegistration.java | 34 +++++++++++--
 .../sling/testing/mock/osgi/OsgiMetadataUtil.java  | 19 ++++++--
 .../sling/testing/mock/osgi/OsgiServiceUtil.java   |  6 +--
 .../mock/osgi/ReferenceViolationException.java     | 31 ++++++++++++
 .../testing/mock/osgi/MockBundleContextTest.java   | 57 ++++++++++++++--------
 6 files changed, 146 insertions(+), 33 deletions(-)

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 cbaa13d..37e6fd6 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
@@ -24,6 +24,7 @@ import java.util.ArrayList;
 import java.util.Dictionary;
 import java.util.List;
 import java.util.Set;
+import java.util.SortedSet;
 import java.util.TreeSet;
 
 import org.apache.commons.lang3.StringUtils;
@@ -44,7 +45,7 @@ import org.osgi.framework.ServiceRegistration;
 class MockBundleContext implements BundleContext {
 
     private final MockBundle bundle;
-    private final List<MockServiceRegistration> registeredServices = new ArrayList<MockServiceRegistration>();
+    private final SortedSet<MockServiceRegistration> registeredServices = new TreeSet<MockServiceRegistration>();
     private final List<ServiceListener> serviceListeners = new ArrayList<ServiceListener>();
     private final List<BundleListener> bundleListeners = new ArrayList<BundleListener>();
 
@@ -77,12 +78,37 @@ class MockBundleContext implements BundleContext {
     @SuppressWarnings("unchecked")
     @Override
     public ServiceRegistration registerService(final String[] clazzes, final Object service, final Dictionary properties) {
-        MockServiceRegistration registration = new MockServiceRegistration(this.bundle, clazzes, service, properties);
+        MockServiceRegistration registration = new MockServiceRegistration(this.bundle, clazzes, service, properties, this);
+        handleRefsUpdateOnRegister(registration);
         this.registeredServices.add(registration);
         notifyServiceListeners(ServiceEvent.REGISTERED, registration.getReference());
         return registration;
     }
-
+    
+    /**
+     * 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.
+     * @param registration
+     */
+    private void handleRefsUpdateOnRegister(MockServiceRegistration registration) {
+        // TODO: implement handling
+    }
+    
+    void unregisterService(MockServiceRegistration registration) {
+        this.registeredServices.remove(registration);
+        handleRefsUpdateOnUnregister(registration);
+        notifyServiceListeners(ServiceEvent.UNREGISTERING, registration.getReference());
+    }
+
+    /**
+     * Check for already registered services that may be affected by the service unregistration - either
+     * adding by removing optional references, or creating a conflict in the dependencies.
+     * @param registration
+     */
+    private void handleRefsUpdateOnUnregister(MockServiceRegistration registration) {
+        // TODO: implement handling
+    }
+    
     @Override
     public ServiceReference getServiceReference(final String clazz) {
         ServiceReference[] serviceRefs = getServiceReferences(clazz, null);
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 f212b49..c9c13dd 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
@@ -35,22 +35,26 @@ import com.google.common.collect.ImmutableList;
 /**
  * Mock {@link ServiceRegistration} implementation.
  */
-class MockServiceRegistration implements ServiceRegistration {
+class MockServiceRegistration implements ServiceRegistration, Comparable<MockServiceRegistration> {
 
     private static volatile long serviceCounter;
 
+    private final Long serviceId;
     private final Set<String> clazzes;
     private final Object service;
     private Dictionary<String, Object> properties;
     private final ServiceReference serviceReference;
+    private final MockBundleContext bundleContext;
 
     public MockServiceRegistration(final Bundle bundle, final String[] clazzes, final Object service,
-            final Dictionary<String, Object> properties) {
+            final Dictionary<String, Object> properties, MockBundleContext bundleContext) {
+        this.serviceId = ++serviceCounter;
         this.clazzes = new HashSet<String>(ImmutableList.copyOf(clazzes));
         this.service = service;
         this.properties = properties != null ? properties : new Hashtable<String,Object>();
-        this.properties.put(Constants.SERVICE_ID, ++serviceCounter);
+        this.properties.put(Constants.SERVICE_ID, this.serviceId);
         this.serviceReference = new MockServiceReference(bundle, this);
+        this.bundleContext = bundleContext;
         readOsgiMetadata();
     }
 
@@ -67,7 +71,7 @@ class MockServiceRegistration implements ServiceRegistration {
 
     @Override
     public void unregister() {
-        // do nothing for now
+        bundleContext.unregisterService(this);
     }
 
     Dictionary<String, Object> getProperties() {
@@ -78,10 +82,32 @@ class MockServiceRegistration implements ServiceRegistration {
         // ignore filter for now
         return this.clazzes.contains(clazz);
     }
+    
+    Set<String> getClasses() {
+        return clazzes;
+    }
 
     Object getService() {
         return this.service;
     }
+    
+    @Override
+    public boolean equals(Object obj) {
+        if (!(obj instanceof MockServiceRegistration)) {
+            return false;
+        }
+        return serviceId.equals(((MockServiceRegistration)obj).serviceId);
+    }
+
+    @Override
+    public int hashCode() {
+        return serviceId.hashCode();
+    }
+
+    @Override
+    public int compareTo(MockServiceRegistration obj) {
+        return serviceId.compareTo(obj.serviceId);
+    }
 
     /**
      * Try to read OSGI-metadata from /OSGI-INF and read all implemented
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 7cf7cfb..b64cd39 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
@@ -207,7 +207,7 @@ final class OsgiMetadataUtil {
         if (nodes != null) {
             for (int i = 0; i < nodes.getLength(); i++) {
                 Node node = nodes.item(i);
-                references.add(new Reference(node));
+                references.add(new Reference(clazz, node));
             }
         }
         return references;
@@ -253,6 +253,7 @@ final class OsgiMetadataUtil {
 
     static class OsgiMetadata {
         
+        private final Class<?> clazz;
         private final Set<String> serviceInterfaces;
         private final Map<String, Object> properties;
         private final List<Reference> references;
@@ -260,7 +261,8 @@ final class OsgiMetadataUtil {
         private final String deactivateMethodName;
         private final String modifiedMethodName;
         
-        private OsgiMetadata(Class clazz, Document metadataDocument) {
+        private OsgiMetadata(Class<?> clazz, Document metadataDocument) {
+            this.clazz = clazz;
             this.serviceInterfaces = OsgiMetadataUtil.getServiceInterfaces(clazz, metadataDocument);
             this.properties = OsgiMetadataUtil.getProperties(clazz, metadataDocument);
             this.references = OsgiMetadataUtil.getReferences(clazz, metadataDocument);
@@ -270,6 +272,7 @@ final class OsgiMetadataUtil {
         }
 
         private OsgiMetadata() {
+            this.clazz = null;
             this.serviceInterfaces = null;
             this.properties = null;
             this.references = null;
@@ -278,6 +281,10 @@ final class OsgiMetadataUtil {
             this.modifiedMethodName = null;
         }
         
+        public Class<?> getServiceClass() {
+            return clazz;
+        }
+
         public Set<String> getServiceInterfaces() {
             return serviceInterfaces;
         }
@@ -306,13 +313,15 @@ final class OsgiMetadataUtil {
 
     static class Reference {
 
+        private final Class<?> clazz;
         private final String name;
         private final String interfaceType;
         private final ReferenceCardinality cardinality;
         private final String bind;
         private final String unbind;
 
-        private Reference(Node node) {
+        private Reference(Class<?> clazz, Node node) {
+            this.clazz = clazz;
             this.name = getAttributeValue(node, "name");
             this.interfaceType = getAttributeValue(node, "interface");
             this.cardinality = toCardinality(getAttributeValue(node, "cardinality"));
@@ -320,6 +329,10 @@ final class OsgiMetadataUtil {
             this.unbind = getAttributeValue(node, "unbind");
         }
 
+        public Class<?> getServiceClass() {
+            return clazz;
+        }
+
         private ReferenceCardinality toCardinality(String value) {
             for (ReferenceCardinality item : ReferenceCardinality.values()) {
                 if (StringUtils.equals(item.getCardinalityString(), value)) {
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 b340b29..306a967 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
@@ -299,14 +299,14 @@ final class OsgiServiceUtil {
             boolean isOptional = (reference.getCardinality() == ReferenceCardinality.OPTIONAL_UNARY || reference
                     .getCardinality() == ReferenceCardinality.OPTIONAL_MULTIPLE);
             if (!isOptional) {
-                throw new RuntimeException("Unable to inject mandatory reference '" + reference.getName() + "' for class " + targetClass.getName());
+                throw new ReferenceViolationException("Unable to inject mandatory reference '" + reference.getName() + "' for class " + targetClass.getName());
             }
         }
 
         // multiple references found? check if reference is not multiple
         if (matchingServices.size() > 1
                 && (reference.getCardinality() == ReferenceCardinality.MANDATORY_UNARY || reference.getCardinality() == ReferenceCardinality.OPTIONAL_UNARY)) {
-            throw new RuntimeException("Multiple matches found for unary reference '" + reference.getName() + "' for class "+ targetClass.getName());
+            throw new ReferenceViolationException("Multiple matches found for unary reference '" + reference.getName() + "' for class "+ targetClass.getName());
         }
 
         // try to invoke bind method
@@ -350,7 +350,7 @@ final class OsgiServiceUtil {
         throw new RuntimeException("Bind method with name " + bindMethodName + " not found "
                 + "for reference '" + reference.getName() + "' for class {}" +  targetClass.getName());
     }
-
+    
     private static List<ServiceInfo> getMatchingServices(Class<?> type, BundleContext bundleContext) {
         List<ServiceInfo> matchingServices = new ArrayList<ServiceInfo>();
         try {
diff --git a/src/main/java/org/apache/sling/testing/mock/osgi/ReferenceViolationException.java b/src/main/java/org/apache/sling/testing/mock/osgi/ReferenceViolationException.java
new file mode 100644
index 0000000..4bfa0f2
--- /dev/null
+++ b/src/main/java/org/apache/sling/testing/mock/osgi/ReferenceViolationException.java
@@ -0,0 +1,31 @@
+/*
+ * 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;
+
+/**
+ * Is thrown when a OSGi reference injection fails due to violated constraints.
+ */
+public final class ReferenceViolationException extends RuntimeException {
+    private static final long serialVersionUID = 1L;
+
+    public ReferenceViolationException(String message) {
+        super(message);
+    }
+
+}
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 6eef138..a6a6258 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
@@ -21,6 +21,7 @@ package org.apache.sling.testing.mock.osgi;
 import static org.junit.Assert.assertArrayEquals;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertSame;
 import static org.mockito.Matchers.any;
 import static org.mockito.Mockito.mock;
@@ -50,12 +51,12 @@ public class MockBundleContextTest {
 
     @Before
     public void setUp() {
-        this.bundleContext = MockOsgi.newBundleContext();
+        bundleContext = MockOsgi.newBundleContext();
     }
 
     @Test
     public void testBundle() {
-        assertNotNull(this.bundleContext.getBundle());
+        assertNotNull(bundleContext.getBundle());
     }
 
     @Test
@@ -64,48 +65,64 @@ public class MockBundleContextTest {
         String clazz1 = String.class.getName();
         Object service1 = new Object();
         Dictionary properties1 = getServiceProperties(null);
-        ServiceRegistration reg1 = this.bundleContext.registerService(clazz1, service1, properties1);
+        ServiceRegistration reg1 = bundleContext.registerService(clazz1, service1, properties1);
 
         String[] clazzes2 = new String[] { String.class.getName(), Integer.class.getName() };
         Object service2 = new Object();
         Dictionary properties2 = getServiceProperties(null);
-        ServiceRegistration reg2 = this.bundleContext.registerService(clazzes2, service2, properties2);
+        ServiceRegistration reg2 = bundleContext.registerService(clazzes2, service2, properties2);
 
         String clazz3 = Integer.class.getName();
         Object service3 = new Object();
         Dictionary properties3 = getServiceProperties(100L);
-        ServiceRegistration reg3 = this.bundleContext.registerService(clazz3, service3, properties3);
+        ServiceRegistration reg3 = bundleContext.registerService(clazz3, service3, properties3);
 
         // test get service references
-        ServiceReference refString = this.bundleContext.getServiceReference(String.class.getName());
+        ServiceReference refString = bundleContext.getServiceReference(String.class.getName());
         assertSame(reg1.getReference(), refString);
 
-        ServiceReference refInteger = this.bundleContext.getServiceReference(Integer.class.getName());
+        ServiceReference refInteger = bundleContext.getServiceReference(Integer.class.getName());
         assertSame(reg3.getReference(), refInteger);
 
-        ServiceReference[] refsString = this.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]);
 
-        ServiceReference[] refsInteger = this.bundleContext.getServiceReferences(Integer.class.getName(), null);
+        ServiceReference[] refsInteger = bundleContext.getServiceReferences(Integer.class.getName(), null);
         assertEquals(2, refsInteger.length);
         assertSame(reg3.getReference(), refsInteger[0]);
         assertSame(reg2.getReference(), refsInteger[1]);
 
-        ServiceReference[] allRefsString = this.bundleContext.getAllServiceReferences(String.class.getName(), null);
+        ServiceReference[] allRefsString = bundleContext.getAllServiceReferences(String.class.getName(), null);
         assertArrayEquals(refsString, allRefsString);
 
         // test get services
-        assertSame(service1, this.bundleContext.getService(refsString[0]));
-        assertSame(service2, this.bundleContext.getService(refsString[1]));
-        assertSame(service3, this.bundleContext.getService(refInteger));
+        assertSame(service1, bundleContext.getService(refsString[0]));
+        assertSame(service2, bundleContext.getService(refsString[1]));
+        assertSame(service3, bundleContext.getService(refInteger));
 
         // unget does nothing
-        this.bundleContext.ungetService(refsString[0]);
-        this.bundleContext.ungetService(refsString[1]);
-        this.bundleContext.ungetService(refInteger);
+        bundleContext.ungetService(refsString[0]);
+        bundleContext.ungetService(refsString[1]);
+        bundleContext.ungetService(refInteger);
     }
+    
+    @Test
+    public void testServiceUnregistration() {
+        // prepare test services
+        String clazz1 = String.class.getName();
+        Object service1 = new Object();
+        Dictionary properties1 = getServiceProperties(null);
+        ServiceRegistration reg1 = bundleContext.registerService(clazz1, service1, properties1);
+        
+        assertNotNull(bundleContext.getServiceReference(clazz1));
+
+        reg1.unregister();
+
+        assertNull(bundleContext.getServiceReference(clazz1));
+    }
+    
 
     private Dictionary getServiceProperties(final Long serviceRanking) {
         Dictionary<String, Object> props = new Hashtable<String, Object>();
@@ -117,7 +134,7 @@ public class MockBundleContextTest {
 
     @Test
     public void testGetBundles() throws Exception {
-        assertEquals(0, this.bundleContext.getBundles().length);
+        assertEquals(0, bundleContext.getBundles().length);
     }
 
     @Test
@@ -128,7 +145,7 @@ public class MockBundleContextTest {
         // prepare test services
         String clazz1 = String.class.getName();
         Object service1 = new Object();
-        this.bundleContext.registerService(clazz1, service1, null);
+        bundleContext.registerService(clazz1, service1, null);
 
         verify(serviceListener).serviceChanged(any(ServiceEvent.class));
 
@@ -152,8 +169,8 @@ public class MockBundleContextTest {
     public void testFrameworkListener() throws Exception {
         // ensure that listeners can be called (although they are not expected
         // to to anything)
-        this.bundleContext.addFrameworkListener(null);
-        this.bundleContext.removeFrameworkListener(null);
+        bundleContext.addFrameworkListener(null);
+        bundleContext.removeFrameworkListener(null);
     }
 
 }

-- 
To stop receiving notification emails like this one, please contact
"commits@sling.apache.org" <co...@sling.apache.org>.

[sling-org-apache-sling-testing-osgi-mock] 05/10: SLING-4439 implement dynamic service registration

Posted by ro...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rombert pushed a commit to annotated tag org.apache.sling.testing.osgi-mock-1.2.0
in repository https://gitbox.apache.org/repos/asf/sling-org-apache-sling-testing-osgi-mock.git

commit e3e8bb10f076e1ea30cdd1e47570ab0bbfab2389
Author: Stefan Seifert <ss...@apache.org>
AuthorDate: Thu Feb 19 16:18:00 2015 +0000

    SLING-4439 implement dynamic service registration
    
    git-svn-id: https://svn.apache.org/repos/asf/sling/trunk/testing/mocks/osgi-mock@1660923 13f79535-47bb-0310-9956-ffa450edef68
---
 .../sling/testing/mock/osgi/MockBundleContext.java |  41 +++++++-
 .../sling/testing/mock/osgi/OsgiServiceUtil.java   | 112 +++++++++++++++++----
 2 files changed, 132 insertions(+), 21 deletions(-)

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 37e6fd6..9ae85bc 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
@@ -28,6 +28,9 @@ import java.util.SortedSet;
 import java.util.TreeSet;
 
 import org.apache.commons.lang3.StringUtils;
+import org.apache.sling.testing.mock.osgi.OsgiMetadataUtil.Reference;
+import org.apache.sling.testing.mock.osgi.OsgiServiceUtil.ReferenceInfo;
+import org.apache.sling.testing.mock.osgi.OsgiServiceUtil.ServiceInfo;
 import org.osgi.framework.Bundle;
 import org.osgi.framework.BundleContext;
 import org.osgi.framework.BundleEvent;
@@ -91,7 +94,23 @@ class MockBundleContext implements BundleContext {
      * @param registration
      */
     private void handleRefsUpdateOnRegister(MockServiceRegistration registration) {
-        // TODO: implement handling
+        List<ReferenceInfo> affectedReferences = OsgiServiceUtil.getMatchingReferences(registeredServices, registration);
+        for (ReferenceInfo referenceInfo : affectedReferences) {
+            Reference reference = referenceInfo.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, registration.getService(),
+                        new ServiceInfo(referenceInfo.getServiceRegistration()));
+                break;
+            default:
+                throw new RuntimeException("Unepxected cardinality: " + reference.getCardinality());
+            }
+        }
     }
     
     void unregisterService(MockServiceRegistration registration) {
@@ -106,7 +125,25 @@ class MockBundleContext implements BundleContext {
      * @param registration
      */
     private void handleRefsUpdateOnUnregister(MockServiceRegistration registration) {
-        // TODO: implement handling
+        List<ReferenceInfo> affectedReferences = OsgiServiceUtil.getMatchingReferences(registeredServices, registration);
+        for (ReferenceInfo referenceInfo : affectedReferences) {
+            Reference reference = referenceInfo.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, registration.getService(),
+                        new ServiceInfo(referenceInfo.getServiceRegistration()));
+                break;
+            default:
+                throw new RuntimeException("Unepxected cardinality: " + reference.getCardinality());
+            }
+        }
     }
     
     @Override
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 306a967..152379f 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
@@ -25,6 +25,7 @@ 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;
@@ -310,15 +311,22 @@ final class OsgiServiceUtil {
         }
 
         // try to invoke bind method
-        String bindMethodName = reference.getBind();
-        if (StringUtils.isNotEmpty(bindMethodName)) {
+        for (ServiceInfo matchingService : matchingServices) {
+            invokeBindUnbindMethod(reference, target, matchingService, true);
+        }
+    }
+    
+    private static void invokeBindUnbindMethod(Reference reference, Object target, ServiceInfo serviceInfo, boolean bind) {
+        Class<?> targetClass = target.getClass();
+
+        // try to invoke bind method
+        String methodName = bind ? reference.getBind() : reference.getUnbind();
+        if (StringUtils.isNotEmpty(methodName)) {
             
             // 1. ServiceReference
-            Method bindMethod = getMethod(targetClass, bindMethodName, new Class<?>[] { ServiceReference.class });
-            if (bindMethod != null) {
-                for (ServiceInfo matchingService : matchingServices) {
-                    invokeMethod(target, bindMethod, new Object[] { matchingService.getServiceReference() });
-                }
+            Method method = getMethod(targetClass, methodName, new Class<?>[] { ServiceReference.class });
+            if (method != null) {
+                invokeMethod(target, method, new Object[] { serviceInfo.getServiceReference() });
                 return;
             }
             
@@ -329,27 +337,43 @@ final class OsgiServiceUtil {
             } catch (ClassNotFoundException e) {
                 throw new RuntimeException("Service reference type not found: " + reference.getInterfaceType());
             }
-            bindMethod = getMethodWithAssignableTypes(targetClass, bindMethodName, new Class<?>[] { interfaceType });
-            if (bindMethod != null) {
-                for (ServiceInfo matchingService : matchingServices) {
-                    invokeMethod(target, bindMethod, new Object[] { matchingService.getServiceInstance() });
-                }
+            method = getMethodWithAssignableTypes(targetClass, methodName, new Class<?>[] { interfaceType });
+            if (method != null) {
+                invokeMethod(target, method, new Object[] { serviceInfo.getServiceInstance() });
                 return;
             }
             
             // 3. assignable from service instance plus map
-            bindMethod = getMethodWithAssignableTypes(targetClass, bindMethodName, new Class<?>[] { interfaceType, Map.class });
-            if (bindMethod != null) {
-                for (ServiceInfo matchingService : matchingServices) {
-                    invokeMethod(target, bindMethod, new Object[] { matchingService.getServiceInstance(), matchingService.getServiceConfig() });
-                }
+            method = getMethodWithAssignableTypes(targetClass, methodName, new Class<?>[] { interfaceType, Map.class });
+            if (method != null) {
+                invokeMethod(target, method, new Object[] { serviceInfo.getServiceInstance(), serviceInfo.getServiceConfig() });
                 return;
             }
         }
 
-        throw new RuntimeException("Bind method with name " + bindMethodName + " not found "
+        throw new RuntimeException((bind ? "Bind" : "Unbind") + "method with name " + methodName + " not found "
                 + "for reference '" + reference.getName() + "' for class {}" +  targetClass.getName());
     }
+
+    /**
+     * Directly invoke bind method on service for the given reference.
+     * @param reference Reference metadata
+     * @param target Target object for reference
+     * @param serviceInfo Service on which to invoke the method
+     */
+    public static void invokeBindMethod(Reference reference, Object target, ServiceInfo serviceInfo) {
+        invokeBindUnbindMethod(reference,  target, serviceInfo, true);
+    }
+    
+    /**
+     * Directly invoke unbind method on service for the given reference.
+     * @param reference Reference metadata
+     * @param target Target object for reference
+     * @param serviceInfo Service on which to invoke the method
+     */
+    public static void invokeUnbindMethod(Reference reference, Object target, ServiceInfo serviceInfo) {
+        invokeBindUnbindMethod(reference,  target, serviceInfo, false);
+    }
     
     private static List<ServiceInfo> getMatchingServices(Class<?> type, BundleContext bundleContext) {
         List<ServiceInfo> matchingServices = new ArrayList<ServiceInfo>();
@@ -372,7 +396,31 @@ final class OsgiServiceUtil {
         return matchingServices;
     }
 
-    private static class ServiceInfo {
+    /**
+     * Collects all references of any registered service that match with any of the exported interfaces of the given service registration.
+     * @param registeredServices Registered Services
+     * @param registration Service registration
+     * @return List of references
+     */
+    public static List<ReferenceInfo> getMatchingReferences(SortedSet<MockServiceRegistration> registeredServices,
+            MockServiceRegistration registration) {
+        List<ReferenceInfo> references = new ArrayList<ReferenceInfo>();
+        for (MockServiceRegistration existingRegistration : registeredServices) {
+            OsgiMetadata metadata = OsgiMetadataUtil.getMetadata(existingRegistration.getService().getClass());
+            if (metadata != null) {
+                for (Reference reference : metadata.getReferences()) {
+                    for (String serviceInterface : registration.getClasses()) {
+                        if (StringUtils.equals(serviceInterface, reference.getInterfaceType())) {
+                            references.add(new ReferenceInfo(existingRegistration, reference));
+                        }
+                    }
+                }
+            }
+        }
+        return references;
+    }
+            
+    static class ServiceInfo {
 
         private final Object serviceInstance;
         private final Map<String, Object> serviceConfig;
@@ -384,6 +432,12 @@ final class OsgiServiceUtil {
             this.serviceReference = serviceReference;
         }
 
+        public ServiceInfo(MockServiceRegistration registration) {
+            this.serviceInstance = registration.getService();
+            this.serviceConfig = MapUtil.toMap(registration.getProperties());
+            this.serviceReference = registration.getReference();
+        }
+
         public Object getServiceInstance() {
             return this.serviceInstance;
         }
@@ -398,4 +452,24 @@ final class OsgiServiceUtil {
 
     }
 
+    static class ReferenceInfo {
+
+        private final MockServiceRegistration serviceRegistration;
+        private final Reference reference;
+        
+        public ReferenceInfo(MockServiceRegistration serviceRegistration, Reference reference) {
+            this.serviceRegistration = serviceRegistration;
+            this.reference = reference;
+        }
+
+        public MockServiceRegistration getServiceRegistration() {
+            return serviceRegistration;
+        }
+
+        public Reference getReference() {
+            return reference;
+        }
+
+    }
+
 }

-- 
To stop receiving notification emails like this one, please contact
"commits@sling.apache.org" <co...@sling.apache.org>.