incubator-sling-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From cziege...@apache.org
Subject svn commit: r1350169 [3/5] - in /sling/trunk/bundles/resourceresolver/src: main/java/org/apache/sling/resourceresolver/impl/ main/java/org/apache/sling/resourceresolver/impl/console/ main/java/org/apache/sling/resourceresolver/impl/helper/ main/java/or...
Date Thu, 14 Jun 2012 09:52:09 GMT
Modified: sling/trunk/bundles/resourceresolver/src/main/java/org/apache/sling/resourceresolver/impl/helper/ResourceIterator.java
URL: http://svn.apache.org/viewvc/sling/trunk/bundles/resourceresolver/src/main/java/org/apache/sling/resourceresolver/impl/helper/ResourceIterator.java?rev=1350169&r1=1350168&r2=1350169&view=diff
==============================================================================
--- sling/trunk/bundles/resourceresolver/src/main/java/org/apache/sling/resourceresolver/impl/helper/ResourceIterator.java (original)
+++ sling/trunk/bundles/resourceresolver/src/main/java/org/apache/sling/resourceresolver/impl/helper/ResourceIterator.java Thu Jun 14 09:52:08 2012
@@ -16,7 +16,7 @@
  * specific language governing permissions and limitations
  * under the License.
  */
-package org.apache.sling.jcr.resource.internal.helper;
+package org.apache.sling.resourceresolver.impl.helper;
 
 import java.util.Arrays;
 import java.util.HashMap;
@@ -31,6 +31,9 @@ import org.apache.sling.api.resource.Res
 import org.apache.sling.api.resource.ResourceProvider;
 import org.apache.sling.api.resource.ResourceResolver;
 import org.apache.sling.api.resource.SyntheticResource;
+import org.apache.sling.resourceresolver.impl.tree.ProviderHandler;
+import org.apache.sling.resourceresolver.impl.tree.ResourceProviderEntry;
+import org.apache.sling.resourceresolver.impl.tree.RootResourceProviderEntry;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -59,13 +62,13 @@ public class ResourceIterator implements
      * tree to collect entries which might provide children for the
      * {@link #parentResource}.
      */
-    private final ResourceProviderEntry rootProviderEntry;
+    private final RootResourceProviderEntry rootProviderEntry;
 
     /**
      * <code>ResourceProvider</code> objects registered as nodes above the
      * {@link #parentResource} up to the root of the resource tree
      */
-    private final Iterator<ResourceProvider> providers;
+    private final Iterator<ProviderHandler> providers;
 
     /**
      * The child {@link ResourceProviderEntry} registered at the node of the
@@ -95,27 +98,31 @@ public class ResourceIterator implements
      * returned. Any delayed entry whose path matches the path of a
      * non-synthetic resource will not returned.
      */
-    private Map<String, Resource> delayed;
+    private final Map<String, Resource> delayed;
 
     /**
      * Set of paths of resources already returned. This is used to prevent
      * duplicate return of resources.
      */
-    private Set<String> visited;
+    private final Set<String> visited;
 
     /**
      * The absolute path prefix of the {@link #parentResource} resource with a
      * trailing slash to build the absolute path of child resources.
      */
-    private String iteratorPath;
+    private final String iteratorPath;
 
     /**
      * Iterator on the map of {@link #delayed} synthetic resources
      */
     private Iterator<Resource> delayedIter;
 
-    public ResourceIterator(final Resource parentResource,
-            final ResourceProviderEntry rootProviderEntry) {
+    private final ResourceResolverContext resourceResolverContext;
+
+    public ResourceIterator(final ResourceResolverContext ctx,
+                    final Resource parentResource,
+                    final RootResourceProviderEntry rootProviderEntry) {
+        this.resourceResolverContext = ctx;
         this.parentResource = parentResource;
         this.rootProviderEntry = rootProviderEntry;
 
@@ -129,12 +136,12 @@ public class ResourceIterator implements
         // gather the providers in linked set, such that we keep
         // the order of addition and make sure we only get one entry
         // for each resource provider
-        Set<ResourceProvider> providersSet = new LinkedHashSet<ResourceProvider>();
-        ResourceProviderEntry atPath = getResourceProviders(path, providersSet);
+        final Set<ProviderHandler> providersSet = new LinkedHashSet<ProviderHandler>();
+        final ResourceProviderEntry atPath = getResourceProviders(path, providersSet);
 
         if (log.isDebugEnabled()) {
-            log.debug(" Provider Set for path {} {} ", path,
-                Arrays.toString(providersSet.toArray(new ResourceProvider[0])));
+            log.debug(" Provider Set for path {} {} ", path, Arrays
+                            .toString(providersSet.toArray(new ProviderHandler[providersSet.size()])));
         }
         this.iteratorPath = path;
         providers = providersSet.iterator();
@@ -153,7 +160,7 @@ public class ResourceIterator implements
             throw new NoSuchElementException();
         }
 
-        Resource result = nextResource;
+        final Resource result = nextResource;
         nextResource = seek();
         log.debug("  Child resource [{}] [{}] ", iteratorPath, result.getPath());
         return result;
@@ -166,15 +173,15 @@ public class ResourceIterator implements
     private Resource seek() {
         while (delayedIter == null) {
             while ((resources == null || !resources.hasNext())
-                && providers.hasNext()) {
-                ResourceProvider provider = providers.next();
-                resources = provider.listChildren(parentResource);
+                            && providers.hasNext()) {
+                final ProviderHandler provider = providers.next();
+                resources = provider.listChildren(this.resourceResolverContext, parentResource);
                 log.debug("     Checking Provider {} ", provider);
             }
 
             if (resources != null && resources.hasNext()) {
-                Resource res = resources.next();
-                String resPath = res.getPath();
+                final Resource res = resources.next();
+                final String resPath = res.getPath();
 
                 if (visited.contains(resPath)) {
 
@@ -207,14 +214,18 @@ public class ResourceIterator implements
                     final ResourceProviderEntry rpw = baseEntryValues.next();
                     final String resPath = iteratorPath + rpw.getPath();
                     if (!visited.contains(resPath)) {
-                        final ResourceResolver rr = parentResource.getResourceResolver();
-                        final Resource res = rpw.getResourceFromProviders(rr,
-                            resPath);
+                        final ResourceResolver rr = parentResource
+                                        .getResourceResolver();
+                        final Resource res = rpw.getResourceFromProviders(this.resourceResolverContext, rr,
+                                        resPath);
                         if (res == null) {
                             if (!delayed.containsKey(resPath)) {
-                                delayed.put(resPath, new SyntheticResource(rr,
-                                    resPath,
-                                    ResourceProvider.RESOURCE_TYPE_SYNTHETIC));
+                                delayed.put(
+                                                resPath,
+                                                new SyntheticResource(
+                                                                rr,
+                                                                resPath,
+                                                                ResourceProvider.RESOURCE_TYPE_SYNTHETIC));
                             }
                         } else {
                             // return the real resource immediately, add
@@ -223,7 +234,7 @@ public class ResourceIterator implements
                             delayed.remove(resPath);
                             visited.add(resPath);
                             log.debug("   B  resource {} {}", resPath,
-                                res.getClass());
+                                            res.getClass());
                             return res;
                         }
                     }
@@ -242,7 +253,7 @@ public class ResourceIterator implements
 
         // we exhausted all resource providers with their concrete
         // resources. now lets do the delayed (synthetic) resources
-        Resource res = delayedIter.hasNext() ? delayedIter.next() : null;
+        final Resource res = delayedIter.hasNext() ? delayedIter.next() : null;
         if (res != null) {
             log.debug("   D  resource {} {}", res.getPath(), res.getClass());
         }
@@ -253,26 +264,28 @@ public class ResourceIterator implements
      * Returns all resource providers which provider resources whose prefix is
      * the given path.
      *
-     * @param path The prefix path to match the resource provider roots against
-     * @param providers The set of already found resource providers to which any
+     * @param path
+     *            The prefix path to match the resource provider roots against
+     * @param providers
+     *            The set of already found resource providers to which any
      *            additional resource providers are added.
      * @return The ResourceProviderEntry at the node identified with the path or
      *         <code>null</code> if there is no entry at the given location
      */
-    private ResourceProviderEntry getResourceProviders(String path,
-            Set<ResourceProvider> providers) {
+    private ResourceProviderEntry getResourceProviders(final String path,
+                    final Set<ProviderHandler> providers) {
 
         // collect providers along the ancestor path segements
-        String[] elements = ResourceProviderEntry.split(path, '/');
+        final String[] elements = ResourceProviderEntry.split(path, '/');
         ResourceProviderEntry base = rootProviderEntry;
-        for (String element : elements) {
+        for (final String element : elements) {
             if (base.containsKey(element)) {
                 base = base.get(element);
                 if (log.isDebugEnabled()) {
                     log.debug("Loading from {}  {} ", element,
-                        base.getResourceProviders().length);
+                                    base.getResourceProviders().length);
                 }
-                for (ResourceProvider rp : base.getResourceProviders()) {
+                for (final ProviderHandler rp : base.getResourceProviders()) {
                     log.debug("Adding {} for {} ", rp, path);
                     providers.add(rp);
                 }
@@ -284,7 +297,7 @@ public class ResourceIterator implements
         }
 
         // add in providers at this node in the tree, ie the root provider
-        for (ResourceProvider rp : rootProviderEntry.getResourceProviders()) {
+        for (final ProviderHandler rp : rootProviderEntry.getResourceProviders()) {
             log.debug("Loading All at {} ", path);
             providers.add(rp);
         }

Modified: sling/trunk/bundles/resourceresolver/src/main/java/org/apache/sling/resourceresolver/impl/helper/ResourceIteratorDecorator.java
URL: http://svn.apache.org/viewvc/sling/trunk/bundles/resourceresolver/src/main/java/org/apache/sling/resourceresolver/impl/helper/ResourceIteratorDecorator.java?rev=1350169&r1=1350168&r2=1350169&view=diff
==============================================================================
--- sling/trunk/bundles/resourceresolver/src/main/java/org/apache/sling/resourceresolver/impl/helper/ResourceIteratorDecorator.java (original)
+++ sling/trunk/bundles/resourceresolver/src/main/java/org/apache/sling/resourceresolver/impl/helper/ResourceIteratorDecorator.java Thu Jun 14 09:52:08 2012
@@ -16,7 +16,7 @@
  * specific language governing permissions and limitations
  * under the License.
  */
-package org.apache.sling.jcr.resource.internal;
+package org.apache.sling.resourceresolver.impl.helper;
 
 import java.util.Iterator;
 
@@ -29,26 +29,31 @@ public class ResourceIteratorDecorator i
 
     private final ResourceDecoratorTracker tracker;
 
-    private final String workspaceName;
-
     private final Iterator<Resource> iterator;
 
     public ResourceIteratorDecorator(final ResourceDecoratorTracker tracker,
-            final String workspaceName,
             final Iterator<Resource> iterator) {
         this.tracker = tracker;
         this.iterator = iterator;
-        this.workspaceName = workspaceName;
     }
 
+    /**
+     * @see java.util.Iterator#hasNext()
+     */
     public boolean hasNext() {
         return this.iterator.hasNext();
     }
 
+    /**
+     * @see java.util.Iterator#next()
+     */
     public Resource next() {
-        return this.tracker.decorate(this.iterator.next(), workspaceName);
+        return this.tracker.decorate(this.iterator.next());
     }
 
+    /**
+     * @see java.util.Iterator#remove()
+     */
     public void remove() {
         this.iterator.remove();
     }

Modified: sling/trunk/bundles/resourceresolver/src/main/java/org/apache/sling/resourceresolver/impl/helper/ResourcePathIterator.java
URL: http://svn.apache.org/viewvc/sling/trunk/bundles/resourceresolver/src/main/java/org/apache/sling/resourceresolver/impl/helper/ResourcePathIterator.java?rev=1350169&r1=1350168&r2=1350169&view=diff
==============================================================================
--- sling/trunk/bundles/resourceresolver/src/main/java/org/apache/sling/resourceresolver/impl/helper/ResourcePathIterator.java (original)
+++ sling/trunk/bundles/resourceresolver/src/main/java/org/apache/sling/resourceresolver/impl/helper/ResourcePathIterator.java Thu Jun 14 09:52:08 2012
@@ -14,7 +14,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package org.apache.sling.jcr.resource.internal.helper;
+package org.apache.sling.resourceresolver.impl.helper;
 
 import java.util.Iterator;
 import java.util.NoSuchElementException;

Modified: sling/trunk/bundles/resourceresolver/src/main/java/org/apache/sling/resourceresolver/impl/helper/StarResource.java
URL: http://svn.apache.org/viewvc/sling/trunk/bundles/resourceresolver/src/main/java/org/apache/sling/resourceresolver/impl/helper/StarResource.java?rev=1350169&r1=1350168&r2=1350169&view=diff
==============================================================================
--- sling/trunk/bundles/resourceresolver/src/main/java/org/apache/sling/resourceresolver/impl/helper/StarResource.java (original)
+++ sling/trunk/bundles/resourceresolver/src/main/java/org/apache/sling/resourceresolver/impl/helper/StarResource.java Thu Jun 14 09:52:08 2012
@@ -16,9 +16,7 @@
  * specific language governing permissions and limitations
  * under the License.
  */
-package org.apache.sling.jcr.resource.internal.helper.starresource;
-
-import java.util.Map;
+package org.apache.sling.resourceresolver.impl.helper;
 
 import org.apache.sling.adapter.annotations.Adaptable;
 import org.apache.sling.adapter.annotations.Adapter;
@@ -28,10 +26,10 @@ import org.apache.sling.api.resource.Res
 import org.apache.sling.api.resource.ResourceResolver;
 import org.apache.sling.api.resource.ResourceUtil;
 import org.apache.sling.api.resource.SyntheticResource;
-import org.apache.sling.api.resource.ValueMap;
 
-/** Used to provide the equivalent of an empty Node for GET requests
- *  to *.something (SLING-344)
+/**
+ * Used to provide the equivalent of an empty Node for GET requests to
+ * *.something (SLING-344)
  */
 @Adaptable(adaptableClass = Resource.class, adapters = @Adapter(value = { String.class }))
 public class StarResource extends SyntheticResource {
@@ -50,35 +48,39 @@ public class StarResource extends Synthe
         }
     }
 
-    /** True if a StarResource should be used for the given request, if
-     *  a real Resource was not found */
+    /**
+     * True if a StarResource should be used for the given request, if a real
+     * Resource was not found
+     */
     public static boolean appliesTo(String path) {
         return path.contains(SLASH_STAR) || path.endsWith(SLASH_STAR);
     }
 
     /**
      * Returns true if the path of the resource ends with the
-     * {@link #SLASH_STAR} and therefore should be considered a star
-     * resource.
+     * {@link #SLASH_STAR} and therefore should be considered a star resource.
      */
     public static boolean isStarResource(Resource res) {
         return res.getPath().endsWith(SLASH_STAR);
     }
 
     public StarResource(ResourceResolver resourceResolver, String path) {
-        super(resourceResolver, getResourceMetadata(path), DEFAULT_RESOURCE_TYPE);
+        super(resourceResolver, getResourceMetadata(path),
+                DEFAULT_RESOURCE_TYPE);
         resourceSuperType = UNSET_RESOURCE_SUPER_TYPE;
     }
 
     /**
-     * Calls {@link ResourceUtil#getResourceSuperType(ResourceResolver, String)} method
-     * to dynamically resolve the resource super type of this star resource.
+     * Calls {@link ResourceUtil#getResourceSuperType(ResourceResolver, String)}
+     * method to dynamically resolve the resource super type of this star
+     * resource.
      */
     public String getResourceSuperType() {
-        // Yes, this isn't how you're supposed to compare Strings, but this is intentional.
+        // Yes, this isn't how you're supposed to compare Strings, but this is
+        // intentional.
         if (resourceSuperType == UNSET_RESOURCE_SUPER_TYPE) {
-            resourceSuperType = ResourceUtil.getResourceSuperType(this.getResourceResolver(),
-                    this.getResourceType());
+            resourceSuperType = ResourceUtil.getResourceSuperType(
+                    this.getResourceResolver(), this.getResourceType());
         }
         return resourceSuperType;
     }
@@ -86,21 +88,22 @@ public class StarResource extends Synthe
     @Override
     @SuppressWarnings("unchecked")
     public <Type> Type adaptTo(Class<Type> type) {
-        if ( type == String.class ) {
-            return (Type)"";
+        if (type == String.class) {
+            return (Type) "";
         }
         return super.adaptTo(type);
     }
 
     /** Get our ResourceMetadata for given path */
     static ResourceMetadata getResourceMetadata(String path) {
-    	ResourceMetadata result = new ResourceMetadata();
+        ResourceMetadata result = new ResourceMetadata();
 
-    	// The path is up to /*, what follows is pathInfo
+        // The path is up to /*, what follows is pathInfo
         final int index = path.indexOf(SLASH_STAR);
-        if(index >= 0) {
+        if (index >= 0) {
             result.setResolutionPath(path.substring(0, index) + SLASH_STAR);
-            result.setResolutionPathInfo(path.substring(index + SLASH_STAR.length()));
+            result.setResolutionPathInfo(path.substring(index
+                    + SLASH_STAR.length()));
         } else {
             result.setResolutionPath(path);
         }

Modified: sling/trunk/bundles/resourceresolver/src/main/java/org/apache/sling/resourceresolver/impl/helper/URI.java
URL: http://svn.apache.org/viewvc/sling/trunk/bundles/resourceresolver/src/main/java/org/apache/sling/resourceresolver/impl/helper/URI.java?rev=1350169&r1=1350168&r2=1350169&view=diff
==============================================================================
--- sling/trunk/bundles/resourceresolver/src/main/java/org/apache/sling/resourceresolver/impl/helper/URI.java (original)
+++ sling/trunk/bundles/resourceresolver/src/main/java/org/apache/sling/resourceresolver/impl/helper/URI.java Thu Jun 14 09:52:08 2012
@@ -16,7 +16,7 @@
  * specific language governing permissions and limitations
  * under the License.
  */
-package org.apache.sling.jcr.resource.internal.helper;
+package org.apache.sling.resourceresolver.impl.helper;
 
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;

Modified: sling/trunk/bundles/resourceresolver/src/main/java/org/apache/sling/resourceresolver/impl/helper/URIException.java
URL: http://svn.apache.org/viewvc/sling/trunk/bundles/resourceresolver/src/main/java/org/apache/sling/resourceresolver/impl/helper/URIException.java?rev=1350169&r1=1350168&r2=1350169&view=diff
==============================================================================
--- sling/trunk/bundles/resourceresolver/src/main/java/org/apache/sling/resourceresolver/impl/helper/URIException.java (original)
+++ sling/trunk/bundles/resourceresolver/src/main/java/org/apache/sling/resourceresolver/impl/helper/URIException.java Thu Jun 14 09:52:08 2012
@@ -16,7 +16,7 @@
  * specific language governing permissions and limitations
  * under the License.
  */
-package org.apache.sling.jcr.resource.internal.helper;
+package org.apache.sling.resourceresolver.impl.helper;
 
 import org.apache.sling.api.SlingException;
 

Modified: sling/trunk/bundles/resourceresolver/src/main/java/org/apache/sling/resourceresolver/impl/mapping/MapEntries.java
URL: http://svn.apache.org/viewvc/sling/trunk/bundles/resourceresolver/src/main/java/org/apache/sling/resourceresolver/impl/mapping/MapEntries.java?rev=1350169&r1=1350168&r2=1350169&view=diff
==============================================================================
--- sling/trunk/bundles/resourceresolver/src/main/java/org/apache/sling/resourceresolver/impl/mapping/MapEntries.java (original)
+++ sling/trunk/bundles/resourceresolver/src/main/java/org/apache/sling/resourceresolver/impl/mapping/MapEntries.java Thu Jun 14 09:52:08 2012
@@ -16,7 +16,7 @@
  * specific language governing permissions and limitations
  * under the License.
  */
-package org.apache.sling.jcr.resource.internal.helper;
+package org.apache.sling.resourceresolver.impl.mapping;
 
 import java.net.MalformedURLException;
 import java.net.URL;
@@ -48,8 +48,8 @@ import org.apache.sling.api.resource.Res
 import org.apache.sling.api.resource.ResourceResolver;
 import org.apache.sling.api.resource.ResourceUtil;
 import org.apache.sling.api.resource.ValueMap;
-import org.apache.sling.jcr.resource.internal.JcrResourceResolver;
-import org.apache.sling.jcr.resource.internal.JcrResourceResolverFactoryImpl;
+import org.apache.sling.resourceresolver.impl.ResourceResolverFactoryImpl;
+import org.apache.sling.resourceresolver.impl.ResourceResolverImpl;
 import org.osgi.framework.BundleContext;
 import org.osgi.framework.Constants;
 import org.osgi.framework.ServiceRegistration;
@@ -57,7 +57,6 @@ import org.osgi.service.event.Event;
 import org.osgi.service.event.EventAdmin;
 import org.osgi.service.event.EventConstants;
 import org.osgi.service.event.EventHandler;
-import org.osgi.util.tracker.ServiceTracker;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -65,6 +64,14 @@ public class MapEntries implements Event
 
     public static final MapEntries EMPTY = new MapEntries();
 
+    private static final String PROP_REG_EXP = "sling:match";
+
+    public static final String PROP_REDIRECT_EXTERNAL = "sling:redirect";
+
+    public static final String PROP_REDIRECT_EXTERNAL_STATUS = "sling:status";
+
+    public static final String PROP_REDIRECT_EXTERNAL_REDIRECT_STATUS = "sling:redirectStatus";
+
     /** Key for the global list. */
     private static final String GLOBAL_LIST_KEY = "*";
 
@@ -77,7 +84,7 @@ public class MapEntries implements Event
     /** default log */
     private final Logger log = LoggerFactory.getLogger(getClass());
 
-    private JcrResourceResolverFactoryImpl factory;
+    private ResourceResolverFactoryImpl factory;
 
     private volatile ResourceResolver resolver;
 
@@ -91,7 +98,7 @@ public class MapEntries implements Event
 
     private ServiceRegistration registration;
 
-    private ServiceTracker eventAdminTracker;
+    private EventAdmin eventAdmin;
 
     private final Semaphore initTrigger = new Semaphore(0);
 
@@ -107,18 +114,16 @@ public class MapEntries implements Event
         this.mapMaps = Collections.<MapEntry> emptyList();
         this.vanityTargets = Collections.<String> emptySet();
         this.registration = null;
-        this.eventAdminTracker = null;
+        this.eventAdmin = null;
     }
 
     @SuppressWarnings("unchecked")
-    public MapEntries(final JcrResourceResolverFactoryImpl factory,
-                      final BundleContext bundleContext,
-                      final ServiceTracker eventAdminTracker)
-    throws LoginException {
+    public MapEntries(final ResourceResolverFactoryImpl factory, final BundleContext bundleContext, final EventAdmin eventAdmin)
+                    throws LoginException {
         this.resolver = factory.getAdministrativeResourceResolver(null);
         this.factory = factory;
         this.mapRoot = factory.getMapRoot();
-        this.eventAdminTracker = eventAdminTracker;
+        this.eventAdmin = eventAdmin;
 
         this.resolveMapsMap = Collections.singletonMap(GLOBAL_LIST_KEY, (List<MapEntry>)Collections.EMPTY_LIST);
         this.mapMaps = Collections.<MapEntry> emptyList();
@@ -143,8 +148,7 @@ public class MapEntries implements Event
     }
 
     /**
-     * Signals the init method that a the doInit method should be
-     * called.
+     * Signals the init method that a the doInit method should be called.
      */
     private void triggerInit() {
         // only release if there is not one in the queue already
@@ -154,9 +158,9 @@ public class MapEntries implements Event
     }
 
     /**
-     * Runs as the method of the update thread. Waits for the triggerInit
-     * method to trigger a call to doInit. Terminates when the resolver
-     * has been null-ed after having been triggered.
+     * Runs as the method of the update thread. Waits for the triggerInit method
+     * to trigger a call to doInit. Terminates when the resolver has been
+     * null-ed after having been triggered.
      */
     void init() {
         while (this.resolver != null) {
@@ -171,16 +175,16 @@ public class MapEntries implements Event
     }
 
     /**
-     * Actual initializer. Guards itself agains concurrent use by
-     * using a ReentrantLock. Does nothing if the resource resolver
-     * has already been null-ed.
+     * Actual initializer. Guards itself agains concurrent use by using a
+     * ReentrantLock. Does nothing if the resource resolver has already been
+     * null-ed.
      */
     private void doInit() {
 
         this.initializing.lock();
         try {
             final ResourceResolver resolver = this.resolver;
-            final JcrResourceResolverFactoryImpl factory = this.factory;
+            final ResourceResolverFactoryImpl factory = this.factory;
             if (resolver == null || factory == null) {
                 return;
             }
@@ -224,19 +228,18 @@ public class MapEntries implements Event
      * Cleans up this class.
      */
     public void dispose() {
-        if ( this.registration != null ) {
+        if (this.registration != null) {
             this.registration.unregister();
             this.registration = null;
         }
 
         /*
-         * Cooperation with doInit: The same lock as used by doInit
-         * is acquired thus preventing doInit from running and waiting
-         * for a concurrent doInit to terminate.
-         * Once the lock has been acquired, the resource resolver is
-         * null-ed (thus causing the init to terminate when triggered
-         * the right after and prevent the doInit method from doing any
-         * thing).
+         * Cooperation with doInit: The same lock as used by doInit is acquired
+         * thus preventing doInit from running and waiting for a concurrent
+         * doInit to terminate. Once the lock has been acquired, the resource
+         * resolver is null-ed (thus causing the init to terminate when
+         * triggered the right after and prevent the doInit method from doing
+         * any thing).
          */
 
         // wait at most 10 seconds for a notifcation during initialization
@@ -274,7 +277,7 @@ public class MapEntries implements Event
 
         // clear the rest of the fields
         this.factory = null;
-        this.eventAdminTracker = null;
+        this.eventAdmin = null;
     }
 
     /**
@@ -282,7 +285,7 @@ public class MapEntries implements Event
      */
     public List<MapEntry> getResolveMaps() {
         final List<MapEntry> entries = new ArrayList<MapEntry>();
-        for(final List<MapEntry> list : this.resolveMapsMap.values()) {
+        for (final List<MapEntry> list : this.resolveMapsMap.values()) {
             entries.addAll(list);
         }
         Collections.sort(entries);
@@ -290,16 +293,14 @@ public class MapEntries implements Event
     }
 
     /**
-     * Calculate the resolve maps.
-     * As the entries have to be sorted by pattern length,
-     * we have to create a new list containing all
-     * relevant entries.
+     * Calculate the resolve maps. As the entries have to be sorted by pattern
+     * length, we have to create a new list containing all relevant entries.
      */
     public Iterator<MapEntry> getResolveMapsIterator(final String requestPath) {
         String key = null;
         final int firstIndex = requestPath.indexOf('/');
         final int secondIndex = requestPath.indexOf('/', firstIndex + 1);
-        if ( secondIndex != -1 ) {
+        if (secondIndex != -1) {
             key = requestPath.substring(secondIndex);
         }
 
@@ -314,8 +315,7 @@ public class MapEntries implements Event
 
     /**
      * Handles the change to any of the node properties relevant for vanity URL
-     * mappings. The
-     * {@link #MapEntries(JcrResourceResolverFactoryImpl, BundleContext, ServiceTracker)}
+     * mappings. The {@link #MapEntries(ResourceResolverFactoryImpl, BundleContext, EventAdmin)}
      * constructor makes sure the event listener is registered to only get
      * appropriate events.
      */
@@ -340,7 +340,7 @@ public class MapEntries implements Event
         boolean doInit = true;
         if (SlingConstants.TOPIC_RESOURCE_REMOVED.equals(event.getTopic()) && !path.startsWith(this.mapRoot)) {
             doInit = false;
-            for (String target : this.vanityTargets) {
+            for (final String target : this.vanityTargets) {
                 if (target.startsWith(path)) {
                     doInit = true;
                     break;
@@ -360,46 +360,43 @@ public class MapEntries implements Event
      * Send an OSGi event
      */
     private void sendChangeEvent() {
-        final EventAdmin ea = (EventAdmin) this.eventAdminTracker.getService();
-        if (ea != null) {
+        if (this.eventAdmin != null) {
             // we hard code the topic here and don't use
             // SlingConstants.TOPIC_RESOURCE_RESOLVER_MAPPING_CHANGED
             // to avoid requiring the latest API version for this bundle to work
             final Event event = new Event("org/apache/sling/api/resource/ResourceResolverMapping/CHANGED",
-                (Dictionary<?, ?>) null);
-            ea.postEvent(event);
+                            (Dictionary<?, ?>) null);
+            this.eventAdmin.postEvent(event);
         }
     }
 
-    private void loadResolverMap(final ResourceResolver resolver,
-            List<MapEntry> entries,
-            Map<String, MapEntry> mapEntries) {
+    private void loadResolverMap(final ResourceResolver resolver, final List<MapEntry> entries, final Map<String, MapEntry> mapEntries) {
         // the standard map configuration
-        Resource res = resolver.getResource(mapRoot);
+        final Resource res = resolver.getResource(mapRoot);
         if (res != null) {
             gather(resolver, entries, mapEntries, res, "");
         }
     }
 
-    private void gather(final ResourceResolver resolver,
-            List<MapEntry> entries,
-            Map<String, MapEntry> mapEntries, Resource parent, String parentPath) {
+    private void gather(final ResourceResolver resolver, final List<MapEntry> entries, final Map<String, MapEntry> mapEntries,
+                    final Resource parent, final String parentPath) {
         // scheme list
-        Iterator<Resource> children = ResourceUtil.listChildren(parent);
+        final Iterator<Resource> children = parent.listChildren();
         while (children.hasNext()) {
             final Resource child = children.next();
             final ValueMap vm = ResourceUtil.getValueMap(child);
 
-            String name = vm.get(JcrResourceResolver.PROP_REG_EXP, String.class);
+            String name = vm.get(PROP_REG_EXP, String.class);
             boolean trailingSlash = false;
             if (name == null) {
-                name = ResourceUtil.getName(child).concat("/");
+                name = child.getName().concat("/");
                 trailingSlash = true;
             }
 
-            String childPath = parentPath.concat(name);
+            final String childPath = parentPath.concat(name);
 
-            // gather the children of this entry (only if child is not end hooked)
+            // gather the children of this entry (only if child is not end
+            // hooked)
             if (!childPath.endsWith("$")) {
 
                 // add trailing slash to child path to append the child
@@ -412,19 +409,16 @@ public class MapEntries implements Event
             }
 
             // add resolution entries for this node
-            final MapEntry childResolveEntry = MapEntry.createResolveEntry(childPath,
-                child, trailingSlash);
+            final MapEntry childResolveEntry = MapEntry.createResolveEntry(childPath, child, trailingSlash);
             if (childResolveEntry != null) {
                 entries.add(childResolveEntry);
             }
 
             // add map entries for this node
-            List<MapEntry> childMapEntries = MapEntry.createMapEntry(childPath,
-                child, trailingSlash);
+            final List<MapEntry> childMapEntries = MapEntry.createMapEntry(childPath, child, trailingSlash);
             if (childMapEntries != null) {
-                for (MapEntry mapEntry : childMapEntries) {
-                    addMapEntry(mapEntries, mapEntry.getPattern(),
-                        mapEntry.getRedirect()[0], mapEntry.getStatus());
+                for (final MapEntry mapEntry : childMapEntries) {
+                    addMapEntry(mapEntries, mapEntry.getPattern(), mapEntry.getRedirect()[0], mapEntry.getStatus());
                 }
             }
 
@@ -434,10 +428,9 @@ public class MapEntries implements Event
     /**
      * Add an entry to the resolve map.
      */
-    private void addEntry(final Map<String, List<MapEntry>> entryMap,
-            final String key, final MapEntry entry) {
+    private void addEntry(final Map<String, List<MapEntry>> entryMap, final String key, final MapEntry entry) {
         List<MapEntry> entries = entryMap.get(key);
-        if ( entries == null ) {
+        if (entries == null) {
             entries = new ArrayList<MapEntry>();
             entryMap.put(key, entries);
         }
@@ -447,11 +440,10 @@ public class MapEntries implements Event
     }
 
     /**
-     * Load vanity paths
-     * Search for all nodes inheriting the sling:VanityPath mixin
+     * Load vanity paths Search for all nodes inheriting the sling:VanityPath
+     * mixin
      */
-    private Collection<String> loadVanityPaths(final ResourceResolver resolver,
-            final Map<String, List<MapEntry>> entryMap) {
+    private Collection<String> loadVanityPaths(final ResourceResolver resolver, final Map<String, List<MapEntry>> entryMap) {
         // sling:VanityPath (uppercase V) is the mixin name
         // sling:vanityPath (lowercase) is the property name
         final Set<String> targetPaths = new HashSet<String>();
@@ -479,11 +471,13 @@ public class MapEntries implements Event
             final String[] pVanityPaths = props.get("sling:vanityPath", new String[0]);
             for (final String pVanityPath : pVanityPaths) {
                 final String[] result = this.getVanityPathDefinition(pVanityPath);
-                if ( result != null ) {
+                if (result != null) {
                     final String url = result[0] + result[1];
 
-                    // redirect target is the node providing the sling:vanityPath
-                    // property (or its parent if the node is called jcr:content)
+                    // redirect target is the node providing the
+                    // sling:vanityPath
+                    // property (or its parent if the node is called
+                    // jcr:content)
                     final String redirect;
                     if (resource.getName().equals("jcr:content")) {
                         redirect = resource.getParent().getPath();
@@ -492,22 +486,21 @@ public class MapEntries implements Event
                     }
 
                     // whether the target is attained by a 302/FOUND or by an
-                    // internal redirect is defined by the sling:redirect property
-                    final int status = props.get("sling:redirect", false)
-                            ? props.get(JcrResourceResolver.PROP_REDIRECT_EXTERNAL_REDIRECT_STATUS, HttpServletResponse.SC_FOUND)
-                            : -1;
-
-                    final String checkPath = result[1];
-                    // 1. entry with exact match
-                    this.addEntry(entryMap, checkPath, new MapEntry(url + "$", status, false, redirect
-                            + ".html"));
-
-                    // 2. entry with match supporting selectors and extension
-                    this.addEntry(entryMap, checkPath, new MapEntry(url + "(\\..*)", status, false,
-                            redirect + "$1"));
+                    // internal redirect is defined by the sling:redirect
+                    // property
+                    final int status = props.get("sling:redirect", false) ? props.get(
+                                    PROP_REDIRECT_EXTERNAL_REDIRECT_STATUS, HttpServletResponse.SC_FOUND)
+                                    : -1;
+
+                                    final String checkPath = result[1];
+                                    // 1. entry with exact match
+                                    this.addEntry(entryMap, checkPath, new MapEntry(url + "$", status, false, redirect + ".html"));
+
+                                    // 2. entry with match supporting selectors and extension
+                                    this.addEntry(entryMap, checkPath, new MapEntry(url + "(\\..*)", status, false, redirect + "$1"));
 
-                    // 3. keep the path to return
-                    targetPaths.add(redirect);
+                                    // 3. keep the path to return
+                                    targetPaths.add(redirect);
                 }
             }
         }
@@ -516,18 +509,17 @@ public class MapEntries implements Event
 
     /**
      * Create the vanity path definition. String array containing:
-     * {protocol}/{host}[.port]
-     * {absolute path}
+     * {protocol}/{host}[.port] {absolute path}
      */
     private String[] getVanityPathDefinition(final String pVanityPath) {
         String[] result = null;
-        if ( pVanityPath != null ) {
+        if (pVanityPath != null) {
             final String info = pVanityPath.trim();
-            if ( info.length() > 0 ) {
+            if (info.length() > 0) {
                 String prefix = null;
                 String path = null;
                 // check for url
-                if ( info.indexOf(":/") > - 1 ) {
+                if (info.indexOf(":/") > -1) {
                     try {
                         final URL u = new URL(info);
                         prefix = u.getProtocol() + '/' + u.getHost() + '.' + u.getPort();
@@ -537,7 +529,7 @@ public class MapEntries implements Event
                     }
                 } else {
                     prefix = "^" + ANY_SCHEME_HOST;
-                    if ( !info.startsWith("/") ) {
+                    if (!info.startsWith("/")) {
                         path = "/" + info;
                     } else {
                         path = info;
@@ -545,22 +537,21 @@ public class MapEntries implements Event
                 }
 
                 // remove extension
-                if ( prefix != null ) {
+                if (prefix != null) {
                     final int lastSlash = path.lastIndexOf('/');
                     final int firstDot = path.indexOf('.', lastSlash + 1);
-                    if ( firstDot != -1 ) {
+                    if (firstDot != -1) {
                         path = path.substring(0, firstDot);
                         log.warn("Removing extension from vanity path {}", pVanityPath);
                     }
-                    result = new String[] {prefix, path};
+                    result = new String[] { prefix, path };
                 }
             }
         }
         return result;
     }
 
-    private void loadConfiguration(final JcrResourceResolverFactoryImpl factory,
-            final List<MapEntry> entries) {
+    private void loadConfiguration(final ResourceResolverFactoryImpl factory, final List<MapEntry> entries) {
         // virtual uris
         final Map<?, ?> virtuals = factory.getVirtualURLMap();
         if (virtuals != null) {
@@ -579,11 +570,11 @@ public class MapEntries implements Event
         // URL Mappings
         final Mapping[] mappings = factory.getMappings();
         if (mappings != null) {
-            Map<String, List<String>> map = new HashMap<String, List<String>>();
-            for (Mapping mapping : mappings) {
+            final Map<String, List<String>> map = new HashMap<String, List<String>>();
+            for (final Mapping mapping : mappings) {
                 if (mapping.mapsInbound()) {
-                    String url = mapping.getTo();
-                    String alias = mapping.getFrom();
+                    final String url = mapping.getTo();
+                    final String alias = mapping.getFrom();
                     if (url.length() > 0) {
                         List<String> aliasList = map.get(url);
                         if (aliasList == null) {
@@ -596,22 +587,20 @@ public class MapEntries implements Event
             }
 
             for (final Entry<String, List<String>> entry : map.entrySet()) {
-                entries.add(new MapEntry(ANY_SCHEME_HOST + entry.getKey(),
-                        -1, false, entry.getValue().toArray(new String[0])));
+                entries.add(new MapEntry(ANY_SCHEME_HOST + entry.getKey(), -1, false, entry.getValue().toArray(new String[0])));
             }
         }
     }
 
-    private void loadMapConfiguration(JcrResourceResolverFactoryImpl factory,
-            Map<String, MapEntry> entries) {
+    private void loadMapConfiguration(final ResourceResolverFactoryImpl factory, final Map<String, MapEntry> entries) {
         // URL Mappings
-        Mapping[] mappings = factory.getMappings();
+        final Mapping[] mappings = factory.getMappings();
         if (mappings != null) {
             for (int i = mappings.length - 1; i >= 0; i--) {
-                Mapping mapping = mappings[i];
+                final Mapping mapping = mappings[i];
                 if (mapping.mapsOutbound()) {
-                    String url = mapping.getTo();
-                    String alias = mapping.getFrom();
+                    final String url = mapping.getTo();
+                    final String alias = mapping.getFrom();
                     if (!url.equals(alias)) {
                         addMapEntry(entries, alias, url, -1);
                     }
@@ -620,33 +609,31 @@ public class MapEntries implements Event
         }
 
         // virtual uris
-        Map<?, ?> virtuals = factory.getVirtualURLMap();
+        final Map<?, ?> virtuals = factory.getVirtualURLMap();
         if (virtuals != null) {
-            for (Entry<?, ?> virtualEntry : virtuals.entrySet()) {
-                String extPath = (String) virtualEntry.getKey();
-                String intPath = (String) virtualEntry.getValue();
+            for (final Entry<?, ?> virtualEntry : virtuals.entrySet()) {
+                final String extPath = (String) virtualEntry.getKey();
+                final String intPath = (String) virtualEntry.getValue();
                 if (!extPath.equals(intPath)) {
                     // this regular expression must match the whole URL !!
-                    String path = "^" + intPath + "$";
-                    String url = extPath;
+                    final String path = "^" + intPath + "$";
+                    final String url = extPath;
                     addMapEntry(entries, path, url, -1);
                 }
             }
         }
     }
 
-    private void addMapEntry(Map<String, MapEntry> entries, String path,
-            String url, int status) {
+    private void addMapEntry(final Map<String, MapEntry> entries, final String path, final String url, final int status) {
         MapEntry entry = entries.get(path);
         if (entry == null) {
             entry = new MapEntry(path, status, false, url);
         } else {
-            String[] redir = entry.getRedirect();
-            String[] newRedir = new String[redir.length + 1];
+            final String[] redir = entry.getRedirect();
+            final String[] newRedir = new String[redir.length + 1];
             System.arraycopy(redir, 0, newRedir, 0, redir.length);
             newRedir[redir.length] = url;
-            entry = new MapEntry(entry.getPattern(), entry.getStatus(),
-                false, newRedir);
+            entry = new MapEntry(entry.getPattern(), entry.getStatus(), false, newRedir);
         }
         entries.put(path, entry);
     }
@@ -658,19 +645,16 @@ public class MapEntries implements Event
      * updating the internal structure
      */
     private static String createFilter() {
-        final String[] nodeProps = {
-            "sling:vanityPath", "sling:vanityOrder", JcrResourceResolver.PROP_REDIRECT_EXTERNAL_REDIRECT_STATUS,
-            JcrResourceResolver.PROP_REDIRECT_EXTERNAL, JcrResourceResolver.PROP_REDIRECT_INTERNAL,
-            JcrResourceResolver.PROP_REDIRECT_EXTERNAL_STATUS, JcrResourceResolver.PROP_REG_EXP
-        };
-        final String[] eventProps = {
-            "resourceAddedAttributes", "resourceChangedAttributes", "resourceRemovedAttributes"
-        };
-        StringBuilder filter = new StringBuilder();
+        final String[] nodeProps = { "sling:vanityPath", "sling:vanityOrder",
+                        PROP_REDIRECT_EXTERNAL_REDIRECT_STATUS, PROP_REDIRECT_EXTERNAL,
+                        ResourceResolverImpl.PROP_REDIRECT_INTERNAL, PROP_REDIRECT_EXTERNAL_STATUS,
+                        PROP_REG_EXP };
+        final String[] eventProps = { "resourceAddedAttributes", "resourceChangedAttributes", "resourceRemovedAttributes" };
+        final StringBuilder filter = new StringBuilder();
         filter.append("(|");
-        for (String eventProp : eventProps) {
+        for (final String eventProp : eventProps) {
             filter.append("(|");
-            for (String nodeProp : nodeProps) {
+            for (final String nodeProp : nodeProps) {
                 filter.append('(').append(eventProp).append('=').append(nodeProp).append(')');
             }
             filter.append(")");
@@ -689,7 +673,7 @@ public class MapEntries implements Event
 
         private MapEntry next;
 
-        private Iterator<MapEntry> globalListIterator;
+        private final Iterator<MapEntry> globalListIterator;
         private MapEntry nextGlobal;
 
         private Iterator<MapEntry> specialIterator;
@@ -702,7 +686,6 @@ public class MapEntries implements Event
             this.seek();
         }
 
-
         /**
          * @see java.util.Iterator#hasNext()
          */
@@ -714,7 +697,7 @@ public class MapEntries implements Event
          * @see java.util.Iterator#next()
          */
         public MapEntry next() {
-            if ( this.next == null ) {
+            if (this.next == null) {
                 throw new NoSuchElementException();
             }
             final MapEntry result = this.next;
@@ -730,28 +713,28 @@ public class MapEntries implements Event
         }
 
         private void seek() {
-            if ( this.nextGlobal == null && this.globalListIterator.hasNext() ) {
+            if (this.nextGlobal == null && this.globalListIterator.hasNext()) {
                 this.nextGlobal = this.globalListIterator.next();
             }
-            if ( this.nextSpecial == null ) {
-                if ( specialIterator != null && !specialIterator.hasNext() ) {
+            if (this.nextSpecial == null) {
+                if (specialIterator != null && !specialIterator.hasNext()) {
                     specialIterator = null;
                 }
-                while ( specialIterator == null && key != null ) {
+                while (specialIterator == null && key != null) {
                     // remove selectors and extension
                     final int lastSlashPos = key.lastIndexOf('/');
                     final int lastDotPos = key.indexOf('.', lastSlashPos);
-                    if ( lastDotPos != -1 ) {
+                    if (lastDotPos != -1) {
                         key = key.substring(0, lastDotPos);
                     }
                     final List<MapEntry> special = this.resolveMapsMap.get(key);
-                    if ( special != null ) {
+                    if (special != null) {
                         specialIterator = special.iterator();
                     }
                     // recurse to the parent
-                    if ( key.length() > 1 ) {
+                    if (key.length() > 1) {
                         final int lastSlash = key.lastIndexOf("/");
-                        if ( lastSlash == 0 ) {
+                        if (lastSlash == 0) {
                             key = null;
                         } else {
                             key = key.substring(0, lastSlash);
@@ -760,17 +743,17 @@ public class MapEntries implements Event
                         key = null;
                     }
                 }
-                if ( this.specialIterator != null && this.specialIterator.hasNext() ) {
+                if (this.specialIterator != null && this.specialIterator.hasNext()) {
                     this.nextSpecial = this.specialIterator.next();
                 }
             }
-            if ( this.nextSpecial == null ) {
+            if (this.nextSpecial == null) {
                 this.next = this.nextGlobal;
                 this.nextGlobal = null;
-            } else if ( this.nextGlobal == null ) {
+            } else if (this.nextGlobal == null) {
                 this.next = this.nextSpecial;
                 this.nextSpecial = null;
-            } else if ( this.nextGlobal.getPattern().length() >= this.nextSpecial.getPattern().length() ) {
+            } else if (this.nextGlobal.getPattern().length() >= this.nextSpecial.getPattern().length()) {
                 this.next = this.nextGlobal;
                 this.nextGlobal = null;
             } else {

Modified: sling/trunk/bundles/resourceresolver/src/main/java/org/apache/sling/resourceresolver/impl/mapping/MapEntry.java
URL: http://svn.apache.org/viewvc/sling/trunk/bundles/resourceresolver/src/main/java/org/apache/sling/resourceresolver/impl/mapping/MapEntry.java?rev=1350169&r1=1350168&r2=1350169&view=diff
==============================================================================
--- sling/trunk/bundles/resourceresolver/src/main/java/org/apache/sling/resourceresolver/impl/mapping/MapEntry.java (original)
+++ sling/trunk/bundles/resourceresolver/src/main/java/org/apache/sling/resourceresolver/impl/mapping/MapEntry.java Thu Jun 14 09:52:08 2012
@@ -16,7 +16,7 @@
  * specific language governing permissions and limitations
  * under the License.
  */
-package org.apache.sling.jcr.resource.internal.helper;
+package org.apache.sling.resourceresolver.impl.mapping;
 
 import java.net.URI;
 import java.net.URISyntaxException;
@@ -28,14 +28,14 @@ import java.util.regex.Pattern;
 
 import org.apache.sling.api.resource.Resource;
 import org.apache.sling.api.resource.ValueMap;
-import org.apache.sling.jcr.resource.internal.JcrResourceResolver;
+import org.apache.sling.resourceresolver.impl.ResourceResolverImpl;
 import org.slf4j.LoggerFactory;
 
 /**
  * The <code>MapEntry</code> class represents a mapping entry in the mapping
  * configuration tree at <code>/etc/map</code>.
  * <p>
- *
+ * 
  * @see "http://cwiki.apache.org/SLING/flexible-resource-resolution.html"
  */
 public class MapEntry implements Comparable<MapEntry> {
@@ -72,22 +72,26 @@ public class MapEntry implements Compara
     /**
      * Returns a string used for matching map entries against the given request
      * or URI parts.
-     *
-     * @param scheme The URI scheme
-     * @param host The host name
-     * @param port The port number. If this is negative, the default value used
+     * 
+     * @param scheme
+     *            The URI scheme
+     * @param host
+     *            The host name
+     * @param port
+     *            The port number. If this is negative, the default value used
      *            is 80 unless the scheme is "https" in which case the default
      *            value is 443.
-     * @param path The (absolute) path
+     * @param path
+     *            The (absolute) path
      * @return The request path string {scheme}://{host}:{port}{path}.
      */
-    public static String getURI(String scheme, String host, int port,
-            String path) {
+    public static String getURI(final String scheme, final String host, final int port,
+                    final String path) {
 
-        StringBuilder sb = new StringBuilder();
+        final StringBuilder sb = new StringBuilder();
         sb.append(scheme).append("://").append(host);
         if (port > 0 && !(port == 80 && "http".equals(scheme))
-            && !(port == 443 && "https".equals(scheme))) {
+                        && !(port == 443 && "https".equals(scheme))) {
             sb.append(':').append(port);
         }
         sb.append(path);
@@ -95,9 +99,9 @@ public class MapEntry implements Compara
         return sb.toString();
     }
 
-    public static String fixUriPath(String uriPath) {
+    public static String fixUriPath(final String uriPath) {
         for (int i = 0; i < URL_WITH_PORT_MATCH.length; i++) {
-            Matcher m = URL_WITH_PORT_MATCH[i].matcher(uriPath);
+            final Matcher m = URL_WITH_PORT_MATCH[i].matcher(uriPath);
             if (m.find()) {
                 return m.replaceAll(URL_WITH_PORT_REPLACEMENT[i]);
             }
@@ -106,14 +110,14 @@ public class MapEntry implements Compara
         return uriPath;
     }
 
-    public static URI toURI(String uriPath) {
+    public static URI toURI(final String uriPath) {
         for (int i = 0; i < PATH_TO_URL_MATCH.length; i++) {
-            Matcher m = PATH_TO_URL_MATCH[i].matcher(uriPath);
+            final Matcher m = PATH_TO_URL_MATCH[i].matcher(uriPath);
             if (m.find()) {
-                String newUriPath = m.replaceAll(PATH_TO_URL_REPLACEMENT[i]);
+                final String newUriPath = m.replaceAll(PATH_TO_URL_REPLACEMENT[i]);
                 try {
                     return new URI(newUriPath);
-                } catch (URISyntaxException use) {
+                } catch (final URISyntaxException use) {
                     // ignore, just don't return the uri as such
                 }
             }
@@ -122,24 +126,26 @@ public class MapEntry implements Compara
         return null;
     }
 
-    public static MapEntry createResolveEntry(String url, Resource resource,
-            boolean trailingSlash) {
-        ValueMap props = resource.adaptTo(ValueMap.class);
+    public static MapEntry createResolveEntry(String url, final Resource resource,
+                    final boolean trailingSlash) {
+        final ValueMap props = resource.adaptTo(ValueMap.class);
         if (props != null) {
 
             // ensure the url contains a port number (if possible)
             url = fixUriPath(url);
 
-            String redirect = props.get(
-                JcrResourceResolver.PROP_REDIRECT_EXTERNAL, String.class);
+            final String redirect = props.get(
+                            MapEntries.PROP_REDIRECT_EXTERNAL, String.class);
             if (redirect != null) {
-                int status = props.get(
-                    JcrResourceResolver.PROP_REDIRECT_EXTERNAL_STATUS, 302);
+                final int status = props
+                                .get(MapEntries.PROP_REDIRECT_EXTERNAL_STATUS,
+                                                302);
                 return new MapEntry(url, status, trailingSlash, redirect);
             }
 
-            String[] internalRedirect = props.get(
-                JcrResourceResolver.PROP_REDIRECT_INTERNAL, String[].class);
+            final String[] internalRedirect = props
+                            .get(ResourceResolverImpl.PROP_REDIRECT_INTERNAL,
+                                            String[].class);
             if (internalRedirect != null) {
                 return new MapEntry(url, -1, trailingSlash, internalRedirect);
             }
@@ -148,25 +154,27 @@ public class MapEntry implements Compara
         return null;
     }
 
-    public static List<MapEntry> createMapEntry(String url, Resource resource,
-            boolean trailingSlash) {
-        ValueMap props = resource.adaptTo(ValueMap.class);
+    public static List<MapEntry> createMapEntry(String url, final Resource resource,
+                    final boolean trailingSlash) {
+        final ValueMap props = resource.adaptTo(ValueMap.class);
         if (props != null) {
-            String redirect = props.get(
-                JcrResourceResolver.PROP_REDIRECT_EXTERNAL, String.class);
+            final String redirect = props.get(
+                            MapEntries.PROP_REDIRECT_EXTERNAL, String.class);
             if (redirect != null) {
                 // ignoring external redirects for mapping
-                LoggerFactory.getLogger(MapEntry.class).info(
-                    "createMapEntry: Configuration has external redirect to {}; not creating mapping for configuration in {}",
-                    redirect, resource.getPath());
+                LoggerFactory
+                .getLogger(MapEntry.class)
+                .info("createMapEntry: Configuration has external redirect to {}; not creating mapping for configuration in {}",
+                                redirect, resource.getPath());
                 return null;
             }
 
             // ignore potential regular expression url
             if (isRegExp(url)) {
-                LoggerFactory.getLogger(MapEntry.class).info(
-                    "createMapEntry: URL {} contains a regular expression; not creating mapping for configuration in {}",
-                    url, resource.getPath());
+                LoggerFactory
+                .getLogger(MapEntry.class)
+                .info("createMapEntry: URL {} contains a regular expression; not creating mapping for configuration in {}",
+                                url, resource.getPath());
 
                 return null;
             }
@@ -175,7 +183,7 @@ public class MapEntry implements Compara
             String endHook = "";
             if (url.endsWith("$")) {
                 endHook = "$";
-                url = url.substring(0, url.length()-1);
+                url = url.substring(0, url.length() - 1);
             }
 
             // check whether the url is for ANY_SCHEME_HOST
@@ -183,25 +191,26 @@ public class MapEntry implements Compara
                 url = url.substring(MapEntries.ANY_SCHEME_HOST.length());
             }
 
-            String[] internalRedirect = props.get(
-                JcrResourceResolver.PROP_REDIRECT_INTERNAL, String[].class);
+            final String[] internalRedirect = props
+                            .get(ResourceResolverImpl.PROP_REDIRECT_INTERNAL,
+                                            String[].class);
             if (internalRedirect != null) {
 
                 int status = -1;
-                URI extPathPrefix = toURI(url);
+                final URI extPathPrefix = toURI(url);
                 if (extPathPrefix != null) {
                     url = getURI(extPathPrefix.getScheme(),
-                        extPathPrefix.getHost(), extPathPrefix.getPort(),
-                        extPathPrefix.getPath());
+                                    extPathPrefix.getHost(), extPathPrefix.getPort(),
+                                    extPathPrefix.getPath());
                     status = 302;
                 }
 
-                List<MapEntry> prepEntries = new ArrayList<MapEntry>(
-                    internalRedirect.length);
-                for (String redir : internalRedirect) {
+                final List<MapEntry> prepEntries = new ArrayList<MapEntry>(
+                                internalRedirect.length);
+                for (final String redir : internalRedirect) {
                     if (!redir.contains("$")) {
                         prepEntries.add(new MapEntry(redir.concat(endHook),
-                            status, trailingSlash, url));
+                                        status, trailingSlash, url));
                     }
                 }
 
@@ -214,8 +223,8 @@ public class MapEntry implements Compara
         return null;
     }
 
-    public MapEntry(String url, int status, boolean trailingSlash,
-            String... redirect) {
+    public MapEntry(String url, final int status, final boolean trailingSlash,
+                    final String... redirect) {
 
         // ensure trailing slashes on redirects if the url
         // ends with a trailing slash
@@ -237,11 +246,11 @@ public class MapEntry implements Compara
     }
 
     // Returns the replacement or null if the value does not match
-    public String[] replace(String value) {
-        Matcher m = urlPattern.matcher(value);
+    public String[] replace(final String value) {
+        final Matcher m = urlPattern.matcher(value);
         if (m.find()) {
-            String[] redirects = getRedirect();
-            String[] results = new String[redirects.length];
+            final String[] redirects = getRedirect();
+            final String[] results = new String[redirects.length];
             for (int i = 0; i < redirects.length; i++) {
                 results[i] = m.replaceFirst(redirects[i]);
             }
@@ -269,13 +278,13 @@ public class MapEntry implements Compara
 
     // ---------- Comparable
 
-    public int compareTo(MapEntry m) {
+    public int compareTo(final MapEntry m) {
         if (this == m) {
             return 0;
         }
 
-        int tlen = urlPattern.toString().length();
-        int mlen = m.urlPattern.toString().length();
+        final int tlen = urlPattern.toString().length();
+        final int mlen = m.urlPattern.toString().length();
         if (tlen < mlen) {
             return 1;
         } else if (tlen > mlen) {
@@ -291,7 +300,7 @@ public class MapEntry implements Compara
 
     @Override
     public String toString() {
-        StringBuilder buf = new StringBuilder();
+        final StringBuilder buf = new StringBuilder();
         buf.append("MapEntry: match:").append(urlPattern);
 
         buf.append(", replacement:");
@@ -309,17 +318,18 @@ public class MapEntry implements Compara
         return buf.toString();
     }
 
-    //---------- helper
+    // ---------- helper
 
     /**
      * Returns <code>true</code> if the string contains unescaped regular
      * expression special characters '+', '*', '?', '|', '(', '), '[', and ']'
+     * 
      * @param string
      * @return
      */
     private static boolean isRegExp(final String string) {
-        for (int i=0; i < string.length(); i++) {
-            char c = string.charAt(i);
+        for (int i = 0; i < string.length(); i++) {
+            final char c = string.charAt(i);
             if (c == '\\') {
                 i++; // just skip
             } else if ("+*?|()[]".indexOf(c) >= 0) {

Modified: sling/trunk/bundles/resourceresolver/src/main/java/org/apache/sling/resourceresolver/impl/mapping/Mapping.java
URL: http://svn.apache.org/viewvc/sling/trunk/bundles/resourceresolver/src/main/java/org/apache/sling/resourceresolver/impl/mapping/Mapping.java?rev=1350169&r1=1350168&r2=1350169&view=diff
==============================================================================
--- sling/trunk/bundles/resourceresolver/src/main/java/org/apache/sling/resourceresolver/impl/mapping/Mapping.java (original)
+++ sling/trunk/bundles/resourceresolver/src/main/java/org/apache/sling/resourceresolver/impl/mapping/Mapping.java Thu Jun 14 09:52:08 2012
@@ -16,15 +16,14 @@
  * specific language governing permissions and limitations
  * under the License.
  */
-package org.apache.sling.jcr.resource.internal.helper;
+package org.apache.sling.resourceresolver.impl.mapping;
 
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
 /**
- * The <code>Mapping</code> class conveys the mapping configuration used by
- * the
- * {@link org.apache.sling.jcr.resource.internal.JcrResourceResolverFactoryImpl}.
+ * The <code>Mapping</code> class conveys the mapping configuration used by the
+ * {@link org.apache.sling.resourceresolver.impl.ResourceResolverFactoryImpl}.
  */
 public class Mapping {
 
@@ -66,10 +65,11 @@ public class Mapping {
 
     // Regular expression to split mapping configuration strings into three
     // groups:
-    //   1 - external path prefix
-    //   2 - direction (Outbound (>), Bidirectional (:), Inbound (>))
-    //   3 - internap path prefix
-    private static final Pattern CONFIG_SPLITTER = Pattern.compile("(.+)([:<>])(.+)");
+    // 1 - external path prefix
+    // 2 - direction (Outbound (>), Bidirectional (:), Inbound (>))
+    // 3 - internap path prefix
+    private static final Pattern CONFIG_SPLITTER = Pattern
+            .compile("(.+)([:<>])(.+)");
 
     /** the 'from' (inside, repository) mapping */
     private final String from;
@@ -96,51 +96,52 @@ public class Mapping {
         this.fromLength = this.from.length();
         this.toLength = this.to.length();
 
-        this.direction = ">".equals(parts[1])
-                ? Mapping.INBOUND
-                : ("<".equals(parts[1]) ? Mapping.OUTBOUND : Mapping.BOTH);
+        this.direction = ">".equals(parts[1]) ? Mapping.INBOUND : ("<"
+                .equals(parts[1]) ? Mapping.OUTBOUND : Mapping.BOTH);
     }
 
     @Override
     public String toString() {
-        return "Mapping (from=" + from + ", to=" + to + ", direction=" + direction
-            + ", lengths=" + fromLength + "/" + toLength;
+        return "Mapping (from=" + from + ", to=" + to + ", direction="
+                + direction + ", lengths=" + fromLength + "/" + toLength;
     }
 
     /**
-     * Replaces the prefix <em>to</em> by the new prefix <em>from</em>, if
-     * and only if <code>uriPath</code> starts with the <em>to</em> prefix.
-     * If <code>uriPath</code> does not start with the <em>to</em> prefix,
-     * or if this mapping is not defined as a 'inward' mapping,
-     * <code>null</code> is returned.
-     *
-     * @param uriPath The URI path for which to replace the <em>to</em> prefix
-     *            by the <em>from</em> prefix.
+     * Replaces the prefix <em>to</em> by the new prefix <em>from</em>, if and
+     * only if <code>uriPath</code> starts with the <em>to</em> prefix. If
+     * <code>uriPath</code> does not start with the <em>to</em> prefix, or if
+     * this mapping is not defined as a 'inward' mapping, <code>null</code> is
+     * returned.
+     * 
+     * @param uriPath
+     *            The URI path for which to replace the <em>to</em> prefix by
+     *            the <em>from</em> prefix.
      * @return The string after replacement or <code>null</code> if the
-     *         <code>uriPath</code> does not start with the <em>to</em>
-     *         prefix, or {@link #mapsInbound()} returns <code>false</code>.
+     *         <code>uriPath</code> does not start with the <em>to</em> prefix,
+     *         or {@link #mapsInbound()} returns <code>false</code>.
      */
     public String mapUri(String uriPath) {
         return (this.mapsInbound() && uriPath.startsWith(this.to)) ? this.from
-            + uriPath.substring(this.toLength) : null;
+                + uriPath.substring(this.toLength) : null;
     }
 
     /**
-     * Replaces the prefix <em>from</em> by the new prefix <em>to</em>, if
-     * and only if <code>handle</code> starts with the <em>from</em> prefix.
-     * If <code>uriPath</code> does not start with the <em>from</em> prefix,
-     * or if this mapping is not defined as a 'outward' mapping,
-     * <code>null</code> is returned.
-     *
-     * @param handle The URI path for which to replace the <em>from</em>
-     *            prefix by the <em>to</em> prefix.
+     * Replaces the prefix <em>from</em> by the new prefix <em>to</em>, if and
+     * only if <code>handle</code> starts with the <em>from</em> prefix. If
+     * <code>uriPath</code> does not start with the <em>from</em> prefix, or if
+     * this mapping is not defined as a 'outward' mapping, <code>null</code> is
+     * returned.
+     * 
+     * @param handle
+     *            The URI path for which to replace the <em>from</em> prefix by
+     *            the <em>to</em> prefix.
      * @return The string after replacement or <code>null</code> if the
-     *         <code>handle</code> does not start with the <em>from</em>
-     *         prefix, or {@link #mapsOutbound()} returns <code>false</code>.
+     *         <code>handle</code> does not start with the <em>from</em> prefix,
+     *         or {@link #mapsOutbound()} returns <code>false</code>.
      */
     public String mapHandle(String handle) {
         return (this.mapsOutbound() && handle.startsWith(this.from)) ? this.to
-            + handle.substring(this.fromLength) : null;
+                + handle.substring(this.fromLength) : null;
     }
 
     // TODO: temporary
@@ -155,9 +156,9 @@ public class Mapping {
 
     /**
      * Checks, if this mapping is defined for inbound mapping.
-     *
-     * @return <code>true</code> if this mapping is defined for inbound
-     *         mapping; <code>false</code> otherwise
+     * 
+     * @return <code>true</code> if this mapping is defined for inbound mapping;
+     *         <code>false</code> otherwise
      */
     public boolean mapsInbound() {
         return (this.direction & Mapping.INBOUND) > 0;
@@ -165,7 +166,7 @@ public class Mapping {
 
     /**
      * Checks, if this mapping is defined for outbound mapping.
-     *
+     * 
      * @return <code>true</code> if this mapping is defined for outbound
      *         mapping; <code>false</code> otherwise
      */
@@ -190,15 +191,15 @@ public class Mapping {
         Matcher mapMatch = CONFIG_SPLITTER.matcher(map);
         if (mapMatch.matches()) {
             return new String[] { mapMatch.group(1), mapMatch.group(2),
-                mapMatch.group(3) };
+                    mapMatch.group(3) };
         }
 
         // backwards compatibility using "-" instead of ":"
         int dash = map.indexOf('-');
         if (dash > 0) {
             return new String[] { map.substring(0, dash),
-                map.substring(dash, dash + 1),
-                map.substring(dash + 1, map.length()) };
+                    map.substring(dash, dash + 1),
+                    map.substring(dash + 1, map.length()) };
         }
 
         return new String[] { map, "-", map };

Modified: sling/trunk/bundles/resourceresolver/src/main/java/org/apache/sling/resourceresolver/impl/tree/ProviderHandler.java
URL: http://svn.apache.org/viewvc/sling/trunk/bundles/resourceresolver/src/main/java/org/apache/sling/resourceresolver/impl/tree/ProviderHandler.java?rev=1350169&r1=1350168&r2=1350169&view=diff
==============================================================================
--- sling/trunk/bundles/resourceresolver/src/main/java/org/apache/sling/resourceresolver/impl/tree/ProviderHandler.java (original)
+++ sling/trunk/bundles/resourceresolver/src/main/java/org/apache/sling/resourceresolver/impl/tree/ProviderHandler.java Thu Jun 14 09:52:08 2012
@@ -15,93 +15,143 @@
  * KIND, either express or implied. See the License for the
  * specific language governing permissions and limitations under the License.
  */
-package org.apache.sling.jcr.resource.internal.helper;
+package org.apache.sling.resourceresolver.impl.tree;
 
+import java.util.ArrayList;
+import java.util.Collections;
 import java.util.Iterator;
-
-import javax.servlet.http.HttpServletRequest;
+import java.util.List;
+import java.util.Map;
 
 import org.apache.sling.api.resource.Resource;
 import org.apache.sling.api.resource.ResourceProvider;
 import org.apache.sling.api.resource.ResourceResolver;
+import org.apache.sling.commons.osgi.PropertiesUtil;
+import org.apache.sling.resourceresolver.impl.helper.ResourceResolverContext;
+import org.osgi.framework.Constants;
 
 /**
- *
+ * The provider handler is the common base class for the
+ * {@link ResourceProviderHandler} and the
+ * {@link ResourceProviderFactoryHandler}.
  */
-public class WrappedResourceProvider  implements ResourceProvider {
+public abstract class ProviderHandler implements Comparable<ProviderHandler> {
 
-    private ResourceProvider resourceProvider;
-    private Comparable<?> serviceReference;
+    /** Service properties. */
+    private final Map<String, Object> properties;
 
-    /**
-     *
-     */
-    public WrappedResourceProvider(ResourceProvider resourceProvider, Comparable<?> serviceReference) {
-        this.resourceProvider = resourceProvider;
-        this.serviceReference = serviceReference;
+    /** Unique service id */
+    private final Long serviceId;
+
+    /** Configured roots. */
+    private final String[] roots;
+
+    /**
+     * Create a new handler
+     */
+    public ProviderHandler(final Map<String, Object> properties) {
+        this.properties = properties;
+        this.serviceId = (Long) properties.get(Constants.SERVICE_ID);
+        // calculate roots
+        final List<String> configuredRoots = new ArrayList<String>();
+        final String[] paths = PropertiesUtil.toStringArray(properties.get(ResourceProvider.ROOTS));
+        if ( paths != null) {
+            for(final String r : paths) {
+                if (r != null) {
+                    String path = r.trim();
+                    // cut off trailing slash
+                    if (path.endsWith("/") && path.length() > 1) {
+                        path = path.substring(0, path.length() - 1);
+                    }
+                    if ( path.length() > 0 && !configuredRoots.contains(path)) {
+                        configuredRoots.add(path);
+                    }
+                }
+            }
+        }
+        if ( configuredRoots.size() == 0 ) {
+            this.roots = null;
+        } else {
+            Collections.sort(configuredRoots);
+            this.roots = configuredRoots.toArray(new String[configuredRoots.size()]);
+        }
     }
 
     /**
-     * {@inheritDoc}
-     * @see org.apache.sling.api.resource.ResourceProvider#getResource(org.apache.sling.api.resource.ResourceResolver, java.lang.String)
+     * Return the service properties.
      */
-    public Resource getResource(ResourceResolver arg0, String arg1) {
-        return resourceProvider.getResource(arg0, arg1);
+    public Map<String, Object> getProperties() {
+        return this.properties;
     }
 
     /**
-     * {@inheritDoc}
-     * @see org.apache.sling.api.resource.ResourceProvider#getResource(org.apache.sling.api.resource.ResourceResolver, javax.servlet.http.HttpServletRequest, java.lang.String)
+     * Return the service id.
      */
-    public Resource getResource(ResourceResolver arg0, HttpServletRequest arg1, String arg2) {
-        return resourceProvider.getResource(arg0, arg1, arg2);
+    public Long getServiceId() {
+        return this.serviceId;
     }
 
     /**
-     * {@inheritDoc}
-     * @see org.apache.sling.api.resource.ResourceProvider#listChildren(org.apache.sling.api.resource.Resource)
+     * Return a sorted array of roots for this provider. If no roots are configured,
+     * this will return <code>null</code>
+     * @return The array of roots or <code>null</code>
      */
-    public Iterator<Resource> listChildren(Resource arg0) {
-        return resourceProvider.listChildren(arg0);
+    public String[] getRoots() {
+        return this.roots;
     }
 
     /**
-     *
+     * @see java.lang.Comparable#compareTo(java.lang.Object)
      */
-    public Comparable<?> getComparable() {
-        return serviceReference;
+    public int compareTo(final ProviderHandler other) {
+        if (this.serviceId.equals(other.serviceId)) {
+            return 0; // same service
+        }
+
+        Object rankObj = this.getProperties().get(Constants.SERVICE_RANKING);
+        Object otherRankObj = other.getProperties().get(Constants.SERVICE_RANKING);
+
+        // If no rank, then spec says it defaults to zero.
+        rankObj = (rankObj == null) ? new Integer(0) : rankObj;
+        otherRankObj = (otherRankObj == null) ? new Integer(0) : otherRankObj;
+
+        // If rank is not Integer, then spec says it defaults to zero.
+        Integer rank = (rankObj instanceof Integer)
+            ? (Integer) rankObj : new Integer(0);
+        Integer otherRank = (otherRankObj instanceof Integer)
+            ? (Integer) otherRankObj : new Integer(0);
+
+        // Sort by rank in ascending order.
+        if (rank.compareTo(otherRank) < 0) {
+            return -1; // lower rank
+        } else if (rank.compareTo(otherRank) > 0) {
+            return 1; // higher rank
+        }
+
+        // If ranks are equal, then sort by service id in descending order.
+        return (this.serviceId.compareTo(other.serviceId) < 0) ? 1 : -1;
     }
 
     /**
-     * {@inheritDoc}
-     * @see java.lang.Object#hashCode()
+     * @see ResourceProvider#getResource(ResourceResolver, String)
      */
-    @Override
-    public int hashCode() {
-        return resourceProvider.hashCode();
-    }
+    public abstract Resource getResource(final ResourceResolverContext ctx, final ResourceResolver resourceResolver, final String path);
 
     /**
-     * {@inheritDoc}
-     * @see java.lang.Object#equals(java.lang.Object)
+     * @see ResourceProvider#listChildren(Resource)
      */
-    @Override
-    public boolean equals(Object obj) {
-        if ( obj instanceof WrappedResourceProvider ) {
-            return resourceProvider.equals(((WrappedResourceProvider) obj).resourceProvider);
-        } else if ( obj instanceof ResourceProvider) {
-            return resourceProvider.equals(obj);
-        }
-        return super.equals(obj);
-    }
+    public abstract Iterator<Resource> listChildren(final ResourceResolverContext ctx, final Resource parent);
 
     /**
-     * {@inheritDoc}
-     *
-     * @see java.lang.Object#toString()
+     * Return a name of the resource provider/factory.
      */
-    @Override
-    public String toString() {
-        return resourceProvider.toString();
+    public String getName() {
+        final StringBuilder snBuilder = new StringBuilder(64);
+        snBuilder.append('{');
+        snBuilder.append(this.toString());
+        snBuilder.append('/');
+        snBuilder.append(this.serviceId.toString());
+        snBuilder.append('}');
+        return snBuilder.toString();
     }
 }



Mime
View raw message