Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
   /*
    * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
    *
    * Copyright (c) 2010-2011 Oracle and/or its affiliates. All rights reserved.
    *
    * The contents of this file are subject to the terms of either the GNU
    * General Public License Version 2 only ("GPL") or the Common Development
    * and Distribution License("CDDL") (collectively, the "License").  You
    * may not use this file except in compliance with the License.  You can
   * obtain a copy of the License at
   * http://glassfish.java.net/public/CDDL+GPL_1_1.html
   * or packager/legal/LICENSE.txt.  See the License for the specific
   * language governing permissions and limitations under the License.
   *
   * When distributing the software, include this License Header Notice in each
   * file and include the License file at packager/legal/LICENSE.txt.
   *
   * GPL Classpath Exception:
   * Oracle designates this particular file as subject to the "Classpath"
   * exception as provided by Oracle in the GPL Version 2 section of the License
   * file that accompanied this code.
   *
   * Modifications:
   * If applicable, add the following below the License Header, with the fields
   * enclosed by brackets [] replaced by your own identifying information:
   * "Portions Copyright [year] [name of copyright owner]"
   *
   * Contributor(s):
   * If you wish your version of this file to be governed by only the CDDL or
   * only the GPL Version 2, indicate your decision by adding "[Contributor]
   * elects to include this software in this distribution under the [CDDL or GPL
   * Version 2] license."  If you don't indicate a single choice of license, a
   * recipient has the option to distribute your version of this file under
   * either the CDDL, the GPL Version 2 or to extend the choice of license to
   * its licensees as provided above.  However, if you add GPL Version 2 code
   * and therefore, elected the GPL Version 2 license, then the option applies
   * only if the new code is made subject to such option by the copyright
   * holder.
   */
  package com.sun.jersey.server.impl.application;
  
  import java.net.URI;
  import java.util.Arrays;
  import java.util.HashMap;
  import java.util.HashSet;
  import java.util.List;
  import java.util.Map;
  import java.util.Set;
  
  
A Web application that contains a set of resources, each referenced by an absolute URI template.

Author(s):
Paul.Sandoz@Sun.Com
 
 public final class WebApplicationImpl implements WebApplication {
 
     private static final Logger LOGGER = Logger.getLogger(WebApplicationImpl.class.getName());
 
     private final Map<ClassAbstractResourceabstractResourceMap =
             new HashMap<ClassAbstractResource>();
 
     private final ConcurrentMap<ClassUriRules<UriRule>> rulesMap =
             new ConcurrentHashMap<ClassUriRules<UriRule>>();
 
             new ConcurrentHashMap<ClassResourceComponentProvider>();
 
     private static class ClassAnnotationKey {
         private final Class c;
 
         private final Set<Annotationas;
 
         public ClassAnnotationKey(Class cAnnotation[] as) {
             this. = c;
             this. = new HashSet<Annotation>(Arrays.asList(as));
         }
 
         @Override
         public int hashCode() {
             int hash = 5;
             hash = 67 * hash + (this. != null ? this..hashCode() : 0);
             hash = 67 * hash + (this. != null ? this..hashCode() : 0);
             return hash;
         }
 
         @Override
         public boolean equals(Object obj) {
             if (obj == null) {
                 return false;
             }
             if (getClass() != obj.getClass()) {
                 return false;
             }
             final ClassAnnotationKey other = (ClassAnnotationKeyobj;
             if (this. != other.c && (this. == null || !this..equals(other.c))) {
                 return false;
             }
             if (this. != other.as && (this. == null || !this..equals(other.as))) {
                 return false;
             }
             return true;
         }
     }
 
 
     private final ThreadLocalHttpContext context;
 
     private final CloseableServiceFactory closeableFactory;
 
     private boolean initiated;
 
     private ResourceConfig resourceConfig;
 
 
 
     private ProviderFactory cpFactory;
 
     private ResourceFactory rcpFactory;
 
 
 
     private Providers providers;
 
     private MessageBodyFactory bodyFactory;
 
 
     private TemplateContext templateContext;
 
 
 
     private ResourceContext resourceContext;
 
 
 
 
             @Override
             public Set<AbstractResourcegetAbstractRootResources() {
                 return ;
             }
         };
 
     private FilterFactory filterFactory;
 
     private WadlFactory wadlFactory;
 
     private boolean isTraceEnabled;
 
     private RequestListener requestListener;
 
 
 
     public WebApplicationImpl() {
         this. = new ThreadLocalHttpContext();
 
         InvocationHandler requestHandler = new InvocationHandler() {
             @Override
             public Object invoke(Object proxyMethod methodObject[] argsthrows Throwable {
                 try {
                     return method.invoke(.getRequest(), args);
                 } catch (IllegalAccessException ex) {
                     throw new IllegalStateException(ex);
                 } catch (InvocationTargetException ex) {
                     throw ex.getTargetException();
                 }
             }
         };
         InvocationHandler uriInfoHandler = new InvocationHandler() {
             @Override
             public Object invoke(Object proxyMethod methodObject[] argsthrows Throwable {
                 try {
                     return method.invoke(.getUriInfo(), args);
                 } catch (IllegalAccessException ex) {
                     throw new IllegalStateException(ex);
                 } catch (InvocationTargetException ex) {
                     throw ex.getTargetException();
                 }
             }
         };
 
         // Create injectable provider factory
         this. = new ServerInjectableProviderFactory();
                 InjectableProviderContext.class));
                 ServerInjectableProviderContext.class));
 
         // Add proxied injectables
         final Map<TypeObjectm = new HashMap<TypeObject>();
         m.put(HttpContext.class);
         m.put(HttpHeaders.classcreateProxy(HttpHeaders.classrequestHandler));
         m.put(UriInfo.classcreateProxy(UriInfo.classuriInfoHandler));
         m.put(ExtendedUriInfo.classcreateProxy(ExtendedUriInfo.classuriInfoHandler));
         m.put(Request.classcreateProxy(Request.classrequestHandler));
         m.put(SecurityContext.classcreateProxy(SecurityContext.classrequestHandler));
         .add(new InjectableProvider<ContextType>() {
             @Override
             public ComponentScope getScope() {
                 return .;
             }
 
             @Override
             public Injectable getInjectable(ComponentContext icContext aType c) {
                 final Object o = m.get(c);
                 if (o != null) {
                     return new Injectable() {
                         @Override
                         public Object getValue() {
                             return o;
                         }
                     };
                 } else
                     return null;
             }
         });
 
         .add(new InjectableProvider<ContextType>() {
             @Override
             public ComponentScope getScope() {
                 return .;
             }
 
             @Override
             public Injectable<InjectablegetInjectable(ComponentContext icContext aType c) {
                 if (c instanceof ParameterizedType) {
                     ParameterizedType pt = (ParameterizedType)c;
                     if (pt.getRawType() == Injectable.class) {
                         if (pt.getActualTypeArguments().length == 1) {
                             final Injectable<?> i = .getInjectable(
                                     a.annotationType(),
                                     ic,
                                     a,
                                     pt.getActualTypeArguments()[0],
                                     .);
                             if (i == null)
                                 return null;
                             return new Injectable<Injectable>() {
                                 @Override
                                 public Injectable getValue() {
                                     return i;
                                 }
                             };
                         }
                     }
                 }
 
                 return null;
             }
         });
 
         .add(new InjectableProvider<InjectType>() {
             @Override
             public ComponentScope getScope() {
                 return .;
             }
 
             @Override
             public Injectable<InjectablegetInjectable(ComponentContext icInject aType c) {
                 if (c instanceof ParameterizedType) {
                     ParameterizedType pt = (ParameterizedType)c;
                     if (pt.getRawType() == Injectable.class) {
                         if (pt.getActualTypeArguments().length == 1) {
                             final Injectable<?> i = .getInjectable(
                                     a.annotationType(),
                                     ic,
                                     a,
                                     pt.getActualTypeArguments()[0],
                                     .);
                             if (i == null)
                                 return null;
                             return new Injectable<Injectable>() {
                                 @Override
                                 public Injectable getValue() {
                                     return i;
                                 }
                             };
                         }
                     }
                 }
 
                 return null;
             }
         });
 
             @Override
             public ComponentScope getScope() {
                 return .;
             }
 
             @Override
             public Injectable<InjectablegetInjectable(ComponentContext icInjectParam aType c) {
                 if (c instanceof ParameterizedType) {
                     ParameterizedType pt = (ParameterizedType)c;
                     if (pt.getRawType() == Injectable.class) {
                         if (pt.getActualTypeArguments().length == 1) {
                             final Injectable<?> i = .getInjectable(
                                     a.annotationType(),
                                     ic,
                                     a,
                                     pt.getActualTypeArguments()[0],
                                     .);
                             if (i == null)
                                 return null;
                             return new Injectable<Injectable>() {
                                 @Override
                                 public Injectable getValue() {
                                     return i;
                                 }
                             };
                         }
                     }
                 }
 
                 return null;
             }
         });
 
     }
 
     private class ComponentProcessorImpl implements IoCComponentProcessor {
         private final ResourceComponentInjector rci;
 
             this. = rci;
         }
 
         @Override
         public void preConstruct() {
         }
 
         @Override
         public void postConstruct(Object o) {
             .inject(.get(), o);
         }
     }
 
     private static final IoCComponentProcessor NULL_COMPONENT_PROCESSOR = new IoCComponentProcessor() {
         @Override
         public void preConstruct() {
         }
 
         @Override
         public void postConstruct(Object o) {
         }
     };
 
     private class ComponentProcessorFactoryImpl implements IoCComponentProcessorFactory {
         private final ConcurrentMap<ClassIoCComponentProcessorcomponentProcessorMap =
                 new ConcurrentHashMap<ClassIoCComponentProcessor>();
 
         @Override
         public ComponentScope getScope(Class c) {
             return .getScope(c);
         }
 
         @Override
         public IoCComponentProcessor get(final Class cfinal ComponentScope scope) {
             IoCComponentProcessor cp = .get(c);
             if (cp != null) {
                 return (cp == ) ? null : cp;
             }
 
             synchronized () {
                 cp = .get(c);
                 if (cp != null) {
                     return (cp == ) ? null : cp;
                 }
 
                 final ResourceComponentInjector rci = Errors.processWithErrors(new Errors.Closure<ResourceComponentInjector>() {
                     @Override
                     public ResourceComponentInjector f() {
                         return new ResourceComponentInjector(
                                 scopegetAbstractResource(c));
                     }
                 });
 
                 if (rci.hasInjectableArtifacts()) {
                     cp = new ComponentProcessorImpl(rci);
                     .put(ccp);
                 } else {
                     cp = null;
                     .put(c);
                 }
             }
             return cp;
         }
     }
 
     @Override
         return ;
     }
 
     @Override
     public WebApplication clone() {
         WebApplicationImpl wa = new WebApplicationImpl();
         wa.initiate();
         return wa;
     }
 
     /* package */ UriRules<UriRulegetUriRules(final Class c) {
         assert c != null;
 
         // Try the non-blocking read, the most common operation
         UriRules<UriRuler = .get(c);
         if (r != null) {
             return r;
         }
 
         // Not present use a synchronized block to ensure that only one
         // instance is created and put to the map
         synchronized () {
             // One or more threads may have been blocking on the synchronized
             // block, re-check the map
             r = .get(c);
             if (r != null) {
                 return r;
             }
 
             r = Errors.processWithErrors(new Errors.Closure<ResourceUriRules>() {
                 @Override
                 public ResourceUriRules f() {
                     return newResourceUriRules(getAbstractResource(c));
                 }
             }).getRules();
             .put(cr);
         }
         return r;
     }
 
     /* package */ ResourceComponentProvider getResourceComponentProvider(final Class c) {
         assert c != null;
 
         // Try the non-blocking read, the most common operation
         ResourceComponentProvider rcp = .get(c);
         if (rcp != null) {
             return rcp;
         }
 
         // Not present use a synchronized block to ensure that only one
         // instance is created and put to the map
         synchronized () {
             // One or more threads may have been blocking on the synchronized
             // block, re-check the map
             rcp = .get(c);
             if (rcp != null) {
                 return rcp;
             }
 
             final ResourceComponentProvider _rcp = rcp = .getComponentProvider(nullc);
             Errors.processWithErrors(new Errors.Closure<Void>() {
                 @Override
                 public Void f() {
                     _rcp.init(getAbstractResource(c));
                     return null;
                 }
             });
 
             .put(crcp);
         }
         return rcp;
     }
 
     /* package */ ResourceComponentProvider getResourceComponentProvider(final ComponentContext ccfinal Class c) {
         assert c != null;
 
         if (cc == null || cc.getAnnotations().length == 0)
             return getResourceComponentProvider(c);
 
         if (cc.getAnnotations().length == 1) {
             final Annotation a = cc.getAnnotations()[0];
             if (a.annotationType() == Inject.class) {
                 final Inject i = Inject.class.cast(a);
                 final String value = (i.value() != null)
                         ? i.value().trim()
                         : "";
                 if (value.isEmpty())
                     return getResourceComponentProvider(c);
             } else if (a.annotationType() == InjectParam.class) {
                 final InjectParam i = InjectParam.class.cast(a);
                 final String value = (i.value() != null)
                         ? i.value().trim()
                         : "";
                 if (value.isEmpty())
                     return getResourceComponentProvider(c);
             }
         }
 
         final ClassAnnotationKey cak = new ClassAnnotationKey(c,
                 cc.getAnnotations());
 
         // Try the non-blocking read, the most common operation
         if (rcp != null) {
             return rcp;
         }
 
         // Not present use a synchronized block to ensure that only one
         // instance is created and put to the map
         synchronized () {
             // One or more threads may have been blocking on the synchronized
             // block, re-check the map
             rcp = .get(cak);
             if (rcp != null) {
                 return rcp;
             }
 
             final ResourceComponentProvider _rcp = rcp = .getComponentProvider(ccc);
             Errors.processWithErrors(new Errors.Closure<Void>() {
                 @Override
                 public Void f() {
                     _rcp.init(getAbstractResource(c));
                     return null;
                 }
             });
 
             .put(cakrcp);
         }
         return rcp;
     }
 
     /* package */ void initiateResource(AbstractResource ar) {
         initiateResource(ar.getResourceClass());
     }
 
     /* package */ void initiateResource(Class c) {
         getUriRules(c);
         getResourceComponentProvider(c);
     }
 
     /* package */ void initiateResource(AbstractResource arfinal Object resource) {
         final Class c = ar.getResourceClass();
         getUriRules(c);
 
         if (!.containsKey(c)) {
             .put(cnew ResourceComponentProvider() {
                 @Override
                 public void init(AbstractResource abstractResource) {
                 }
 
                 @Override
                 public ComponentScope getScope() {
                     return .;
                 }
 
                 @Override
                 public Object getInstance(HttpContext hc) {
                     return getInstance();
                 }
 
                 @Override
                 public void destroy() {
                 }
 
                 @Override
                 public Object getInstance() {
                     return resource;
                 }
             });
         }
     }
 
     /* package */ Set<AbstractResourcegetAbstractRootResources() {
         return ;
     }
 
         return ;
     }
 
     private ResourceUriRules newResourceUriRules(final AbstractResource ar) {
         assert null != ar;
 
         BasicValidator validator = new BasicValidator();
         validator.validate(ar);
         for (ResourceModelIssue issue : validator.getIssueList()) {
             Errors.error(issue.getMessage(), issue.isFatal());
         }
         return new ResourceUriRules(
                 ,
                 getDispatchProvider(),
                 ,
                 ,
                 ,
                 ,
                 ar);
     }
 
         return ;
     }
 
     @Override
     public RequestListener getRequestListener() {
         return ;
     }
 
     @Override
         return ;
     }
 
     @Override
         return ;
     }
 
     /* package */ AbstractResource getAbstractResource(Object o) {
         return getAbstractResource(o.getClass());
     }
 
     /* package */ AbstractResource getAbstractResource(Class c) {
         AbstractResource ar = .get(c);
         if (ar == null) {
             ar = IntrospectionModeller.createResource(c);
             .put(car);
         }
 
         return ar;
     }
 
     private static class ContextInjectableProvider<T> extends
             SingletonTypeInjectableProvider<Context, T> {
         ContextInjectableProvider(Type type, T instance) {
             super(typeinstance);
         }
     }
 
     @Override
     public boolean isInitiated () {
         return ;
     }
 
     @Override
     public void initiate(ResourceConfig resourceConfig) {
         initiate(resourceConfignull);
     }
 
     @Override
     public void initiate(final ResourceConfig rcfinal IoCComponentProviderFactory _provider) {
         Errors.processWithErrors(new Errors.Closure<Void>() {
             @Override
             public Void f() {
                 Errors.setReportMissingDependentFieldOrMethod(false);
                 _initiate(rc_provider);
                 return null;
             }
         });
     }
 
     private void _initiate(final ResourceConfig rcfinal IoCComponentProviderFactory _provider) {
         if (rc == null) {
             throw new IllegalArgumentException("ResourceConfig instance MUST NOT be null");
         }
 
         if () {
             throw new ContainerException(ImplMessages.WEB_APP_ALREADY_INITIATED());
         }
         this. = true;
 
         .info("Initiating Jersey application, version '" + BuildId.getBuildId() + "'");
 
         // If there are components defined in jaxrs-components then
         // wrap resource config with appended set of classes
         Class<?>[] components = ServiceFinder.find("jersey-server-components").toClassArray();
         if (components.length > 0) {
             if (.isLoggable(.)) {
                 StringBuilder b = new StringBuilder();
                 b.append("Adding the following classes declared in META-INF/services/jersey-server-components to the resource configuration:");
                 for (Class c : components)
                     b.append('\n').append("  ").append(c);
                 .log(.b.toString());
             }
 
             this. = rc.clone();
             this..getClasses().addAll(Arrays.asList(components));
         } else {
             this. = rc;
         }
 
         this. = _provider;
 
         this. = new ArrayList<IoCComponentProviderFactory>(2);
 
         for (Object o : .getProviderSingletons()) {
             if (o instanceof IoCComponentProviderFactory) {
                 .add((IoCComponentProviderFactory)o);
             }
         }
 
         if (_provider != null)
             .add(_provider);
 
         // Set up the component provider factory to be
         // used with non-resource class components
         this. = (.isEmpty())
                 ? new ProviderFactory()
                 : new IoCProviderFactory();
 
         // Set up the resource component provider factory
         this. = (.isEmpty())
                 ? new ResourceFactory(this.this.)
                 : new IoCResourceFactory(this.this.);
 
         // Initiate IoCComponentProcessorFactoryInitializer
         for (IoCComponentProviderFactory f : ) {
             IoCComponentProcessorFactory cpf;
             if (f instanceof IoCComponentProcessorFactoryInitializer) {
                 cpf = new ComponentProcessorFactoryImpl();
                 i.init(cpf);
             }
 
         }
 
         this. = new ResourceContext() {
             @Override
             public ExtendedUriInfo matchUriInfo(URI uthrows ContainerException {
                 try {
                     return handleMatchResourceRequest(u);
                 } catch (ContainerException ex) {
                     throw ex;
                 } catch (WebApplicationException ex) {
                     if (ex.getResponse().getStatus() == 404) {
                         return null;
                     } else {
                         throw new ContainerException(ex);
                     }
                 } catch (RuntimeException ex) {
                     throw new ContainerException(ex);
                 }
             }
 
             @Override
             public Object matchResource(URI uthrows ContainerException {
                 ExtendedUriInfo ui = matchUriInfo(u);
                 return (ui != null) ? ui.getMatchedResources().get(0) : null;
             }
 
             @Override
             public <T> T matchResource(URI uClass<T> cthrows ContainerExceptionClassCastException {
                 return c.cast(matchResource(u));
             }
 
             @Override
             public <T> T getResource(Class<T> c) {
                 return c.cast(getResourceComponentProvider(c).getInstance());
             }
         };
 
         final ProviderServices providerServices = new ProviderServices(
                 ServerSide.class,
                 this.,
                 .getProviderClasses(),
                 .getProviderSingletons());
 
                 ProviderServices.classproviderServices));
 
                 ResourceMethodCustomInvokerDispatchFactory.classnew ResourceMethodCustomInvokerDispatchFactory(providerServices)));
 
         // Add injectable provider for @ParentRef
         .add(
                 new InjectableProvider<ParentRefType>() {
                     @Override
                     public ComponentScope getScope() {
                         return .;
                     }
 
                     @Override
                     public Injectable<ObjectgetInjectable(ComponentContext ccParentRef aType t) {
                         if (!(t instanceof Class))
                             return null;
 
                         final Class target = ReflectionHelper.getDeclaringClass(cc.getAccesibleObject());
                         final Class inject = (Class)t;
                         return new Injectable<Object>() {
                             @Override
                             public Object getValue() {
                                 final UriInfo ui = .getUriInfo();
                                 final List l = ui.getMatchedResources();
 
                                 final Object parent = getParent(ltarget);
                                 if (parent == nullreturn null;
                                 try {
                                     return inject.cast(parent);
                                 } catch (ClassCastException ex) {
                                     throw new ContainerException(
                                             "The parent resource is expected to be of class " + inject.getName() +
                                                     " but is of class " + parent.getClass().getName(),
                                             ex);
                                 }
                             }
 
                             private Object getParent(List lClass target) {
                                 if (l.isEmpty()) {
                                     return null;
                                 } else if (l.size() == 1) {
                                     return (l.get(0).getClass() == target) ? null : l.get(0);
                                 } else {
                                     return (l.get(0).getClass() == target) ? l.get(1) : l.get(0);
                                 }
                             }
                         };
                     }
 
 
                 });
 
         // Add injectable provider for @Inject
 
         .add(
                 new InjectableProvider<InjectType>() {
                     @Override
                     public ComponentScope getScope() {
                         return .;
                     }
 
                     @Override
                     public Injectable<ObjectgetInjectable(ComponentContext ccInject aType t) {
                         if (!(t instanceof Class))
                             return null;
 
                         final ResourceComponentProvider rcp = getResourceComponentProvider(cc, (Class)t);
 
                         return new Injectable<Object>() {
                             @Override
                             public Object getValue() {
                                 return rcp.getInstance();
                             }
                         };
                     }
 
                 });
 
         .add(
                 new InjectableProvider<InjectType>() {
                     @Override
                     public ComponentScope getScope() {
                         return .;
                     }
 
                     @Override
                     public Injectable<ObjectgetInjectable(ComponentContext ccInject aType t) {
                         if (!(t instanceof Class))
                             return null;
 
                         final ResourceComponentProvider rcp = getResourceComponentProvider(cc, (Class)t);
                         if (rcp.getScope() == .)
                             return null;
 
                         return new Injectable<Object>() {
                             @Override
                             public Object getValue() {
                                 return rcp.getInstance();
                             }
                         };
                     }
 
                 });
 
         .add(
                 new InjectableProvider<InjectType>() {
                     @Override
                     public ComponentScope getScope() {
                         return .;
                     }
 
                     @Override
                    public Injectable<ObjectgetInjectable(ComponentContext ccInject aType t) {
                        if (!(t instanceof Class))
                            return null;
                        final ResourceComponentProvider rcp = getResourceComponentProvider(cc, (Class)t);
                        if (rcp.getScope() != .)