incubator-wink-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From ngalla...@apache.org
Subject svn commit: r787557 [11/12] - in /incubator/wink/contrib/ibm-jaxrs: ./ lib/ src/ src/com/ src/com/ibm/ src/com/ibm/ws/ src/com/ibm/ws/jaxrs/ src/com/ibm/ws/jaxrs/annotations/ src/com/ibm/ws/jaxrs/context/ src/com/ibm/ws/jaxrs/core/ src/com/ibm/ws/jaxrs...
Date Tue, 23 Jun 2009 05:41:55 GMT
Added: incubator/wink/contrib/ibm-jaxrs/src/org/apache/cxf/jaxrs/utils/AnnotationUtils.java
URL: http://svn.apache.org/viewvc/incubator/wink/contrib/ibm-jaxrs/src/org/apache/cxf/jaxrs/utils/AnnotationUtils.java?rev=787557&view=auto
==============================================================================
--- incubator/wink/contrib/ibm-jaxrs/src/org/apache/cxf/jaxrs/utils/AnnotationUtils.java (added)
+++ incubator/wink/contrib/ibm-jaxrs/src/org/apache/cxf/jaxrs/utils/AnnotationUtils.java Tue Jun 23 05:41:49 2009
@@ -0,0 +1,399 @@
+/*
+ * 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.cxf.jaxrs.utils;
+
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Method;
+import java.util.HashSet;
+import java.util.Set;
+
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.CookieParam;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.DefaultValue;
+import javax.ws.rs.Encoded;
+import javax.ws.rs.FormParam;
+import javax.ws.rs.GET;
+import javax.ws.rs.HEAD;
+import javax.ws.rs.HeaderParam;
+import javax.ws.rs.HttpMethod;
+import javax.ws.rs.MatrixParam;
+import javax.ws.rs.POST;
+import javax.ws.rs.PUT;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.QueryParam;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.Request;
+import javax.ws.rs.core.SecurityContext;
+import javax.ws.rs.core.UriInfo;
+import javax.ws.rs.ext.ContextResolver;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.cxf.jaxrs.model.OperationResourceInfo;
+
+public final class AnnotationUtils {
+
+    private static final Log log = LogFactory.getLog(AnnotationUtils.class);
+
+    private static final Set<Class> CONTEXT_CLASSES;
+
+    private static final Set<Class> PARAM_ANNOTATION_CLASSES;
+
+    private static final Set<Class> METHOD_ANNOTATION_CLASSES;
+
+    private static final Set<Class<? extends Annotation>> RESOURCE_METHOD_ANNOTATION_CLASSES;
+    static {
+        CONTEXT_CLASSES = initContextClasses();
+        PARAM_ANNOTATION_CLASSES = initParamAnnotationClasses();
+        METHOD_ANNOTATION_CLASSES = initMethodAnnotationClasses();
+        RESOURCE_METHOD_ANNOTATION_CLASSES = initResourceMethodAnnotationClasses();
+    }
+
+    private AnnotationUtils() {
+
+    }
+
+    private static Set<Class> initContextClasses() {
+        Set<Class> classes = new HashSet<Class>();
+        classes.add(UriInfo.class);
+        classes.add(SecurityContext.class);
+        classes.add(HttpHeaders.class);
+        classes.add(ContextResolver.class);
+        classes.add(Request.class);
+        classes.add(HttpServletRequest.class);
+        classes.add(HttpServletResponse.class);
+        classes.add(ServletContext.class);
+        return classes;
+    }
+
+    private static Set<Class> initParamAnnotationClasses() {
+        Set<Class> classes = new HashSet<Class>();
+        classes.add(PathParam.class);
+        classes.add(QueryParam.class);
+        classes.add(MatrixParam.class);
+        classes.add(HeaderParam.class);
+        classes.add(CookieParam.class);
+        classes.add(FormParam.class);
+        classes.add(Context.class);
+        return classes;
+    }
+
+    private static Set<Class> initMethodAnnotationClasses() {
+        Set<Class> classes = new HashSet<Class>();
+        classes.add(HttpMethod.class);
+        classes.add(Path.class);
+        classes.add(Produces.class);
+        classes.add(Consumes.class);
+        return classes;
+    }
+
+    private static Set<Class<? extends Annotation>> initResourceMethodAnnotationClasses() {
+        Set<Class<? extends Annotation>> classes = new HashSet<Class<? extends Annotation>>();
+        classes.add(GET.class);
+        classes.add(POST.class);
+        classes.add(PUT.class);
+        classes.add(DELETE.class);
+        classes.add(HEAD.class);
+        return classes;
+    }
+
+    public static boolean isContextClass(Class<?> contextClass) {
+        return CONTEXT_CLASSES.contains(contextClass);
+    }
+
+    public static boolean isParamAnnotationClass(Class<?> annotationClass) {
+        return PARAM_ANNOTATION_CLASSES.contains(annotationClass);
+    }
+
+    public static boolean isMethodAnnotation(Annotation a) {
+        return METHOD_ANNOTATION_CLASSES.contains(a.annotationType())
+                || a.annotationType() == HttpMethod.class;
+    }
+
+    /**
+     * This method will indicate if a given annotation is a resource method
+     * indicator. True will be returned if the annotation type is annotated
+     * with the @HttpMethod annotation.
+     */
+    public static boolean isResourceMethodAnnotation(Annotation a) {
+        boolean resourceMethodAnnot = RESOURCE_METHOD_ANNOTATION_CLASSES
+                .contains(a.annotationType());
+        if (!resourceMethodAnnot) {
+            resourceMethodAnnot = a.annotationType().getAnnotation(
+                    HttpMethod.class) != null;
+        }
+        return resourceMethodAnnot;
+    }
+
+    /**
+     * This method will indicate if a given method is a subresource locator
+     * method. This is true if the method is annotated with the
+     *
+     * @Path annotation, but not with a resource method indicator.
+     *
+     */
+    public static boolean isSubResourceLocator(Method method) {
+        if (log.isDebugEnabled()) {
+            log.debug("isSubResourceLocator, method= " + method.getName());
+        }
+
+        boolean resourceFound = false;
+        boolean pathFound = false;
+        boolean result = false;
+        if (method.getAnnotations() != null) {
+            for (Annotation mAnnot : method.getAnnotations()) {
+                if (!resourceFound) {
+                    resourceFound = isResourceMethodAnnotation(mAnnot);
+                }
+                if (!pathFound) {
+                    pathFound = (mAnnot.annotationType() == Path.class);
+                }
+                if (resourceFound && pathFound) {
+                    break;
+                }
+            }
+        }
+        result = !resourceFound && pathFound;
+
+        if (log.isDebugEnabled()) {
+            log.debug("isSubResourceLocator, method= " + method.getName()
+                    + ", subResourceLocator= " + result);
+        }
+        return result;
+    }
+
+    /**
+     * This method will indicate if a given method is a resource method. This is
+     * true if the method is annotated with a resource method indicator and not
+     * the @Path annotation.
+     *
+     */
+    public static boolean isResourceMethod(Method method) {
+        if (log.isDebugEnabled()) {
+            log.debug("isResourceMethod, method= " + method.getName());
+        }
+
+        boolean resourceFound = false;
+        boolean pathFound = false;
+        boolean result = false;
+        if (method.getAnnotations() != null) {
+            for (Annotation mAnnot : method.getAnnotations()) {
+                if (!resourceFound) {
+                    resourceFound = isResourceMethodAnnotation(mAnnot);
+                }
+                if (!pathFound) {
+                    pathFound = (mAnnot.annotationType() == Path.class);
+                }
+                if (resourceFound && pathFound) {
+                    break;
+                }
+            }
+        }
+        result = resourceFound && !pathFound;
+
+        if (log.isDebugEnabled()) {
+            log.debug("isResourceMethod, method= " + method.getName()
+                    + ", isResourceMethod= " + result);
+        }
+        return result;
+    }
+
+    /**
+     * This method will indicate if a given method is a sub-resource method.
+     * This is true if the method is annotated with both a resource method
+     * indicator and the
+     *
+     * @Path annotation.
+     */
+    public static boolean isSubResourceMethod(Method method) {
+        if (log.isDebugEnabled()) {
+            log.debug("isSubResourceMethod, method= " + method.getName());
+        }
+
+        boolean resourceFound = false;
+        boolean pathFound = false;
+        boolean result = false;
+        if (method.getAnnotations() != null) {
+            for (Annotation mAnnot : method.getAnnotations()) {
+                if (!resourceFound) {
+                    resourceFound = isResourceMethodAnnotation(mAnnot);
+                }
+                if (!pathFound) {
+                    pathFound = (mAnnot.annotationType() == Path.class);
+                }
+                if (resourceFound && pathFound) {
+                    break;
+                }
+            }
+        }
+        result = resourceFound && pathFound;
+
+        if (log.isDebugEnabled()) {
+            log.debug("isResourceMethod, method= " + method.getName()
+                    + ", isSubResourceMethod= " + result);
+        }
+        return result;
+    }
+
+    public static String getAnnotationValue(Annotation a) {
+        if (a.annotationType() == PathParam.class) {
+            return ((PathParam) a).value();
+        } else if (a.annotationType() == QueryParam.class) {
+            return ((QueryParam) a).value();
+        } else if (a.annotationType() == MatrixParam.class) {
+            return ((MatrixParam) a).value();
+        } else if (a.annotationType() == HeaderParam.class) {
+            return ((HeaderParam) a).value();
+        } else if (a.annotationType() == CookieParam.class) {
+            return ((CookieParam) a).value();
+        } else if (a.annotationType() == FormParam.class) {
+            return ((FormParam) a).value();
+        }
+        return null;
+    }
+
+    @SuppressWarnings("unchecked")
+    public static <T> T getAnnotation(Annotation[] anns, Class<T> type) {
+        if (anns == null) {
+            return null;
+        }
+        for (Annotation a : anns) {
+            if (a.annotationType() == type) {
+                return (T) a;
+            }
+        }
+        return null;
+    }
+
+    public static Method getAnnotatedMethod(Method m) {
+        if (m == null) {
+            return m;
+        }
+        for (Annotation a : m.getAnnotations()) {
+            if (AnnotationUtils.isMethodAnnotation(a)) {
+                return m;
+            }
+        }
+        for (Annotation[] paramAnnotations : m.getParameterAnnotations()) {
+            for (Annotation a : paramAnnotations) {
+                if (AnnotationUtils.isParamAnnotationClass(a.annotationType())) {
+                    return m;
+                }
+            }
+        }
+
+        Class<?> superC = m.getDeclaringClass().getSuperclass();
+        if (superC != null) {
+            try {
+                Method method = getAnnotatedMethod(superC.getMethod(
+                        m.getName(), m.getParameterTypes()));
+                if (method != null) {
+                    return method;
+                }
+            } catch (NoSuchMethodException ex) {
+                // ignore
+            }
+        }
+        for (Class<?> i : m.getDeclaringClass().getInterfaces()) {
+            try {
+                Method method = getAnnotatedMethod(i.getMethod(m.getName(), m
+                        .getParameterTypes()));
+                if (method != null) {
+                    return method;
+                }
+            } catch (NoSuchMethodException ex) {
+                // ignore
+            }
+        }
+        return m;
+    }
+
+    public static String getHttpMethodValue(Method m) {
+        for (Annotation a : m.getAnnotations()) {
+            HttpMethod httpM = a.annotationType().getAnnotation(
+                    HttpMethod.class);
+            if (httpM != null) {
+                return httpM.value();
+            }
+        }
+        return null;
+    }
+
+    public static Annotation getMethodAnnotation(Method m, Class<? extends Annotation> aClass) {
+        return m == null ? null : m.getAnnotation(aClass);
+    }
+
+    public static Annotation getClassAnnotation(Class<?> c, Class<? extends Annotation> aClass) {
+        if (c == null) {
+            return null;
+        }
+        Annotation p = c.getAnnotation(aClass);
+        if (p != null) {
+            return p;
+        }
+
+        p = getClassAnnotation(c.getSuperclass(), aClass);
+        if (p != null) {
+            return p;
+        }
+
+        // finally try the first one on the interface
+        for (Class<?> i : c.getInterfaces()) {
+            p = getClassAnnotation(i, aClass);
+            if (p != null) {
+                return p;
+            }
+        }
+        return null;
+    }
+
+    public static boolean isEncoded(Annotation[] anns, OperationResourceInfo ori) {
+
+        if (AnnotationUtils.getAnnotation(anns, Encoded.class) != null) {
+            return true;
+        }
+
+        if (ori == null) {
+            return false;
+        }
+        return ori.isEncodedEnabled();
+    }
+
+    public static String getDefaultParameterValue(Annotation[] anns, OperationResourceInfo ori) {
+
+        DefaultValue dv = AnnotationUtils.getAnnotation(anns,
+                DefaultValue.class);
+        if (dv != null) {
+            return dv.value();
+        }
+
+        if (ori == null) {
+            return null;
+        }
+        return ori.getDefaultParameterValue();
+    }
+}

Added: incubator/wink/contrib/ibm-jaxrs/src/org/apache/cxf/jaxrs/utils/HttpUtils.java
URL: http://svn.apache.org/viewvc/incubator/wink/contrib/ibm-jaxrs/src/org/apache/cxf/jaxrs/utils/HttpUtils.java?rev=787557&view=auto
==============================================================================
--- incubator/wink/contrib/ibm-jaxrs/src/org/apache/cxf/jaxrs/utils/HttpUtils.java (added)
+++ incubator/wink/contrib/ibm-jaxrs/src/org/apache/cxf/jaxrs/utils/HttpUtils.java Tue Jun 23 05:41:49 2009
@@ -0,0 +1,77 @@
+/*
+ * 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.cxf.jaxrs.utils;
+
+import java.net.URI;
+import java.util.List;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.core.PathSegment;
+
+import org.apache.cxf.jaxrs.impl.PathSegmentImpl;
+
+import com.ibm.ws.jaxrs.context.ContextConstants;
+import com.ibm.ws.jaxrs.context.RESTContext;
+
+public final class HttpUtils {
+    private static final String LOCAL_IP_ADDRESS = "127.0.0.1";
+    private static final String LOCAL_HOST = "localhost";
+
+    private HttpUtils() {
+    }
+
+    public static URI toAbsoluteUri(URI u, RESTContext context) {
+        if (!u.isAbsolute()) {
+            HttpServletRequest httpRequest = (HttpServletRequest) context
+                    .getProperty(ContextConstants.SERVLET_REQUEST);
+            if (httpRequest != null) {
+                String scheme = httpRequest.isSecure() ? "https" : "http";
+                String host = httpRequest.getLocalName();
+                if (LOCAL_IP_ADDRESS.equals(host)) {
+                    host = LOCAL_HOST;
+                }
+                int port = httpRequest.getLocalPort();
+                return URI.create(scheme + "://" + host + ':' + port
+                        + u.toString());
+            }
+        }
+        return u;
+    }
+
+    public static String fromPathSegment(PathSegment ps) {
+        if (PathSegmentImpl.class.isAssignableFrom(ps.getClass())) {
+            return ((PathSegmentImpl) ps).getOriginalPath();
+        }
+        StringBuilder sb = new StringBuilder();
+        sb.append(ps.getPath());
+        for (Map.Entry<String, List<String>> entry : ps.getMatrixParameters()
+                .entrySet()) {
+            for (String value : entry.getValue()) {
+                sb.append(';').append(entry.getKey());
+                if (value != null) {
+                    sb.append('=').append(value);
+                }
+            }
+        }
+        return sb.toString();
+    }
+
+}

Added: incubator/wink/contrib/ibm-jaxrs/src/org/apache/cxf/jaxrs/utils/InjectionUtils.java
URL: http://svn.apache.org/viewvc/incubator/wink/contrib/ibm-jaxrs/src/org/apache/cxf/jaxrs/utils/InjectionUtils.java?rev=787557&view=auto
==============================================================================
--- incubator/wink/contrib/ibm-jaxrs/src/org/apache/cxf/jaxrs/utils/InjectionUtils.java (added)
+++ incubator/wink/contrib/ibm-jaxrs/src/org/apache/cxf/jaxrs/utils/InjectionUtils.java Tue Jun 23 05:41:49 2009
@@ -0,0 +1,787 @@
+/*
+ * 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.cxf.jaxrs.utils;
+
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Proxy;
+import java.lang.reflect.Type;
+import java.net.URLDecoder;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.SortedSet;
+import java.util.TreeSet;
+import java.util.WeakHashMap;
+
+import javax.servlet.ServletConfig;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.ws.rs.CookieParam;
+import javax.ws.rs.DefaultValue;
+import javax.ws.rs.Encoded;
+import javax.ws.rs.FormParam;
+import javax.ws.rs.HeaderParam;
+import javax.ws.rs.MatrixParam;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.QueryParam;
+import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.PathSegment;
+import javax.ws.rs.core.Request;
+import javax.ws.rs.core.SecurityContext;
+import javax.ws.rs.core.UriInfo;
+import javax.ws.rs.ext.ContextResolver;
+import javax.ws.rs.ext.Providers;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.cxf.common.util.PrimitiveUtils;
+import org.apache.cxf.jaxrs.impl.MetadataMap;
+import org.apache.cxf.jaxrs.impl.PathSegmentImpl;
+import org.apache.cxf.jaxrs.impl.tl.ThreadLocalHttpHeaders;
+import org.apache.cxf.jaxrs.impl.tl.ThreadLocalHttpServletRequest;
+import org.apache.cxf.jaxrs.impl.tl.ThreadLocalProxy;
+import org.apache.cxf.jaxrs.impl.tl.ThreadLocalRequest;
+import org.apache.cxf.jaxrs.impl.tl.ThreadLocalSecurityContext;
+import org.apache.cxf.jaxrs.impl.tl.ThreadLocalUriInfo;
+import org.apache.cxf.jaxrs.model.AbstractResourceInfo;
+import org.apache.cxf.jaxrs.model.OperationResourceInfo;
+
+import com.ibm.ws.jaxrs.context.ContextConstants;
+import com.ibm.ws.jaxrs.context.RESTContext;
+import com.ibm.ws.jaxrs.injection.ThreadLocalContextResolver;
+import com.ibm.ws.jaxrs.injection.ThreadLocalHttpServletResponse;
+import com.ibm.ws.jaxrs.injection.ThreadLocalProviders;
+import com.ibm.ws.jaxrs.injection.ThreadLocalServletConfig;
+import com.ibm.ws.jaxrs.injection.ThreadLocalServletContext;
+
+public final class InjectionUtils {
+
+    private InjectionUtils() {
+
+    }
+
+    private static Log log = LogFactory.getLog(InjectionUtils.class);
+
+    public static Method checkProxy(Method methodToInvoke, Object resourceObject) {
+        if (Proxy.class.isInstance(resourceObject)) {
+
+            for (Class<?> c : resourceObject.getClass().getInterfaces()) {
+                try {
+                    Method m = c.getMethod(methodToInvoke.getName(),
+                            methodToInvoke.getParameterTypes());
+                    if (m != null) {
+                        return m;
+                    }
+                } catch (NoSuchMethodException ex) {
+                    //ignore
+                }
+            }
+
+        }
+        return methodToInvoke;
+    }
+
+    @SuppressWarnings("unchecked")
+    public static void injectFieldValue(final Field f, final Object o, final Object v) {
+        AccessController.doPrivileged(new PrivilegedAction() {
+            public Object run() {
+                f.setAccessible(true);
+                try {
+                    f.set(o, v);
+                    if (log.isDebugEnabled()) {
+                        log.debug("Injected the " + f.getName()
+                                + " field, in the "
+                                + f.getDeclaringClass().getName()
+                                + " class with the value: " + v);
+                    }
+                } catch (IllegalAccessException ex) {
+                    throw new WebApplicationException(ex);
+                }
+                return null;
+            }
+        });
+
+    }
+
+    public static Class<?> getActualType(Type genericType) {
+        if (genericType == null
+                || !ParameterizedType.class.isAssignableFrom(genericType
+                        .getClass())) {
+            return null;
+        }
+        ParameterizedType paramType = (ParameterizedType) genericType;
+        return (Class<?>) paramType.getActualTypeArguments()[0];
+    }
+
+    public static void injectThroughMethod(Object requestObject, Method method, Object parameterValue) {
+        try {
+            Method methodToInvoke = checkProxy(method, requestObject);
+            methodToInvoke.invoke(requestObject,
+                    new Object[] { parameterValue });
+            if (log.isDebugEnabled()) {
+                log.debug("Injected the " + method.getName()
+                        + " method, in the "
+                        + method.getDeclaringClass().getName()
+                        + " class with the value: " + parameterValue);
+            }
+        } catch (Exception ex) {
+            throw new WebApplicationException(ex);
+        }
+    }
+
+    /**
+     * This method will drive the injection of a member that is requesting injection
+     * via an annotation other than the @Context annotation.
+     *
+     * This method returns null if the parameter should not or cannot be injected.
+     */
+    public static Object handleNonContextParam(Class<?> pClass, Type genericType, RESTContext context, Annotation... annotations)
+            throws Exception {
+        Object instance = null;
+        List<String> values = null;
+        boolean isEncoded = AnnotationUtils.isEncoded(annotations,
+                (OperationResourceInfo) context
+                        .getProperty(ContextConstants.OPERATION_RESOURCE));
+        DefaultValue defaultValue = getDefaultValueAnnotation(annotations);
+        boolean isHeaderOrCookieParam = false;
+        boolean isJAXRSAnnotationFound = false;
+
+        if (log.isDebugEnabled()) {
+            log.debug("Processing non-context param: " + pClass.getName());
+            log.debug("    encoded = " + isEncoded);
+            if (defaultValue != null)
+                log.debug("    default value = " + defaultValue.value());
+        }
+
+        for (Annotation annotation : annotations) {
+            Class<? extends Annotation> annoType = annotation.annotationType();
+            if (annoType.equals(QueryParam.class)) {
+                String queryId = ((QueryParam) annotation).value();
+                String propertyName = isEncoded ? ContextConstants.QUERY_STRING_ENCODED_VALUES
+                        : ContextConstants.QUERY_STRING_DECODED_VALUES;
+                MultivaluedMap<String, String> queryValues = (MultivaluedMap<String, String>) context
+                        .getProperty(propertyName);
+                values = queryValues != null ? queryValues.get(queryId) : null;
+                isJAXRSAnnotationFound = true;
+                break;
+            } else if (annoType.equals(HeaderParam.class)) {
+                String headerId = ((HeaderParam) annotation).value();
+                MultivaluedMap<String, String> headerValues = (MultivaluedMap<String, String>) context
+                        .getProperty(ContextConstants.HTTP_HEADER_VALUES);
+                headerId = headerId.toLowerCase();
+                values = headerValues != null ? headerValues.get(headerId)
+                        : null;
+                isHeaderOrCookieParam = true;
+                isJAXRSAnnotationFound = true;
+                break;
+            } else if (annoType.equals(MatrixParam.class)) {
+                String matrixParamId = ((MatrixParam) annotation).value();
+                String propertyName = isEncoded ? ContextConstants.MATRIX_PARAMETER_VALUES_ENCODED
+                        : ContextConstants.MATRIX_PARAMETER_VALUES_DECODED;
+                MultivaluedMap<String, String> matrixValues = (MultivaluedMap<String, String>) context
+                        .getProperty(propertyName);
+                values = matrixValues != null ? matrixValues.get(matrixParamId)
+                        : null;
+                isJAXRSAnnotationFound = true;
+                break;
+            } else if (annoType.equals(FormParam.class)) {
+                String formParamId = ((FormParam) annotation).value();
+
+                // set the form parameters
+                MultivaluedMap<String, String> formValues = null;
+                if (context.getProperty(ContextConstants.FORM_VALUES) == null) {
+                    HttpServletRequest servletRequest = (HttpServletRequest) context
+                            .getProperty(ContextConstants.SERVLET_REQUEST);
+                    if (servletRequest != null) {
+                        Map<String, List<String>> formParams = getFormParameters(servletRequest);
+                        formValues = new MetadataMap<String, String>(formParams);
+                        context.setProperty(ContextConstants.FORM_VALUES,
+                                formValues);
+                    }
+                } else {
+                    formValues = new MetadataMap<String, String>(
+                            (Map<String, List<String>>) context
+                                    .getProperty(ContextConstants.FORM_VALUES));
+                }
+
+                values = formValues != null ? formValues.get(formParamId)
+                        : null;
+                if (!isEncoded) {
+                    decodeValues(values);
+                }
+                OperationResourceInfo ori = (OperationResourceInfo) context
+                        .getProperty(ContextConstants.OPERATION_RESOURCE);
+                if (ori != null) {
+                    ori.setIsFormParamFound(true);
+                }
+                isJAXRSAnnotationFound = true;
+                break;
+            } else if (annoType.equals(PathParam.class)) {
+                String pathParamId = ((PathParam) annotation).value();
+                MultivaluedMap<String, String> pathValues = (MultivaluedMap<String, String>) context
+                        .getProperty(ContextConstants.TEMPLATE_VALUES);
+
+                if (log.isDebugEnabled()) {
+                    log.debug("Param id: " + pathParamId);
+                    if (pathValues != null)
+                        log.debug("Available ids: " + pathValues.keySet());
+                }
+
+                values = pathValues != null ? pathValues.get(pathParamId)
+                        : null;
+                if (values == null) {
+                    values = new ArrayList<String>();
+                    values.add(pathParamId);
+                } else {
+                    /*
+                     * make a copy of the arraylist so any changes won't affect
+                     * UriInfo getPathParameters calls
+                     */
+                    values = new ArrayList<String>(values);
+                }
+
+                if (log.isDebugEnabled()) {
+                    log.debug("Found param value: " + values);
+                }
+
+                if (!isEncoded) {
+                    decodeValues(values);
+                }
+                isJAXRSAnnotationFound = true;
+                break;
+            } else if (annoType.equals(CookieParam.class)) {
+                String cookieId = ((CookieParam) annotation).value();
+                Map<String, javax.ws.rs.core.Cookie> cookies = (Map<String, javax.ws.rs.core.Cookie>) context
+                        .getProperty(ContextConstants.HTTP_COOKIES);
+
+                // if the parameter is of type Cookie we need to set the String value to
+                // the value of the cookie in the HTTP request, otherwise, we will simply
+                // set the value to the result of 'getValue' on the Cookie object
+                boolean useHttpValue = javax.ws.rs.core.Cookie.class
+                        .isAssignableFrom(pClass);
+
+                if (cookies != null && cookies.get(cookieId) != null) {
+                    javax.ws.rs.core.Cookie cookie = cookies.get(cookieId);
+                    values = new ArrayList<String>();
+
+                    // if we need to get the actual cookie header value, we will need to
+                    // retrieve it from the headers map
+                    if (useHttpValue) {
+                        MultivaluedMap<String, String> headers = (MultivaluedMap<String, String>) context
+                                .getProperty(ContextConstants.HTTP_HEADER_VALUES);
+                        String cookieHeader = headers != null ? headers
+                                .getFirst("Cookie") : null;
+                        if (cookieHeader != null
+                                && cookieHeader.contains(cookieId + "=")) {
+                            values.add(cookieHeader);
+                        }
+                    } else {
+                        values.add(cookie.getValue());
+                    }
+                }
+                isHeaderOrCookieParam = true;
+                isJAXRSAnnotationFound = true;
+                break;
+            }
+        }
+
+        if (!isJAXRSAnnotationFound) {
+            // couldn't find a JAX-RS annotation so should not inject even if there's
+            // a @DefaultValue or it matches a Java primitive type
+            return null;
+        }
+
+        // check for the @DefaultValue value if it was specified
+        if ((values == null || values.isEmpty()) && (defaultValue != null)) {
+            if (values == null) {
+                values = new ArrayList<String>();
+            }
+            if (log.isDebugEnabled()) {
+                log.debug("For the parameter type: " + pClass.getName()
+                        + " injecting " + "default value: "
+                        + defaultValue.value());
+            }
+            values.add(defaultValue.value());
+        }
+
+        if (values != null && !values.isEmpty()) {
+
+            // handle the injection based on the type of the parameter
+            if (List.class.isAssignableFrom(pClass)) {
+                instance = injectIntoList(genericType, values, !isEncoded,
+                        isHeaderOrCookieParam);
+            } else if (Set.class.isAssignableFrom(pClass)
+                    || SortedSet.class.isAssignableFrom(pClass)) {
+                boolean sorted = SortedSet.class.isAssignableFrom(pClass);
+                instance = injectIntoSet(genericType, values, sorted,
+                        !isEncoded, isHeaderOrCookieParam);
+            } else if (PathSegment.class.isAssignableFrom(pClass)) {
+                String value = values.get(0);
+                instance = new PathSegmentImpl(value, isEncoded);
+            } else {
+                try {
+                    String value = values.get(0);
+                    instance = handleParameter(value, pClass,
+                            isHeaderOrCookieParam);
+                } catch (Exception e) {
+                    if (e instanceof WebApplicationException) {
+                        throw e;
+                    }
+                    if (isHeaderOrCookieParam) {
+                        throw new WebApplicationException(e, 400);
+                    }
+                    throw new WebApplicationException(e, 404);
+                }
+            }
+        }
+        if (instance == null) {
+            instance = insertJavaDefault(pClass);
+        }
+        return instance;
+    }
+
+    /**
+     * This method returns the Java-defined default value for the given class type.
+     *
+     */
+    static Object insertJavaDefault(Class<?> paramClass) {
+        if (paramClass.isPrimitive()) {
+            if (Boolean.TYPE.equals(paramClass)) {
+                return Boolean.FALSE;
+            } else if (Character.TYPE.equals(paramClass)) {
+                return new Character('\u0000');
+            } else if (Byte.TYPE.equals(paramClass)) {
+                return new Byte((byte) 0);
+            } else if (Short.TYPE.equals(paramClass)) {
+                return new Short((short) 0);
+            } else if (Integer.TYPE.equals(paramClass)) {
+                return new Integer(0);
+            } else if (Long.TYPE.equals(paramClass)) {
+                return new Long(0L);
+            } else if (Float.TYPE.equals(paramClass)) {
+                return new Float(0.0f);
+            } else if (Double.TYPE.equals(paramClass)) {
+                return new Double(0.0d);
+            }
+        } else if (Set.class.equals(paramClass)) {
+            return Collections.emptySet();
+        } else if (List.class.equals(paramClass)) {
+            return Collections.emptyList();
+        }
+        return null;
+    }
+
+    /**
+     * This method will decode a list of string values.
+     *
+     */
+    static void decodeValues(List<String> values) {
+        if (values != null && !values.isEmpty()) {
+            try {
+                for (int i = 0; i < values.size(); i++) {
+                    String value = values.remove(i);
+                    value = URLDecoder.decode(value, "UTF-8");
+                    values.add(i, value);
+                }
+            } catch (Exception e) {
+                throw new WebApplicationException(e);
+            }
+        }
+    }
+
+    /**
+     * This method will search an array of annotations for an instance of the
+     * @DefaultValue annotation. If that is found, the instance will be returned,
+     * otherwise null will be returned.
+     *
+     */
+    static DefaultValue getDefaultValueAnnotation(Annotation... annotations) {
+        DefaultValue dValueAnnot = null;
+        if (annotations != null) {
+            for (Annotation annotation : annotations) {
+                if (annotation.annotationType().equals(DefaultValue.class)) {
+                    dValueAnnot = (DefaultValue) annotation;
+                    break;
+                }
+            }
+        }
+        return dValueAnnot;
+    }
+
+    /**
+     * This method will determine if the @Encoded annotation is present in a
+     * supplied array of annotations.
+     */
+    static boolean getEncodedAnnotValue(Annotation... annotations) {
+        boolean encodedPresent = false;
+
+        for (Annotation annotation : annotations) {
+            if (annotation.annotationType().equals(Encoded.class)) {
+                encodedPresent = true;
+                break;
+            }
+        }
+
+        return encodedPresent;
+    }
+
+    public static Object handleParameter(String value, Class<?> pClass, boolean isHeaderOrCookieParam) {
+        if (pClass.isPrimitive()) {
+            return PrimitiveUtils.read(value, pClass);
+        }
+        // check constructors accepting a single String value
+        Constructor<?> c = null;
+        try {
+            c = pClass.getConstructor(new Class<?>[] { String.class });
+        } catch (Exception ex) {
+            // try valueOf
+        }
+
+        if (c != null) {
+            if (log.isDebugEnabled()) {
+                log.debug("Injecting the " + value
+                        + " value into parameter type: " + pClass.getName());
+            }
+            try {
+                return c.newInstance(new Object[] { value });
+            } catch (Exception ex) {
+                if (ex instanceof InvocationTargetException) {
+                    InvocationTargetException ite = (InvocationTargetException) ex;
+                    if (ite.getCause() != null
+                            && ite.getCause() instanceof Exception) {
+                        ex = (Exception) ite.getCause();
+                    }
+                    /*
+                     * If ite.getCause() is an error, it should have been thrown
+                     * as an error already
+                     */
+                }
+                if (ex instanceof WebApplicationException) {
+                    throw (WebApplicationException) ex;
+                }
+                if (isHeaderOrCookieParam) {
+                    throw new WebApplicationException(ex, 400);
+                }
+                throw new WebApplicationException(ex, 404);
+            }
+        }
+
+        // check for valueOf(String) static methods
+        Method m = null;
+        try {
+            m = pClass.getMethod("valueOf", new Class<?>[] { String.class });
+        } catch (Exception ex) {
+            // no luck
+            ex.printStackTrace();
+        }
+        if (m != null && Modifier.isStatic(m.getModifiers())) {
+            if (log.isDebugEnabled()) {
+                log.debug("Injecting the " + value
+                        + " value into parameter type: " + pClass.getName()
+                        + " by the 'valueOf' method");
+            }
+            try {
+                return m.invoke(null, new Object[] { value });
+            } catch (Exception ex) {
+                if (ex instanceof InvocationTargetException) {
+                    InvocationTargetException ite = (InvocationTargetException) ex;
+                    if (ite.getCause() != null
+                            && ite.getCause() instanceof Exception) {
+                        ex = (Exception) ite.getCause();
+                    }
+                    /*
+                     * If ite.getCause() is an error, it should have been thrown
+                     * as an error already
+                     */
+                }
+                if (ex instanceof WebApplicationException) {
+                    throw (WebApplicationException) ex;
+                }
+
+                if (isHeaderOrCookieParam) {
+                    throw new WebApplicationException(ex, 400);
+                }
+                throw new WebApplicationException(ex, 404);
+            }
+        }
+        return null;
+    }
+
+    @SuppressWarnings("unchecked")
+    public static Object injectIntoList(Type genericType, List<String> values, boolean decoded, boolean isHeaderOrCookieParam) {
+        Class<?> realType = InjectionUtils.getActualType(genericType);
+        List theValues = new ArrayList();
+        for (String r : values) {
+            if (decoded) {
+                r = JAXRSUtils.uriDecode(r);
+            }
+            Object o = InjectionUtils.handleParameter(r, realType,
+                    isHeaderOrCookieParam);
+            if (o != null) {
+                theValues.add(o);
+            }
+        }
+        return theValues;
+    }
+
+    @SuppressWarnings("unchecked")
+    public static Object injectIntoSet(Type genericType, List<String> values, boolean sorted, boolean decoded, boolean isHeaderOrCookieParam) {
+        Class<?> realType = InjectionUtils.getActualType(genericType);
+        Set theValues = sorted ? new TreeSet() : new HashSet();
+        for (String r : values) {
+            if (decoded) {
+                r = JAXRSUtils.uriDecode(r);
+            }
+            Object o = InjectionUtils.handleParameter(r, realType,
+                    isHeaderOrCookieParam);
+            if (o != null) {
+                theValues.add(o);
+            }
+        }
+        return theValues;
+    }
+
+    public static ThreadLocalProxy createThreadLocalProxy(Class<?> type) {
+        ThreadLocalProxy proxy = null;
+        if (UriInfo.class.equals(type)) {
+            proxy = new ThreadLocalUriInfo();
+        } else if (HttpHeaders.class.equals(type)) {
+            proxy = new ThreadLocalHttpHeaders();
+        } else if (SecurityContext.class.equals(type)) {
+            proxy = new ThreadLocalSecurityContext();
+        } else if (Request.class.equals(type)) {
+            proxy = new ThreadLocalRequest();
+        } else if (HttpServletRequest.class.equals(type)) {
+            proxy = new ThreadLocalHttpServletRequest();
+        } else if (HttpServletResponse.class.equals(type)) {
+            proxy = new ThreadLocalHttpServletResponse();
+        } else if (ServletContext.class.equals(type)) {
+            proxy = new ThreadLocalServletContext();
+        } else if (ServletConfig.class.equals(type)) {
+            proxy = new ThreadLocalServletConfig();
+        } else if (ContextResolver.class.equals(type)) {
+            proxy = new ThreadLocalContextResolver();
+        } else if (Providers.class.equals(type)) {
+            proxy = new ThreadLocalProviders();
+        }
+        return proxy;
+    }
+
+    /**
+     * This will drive injection of the fields and methods of a REST resource instance.
+     *
+     */
+    public static void injectResourceBeanFields(Object instance, AbstractResourceInfo info, RESTContext context)
+            throws Exception {
+        Class<?> clazz = info.getServiceClass();
+        injectBeanFields(context, instance, clazz.getDeclaredFields());
+
+    }
+
+    /**
+     * This will drive injection of the fields and methods of a REST resource instance.
+     *
+     */
+    public static void injectResourceBeanMethods(Object instance, AbstractResourceInfo info, RESTContext context)
+            throws Exception {
+        Class<?> clazz = info.getServiceClass();
+        injectBeanMethods(context, instance, clazz.getDeclaredMethods());
+    }
+
+    /**
+     * This method will drive the injection of values indicated by annotations
+     * found at the method level of a resource class.
+     *
+     */
+    static void injectBeanFields(RESTContext context, Object resourceInstance, Field... fields)
+            throws Exception {
+        for (Field field : fields) {
+            Object instance = handleNonContextParam(field.getType(), field
+                    .getGenericType(), context, field.getAnnotations());
+            if (instance != null) {
+                injectFieldValue(field, resourceInstance, instance);
+            }
+        }
+    }
+
+    /**
+     * This method will drive the injection of values indicated by annotations
+     * found at the method level of a resource class.
+     *
+     */
+    static void injectBeanMethods(RESTContext context, Object resourceInstance, Method... methods)
+            throws Exception {
+        for (Method method : methods) {
+            if (method.getParameterTypes().length > 0) {
+                Class<?> paramType = method.getParameterTypes()[0];
+                Type genericType = null;
+                if (method.getGenericParameterTypes().length != 0) {
+                    genericType = method.getGenericParameterTypes()[0];
+                }
+                Object instance = handleNonContextParam(paramType, genericType,
+                        context, getAnnotations(method));
+                if (instance != null) {
+                    injectThroughMethod(resourceInstance, method, instance);
+                }
+            }
+        }
+    }
+
+    // Cache for Annotations for a method
+    private static WeakHashMap<Method, Annotation[]> annoMethodMap = new WeakHashMap<Method, Annotation[]>();
+
+    private static Annotation[] getAnnotations(Method method) {
+        Annotation[] annotations = annoMethodMap.get(method);
+        if (annotations == null) {
+            annotations = method.getAnnotations();
+            annoMethodMap.put(method, annotations);
+        }
+        return annotations;
+    }
+
+    public static void injectContextProxies(AbstractResourceInfo cri, Object instance) {
+
+        if (!cri.isSingleton()) {
+            return;
+        }
+
+        for (Map.Entry<Class<?>, Method> entry : cri.getContextMethods()
+                .entrySet()) {
+            ThreadLocalProxy proxy = cri
+                    .getContextSetterProxy(entry.getValue());
+            if (log.isDebugEnabled()) {
+                log.debug("Injecting ThreadLocalProxy: " + proxy
+                        + " into method: " + entry.getValue().getName()
+                        + " in the class: " + instance.getClass().getName());
+            }
+            InjectionUtils.injectThroughMethod(instance, entry.getValue(),
+                    proxy);
+        }
+
+        for (Field f : cri.getContextFields()) {
+            ThreadLocalProxy proxy = cri.getContextFieldProxy(f);
+            if (log.isDebugEnabled()) {
+                log.debug("Injecting ThreadLocalProxy: " + proxy
+                        + " into method: " + f.getName() + " in the class: "
+                        + instance.getClass().getName());
+            }
+            InjectionUtils.injectFieldValue(f, instance, proxy);
+        }
+    }
+
+    @SuppressWarnings("unchecked")
+    private static void injectEnvironmentOrContextField(AbstractResourceInfo cri, Field f, Object o, Object value, boolean isEnviornmentField) {
+        if (!cri.isSingleton()) {
+            InjectionUtils.injectFieldValue(f, o, value);
+        } else {
+            ThreadLocalProxy proxy = isEnviornmentField ? cri
+                    .getResourceFieldProxy(f) : cri.getContextFieldProxy(f);
+            if (proxy != null) {
+                proxy.set(value);
+            }
+        }
+    }
+
+    @SuppressWarnings("unchecked")
+    public static void injectContextMethods(Object requestObject, AbstractResourceInfo cri, RESTContext context) {
+        for (Map.Entry<Class<?>, Method> entry : cri.getContextMethods()
+                .entrySet()) {
+            Object o = JAXRSUtils.createContextValue(context, entry.getValue()
+                    .getGenericParameterTypes()[0], entry.getKey());
+
+            if (o != null) {
+                if (!cri.isSingleton()) {
+                    InjectionUtils.injectThroughMethod(requestObject, entry
+                            .getValue(), o);
+                } else {
+                    ThreadLocalProxy proxy = cri.getContextSetterProxy(entry
+                            .getValue());
+                    if (proxy != null) {
+                        proxy.set(o);
+                    }
+                }
+
+            }
+        }
+    }
+
+    public static void injectContextFields(Object o, AbstractResourceInfo cri, RESTContext context) {
+        for (Field f : cri.getContextFields()) {
+            Object value = JAXRSUtils.createContextValue(context, f
+                    .getGenericType(), f.getType());
+            InjectionUtils.injectEnvironmentOrContextField(cri, f, o, value,
+                    false);
+        }
+    }
+
+    public static void injectEnvironmentFields(Object o, AbstractResourceInfo cri, RESTContext context) {
+        /*
+         * resource fields in this instance are only the ones marked with @Resource (Java EE 6).  this work is not completed 
+         */
+        for (Field f : cri.getResourceFields()) {
+
+            Object value = JAXRSUtils.createServletResourceValue(context, f
+                    .getType());
+            InjectionUtils.injectEnvironmentOrContextField(cri, f, o, value,
+                    true);
+        }
+    }
+
+    /**
+     * This method retrieves all the parameters and establishes a multivalued map
+     * that is stored on the RESTContext.
+     *
+     */
+    private static Map<String, List<String>> getFormParameters(HttpServletRequest request) {
+        Map<String, List<String>> formParams = new HashMap<String, List<String>>();
+        Enumeration paramNames = request.getParameterNames();
+        if (paramNames != null) {
+            while (paramNames.hasMoreElements()) {
+                String paramName = (String) paramNames.nextElement();
+                String[] paramValues = request.getParameterValues(paramName);
+                if (paramValues != null) {
+                    List<String> paramValueList = new ArrayList<String>(
+                            paramValues.length);
+                    formParams.put(paramName, paramValueList);
+                    for (String paramValue : paramValues) {
+                        paramValueList.add(paramValue);
+                    }
+                }
+            }
+        }
+        return formParams;
+    }
+}



Mime
View raw message