SLING-4217 - Register OSGi services corresponding to available adapter
factories

Extend the AdapterManagerImpl to register OSGi services for the adapter
factories that it manages. These services are unregistered when the
adapter factories themselves are unregistered.

git-svn-id: https://svn.apache.org/repos/asf/sling/trunk@1644110 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/pom.xml b/pom.xml
index 4f71590..9e66850 100644
--- a/pom.xml
+++ b/pom.xml
@@ -62,7 +62,7 @@
                 <configuration>
                     <instructions>
                         <Export-Package>
-                            org.apache.sling.adapter;version=2.0.6
+                            org.apache.sling.adapter;version=2.1.0
                         </Export-Package>
                         <Private-Package>
                             org.apache.sling.adapter.internal
diff --git a/src/main/java/org/apache/sling/adapter/Adaption.java b/src/main/java/org/apache/sling/adapter/Adaption.java
new file mode 100644
index 0000000..aeee6ea
--- /dev/null
+++ b/src/main/java/org/apache/sling/adapter/Adaption.java
@@ -0,0 +1,37 @@
+/*
+ * 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.adapter;
+
+/**
+ * The <tt>Adaption</tt> is a marker interface which is registered as a service by the <tt>AdapterManager</tt> once a
+ * certain <tt>AdapterFactory</tt> is available
+ * 
+ * <p>
+ * Its intended use is to make it simple for declarative service components to wait for a certain
+ * <tt>AdapterFactory</tt> to be available
+ * 
+ * <p>
+ * A usage sample is
+ * 
+ * <code>@Reference(referenceInterface=Adaptation.class,target="(&(adaptable=com.myco.MyClass)(adaptable=org.apache.sling.api.Resource), name = "ignore", strategy = ReferenceStrategy.LOOKUP)")</code>
+ *
+ */
+public interface Adaption {
+
+}
diff --git a/src/main/java/org/apache/sling/adapter/internal/AdapterFactoryDescriptor.java b/src/main/java/org/apache/sling/adapter/internal/AdapterFactoryDescriptor.java
index efb215a..1075e5f 100644
--- a/src/main/java/org/apache/sling/adapter/internal/AdapterFactoryDescriptor.java
+++ b/src/main/java/org/apache/sling/adapter/internal/AdapterFactoryDescriptor.java
@@ -20,6 +20,7 @@
 
 import org.apache.sling.api.adapter.AdapterFactory;
 import org.osgi.framework.ServiceReference;
+import org.osgi.framework.ServiceRegistration;
 import org.osgi.service.component.ComponentContext;
 
 /**
@@ -37,6 +38,8 @@
 
     private final ComponentContext context;
 
+    private ServiceRegistration adaption;
+
     public AdapterFactoryDescriptor(
             final ComponentContext context,
             final ServiceReference reference,
@@ -57,4 +60,12 @@
     public String[] getAdapters() {
         return adapters;
     }
+
+    public ServiceRegistration getAdaption() {
+        return adaption;
+    }
+
+    public void setAdaption(ServiceRegistration adaption) {
+        this.adaption = adaption;
+    }
 }
diff --git a/src/main/java/org/apache/sling/adapter/internal/AdapterManagerImpl.java b/src/main/java/org/apache/sling/adapter/internal/AdapterManagerImpl.java
index 92fd8c2..41142d4 100644
--- a/src/main/java/org/apache/sling/adapter/internal/AdapterManagerImpl.java
+++ b/src/main/java/org/apache/sling/adapter/internal/AdapterManagerImpl.java
@@ -22,6 +22,7 @@
 import static org.apache.sling.api.adapter.AdapterFactory.ADAPTER_CLASSES;
 
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.Dictionary;
 import java.util.HashMap;
 import java.util.Hashtable;
@@ -38,6 +39,7 @@
 import org.apache.felix.scr.annotations.ReferenceCardinality;
 import org.apache.felix.scr.annotations.ReferencePolicy;
 import org.apache.felix.scr.annotations.Service;
+import org.apache.sling.adapter.Adaption;
 import org.apache.sling.api.SlingConstants;
 import org.apache.sling.api.adapter.AdapterFactory;
 import org.apache.sling.api.adapter.AdapterManager;
@@ -45,6 +47,7 @@
 import org.apache.sling.commons.osgi.PropertiesUtil;
 import org.osgi.framework.Constants;
 import org.osgi.framework.ServiceReference;
+import org.osgi.framework.ServiceRegistration;
 import org.osgi.service.component.ComponentContext;
 import org.osgi.service.event.Event;
 import org.osgi.service.event.EventAdmin;
@@ -283,12 +286,23 @@
         // clear the factory cache to force rebuild on next access
         this.factoryCache.clear();
 
+        // register adaption
+        final Dictionary<String, Object> props = new Hashtable<String, Object>();
+        props.put(SlingConstants.PROPERTY_ADAPTABLE_CLASSES, adaptables);
+        props.put(SlingConstants.PROPERTY_ADAPTER_CLASSES, adapters);
+
+        ServiceRegistration adaptionRegistration = this.context.getBundleContext().registerService(
+                Adaption.class.getName(), AdaptionImpl.INSTANCE, props);
+        if (log.isDebugEnabled()) {
+            log.debug("Registered service {} with {} : {} and {} : {}", new Object[] { Adaption.class.getName(),
+                    SlingConstants.PROPERTY_ADAPTABLE_CLASSES, Arrays.toString(adaptables),
+                    SlingConstants.PROPERTY_ADAPTER_CLASSES, Arrays.toString(adapters) });
+        }
+        factoryDesc.setAdaption(adaptionRegistration);
+
         // send event
         final EventAdmin localEA = this.eventAdmin;
         if ( localEA != null ) {
-            final Dictionary<String, Object> props = new Hashtable<String, Object>();
-            props.put(SlingConstants.PROPERTY_ADAPTABLE_CLASSES, adaptables);
-            props.put(SlingConstants.PROPERTY_ADAPTER_CLASSES, adapters);
             localEA.postEvent(new Event(SlingConstants.TOPIC_ADAPTER_FACTORY_ADDED,
                     props));
         }
@@ -328,13 +342,25 @@
 
         boolean factoriesModified = false;
         AdapterFactoryDescriptorMap adfMap = null;
+
+        AdapterFactoryDescriptor removedDescriptor = null;
         for (final String adaptable : adaptables) {
             synchronized ( this.descriptors ) {
                 adfMap = this.descriptors.get(adaptable);
             }
             if (adfMap != null) {
                 synchronized ( adfMap ) {
-                    factoriesModified |= (adfMap.remove(reference) != null);
+                    AdapterFactoryDescriptor factoryDesc = adfMap.remove(reference);
+                    if (factoryDesc != null) {
+                        factoriesModified = true;
+                        // A single ServiceReference should correspond to a single Adaption service being registered
+                        // Since the code paths above does not fully guarantee it though, let's keep this check in place
+                        if (removedDescriptor != null && removedDescriptor != factoryDesc) {
+                            log.error("When unregistering reference {} got duplicate service descriptors {} and {}. Unregistration of {} services may be incomplete.",
+                                    new Object[] { reference, removedDescriptor, factoryDesc, Adaption.class.getName()} );
+                        }
+                        removedDescriptor = factoryDesc;
+                    }
                 }
             }
         }
@@ -345,6 +371,16 @@
             this.factoryCache.clear();
         }
 
+        // unregister adaption
+        if (removedDescriptor != null) {
+            removedDescriptor.getAdaption().unregister();
+            if (log.isDebugEnabled()) {
+                log.debug("Unregistered service {} with {} : {} and {} : {}", new Object[] { Adaption.class.getName(),
+                        SlingConstants.PROPERTY_ADAPTABLE_CLASSES, Arrays.toString(adaptables),
+                        SlingConstants.PROPERTY_ADAPTER_CLASSES, Arrays.toString(adapters) });
+            }
+        }
+
         // send event
         final EventAdmin localEA = this.eventAdmin;
         if ( localEA != null ) {
diff --git a/src/main/java/org/apache/sling/adapter/internal/AdaptionImpl.java b/src/main/java/org/apache/sling/adapter/internal/AdaptionImpl.java
new file mode 100644
index 0000000..b968043
--- /dev/null
+++ b/src/main/java/org/apache/sling/adapter/internal/AdaptionImpl.java
@@ -0,0 +1,30 @@
+/*
+ * 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.adapter.internal;
+
+import org.apache.sling.adapter.Adaption;
+
+/**
+ * The <tt>AdaptionImpl</tt> is a default, empty, implementation of the <tt>Adaption</tt> interface
+ *
+ */
+public enum AdaptionImpl implements Adaption {
+
+    INSTANCE;
+}
diff --git a/src/test/java/org/apache/sling/adapter/internal/AdapterManagerTest.java b/src/test/java/org/apache/sling/adapter/internal/AdapterManagerTest.java
index d449d70..ae3e18a 100644
--- a/src/test/java/org/apache/sling/adapter/internal/AdapterManagerTest.java
+++ b/src/test/java/org/apache/sling/adapter/internal/AdapterManagerTest.java
@@ -18,6 +18,7 @@
  */
 package org.apache.sling.adapter.internal;
 
+import org.apache.sling.adapter.Adaption;
 import org.apache.sling.adapter.mock.MockAdapterFactory;
 import org.apache.sling.api.adapter.AdapterFactory;
 import org.apache.sling.api.adapter.SlingAdaptable;
@@ -38,6 +39,7 @@
 import org.osgi.service.packageadmin.ExportedPackage;
 import org.osgi.service.packageadmin.PackageAdmin;
 
+import java.util.Dictionary;
 import java.util.Map;
 
 import junitx.util.PrivateAccessor;
@@ -98,6 +100,8 @@
             allowing(bundleCtx).getServiceReferences(with(any(String.class)), with(any(String.class)));
             will(returnValue(null));
             allowing(bundleCtx).removeServiceListener(with(any(ServiceListener.class)));
+            allowing(bundleCtx).registerService(with(Adaption.class.getName()), with(AdaptionImpl.INSTANCE), with(any(Dictionary.class)));
+            will(returnValue(null));
         }});
         return ctx;
     }
@@ -122,6 +126,8 @@
             allowing(bundleCtx).getServiceReferences(with(any(String.class)), with(any(String.class)));
             will(returnValue(null));
             allowing(bundleCtx).removeServiceListener(with(any(ServiceListener.class)));
+            allowing(bundleCtx).registerService(with(Adaption.class.getName()), with(AdaptionImpl.INSTANCE), with(any(Dictionary.class)));
+            will(returnValue(null));
         }});
         return ctx;
     }