You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@wink.apache.org by nf...@apache.org on 2009/07/15 08:24:40 UTC

svn commit: r794149 - in /incubator/wink/trunk: wink-common/src/main/java/org/apache/wink/common/internal/lifecycle/ wink-common/src/main/java/org/apache/wink/common/internal/registry/metadata/ wink-common/src/test/java/org/apache/wink/common/internal/...

Author: nfischer
Date: Wed Jul 15 06:24:39 2009
New Revision: 794149

URL: http://svn.apache.org/viewvc?rev=794149&view=rev
Log:
Fix for Singletons should be injected [WINK-83]

Added:
    incubator/wink/trunk/wink-common/src/main/java/org/apache/wink/common/internal/lifecycle/LifecycleManagerUtils.java
    incubator/wink/trunk/wink-common/src/main/java/org/apache/wink/common/internal/lifecycle/PrototypeObjectFactory.java
      - copied, changed from r793268, incubator/wink/trunk/wink-common/src/main/java/org/apache/wink/common/internal/lifecycle/ClassMetadataPrototypeOF.java
Removed:
    incubator/wink/trunk/wink-common/src/main/java/org/apache/wink/common/internal/lifecycle/ClassMetadataPrototypeOF.java
Modified:
    incubator/wink/trunk/wink-common/src/main/java/org/apache/wink/common/internal/lifecycle/CreationUtils.java
    incubator/wink/trunk/wink-common/src/main/java/org/apache/wink/common/internal/lifecycle/DefaultLifecycleManager.java
    incubator/wink/trunk/wink-common/src/main/java/org/apache/wink/common/internal/lifecycle/ScopeLifecycleManager.java
    incubator/wink/trunk/wink-common/src/main/java/org/apache/wink/common/internal/registry/metadata/AbstractMetadataCollector.java
    incubator/wink/trunk/wink-common/src/test/java/org/apache/wink/common/internal/lifecycle/DefaultOFFactoryTest.java
    incubator/wink/trunk/wink-common/src/test/java/org/apache/wink/common/internal/lifecycle/OFFactoryTest.java
    incubator/wink/trunk/wink-common/src/test/java/org/apache/wink/common/internal/providers/ProvidersContextResolverTest.java
    incubator/wink/trunk/wink-server/src/main/java/org/apache/wink/server/internal/handlers/FindResourceMethodHandler.java
    incubator/wink/trunk/wink-server/src/main/java/org/apache/wink/server/internal/registry/ResourceRecordFactory.java
    incubator/wink/trunk/wink-server/src/main/java/org/apache/wink/server/internal/registry/ResourceRegistry.java
    incubator/wink/trunk/wink-server/src/test/java/org/apache/wink/server/internal/registry/FindResourceMethodTest.java
    incubator/wink/trunk/wink-server/src/test/java/org/apache/wink/server/internal/registry/ResourceRecordFactoryTest.java

Modified: incubator/wink/trunk/wink-common/src/main/java/org/apache/wink/common/internal/lifecycle/CreationUtils.java
URL: http://svn.apache.org/viewvc/incubator/wink/trunk/wink-common/src/main/java/org/apache/wink/common/internal/lifecycle/CreationUtils.java?rev=794149&r1=794148&r2=794149&view=diff
==============================================================================
--- incubator/wink/trunk/wink-common/src/main/java/org/apache/wink/common/internal/lifecycle/CreationUtils.java (original)
+++ incubator/wink/trunk/wink-common/src/main/java/org/apache/wink/common/internal/lifecycle/CreationUtils.java Wed Jul 15 06:24:39 2009
@@ -37,8 +37,6 @@
 import org.apache.wink.common.internal.registry.InjectableFactory;
 import org.apache.wink.common.internal.registry.metadata.ClassMetadata;
 import org.apache.wink.common.internal.registry.metadata.ConstructorMetadata;
-import org.apache.wink.common.internal.registry.metadata.ProviderMetadataCollector;
-import org.apache.wink.common.internal.registry.metadata.ResourceMetadataCollector;
 import org.apache.wink.common.internal.runtime.RuntimeContext;
 
 public class CreationUtils {
@@ -126,21 +124,4 @@
             }
         });
     }
-
-    @SuppressWarnings("unchecked")
-    static <T> T createProvider(Class<T> cls, RuntimeContext context) {
-        T provider = (T) createObject(ProviderMetadataCollector.collectMetadata(cls), context);
-        return provider;
-    }
-
-    @SuppressWarnings("unchecked")
-    static <T> T createResource(Class<T> cls, RuntimeContext context) {
-        T resource = (T) createObject(ResourceMetadataCollector.collectMetadata(cls), context);
-        return resource;
-    }
-
-    static <T> T createProvider(Class<T> cls) {
-        return createProvider(cls, null);
-    }
-
 }

Modified: incubator/wink/trunk/wink-common/src/main/java/org/apache/wink/common/internal/lifecycle/DefaultLifecycleManager.java
URL: http://svn.apache.org/viewvc/incubator/wink/trunk/wink-common/src/main/java/org/apache/wink/common/internal/lifecycle/DefaultLifecycleManager.java?rev=794149&r1=794148&r2=794149&view=diff
==============================================================================
--- incubator/wink/trunk/wink-common/src/main/java/org/apache/wink/common/internal/lifecycle/DefaultLifecycleManager.java (original)
+++ incubator/wink/trunk/wink-common/src/main/java/org/apache/wink/common/internal/lifecycle/DefaultLifecycleManager.java Wed Jul 15 06:24:39 2009
@@ -44,7 +44,7 @@
  * 
  * @param <T>
  * @see SingletonObjectFactory
- * @see ClassMetadataPrototypeOF
+ * @see PrototypeObjectFactory
  * @see SimplePrototypeOF
  */
 class DefaultLifecycleManager<T> implements LifecycleManager<T> {
@@ -61,7 +61,7 @@
 
         logger.debug("Creating a {} for {}", SingletonObjectFactory.class, object);
 
-        return new SingletonObjectFactory<T>(object);
+        return LifecycleManagerUtils.createSingletonObjectFactory(object);
     }
 
     public ObjectFactory<T> createObjectFactory(final Class<T> cls) {
@@ -73,21 +73,21 @@
         if (ResourceMetadataCollector.isDynamicResource(cls)) {
             // default factory cannot create instance of DynamicResource
             throw new IllegalArgumentException(String.format(
-                "Cannot create factory for a DynamicResource: %s", String.valueOf(cls)));
+                "Cannot create default factory for DynamicResource: %s", String.valueOf(cls)));
         }
 
         if (ProviderMetadataCollector.isProvider(cls)) {
             // by default providers are singletons
-            return new SingletonObjectFactory<T>(CreationUtils.createProvider(cls));
+            return LifecycleManagerUtils.createSingletonObjectFactory(cls);
         }
 
         if (ResourceMetadataCollector.isStaticResource(cls)) {
             // by default resources are prototypes (created per request)
-            return new ClassMetadataPrototypeOF<T>(ResourceMetadataCollector.collectMetadata(cls));
+            return LifecycleManagerUtils.createPrototypeObjectFactory(cls);
         }
 
         // unknown object, should never reach this code
-        throw new IllegalArgumentException(String.format("Cannot create factory for a class: %s",
+        throw new IllegalArgumentException(String.format("Cannot create default factory for class: %s",
             String.valueOf(cls)));
     }
 

Added: incubator/wink/trunk/wink-common/src/main/java/org/apache/wink/common/internal/lifecycle/LifecycleManagerUtils.java
URL: http://svn.apache.org/viewvc/incubator/wink/trunk/wink-common/src/main/java/org/apache/wink/common/internal/lifecycle/LifecycleManagerUtils.java?rev=794149&view=auto
==============================================================================
--- incubator/wink/trunk/wink-common/src/main/java/org/apache/wink/common/internal/lifecycle/LifecycleManagerUtils.java (added)
+++ incubator/wink/trunk/wink-common/src/main/java/org/apache/wink/common/internal/lifecycle/LifecycleManagerUtils.java Wed Jul 15 06:24:39 2009
@@ -0,0 +1,83 @@
+/*******************************************************************************
+ * 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.wink.common.internal.lifecycle;
+
+import java.io.IOException;
+import java.security.PrivilegedActionException;
+
+import org.apache.wink.common.internal.registry.metadata.ClassMetadata;
+import org.apache.wink.common.internal.registry.metadata.ProviderMetadataCollector;
+import org.apache.wink.common.internal.registry.metadata.ResourceMetadataCollector;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class LifecycleManagerUtils {
+
+    private static Logger logger = LoggerFactory.getLogger(LifecycleManagerUtils.class);
+
+    @SuppressWarnings("unchecked")
+    public static <T> ObjectFactory<T> createSingletonObjectFactory(T object) {
+        Class<T> cls = (Class<T>)object.getClass();
+        ClassMetadata classMetadata = collectClassMetadata(cls, false);
+        try {
+            CreationUtils.injectFields(object, classMetadata, null);
+            return new SingletonObjectFactory<T>(object);
+        } catch (IOException e) {
+            logger.error("Failed to inject fields of singleton {}", cls);
+            throw new ObjectCreationException(e);
+        } catch (PrivilegedActionException e) {
+            logger.error("Failed to inject fields of singleton {}", cls);
+            throw new ObjectCreationException(e);
+        }
+    }
+
+    @SuppressWarnings("unchecked")
+    public static <T> ObjectFactory<T> createSingletonObjectFactory(final Class<T> cls) {
+        ClassMetadata classMetadata = collectClassMetadata(cls, true);
+        T object = (T)CreationUtils.createObject(classMetadata, null);
+        return new SingletonObjectFactory<T>(object);
+    }
+
+    public static <T> ObjectFactory<T> createPrototypeObjectFactory(final Class<T> cls) {
+        ClassMetadata classMetadata = collectClassMetadata(cls, true);
+        return new PrototypeObjectFactory<T>(classMetadata);
+    }
+
+    private static <T> ClassMetadata collectClassMetadata(final Class<T> cls,
+            boolean validateConstructor) {
+        ClassMetadata classMetadata = null;
+        if (ProviderMetadataCollector.isProvider(cls)) {
+            classMetadata = ProviderMetadataCollector.collectMetadata(cls);
+        } else if (ResourceMetadataCollector.isResource(cls)) {
+            classMetadata = ResourceMetadataCollector.collectMetadata(cls);
+        } else {
+            throw new IllegalArgumentException("Cannot create factory for class " + cls);
+        }
+
+        // validate that there is a valid constructor if needed
+        if (validateConstructor && classMetadata.getConstructor().getConstructor() == null) {
+            throw new IllegalStateException("No valid constructor found for "
+                    + cls.getCanonicalName());
+        }
+        return classMetadata;
+    }
+
+}

Copied: incubator/wink/trunk/wink-common/src/main/java/org/apache/wink/common/internal/lifecycle/PrototypeObjectFactory.java (from r793268, incubator/wink/trunk/wink-common/src/main/java/org/apache/wink/common/internal/lifecycle/ClassMetadataPrototypeOF.java)
URL: http://svn.apache.org/viewvc/incubator/wink/trunk/wink-common/src/main/java/org/apache/wink/common/internal/lifecycle/PrototypeObjectFactory.java?p2=incubator/wink/trunk/wink-common/src/main/java/org/apache/wink/common/internal/lifecycle/PrototypeObjectFactory.java&p1=incubator/wink/trunk/wink-common/src/main/java/org/apache/wink/common/internal/lifecycle/ClassMetadataPrototypeOF.java&r1=793268&r2=794149&rev=794149&view=diff
==============================================================================
--- incubator/wink/trunk/wink-common/src/main/java/org/apache/wink/common/internal/lifecycle/ClassMetadataPrototypeOF.java (original)
+++ incubator/wink/trunk/wink-common/src/main/java/org/apache/wink/common/internal/lifecycle/PrototypeObjectFactory.java Wed Jul 15 06:24:39 2009
@@ -28,11 +28,11 @@
  * 
  * @param <T>
  */
-class ClassMetadataPrototypeOF<T> implements ObjectFactory<T> {
+class PrototypeObjectFactory<T> implements ObjectFactory<T> {
 
     private final ClassMetadata metadata;
 
-    public ClassMetadataPrototypeOF(ClassMetadata metadata) {
+    public PrototypeObjectFactory(ClassMetadata metadata) {
         this.metadata = metadata;
         if (metadata == null) {
             throw new NullPointerException("metadata");

Modified: incubator/wink/trunk/wink-common/src/main/java/org/apache/wink/common/internal/lifecycle/ScopeLifecycleManager.java
URL: http://svn.apache.org/viewvc/incubator/wink/trunk/wink-common/src/main/java/org/apache/wink/common/internal/lifecycle/ScopeLifecycleManager.java?rev=794149&r1=794148&r2=794149&view=diff
==============================================================================
--- incubator/wink/trunk/wink-common/src/main/java/org/apache/wink/common/internal/lifecycle/ScopeLifecycleManager.java (original)
+++ incubator/wink/trunk/wink-common/src/main/java/org/apache/wink/common/internal/lifecycle/ScopeLifecycleManager.java Wed Jul 15 06:24:39 2009
@@ -22,8 +22,6 @@
 
 import org.apache.wink.common.annotations.Scope;
 import org.apache.wink.common.annotations.Scope.ScopeType;
-import org.apache.wink.common.internal.registry.metadata.ProviderMetadataCollector;
-import org.apache.wink.common.internal.registry.metadata.ResourceMetadataCollector;
 
 /**
  * Implements a LifecycleManager that creates objects based on the Scope annotation.
@@ -44,12 +42,11 @@
         Scope scope = cls.getAnnotation(Scope.class);
 
         if (scope != null) {
-
             if (scope.value() == ScopeType.SINGLETON) {
-                return new SingletonObjectFactory<T>(object);
+                return LifecycleManagerUtils.createSingletonObjectFactory(object);
             } else if (scope.value() == ScopeType.PROTOTYPE) {
                 // It's a prototype
-                return createPrototype(cls);
+                return LifecycleManagerUtils.createPrototypeObjectFactory(cls);
             }
         }
         // has no Scope annotation, do nothing
@@ -65,35 +62,14 @@
         Scope scope = cls.getAnnotation(Scope.class);
         if (scope != null) {
             if (scope.value() == ScopeType.SINGLETON) {
-                T object;
-                if (ProviderMetadataCollector.isProvider(cls)) {
-                    object = CreationUtils.createProvider(cls, null);
-                } else if (ResourceMetadataCollector.isStaticResource(cls)) {
-                    object = CreationUtils.createResource(cls, null);
-                } else {
-                    // unknown object, should never reach this code
-                    throw new IllegalArgumentException(String.format(
-                        "Cannot create factory for a class: %s", String.valueOf(cls)));
-                }
-                return new SingletonObjectFactory<T>(object);
+                return LifecycleManagerUtils.createSingletonObjectFactory(cls);
             } else if (scope.value() == ScopeType.PROTOTYPE) {
-                return createPrototype(cls);
+                return LifecycleManagerUtils.createPrototypeObjectFactory(cls);
             }
         }
         // has no Scope annotation, do nothing
         return null;
     }
 
-    private ObjectFactory<T> createPrototype(final Class<T> cls) {
-        if (ResourceMetadataCollector.isStaticResource(cls)) {
-            return new ClassMetadataPrototypeOF<T>(ResourceMetadataCollector.collectMetadata(cls));
-        }
 
-        if (ProviderMetadataCollector.isProvider(cls)) {
-            return new ClassMetadataPrototypeOF<T>(ProviderMetadataCollector.collectMetadata(cls));
-        }
-        // unknown object, should never reach this code
-        throw new IllegalArgumentException(String.format("Cannot create factory for a class: %s",
-            String.valueOf(cls)));
-    }
 }

Modified: incubator/wink/trunk/wink-common/src/main/java/org/apache/wink/common/internal/registry/metadata/AbstractMetadataCollector.java
URL: http://svn.apache.org/viewvc/incubator/wink/trunk/wink-common/src/main/java/org/apache/wink/common/internal/registry/metadata/AbstractMetadataCollector.java?rev=794149&r1=794148&r2=794149&view=diff
==============================================================================
--- incubator/wink/trunk/wink-common/src/main/java/org/apache/wink/common/internal/registry/metadata/AbstractMetadataCollector.java (original)
+++ incubator/wink/trunk/wink-common/src/main/java/org/apache/wink/common/internal/registry/metadata/AbstractMetadataCollector.java Wed Jul 15 06:24:39 2009
@@ -151,12 +151,6 @@
             }
         }
 
-        // error if we haven't found a valid constructor 
-        if (constructorMetadata.getConstructor() == null) {
-            throw new IllegalStateException("No valid constrcutor found for resource "
-                + metadata.getResourceClass().getCanonicalName());
-        }
-
         metadata.setConstructor(constructorMetadata);
     }
 

Modified: incubator/wink/trunk/wink-common/src/test/java/org/apache/wink/common/internal/lifecycle/DefaultOFFactoryTest.java
URL: http://svn.apache.org/viewvc/incubator/wink/trunk/wink-common/src/test/java/org/apache/wink/common/internal/lifecycle/DefaultOFFactoryTest.java?rev=794149&r1=794148&r2=794149&view=diff
==============================================================================
--- incubator/wink/trunk/wink-common/src/test/java/org/apache/wink/common/internal/lifecycle/DefaultOFFactoryTest.java (original)
+++ incubator/wink/trunk/wink-common/src/test/java/org/apache/wink/common/internal/lifecycle/DefaultOFFactoryTest.java Wed Jul 15 06:24:39 2009
@@ -61,14 +61,18 @@
     @SuppressWarnings("unchecked")
     public void testDummy() {
         DefaultLifecycleManager defaultOFFactory = new DefaultLifecycleManager();
-        assertEquals(SingletonObjectFactory.class,
-            defaultOFFactory.createObjectFactory(new Dummy()).getClass());
         
         try {
+            defaultOFFactory.createObjectFactory(new Dummy());
+            fail("IllegalArgumentException should be thrown.");
+        } catch (IllegalArgumentException e) {
+        }
+
+        try {
             defaultOFFactory.createObjectFactory(Dummy.class);
+            fail("IllegalArgumentException should be thrown.");
         } catch (IllegalArgumentException e) {
-            return;
         }
-        fail("IllegalArgumentException should be thrown.");
+        
     }
 }

Modified: incubator/wink/trunk/wink-common/src/test/java/org/apache/wink/common/internal/lifecycle/OFFactoryTest.java
URL: http://svn.apache.org/viewvc/incubator/wink/trunk/wink-common/src/test/java/org/apache/wink/common/internal/lifecycle/OFFactoryTest.java?rev=794149&r1=794148&r2=794149&view=diff
==============================================================================
--- incubator/wink/trunk/wink-common/src/test/java/org/apache/wink/common/internal/lifecycle/OFFactoryTest.java (original)
+++ incubator/wink/trunk/wink-common/src/test/java/org/apache/wink/common/internal/lifecycle/OFFactoryTest.java Wed Jul 15 06:24:39 2009
@@ -24,7 +24,7 @@
 
 import org.apache.wink.common.annotations.Scope;
 import org.apache.wink.common.annotations.Scope.ScopeType;
-import org.apache.wink.common.internal.lifecycle.ClassMetadataPrototypeOF;
+import org.apache.wink.common.internal.lifecycle.PrototypeObjectFactory;
 import org.apache.wink.common.internal.lifecycle.LifecycleManagersRegistry;
 import org.apache.wink.common.internal.lifecycle.ScopeLifecycleManager;
 import org.apache.wink.common.internal.lifecycle.SingletonObjectFactory;
@@ -89,11 +89,11 @@
             new ProviderScopeableSingleton()).getClass());
 
         // by default resources are prototypes, when added as classes
-        assertEquals(ClassMetadataPrototypeOF.class, factoryRegistry.getObjectFactory(
+        assertEquals(PrototypeObjectFactory.class, factoryRegistry.getObjectFactory(
             ResourceA.class).getClass());
-        assertEquals(ClassMetadataPrototypeOF.class, factoryRegistry.getObjectFactory(
+        assertEquals(PrototypeObjectFactory.class, factoryRegistry.getObjectFactory(
             ResourceScopableSingleton.class).getClass());
-        assertEquals(ClassMetadataPrototypeOF.class, factoryRegistry.getObjectFactory(
+        assertEquals(PrototypeObjectFactory.class, factoryRegistry.getObjectFactory(
             ResourceScopablePrototype.class).getClass());
 
         // by default resources are singletons, when added as instances
@@ -116,7 +116,7 @@
             factoryRegistry.getObjectFactory(ProviderA.class).getClass());
 
         // prototype
-        assertEquals(ClassMetadataPrototypeOF.class, factoryRegistry.getObjectFactory(
+        assertEquals(PrototypeObjectFactory.class, factoryRegistry.getObjectFactory(
             ProviderScopeablePrototype.class).getClass());
 
         // singleton
@@ -128,7 +128,7 @@
             factoryRegistry.getObjectFactory(new ProviderA()).getClass());
 
         // prototype
-        assertEquals(ClassMetadataPrototypeOF.class, factoryRegistry.getObjectFactory(
+        assertEquals(PrototypeObjectFactory.class, factoryRegistry.getObjectFactory(
             new ProviderScopeablePrototype()).getClass());
 
         // singleton
@@ -136,7 +136,7 @@
             new ProviderScopeableSingleton()).getClass());
 
         // default
-        assertEquals(ClassMetadataPrototypeOF.class, factoryRegistry.getObjectFactory(
+        assertEquals(PrototypeObjectFactory.class, factoryRegistry.getObjectFactory(
             ResourceA.class).getClass());
 
         // singleton
@@ -144,7 +144,7 @@
             ResourceScopableSingleton.class).getClass());
 
         // prototype
-        assertEquals(ClassMetadataPrototypeOF.class, factoryRegistry.getObjectFactory(
+        assertEquals(PrototypeObjectFactory.class, factoryRegistry.getObjectFactory(
             ResourceScopablePrototype.class).getClass());
 
         // default
@@ -156,7 +156,7 @@
             new ResourceScopableSingleton()).getClass());
 
         // prototype
-        assertEquals(ClassMetadataPrototypeOF.class, factoryRegistry.getObjectFactory(
+        assertEquals(PrototypeObjectFactory.class, factoryRegistry.getObjectFactory(
             new ResourceScopablePrototype()).getClass());
 
     }

Modified: incubator/wink/trunk/wink-common/src/test/java/org/apache/wink/common/internal/providers/ProvidersContextResolverTest.java
URL: http://svn.apache.org/viewvc/incubator/wink/trunk/wink-common/src/test/java/org/apache/wink/common/internal/providers/ProvidersContextResolverTest.java?rev=794149&r1=794148&r2=794149&view=diff
==============================================================================
--- incubator/wink/trunk/wink-common/src/test/java/org/apache/wink/common/internal/providers/ProvidersContextResolverTest.java (original)
+++ incubator/wink/trunk/wink-common/src/test/java/org/apache/wink/common/internal/providers/ProvidersContextResolverTest.java Wed Jul 15 06:24:39 2009
@@ -149,7 +149,12 @@
         assertTrue(providers.addProvider(new IntegerContextResolver()));
         assertTrue(providers.addProvider(new ByteContextResolver()));
         assertTrue(providers.addProvider(new ListContextResolver()));
-        assertFalse(providers.addProvider(new NotAProvider()));
+        
+        try {
+            providers.addProvider(new NotAProvider());
+            fail("expected IllegalArgumentException");
+        } catch (IllegalArgumentException e) {
+        }
 
         /*
          * String and text/pain, should invoke StringContextResolver

Modified: incubator/wink/trunk/wink-server/src/main/java/org/apache/wink/server/internal/handlers/FindResourceMethodHandler.java
URL: http://svn.apache.org/viewvc/incubator/wink/trunk/wink-server/src/main/java/org/apache/wink/server/internal/handlers/FindResourceMethodHandler.java?rev=794149&r1=794148&r2=794149&view=diff
==============================================================================
--- incubator/wink/trunk/wink-server/src/main/java/org/apache/wink/server/internal/handlers/FindResourceMethodHandler.java (original)
+++ incubator/wink/trunk/wink-server/src/main/java/org/apache/wink/server/internal/handlers/FindResourceMethodHandler.java Wed Jul 15 06:24:39 2009
@@ -178,7 +178,7 @@
             result.setError(new WebApplicationException(Status.NOT_FOUND));
             return;
         }
-        ResourceRecord record = registry.getRecord(subResource);
+        ResourceRecord record = registry.getRecord(subResource, false);
         ResourceInstance resourceInstance = new ResourceInstance(subResource, record, matcher);
         // save the resource for UriInfo
         result.getData().getMatchedResources().addFirst(resourceInstance);

Modified: incubator/wink/trunk/wink-server/src/main/java/org/apache/wink/server/internal/registry/ResourceRecordFactory.java
URL: http://svn.apache.org/viewvc/incubator/wink/trunk/wink-server/src/main/java/org/apache/wink/server/internal/registry/ResourceRecordFactory.java?rev=794149&r1=794148&r2=794149&view=diff
==============================================================================
--- incubator/wink/trunk/wink-server/src/main/java/org/apache/wink/server/internal/registry/ResourceRecordFactory.java (original)
+++ incubator/wink/trunk/wink-server/src/main/java/org/apache/wink/server/internal/registry/ResourceRecordFactory.java Wed Jul 15 06:24:39 2009
@@ -17,7 +17,6 @@
  *  under the License.
  *  
  *******************************************************************************/
- 
 
 package org.apache.wink.server.internal.registry;
 
@@ -35,24 +34,24 @@
 import org.apache.wink.common.internal.lifecycle.ObjectFactory;
 import org.apache.wink.common.internal.registry.metadata.ClassMetadata;
 import org.apache.wink.common.internal.registry.metadata.ResourceMetadataCollector;
+import org.apache.wink.common.internal.runtime.RuntimeContext;
 import org.apache.wink.common.internal.uritemplate.UriTemplateProcessor;
 
-
 public class ResourceRecordFactory {
 
     private static final Logger logger = LoggerFactory.getLogger(ResourceRecordFactory.class);
 
-    private final LifecycleManagersRegistry objectFactoryRegistry;
+    private final LifecycleManagersRegistry lifecycleManagerRegistry;
     private final Map<Class<?>,ResourceRecord> cacheByClass;
 
     private Lock readersLock;
     private Lock writersLock;
 
-    public ResourceRecordFactory(LifecycleManagersRegistry objectFactoryRegistry) {
-        if (objectFactoryRegistry == null) {
-            throw new NullPointerException("objectFactoryRegistry");
+    public ResourceRecordFactory(LifecycleManagersRegistry lifecycleManagerRegistry) {
+        if (lifecycleManagerRegistry == null) {
+            throw new NullPointerException("lifecycleManagerRegistry");
         }
-        this.objectFactoryRegistry = objectFactoryRegistry;
+        this.lifecycleManagerRegistry = lifecycleManagerRegistry;
         this.cacheByClass = new HashMap<Class<?>,ResourceRecord>();
         ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
         readersLock = readWriteLock.readLock();
@@ -72,10 +71,10 @@
         try {
             ResourceRecord record = cacheByClass.get(cls);
             if (record == null) {
-                ObjectFactory<?> of = objectFactoryRegistry.getObjectFactory(cls);
+                ObjectFactory<?> of = lifecycleManagerRegistry.getObjectFactory(cls);
                 readersLock.unlock();
                 try {
-                    record = createAndCacheResourceRecord(cls, of);
+                    record = createStaticResourceRecord(cls, of);
                 } finally {
                     readersLock.lock();
                 }
@@ -87,36 +86,67 @@
     }
 
     /**
+     * Gets a root resource record from a cache of records for the specified resource instance. This
+     * is a shortcut for {@code getResourceRecord(instance, true)}
+     * 
+     * @param instance
+     *            the resource instance to get the record for
+     * @return ResourceRecord for the resource instance
+     */
+    public ResourceRecord getResourceRecord(Object instance) {
+        return getResourceRecord(instance, true);
+    }
+
+    /**
      * Gets a resource record from a cache of records for the specified resource instance. If there
      * is no record in the cache, or if the instance is a dynamic resource, then a new record is
      * created
      * 
-     * @param Object
+     * @param instance
      *            the resource instance to get the record for
+     * @param isRootResource
+     *            specifies whether the instance is a root resource (true) or sub-resource (false)
      * @return ResourceRecord for the resource instance
      */
-    public ResourceRecord getResourceRecord(Object instance) {
+    public ResourceRecord getResourceRecord(Object instance, boolean isRootResource) {
         Class<? extends Object> cls = instance.getClass();
         ResourceRecord record = null;
         readersLock.lock();
         try {
-            if (ResourceMetadataCollector.isStaticResource(cls)) {
-                record = cacheByClass.get(cls);
-                if (record == null) {
-                    ObjectFactory<?> of = objectFactoryRegistry.getObjectFactory(instance);
+            // if this is a root resource
+            if (isRootResource) {
+                if (ResourceMetadataCollector.isStaticResource(cls)) {
+                    // if this is a static resource, and use cache
+                    record = cacheByClass.get(cls);
+                    if (record == null) {
+                        ObjectFactory<?> of = lifecycleManagerRegistry.getObjectFactory(instance);
+                        readersLock.unlock();
+                        try {
+                            record = createStaticResourceRecord(cls, of);
+                        } finally {
+                            readersLock.lock();
+                        }
+                    }
+                } else if (ResourceMetadataCollector.isDynamicResource(cls)) {
+                    // if this is a dynamic resource, don't use cache
+                    ObjectFactory<?> of = lifecycleManagerRegistry.getObjectFactory(instance);
                     readersLock.unlock();
                     try {
-                        record = createAndCacheResourceRecord(cls, of);
+                        record = createDynamicResourceRecord((DynamicResource)instance, of);
                     } finally {
                         readersLock.lock();
                     }
+                } else {
+                    throw new IllegalArgumentException(String.format(
+                            "Root resource %s instance is an invalid resource", instance.getClass()
+                                    .getCanonicalName()));
                 }
             } else {
-                // don't use cache
-                ObjectFactory<?> of = objectFactoryRegistry.getObjectFactory(instance);
+                // if this is a sub-resource, don't use cache, and don't use the life-cycle manager
+                ObjectFactory<?> of = new InstanceObjectFactory<Object>(instance);
                 readersLock.unlock();
                 try {
-                    record = createResourceRecord(instance, of);
+                    record = createSubResourceRecord(instance, of);
                 } finally {
                     readersLock.lock();
                 }
@@ -127,13 +157,14 @@
         }
     }
 
-    private ResourceRecord createAndCacheResourceRecord(Class<? extends Object> cls, ObjectFactory<?> of) {
+    private ResourceRecord createStaticResourceRecord(Class<? extends Object> cls,
+            ObjectFactory<?> of) {
         ClassMetadata metadata = createMetadata(cls);
         UriTemplateProcessor processor = createUriTemplateProcessor(metadata);
         ResourceRecord record = new ResourceRecord(metadata, of, processor);
         writersLock.lock();
         try {
-            // double check so as not to put the same resource twice 
+            // double check so as not to put the same resource twice
             if (cacheByClass.get(cls) == null) {
                 cacheByClass.put(cls, record);
             }
@@ -143,7 +174,7 @@
         return record;
     }
 
-    private ResourceRecord createResourceRecord(Object instance, ObjectFactory<?> of) {
+    private ResourceRecord createDynamicResourceRecord(DynamicResource instance, ObjectFactory<?> of) {
         Class<? extends Object> cls = instance.getClass();
         ClassMetadata metadata = createMetadata(cls);
         metadata = fixInstanceMetadata(metadata, instance);
@@ -151,6 +182,12 @@
         return new ResourceRecord(metadata, of, processor);
     }
 
+    private ResourceRecord createSubResourceRecord(Object instance, ObjectFactory<?> of) {
+        Class<? extends Object> cls = instance.getClass();
+        ClassMetadata metadata = createMetadata(cls);
+        return new ResourceRecord(metadata, of, null);
+    }
+
     private ClassMetadata createMetadata(Class<? extends Object> cls) {
         return ResourceMetadataCollector.collectMetadata(cls);
     }
@@ -158,12 +195,12 @@
     private UriTemplateProcessor createUriTemplateProcessor(ClassMetadata metadata) {
         // create the resource path using the parents paths
         StringBuilder path = new StringBuilder();
-        // Recursively append parent paths 
+        // Recursively append parent paths
         appendPathWithParent(metadata, path);
         // create the processor
         return UriTemplateProcessor.newNormalizedInstance(path.toString());
     }
-    
+
     private void appendPathWithParent(ClassMetadata metadata, StringBuilder pathStr) {
         ResourceRecord parentRecord = getParent(metadata);
         if (parentRecord != null) {
@@ -188,7 +225,7 @@
         }
         return parentRecord;
     }
-    
+
     /**
      * Fixed the metadata to reflect the information stored on the instance of the dynamic resource.
      * 
@@ -196,36 +233,58 @@
      * @param instance
      * @return
      */
-    private ClassMetadata fixInstanceMetadata(ClassMetadata classMetadata, Object instance) {
-        if (instance instanceof DynamicResource) {
-            DynamicResource dynamicResource = (DynamicResource)instance;
-            String[] dispatchedPath = dynamicResource.getDispatchedPath();
-            if (dispatchedPath != null) {
-                classMetadata.addPaths(Arrays.asList(dispatchedPath));
-                if (logger.isDebugEnabled()) {
-                    logger.debug("Adding dispatched path from instance: {}", Arrays.toString(dispatchedPath));
-                }
+    private ClassMetadata fixInstanceMetadata(ClassMetadata classMetadata,
+            DynamicResource dynamicResource) {
+        String[] dispatchedPath = dynamicResource.getDispatchedPath();
+        if (dispatchedPath != null) {
+            classMetadata.addPaths(Arrays.asList(dispatchedPath));
+            if (logger.isDebugEnabled()) {
+                logger.debug("Adding dispatched path from instance: {}", Arrays
+                        .toString(dispatchedPath));
             }
+        }
 
-            Object[] parents = dynamicResource.getParents();
-            if (parents != null) {
-                classMetadata.getParentInstances().addAll(Arrays.asList(parents));
-                if (logger.isDebugEnabled()) {
-                    logger.debug("Adding parent beans from instance: {}", Arrays.toString(parents));
-                }
+        Object[] parents = dynamicResource.getParents();
+        if (parents != null) {
+            classMetadata.getParentInstances().addAll(Arrays.asList(parents));
+            if (logger.isDebugEnabled()) {
+                logger.debug("Adding parent beans from instance: {}", Arrays.toString(parents));
             }
+        }
 
-            String workspaceTitle = dynamicResource.getWorkspaceTitle();
-            if (workspaceTitle != null) {
-                classMetadata.setWorkspaceName(workspaceTitle);
-            }
+        String workspaceTitle = dynamicResource.getWorkspaceTitle();
+        if (workspaceTitle != null) {
+            classMetadata.setWorkspaceName(workspaceTitle);
+        }
 
-            String collectionTitle = dynamicResource.getCollectionTitle();
-            if (collectionTitle != null) {
-                classMetadata.setCollectionTitle(collectionTitle);
-            }
+        String collectionTitle = dynamicResource.getCollectionTitle();
+        if (collectionTitle != null) {
+            classMetadata.setCollectionTitle(collectionTitle);
         }
         return classMetadata;
     }
 
+    private static class InstanceObjectFactory<T> implements ObjectFactory<T> {
+
+        private final T object;
+
+        public InstanceObjectFactory(T object) {
+            this.object = object;
+        }
+
+        public T getInstance(RuntimeContext context) {
+            return object;
+        }
+
+        @SuppressWarnings("unchecked")
+        public Class<T> getInstanceClass() {
+            return (Class<T>)object.getClass();
+        }
+
+        @Override
+        public String toString() {
+            return String.format("InstanceObjectFactory: %s", getInstanceClass());
+        }
+    }
+
 }

Modified: incubator/wink/trunk/wink-server/src/main/java/org/apache/wink/server/internal/registry/ResourceRegistry.java
URL: http://svn.apache.org/viewvc/incubator/wink/trunk/wink-server/src/main/java/org/apache/wink/server/internal/registry/ResourceRegistry.java?rev=794149&r1=794148&r2=794149&view=diff
==============================================================================
--- incubator/wink/trunk/wink-server/src/main/java/org/apache/wink/server/internal/registry/ResourceRegistry.java (original)
+++ incubator/wink/trunk/wink-server/src/main/java/org/apache/wink/server/internal/registry/ResourceRegistry.java Wed Jul 15 06:24:39 2009
@@ -66,7 +66,8 @@
     private Lock writersLock;
     private final ApplicationValidator applicationValidator;
 
-    public ResourceRegistry(LifecycleManagersRegistry factoryRegistry, ApplicationValidator applicationValidator) {
+    public ResourceRegistry(LifecycleManagersRegistry factoryRegistry,
+            ApplicationValidator applicationValidator) {
         this.applicationValidator = applicationValidator;
         rootResources = new LinkedList<ResourceRecord>();
         dirty = false;
@@ -114,7 +115,7 @@
                 return;
             }
 
-            ResourceRecord record = resourceRecordsFactory.getResourceRecord(instance);
+            ResourceRecord record = getRecord(instance);
             record.setPriority(priority);
             rootResources.add(record);
             dirty = true;
@@ -140,7 +141,7 @@
                 logger.warn("The resource class {} is not a valid resource. Ignoring.", clazz);
                 return;
             }
-            ResourceRecord record = resourceRecordsFactory.getResourceRecord(clazz);
+            ResourceRecord record = getRecord(clazz);
             record.setPriority(priority);
             rootResources.add(record);
             dirty = true;
@@ -150,14 +151,28 @@
     }
 
     /**
-     * Get the {@link ResourceRecord} of the specified resource instance
+     * Get the {@link ResourceRecord} of the specified root resource instance. This is a
+     * shortcut for {@code getRecord(instance, true)}
      * 
      * @param instance
      *            the resource instance to get the record for
      * @return {@link ResourceRecord} of the instance
      */
     public ResourceRecord getRecord(Object instance) {
-        return resourceRecordsFactory.getResourceRecord(instance);
+        return getRecord(instance, true);
+    }
+
+    /**
+     * Get the {@link ResourceRecord} of the specified resource instance
+     * 
+     * @param instance
+     *            the resource instance to get the record for
+     * @param isRootResource
+     *            specifies whether the instance is a root resource (true) or sub-resource (false)
+     * @return {@link ResourceRecord} of the instance
+     */
+    public ResourceRecord getRecord(Object instance, boolean isRootResource) {
+        return resourceRecordsFactory.getResourceRecord(instance, isRootResource);
     }
 
     /**
@@ -189,7 +204,8 @@
             resourceMethods = resource.getRecord().getMetadata().getResourceMethods();
         } else {
             String uri = UriTemplateProcessor.normalizeUri(resource.getMatcher().getTail(false));
-            List<SubResourceInstance> matchingMethods = resource.getRecord().getMatchingSubResourceMethods(uri);
+            List<SubResourceInstance> matchingMethods = resource.getRecord()
+                    .getMatchingSubResourceMethods(uri);
             resourceMethods = new LinkedList<MethodMetadata>();
             for (SubResourceInstance subResource : matchingMethods) {
                 resourceMethods.add(subResource.getRecord().getMetadata());
@@ -262,7 +278,8 @@
      *            the context of the current request
      * @return
      */
-    public MethodRecord findMethod(ResourceInstance resource, RuntimeContext context) throws WebApplicationException {
+    public MethodRecord findMethod(ResourceInstance resource, RuntimeContext context)
+            throws WebApplicationException {
         List<MethodMetadata> methods = resource.getRecord().getMetadata().getResourceMethods();
         List<MethodMetadataRecord> records = new LinkedList<MethodMetadataRecord>();
         for (MethodMetadata metadata : methods) {
@@ -293,11 +310,13 @@
      *            the context of the current request
      * @return
      */
-    public SubResourceInstance findSubResourceMethod(String pattern, List<SubResourceInstance> subResourceRecords,
-            ResourceInstance resource, RuntimeContext context) throws WebApplicationException {
+    public SubResourceInstance findSubResourceMethod(String pattern,
+            List<SubResourceInstance> subResourceRecords, ResourceInstance resource,
+            RuntimeContext context) throws WebApplicationException {
         // extract the sub-resource methods that have the same path template
         // as the first sub-resource method
-        List<SubResourceInstance> subResourceMethods = extractSubResourceMethods(pattern, subResourceRecords);
+        List<SubResourceInstance> subResourceMethods = extractSubResourceMethods(pattern,
+                subResourceRecords);
 
         // filter the methods according to http method/consumes/produces
         filterDispatchMethods(resource, subResourceMethods, context);
@@ -348,8 +367,9 @@
      *            the context of the current request
      * @return
      */
-    private void filterDispatchMethods(ResourceInstance resource, List<? extends MethodRecord> methodRecords,
-            RuntimeContext context) throws WebApplicationException {
+    private void filterDispatchMethods(ResourceInstance resource,
+            List<? extends MethodRecord> methodRecords, RuntimeContext context)
+            throws WebApplicationException {
         // filter by http method
         ListIterator<? extends MethodRecord> iterator = methodRecords.listIterator();
         while (iterator.hasNext()) {
@@ -359,8 +379,8 @@
             }
         }
         if (methodRecords.size() == 0) {
-            logger.info("Could not find any method in class {} that supports {}",
-                    resource.getResourceClass().getName(), context.getRequest().getMethod());
+            logger.info("Could not find any method in class {} that supports {}", resource
+                    .getResourceClass().getName(), context.getRequest().getMethod());
             throw new WebApplicationException(HttpStatus.METHOD_NOT_ALLOWED.getCode());
         }
 
@@ -373,8 +393,8 @@
             }
         }
         if (methodRecords.size() == 0) {
-            logger.info("Could not find any method in class {} that consumes {}",
-                    resource.getResourceClass().getName(), context.getHttpHeaders().getMediaType());
+            logger.info("Could not find any method in class {} that consumes {}", resource
+                    .getResourceClass().getName(), context.getHttpHeaders().getMediaType());
             throw new WebApplicationException(Response.Status.UNSUPPORTED_MEDIA_TYPE);
         }
 
@@ -387,8 +407,9 @@
             }
         }
         if (methodRecords.size() == 0) {
-            logger.info("Could not find any method in class {} capable of producing {}", resource.getResourceClass()
-                    .getName(), context.getHttpHeaders().getRequestHeader(HttpHeaders.ACCEPT));
+            logger.info("Could not find any method in class {} capable of producing {}", resource
+                    .getResourceClass().getName(), context.getHttpHeaders().getRequestHeader(
+                    HttpHeaders.ACCEPT));
             throw new WebApplicationException(Response.Status.NOT_ACCEPTABLE);
         }
     }
@@ -485,7 +506,8 @@
      *            the context of the current request
      * @return
      */
-    private MethodRecord selectBestMatchingMethod(List<? extends MethodRecord> methodRecords, RuntimeContext context) {
+    private MethodRecord selectBestMatchingMethod(List<? extends MethodRecord> methodRecords,
+            RuntimeContext context) {
         HttpHeaders httpHeaders = context.getHttpHeaders();
         MediaType inputMediaType = httpHeaders.getMediaType();
         List<MediaType> acceptableMediaTypes = httpHeaders.getAcceptableMediaTypes();
@@ -514,8 +536,8 @@
      * @return positive integer if record1 is a better match, negative integer if record2 is a
      *         better match, 0 if they are equal in matching terms
      */
-    private int compareMethods(MethodRecord record1, MethodRecord record2, MediaType inputMediaType,
-            List<MediaType> acceptableMediaTypes) {
+    private int compareMethods(MethodRecord record1, MethodRecord record2,
+            MediaType inputMediaType, List<MediaType> acceptableMediaTypes) {
 
         if (record1 == null && record2 == null) {
             return 0;
@@ -575,11 +597,14 @@
      * @return positive integer if record1 is a better match, negative integer if record2 is a
      *         better match, 0 if they are equal in matching terms
      */
-    private int compareMethodsConsumes(MethodRecord record1, MethodRecord record2, MediaType inputMediaType) {
+    private int compareMethodsConsumes(MethodRecord record1, MethodRecord record2,
+            MediaType inputMediaType) {
         // get media type of metadata 1 best matching the input media type
-        MediaType bestMatch1 = selectBestMatchingMediaType(inputMediaType, record1.getMetadata().getConsumes());
+        MediaType bestMatch1 = selectBestMatchingMediaType(inputMediaType, record1.getMetadata()
+                .getConsumes());
         // get media type of metadata 2 best matching the input media type
-        MediaType bestMatch2 = selectBestMatchingMediaType(inputMediaType, record2.getMetadata().getConsumes());
+        MediaType bestMatch2 = selectBestMatchingMediaType(inputMediaType, record2.getMetadata()
+                .getConsumes());
 
         if (bestMatch1 == null && bestMatch2 == null) {
             return 0;
@@ -608,7 +633,8 @@
      * @return positive integer if record1 is a better match, negative integer if record2 is a
      *         better match, 0 if they are equal in matching terms
      */
-    private int compareMethodsProduces(MethodRecord record1, MethodRecord record2, List<MediaType> acceptableMediaTypes) {
+    private int compareMethodsProduces(MethodRecord record1, MethodRecord record2,
+            List<MediaType> acceptableMediaTypes) {
 
         MediaType bestMatch1 = null;
         MediaType bestMatch2 = null;
@@ -617,9 +643,11 @@
         // so we need to stop with the first media type that has a match
         for (MediaType acceptableMediaType : acceptableMediaTypes) {
             // get media type of metadata 1 best matching the current acceptable media type
-            bestMatch1 = selectBestMatchingMediaType(acceptableMediaType, record1.getMetadata().getProduces());
+            bestMatch1 = selectBestMatchingMediaType(acceptableMediaType, record1.getMetadata()
+                    .getProduces());
             // get media type of metadata 2 best matching the current acceptable media type
-            bestMatch2 = selectBestMatchingMediaType(acceptableMediaType, record2.getMetadata().getProduces());
+            bestMatch2 = selectBestMatchingMediaType(acceptableMediaType, record2.getMetadata()
+                    .getProduces());
             // if either of them returned a match, it's enough for a comparison
             if (bestMatch1 != null || bestMatch2 != null) {
                 break;

Modified: incubator/wink/trunk/wink-server/src/test/java/org/apache/wink/server/internal/registry/FindResourceMethodTest.java
URL: http://svn.apache.org/viewvc/incubator/wink/trunk/wink-server/src/test/java/org/apache/wink/server/internal/registry/FindResourceMethodTest.java?rev=794149&r1=794148&r2=794149&view=diff
==============================================================================
--- incubator/wink/trunk/wink-server/src/test/java/org/apache/wink/server/internal/registry/FindResourceMethodTest.java (original)
+++ incubator/wink/trunk/wink-server/src/test/java/org/apache/wink/server/internal/registry/FindResourceMethodTest.java Wed Jul 15 06:24:39 2009
@@ -345,12 +345,27 @@
             return new ResourceWithSubResourceMethodSimpleGet();
         }
         
+        @Path("sub-resource-with-no-constructor")
+        @Produces("text/plain")
+        public SubResourceNoDefaultConstructor subResourceWithNoConstructor() {
+            return new SubResourceNoDefaultConstructor(1, "2");
+        }
+        
         // locators cannot have an entity param
         @Path("bad-locator")
         public void badLocator(String entity) {
             fail("locator method should not have been invoked");
         }
+    }
+    
+    public static class SubResourceNoDefaultConstructor {
+        public SubResourceNoDefaultConstructor(Integer i, String s) {}
         
+        @GET
+        @Path("{id}")
+        public String getAny(@PathParam("id") String id) {
+            return "SubResourceNoDefaultConstructor.getAny";
+        }
     }
 
     @Path("/mixed/{id}")
@@ -681,6 +696,10 @@
         response = invoke(request);
         assertMethodFound(response, ResourceWithSubResourceMethodSimpleGet.class, "getTextPlain");
     
+        request = MockRequestConstructor.constructMockRequest("GET", "/subResourceLocatorSimpleGet/sub-resource-with-no-constructor/2", "text/plain");
+        response = invoke(request);
+        assertMethodFound(response, SubResourceNoDefaultConstructor.class, "getAny");
+
         request = MockRequestConstructor.constructMockRequest("GET", "/subResourceLocatorSimpleGet/bad-locator/2", "text/plain");
         response = invoke(request);
         assertMethodFound(response, ResourceWithSubResourceMethodSimpleGet.class, "getTextPlain");

Modified: incubator/wink/trunk/wink-server/src/test/java/org/apache/wink/server/internal/registry/ResourceRecordFactoryTest.java
URL: http://svn.apache.org/viewvc/incubator/wink/trunk/wink-server/src/test/java/org/apache/wink/server/internal/registry/ResourceRecordFactoryTest.java?rev=794149&r1=794148&r2=794149&view=diff
==============================================================================
--- incubator/wink/trunk/wink-server/src/test/java/org/apache/wink/server/internal/registry/ResourceRecordFactoryTest.java (original)
+++ incubator/wink/trunk/wink-server/src/test/java/org/apache/wink/server/internal/registry/ResourceRecordFactoryTest.java Wed Jul 15 06:24:39 2009
@@ -24,6 +24,7 @@
 import javax.ws.rs.GET;
 import javax.ws.rs.Path;
 
+import org.apache.wink.common.AbstractDynamicResource;
 import org.apache.wink.common.internal.lifecycle.LifecycleManagersRegistry;
 import org.apache.wink.server.internal.registry.ResourceRecord;
 import org.apache.wink.server.internal.registry.ResourceRecordFactory;
@@ -50,8 +51,17 @@
             return "GET";
         }
     }
+    
 
-    public void testFactory() {
+    public static class Dynamic extends AbstractDynamicResource {
+        
+    }
+    
+    public static class Dummy {
+        
+    }
+
+    public void testStaticResource() {
         ResourceRecordFactory factory = new ResourceRecordFactory(new LifecycleManagersRegistry());
         
         ResourceRecord record = factory.getResourceRecord(Resource1.class);
@@ -79,4 +89,60 @@
         o = record.getObjectFactory().getInstance(null);
         assertTrue(o instanceof Resource2);
     }
+        
+    public void testDynamicResource() {
+        ResourceRecordFactory factory = new ResourceRecordFactory(new LifecycleManagersRegistry());
+        Dynamic dynamic = new Dynamic();
+        dynamic.setDispatchedPath(new String[] {"/pathDyna"});
+        
+        ResourceRecord dynamicRecord = factory.getResourceRecord(dynamic);
+        assertEquals("/pathDyna", dynamicRecord.getMetadata().getPath());
+        Object o = dynamicRecord.getObjectFactory().getInstance(null);
+        assertTrue(o instanceof Dynamic);
+        assertTrue(o == dynamic);
+        
+        Dynamic dynamic2 = new Dynamic();
+        dynamic2.setDispatchedPath(new String[] {"/pathDyna2"});
+        ResourceRecord dynamicRecord2 = factory.getResourceRecord(dynamic2);
+        assertEquals("/pathDyna2", dynamicRecord2.getMetadata().getPath());
+        Object o2 = dynamicRecord2.getObjectFactory().getInstance(null);
+        assertTrue(o2 instanceof Dynamic);
+        assertTrue(dynamicRecord2 != dynamicRecord);
+        
+        try {
+            factory.getResourceRecord(Dynamic.class);
+            fail("Expected IllegalArgumentException");
+        } catch (IllegalArgumentException e) {
+        }
+    }
+    
+    public void testSubResource() {
+        ResourceRecordFactory factory = new ResourceRecordFactory(new LifecycleManagersRegistry());
+        
+        // test for sub-resource
+        Dummy dummy = new Dummy();
+        ResourceRecord dummyRecord = factory.getResourceRecord(dummy, false);
+        Object o = dummyRecord.getObjectFactory().getInstance(null);
+        assertTrue(o instanceof Dummy);
+        assertTrue(o == dummy);
+
+        Dummy dummy2 = new Dummy();
+        ResourceRecord dummyRecord2 = factory.getResourceRecord(dummy2, false);
+        Object o2 = dummyRecord2.getObjectFactory().getInstance(null);
+        assertTrue(o2 instanceof Dummy);
+        assertTrue(dummyRecord2 != dummyRecord);
+
+        try {
+            factory.getResourceRecord(new Dummy());
+            fail("Expected IllegalArgumentException");
+        } catch (IllegalArgumentException e) {
+        }
+        
+        try {
+            factory.getResourceRecord(Dummy.class);
+            fail("Expected IllegalArgumentException");
+        } catch (IllegalArgumentException e) {
+        }
+        
+    }
 }