Author: justin
Date: Mon Dec 23 16:27:35 2013
New Revision: 1553142

URL: http://svn.apache.org/r1553142
Log:
refactor bundle listener into separate class

Added:
    
sling/whiteboard/justin/yamf/org.apache.sling.yamf.impl/src/main/java/org/apache/sling/yamf/impl/ModelPackageBundleListener.java
Modified:
    
sling/whiteboard/justin/yamf/org.apache.sling.yamf.impl/src/main/java/org/apache/sling/yamf/impl/YamfAdapterFactory.java

Added: 
sling/whiteboard/justin/yamf/org.apache.sling.yamf.impl/src/main/java/org/apache/sling/yamf/impl/ModelPackageBundleListener.java
URL: 
http://svn.apache.org/viewvc/sling/whiteboard/justin/yamf/org.apache.sling.yamf.impl/src/main/java/org/apache/sling/yamf/impl/ModelPackageBundleListener.java?rev=1553142&view=auto
==============================================================================
--- 
sling/whiteboard/justin/yamf/org.apache.sling.yamf.impl/src/main/java/org/apache/sling/yamf/impl/ModelPackageBundleListener.java
 (added)
+++ 
sling/whiteboard/justin/yamf/org.apache.sling.yamf.impl/src/main/java/org/apache/sling/yamf/impl/ModelPackageBundleListener.java
 Mon Dec 23 16:27:35 2013
@@ -0,0 +1,151 @@
+/*
+ * 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.yamf.impl;
+
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Dictionary;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.Hashtable;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.commons.lang.StringUtils;
+import org.apache.sling.api.adapter.AdapterFactory;
+import org.apache.sling.commons.osgi.PropertiesUtil;
+import org.apache.sling.yamf.api.Model;
+import org.osgi.framework.Bundle;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.BundleEvent;
+import org.osgi.framework.BundleListener;
+import org.osgi.framework.ServiceRegistration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class ModelPackageBundleListener implements BundleListener {
+
+    private static final Logger log = 
LoggerFactory.getLogger(ModelPackageBundleListener.class);
+
+    private final BundleContext bundleContext;
+    
+    private final AdapterFactory factory;
+
+    private final Map<Bundle, List<ServiceRegistration>> 
registeredModelFactories;
+
+    public ModelPackageBundleListener(BundleContext bundleContext, 
AdapterFactory factory) {
+        this.bundleContext = bundleContext;
+        this.factory = factory;
+        this.registeredModelFactories = new HashMap<Bundle, 
List<ServiceRegistration>>();
+        for (final Bundle bundle : this.bundleContext.getBundles()) {
+            if (bundle.getState() == Bundle.ACTIVE) {
+                addBundle(bundle);
+            }
+        }
+
+        this.bundleContext.addBundleListener(this);
+    }
+
+    @Override
+    public synchronized void bundleChanged(BundleEvent event) {
+        if (event.getType() == BundleEvent.STOPPED) {
+            removeBundle(event.getBundle());
+        } else if (event.getType() == BundleEvent.STARTED) {
+            addBundle(event.getBundle());
+        }
+    }
+
+    public synchronized void unregisterAll() {
+        Iterator<Map.Entry<Bundle, List<ServiceRegistration>>> it = 
registeredModelFactories.entrySet().iterator();
+        while (it.hasNext()) {
+            for (ServiceRegistration reg : it.next().getValue()) {
+                reg.unregister();
+            }
+            it.remove();
+        }
+    }
+
+    private void addBundle(final Bundle bundle) {
+        Dictionary<?, ?> headers = bundle.getHeaders();
+        String packageList = 
PropertiesUtil.toString(headers.get("Sling-YAMF-Packages"), null);
+        if (packageList != null) {
+            List<ServiceRegistration> regs = new 
ArrayList<ServiceRegistration>();
+
+            packageList = StringUtils.deleteWhitespace(packageList);
+            String[] packages = packageList.split(",");
+            for (String singlePackage : packages) {
+                @SuppressWarnings("unchecked")
+                Enumeration<URL> classUrls = bundle.findEntries("/" + 
singlePackage.replace('.', '/'), "*.class",
+                        true);
+                while (classUrls.hasMoreElements()) {
+                    URL url = classUrls.nextElement();
+                    String className = toClassName(url);
+                    try {
+                        Class<?> clazz = bundle.loadClass(className);
+                        Model annotation = clazz.getAnnotation(Model.class);
+                        if (annotation != null) {
+                            Class<?>[] adaptables = annotation.adaptables();
+                            String[] classNames = toStringArray(adaptables);
+                            Dictionary<String, Object> registrationProps = new 
Hashtable<String, Object>();
+                            
registrationProps.put(AdapterFactory.ADAPTER_CLASSES, className);
+                            
registrationProps.put(AdapterFactory.ADAPTABLE_CLASSES, classNames);
+                            ServiceRegistration reg = 
bundleContext.registerService(AdapterFactory.SERVICE_NAME,
+                                    factory, registrationProps);
+                            regs.add(reg);
+                        }
+                    } catch (ClassNotFoundException e) {
+                        log.warn("Unable to load class", e);
+                    }
+
+                }
+            }
+
+            if (!regs.isEmpty()) {
+                synchronized (this) {
+                    registeredModelFactories.put(bundle, regs);
+                }
+            }
+        }
+    }
+
+    private void removeBundle(final Bundle bundle) {
+        if (registeredModelFactories.containsKey(bundle)) {
+            List<ServiceRegistration> regs = 
registeredModelFactories.get(bundle);
+            for (ServiceRegistration reg : regs) {
+                reg.unregister();
+            }
+            registeredModelFactories.remove(bundle);
+        }
+    }
+
+    /** Convert class URL to class name */
+    private String toClassName(URL url) {
+        final String f = url.getFile();
+        final String cn = f.substring(1, f.length() - ".class".length());
+        return cn.replace('/', '.');
+    }
+
+    private String[] toStringArray(Class<?>[] classes) {
+        String[] arr = new String[classes.length];
+        for (int i = 0; i < classes.length; i++) {
+            arr[i] = classes[i].getName();
+        }
+        return arr;
+    }
+
+}

Modified: 
sling/whiteboard/justin/yamf/org.apache.sling.yamf.impl/src/main/java/org/apache/sling/yamf/impl/YamfAdapterFactory.java
URL: 
http://svn.apache.org/viewvc/sling/whiteboard/justin/yamf/org.apache.sling.yamf.impl/src/main/java/org/apache/sling/yamf/impl/YamfAdapterFactory.java?rev=1553142&r1=1553141&r2=1553142&view=diff
==============================================================================
--- 
sling/whiteboard/justin/yamf/org.apache.sling.yamf.impl/src/main/java/org/apache/sling/yamf/impl/YamfAdapterFactory.java
 (original)
+++ 
sling/whiteboard/justin/yamf/org.apache.sling.yamf.impl/src/main/java/org/apache/sling/yamf/impl/YamfAdapterFactory.java
 Mon Dec 23 16:27:35 2013
@@ -20,19 +20,12 @@ import java.lang.reflect.AnnotatedElemen
 import java.lang.reflect.Field;
 import java.lang.reflect.InvocationHandler;
 import java.lang.reflect.Method;
-import java.lang.reflect.ParameterizedType;
 import java.lang.reflect.Proxy;
 import java.lang.reflect.Type;
-import java.net.URL;
 import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
 import java.util.Collections;
-import java.util.Dictionary;
-import java.util.Enumeration;
 import java.util.HashMap;
 import java.util.HashSet;
-import java.util.Hashtable;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
@@ -44,32 +37,27 @@ import javax.inject.Inject;
 import javax.inject.Named;
 
 import org.apache.commons.beanutils.PropertyUtils;
-import org.apache.commons.lang.StringUtils;
 import org.apache.felix.scr.annotations.Activate;
 import org.apache.felix.scr.annotations.Component;
+import org.apache.felix.scr.annotations.Deactivate;
 import org.apache.felix.scr.annotations.Reference;
 import org.apache.felix.scr.annotations.ReferenceCardinality;
 import org.apache.felix.scr.annotations.ReferencePolicy;
 import org.apache.sling.api.adapter.AdapterFactory;
-import org.apache.sling.commons.osgi.PropertiesUtil;
 import org.apache.sling.commons.osgi.ServiceUtil;
 import org.apache.sling.yamf.api.Default;
 import org.apache.sling.yamf.api.Model;
 import org.apache.sling.yamf.api.Optional;
 import org.apache.sling.yamf.api.Projection;
 import org.apache.sling.yamf.spi.Injector;
-import org.osgi.framework.Bundle;
 import org.osgi.framework.BundleContext;
-import org.osgi.framework.BundleEvent;
-import org.osgi.framework.BundleListener;
 import org.osgi.framework.InvalidSyntaxException;
-import org.osgi.framework.ServiceRegistration;
 import org.osgi.service.component.ComponentContext;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 @Component
-public class YamfAdapterFactory implements AdapterFactory, BundleListener {
+public class YamfAdapterFactory implements AdapterFactory {
 
     public static class MapBackedInvocationHandler implements 
InvocationHandler {
 
@@ -87,24 +75,13 @@ public class YamfAdapterFactory implemen
 
     private static final Logger log = 
LoggerFactory.getLogger(YamfAdapterFactory.class);
 
-    private BundleContext bundleContext;
-
     @Reference(name = "injector", referenceInterface = Injector.class,
             cardinality = ReferenceCardinality.OPTIONAL_MULTIPLE, policy = 
ReferencePolicy.DYNAMIC)
     private final Map<Object, Injector> injectors = new TreeMap<Object, 
Injector>();
 
-    private Map<Bundle, List<ServiceRegistration>> registeredModelFactories;
-
     private volatile Injector[] sortedInjectors = new Injector[0];
 
-    @Override
-    public synchronized void bundleChanged(BundleEvent event) {
-        if (event.getType() == BundleEvent.STOPPED) {
-            removeBundle(event.getBundle());
-        } else if (event.getType() == BundleEvent.STARTED) {
-            addBundle(event.getBundle());
-        }
-    }
+    private ModelPackageBundleListener listener;
 
     @SuppressWarnings("unchecked")
     public <AdapterType> AdapterType getAdapter(Object adaptable, 
Class<AdapterType> type) {
@@ -142,64 +119,6 @@ public class YamfAdapterFactory implemen
         }
     }
 
-    private void addBundle(final Bundle bundle) {
-        Dictionary<?, ?> headers = bundle.getHeaders();
-        String packageList = 
PropertiesUtil.toString(headers.get("Sling-YAMF-Packages"), null);
-        if (packageList != null) {
-            List<ServiceRegistration> regs = new 
ArrayList<ServiceRegistration>();
-
-            packageList = StringUtils.deleteWhitespace(packageList);
-            String[] packages = packageList.split(",");
-            for (String singlePackage : packages) {
-                @SuppressWarnings("unchecked")
-                Enumeration<URL> classUrls = bundle.findEntries("/" + 
singlePackage.replace('.', '/'), "*.class",
-                        true);
-                while (classUrls.hasMoreElements()) {
-                    URL url = classUrls.nextElement();
-                    String className = toClassName(url);
-                    try {
-                        Class<?> clazz = bundle.loadClass(className);
-                        Model annotation = clazz.getAnnotation(Model.class);
-                        if (annotation != null) {
-                            Class<?>[] adaptables = annotation.adaptables();
-                            String[] classNames = toStringArray(adaptables);
-                            Dictionary<String, Object> registrationProps = new 
Hashtable<String, Object>();
-                            
registrationProps.put(AdapterFactory.ADAPTER_CLASSES, className);
-                            
registrationProps.put(AdapterFactory.ADAPTABLE_CLASSES, classNames);
-                            ServiceRegistration reg = 
bundleContext.registerService(AdapterFactory.SERVICE_NAME,
-                                    this, registrationProps);
-                            regs.add(reg);
-                        }
-                    } catch (ClassNotFoundException e) {
-                        log.warn("Unable to load class", e);
-                    }
-
-                }
-            }
-
-            if (!regs.isEmpty()) {
-                synchronized (this) {
-                    registeredModelFactories.put(bundle, regs);
-                }
-            }
-        }
-    }
-
-    private String[] toStringArray(Class<?>[] classes) {
-        String[] arr = new String[classes.length];
-        for (int i = 0; i < classes.length; i++) {
-            arr[i] = classes[i].getName();
-        }
-        return arr;
-    }
-
-    /** Convert class URL to class name */
-    private String toClassName(URL url) {
-        final String f = url.getFile();
-        final String cn = f.substring(1, f.length() - ".class".length());
-        return cn.replace('/', '.');
-    }
-
     private Set<Field> collectInjectableFields(Class<?> type) {
         Set<Field> result = new HashSet<Field>();
         while (type != null) {
@@ -502,16 +421,6 @@ public class YamfAdapterFactory implemen
         return type;
     }
 
-    private void removeBundle(final Bundle bundle) {
-        if (registeredModelFactories.containsKey(bundle)) {
-            List<ServiceRegistration> regs = 
registeredModelFactories.get(bundle);
-            for (ServiceRegistration reg : regs) {
-                reg.unregister();
-            }
-            registeredModelFactories.remove(bundle);
-        }
-    }
-
     private boolean setField(Field field, Object createdObject, Object value) {
         if (value != null) {
             boolean accessible = field.isAccessible();
@@ -535,9 +444,7 @@ public class YamfAdapterFactory implemen
     }
 
     private boolean setMethod(Method method, Map<Method, Object> methods, 
Object value) {
-        if (value != null
-                && (isAcceptableType(
-                        method.getReturnType(), value))) {
+        if (value != null && (isAcceptableType(method.getReturnType(), 
value))) {
             methods.put(method, value);
             return true;
         } else {
@@ -549,7 +456,7 @@ public class YamfAdapterFactory implemen
         if (type.isInstance(value)) {
             return true;
         }
-        
+
         if (type == Integer.TYPE) {
             return Integer.class.isInstance(value);
         }
@@ -577,15 +484,12 @@ public class YamfAdapterFactory implemen
 
     @Activate
     protected void activate(final ComponentContext ctx) throws 
InvalidSyntaxException {
-        this.bundleContext = ctx.getBundleContext();
-        this.registeredModelFactories = new HashMap<Bundle, 
List<ServiceRegistration>>();
-        for (final Bundle bundle : this.bundleContext.getBundles()) {
-            if (bundle.getState() == Bundle.ACTIVE) {
-                addBundle(bundle);
-            }
-        }
+        this.listener = new ModelPackageBundleListener(ctx.getBundleContext(), 
this);
+    }
 
-        this.bundleContext.addBundleListener(this);
+    @Deactivate
+    protected void deactivate() {
+        this.listener.unregisterAll();
     }
 
     protected void bindInjector(final Injector injector, final Map<String, 
Object> props) {


Reply via email to