You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cxf.apache.org by se...@apache.org on 2009/01/15 19:18:03 UTC
svn commit: r734772 - in /cxf/trunk:
rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/
rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/
rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/interceptor/
rt/frontend/jaxrs/src/main/java/org/a...
Author: sergeyb
Date: Thu Jan 15 10:18:02 2009
New Revision: 734772
URL: http://svn.apache.org/viewvc?rev=734772&view=rev
Log:
JAXRS: improving exception and parameter handling
Added:
cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/ParameterHandler.java (with props)
cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/utils/ParameterType.java (with props)
cxf/trunk/rt/frontend/jaxrs/src/test/java/org/apache/cxf/jaxrs/CustomerGender.java (with props)
cxf/trunk/rt/frontend/jaxrs/src/test/java/org/apache/cxf/jaxrs/CustomerParameterHandler.java (with props)
Modified:
cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/JAXRSInvoker.java
cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/Messages.properties
cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/RequestHandler.java
cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/ResponseHandler.java
cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/interceptor/JAXRSInInterceptor.java
cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/interceptor/JAXRSOutInterceptor.java
cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/interceptor/Messages.properties
cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/provider/PrimitiveTextProvider.java
cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/provider/ProviderFactory.java
cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/utils/InjectionUtils.java
cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/utils/JAXRSUtils.java
cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/utils/Messages.properties
cxf/trunk/rt/frontend/jaxrs/src/test/java/org/apache/cxf/jaxrs/Customer.java
cxf/trunk/rt/frontend/jaxrs/src/test/java/org/apache/cxf/jaxrs/provider/ProviderFactoryTest.java
cxf/trunk/rt/frontend/jaxrs/src/test/java/org/apache/cxf/jaxrs/utils/JAXRSUtilsTest.java
cxf/trunk/systests/src/test/java/org/apache/cxf/systest/jaxrs/BookStore.java
cxf/trunk/systests/src/test/java/org/apache/cxf/systest/jaxrs/JAXRSClientServerBookTest.java
Modified: cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/JAXRSInvoker.java
URL: http://svn.apache.org/viewvc/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/JAXRSInvoker.java?rev=734772&r1=734771&r2=734772&view=diff
==============================================================================
--- cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/JAXRSInvoker.java (original)
+++ cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/JAXRSInvoker.java Thu Jan 15 10:18:02 2009
@@ -26,6 +26,7 @@
import java.util.ResourceBundle;
import java.util.logging.Logger;
+import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
@@ -98,6 +99,8 @@
exchange.getInMessage());
}
+ String baseAddress = HttpUtils.getOriginalAddress(exchange.getInMessage());
+
List<Object> params = null;
if (request instanceof List) {
params = CastUtils.cast((List<?>)request);
@@ -109,7 +112,6 @@
try {
result = invoke(exchange, resourceObject, methodToInvoke, params);
} catch (Fault ex) {
- String baseAddress = HttpUtils.getOriginalAddress(exchange.getInMessage());
Response excResponse = JAXRSUtils.convertFaultToResponse(ex.getCause(), baseAddress);
if (excResponse == null) {
ProviderFactory.getInstance(baseAddress).clearThreadLocalProxies();
@@ -147,31 +149,28 @@
}
List<MediaType> acceptContentType =
(List<MediaType>)msg.getExchange().get(Message.ACCEPT_CONTENT_TYPE);
+
ClassResourceInfo subCri = JAXRSUtils.findSubResourceClass(cri, result.getClass());
-
if (subCri == null) {
org.apache.cxf.common.i18n.Message errorM =
new org.apache.cxf.common.i18n.Message("NO_SUBRESOURCE_FOUND",
BUNDLE,
subResourcePath);
LOG.severe(errorM.toString());
- throw new Fault(errorM);
+ throw new WebApplicationException(404);
}
- OperationResourceInfo subOri = JAXRSUtils.findTargetMethod(subCri,
- subResourcePath,
- httpMethod,
- values,
- contentType,
- acceptContentType);
-
- if (subOri == null) {
- org.apache.cxf.common.i18n.Message errorM =
- new org.apache.cxf.common.i18n.Message("NO_SUBRESOURCE_METHOD_FOUND",
- BUNDLE,
- subCri.getResourceClass().getSimpleName());
- LOG.severe(errorM.toString());
- throw new Fault(errorM);
+ OperationResourceInfo subOri = null;
+ try {
+ subOri = JAXRSUtils.findTargetMethod(subCri,
+ subResourcePath,
+ httpMethod,
+ values,
+ contentType,
+ acceptContentType);
+ } catch (WebApplicationException ex) {
+ Response excResponse = JAXRSUtils.convertFaultToResponse(ex, baseAddress);
+ return new MessageContentsList(excResponse);
}
exchange.put(OperationResourceInfo.class, subOri);
Modified: cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/Messages.properties
URL: http://svn.apache.org/viewvc/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/Messages.properties?rev=734772&r1=734771&r2=734772&view=diff
==============================================================================
--- cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/Messages.properties (original)
+++ cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/Messages.properties Thu Jan 15 10:18:02 2009
@@ -20,4 +20,4 @@
#
NO_RESOURCE_OP_EXC=No resource methods found for resource class {0}
NO_SUBRESOURCE_FOUND=No subresource locator found for path {0}
-NO_SUBRESOURCE_METHOD_FOUND=No resource method found on a subresource locator {0}
+
Added: cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/ParameterHandler.java
URL: http://svn.apache.org/viewvc/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/ParameterHandler.java?rev=734772&view=auto
==============================================================================
--- cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/ParameterHandler.java (added)
+++ cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/ParameterHandler.java Thu Jan 15 10:18:02 2009
@@ -0,0 +1,24 @@
+/**
+ * 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.ext;
+
+public interface ParameterHandler<T> {
+ T fromString(String s);
+}
Propchange: cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/ParameterHandler.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/ParameterHandler.java
------------------------------------------------------------------------------
svn:keywords = Rev Date
Modified: cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/RequestHandler.java
URL: http://svn.apache.org/viewvc/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/RequestHandler.java?rev=734772&r1=734771&r2=734772&view=diff
==============================================================================
--- cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/RequestHandler.java (original)
+++ cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/RequestHandler.java Thu Jan 15 10:18:02 2009
@@ -25,7 +25,7 @@
import org.apache.cxf.message.Message;
/**
- * SystemHandler is capable of pre/post processing requests
+ * RequestHandler is capable of preprocessing requests
* ex., they can handle query extensions starting from _type
*
*/
Modified: cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/ResponseHandler.java
URL: http://svn.apache.org/viewvc/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/ResponseHandler.java?rev=734772&r1=734771&r2=734772&view=diff
==============================================================================
--- cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/ResponseHandler.java (original)
+++ cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/ResponseHandler.java Thu Jan 15 10:18:02 2009
@@ -24,6 +24,11 @@
import org.apache.cxf.jaxrs.model.OperationResourceInfo;
import org.apache.cxf.message.Message;
+/**
+ * ResponseHandler is capable of postprocessing requests
+ * ex., they can update the response status code, etc
+ *
+ */
public interface ResponseHandler {
Response handleResponse(Message m,
OperationResourceInfo ori,
Modified: cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/interceptor/JAXRSInInterceptor.java
URL: http://svn.apache.org/viewvc/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/interceptor/JAXRSInInterceptor.java?rev=734772&r1=734771&r2=734772&view=diff
==============================================================================
--- cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/interceptor/JAXRSInInterceptor.java (original)
+++ cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/interceptor/JAXRSInInterceptor.java Thu Jan 15 10:18:02 2009
@@ -30,7 +30,6 @@
import org.apache.cxf.common.i18n.BundleUtils;
import org.apache.cxf.common.logging.LogUtils;
-import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.jaxrs.JAXRSServiceImpl;
import org.apache.cxf.jaxrs.ext.RequestHandler;
import org.apache.cxf.jaxrs.impl.MetadataMap;
@@ -123,7 +122,7 @@
rawPath);
LOG.severe(errorMsg.toString());
- throw new WebApplicationException(404);
+ throw new WebApplicationException(Response.Status.NOT_FOUND);
}
message.getExchange().put(ROOT_RESOURCE_CLASS, resource);
@@ -178,16 +177,6 @@
LOG.fine("Request contentType is: " + requestContentType);
LOG.fine("Accept contentType is: " + acceptTypes);
- if (ori == null) {
- org.apache.cxf.common.i18n.Message errorMsg =
- new org.apache.cxf.common.i18n.Message("NO_OP_EXC",
- BUNDLE,
- rawPath,
- requestContentType,
- acceptTypes);
- LOG.severe(errorMsg.toString());
- throw new Fault(errorMsg);
- }
LOG.fine("Found operation: " + ori.getMethodToInvoke().getName());
message.getExchange().put(OperationResourceInfo.class, ori);
Modified: cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/interceptor/JAXRSOutInterceptor.java
URL: http://svn.apache.org/viewvc/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/interceptor/JAXRSOutInterceptor.java?rev=734772&r1=734771&r2=734772&view=diff
==============================================================================
--- cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/interceptor/JAXRSOutInterceptor.java (original)
+++ cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/interceptor/JAXRSOutInterceptor.java Thu Jan 15 10:18:02 2009
@@ -135,7 +135,7 @@
OutputStream out = message.getContent(OutputStream.class);
if (writer == null) {
- message.put(Message.RESPONSE_CODE, 406);
+ message.put(Message.RESPONSE_CODE, 500);
writeResponseErrorMessage(out,
"NO_MSG_WRITER",
invoked != null ? invoked.getReturnType().getSimpleName() : "");
@@ -171,7 +171,6 @@
private void writeResponseErrorMessage(OutputStream out, String errorString,
String parameter) {
try {
- // TODO : make sure this message is picked up from a resource bundle
out.write(new org.apache.cxf.common.i18n.Message(errorString,
BUNDLE,
parameter
Modified: cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/interceptor/Messages.properties
URL: http://svn.apache.org/viewvc/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/interceptor/Messages.properties?rev=734772&r1=734771&r2=734772&view=diff
==============================================================================
--- cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/interceptor/Messages.properties (original)
+++ cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/interceptor/Messages.properties Thu Jan 15 10:18:02 2009
@@ -18,9 +18,6 @@
# under the License.
#
#
-NO_OP_EXC =.No operation matching request path {0} is found, ContentType : {1}, Accept : {2}.
-NO_ROOT_EXC =.No root resource matching request path {0} is found.
SERIALIZE_ERROR =.Error serializing the response, please check the server logs, response class : {0}.
NO_MSG_WRITER =.No message body writer found for response class : {0}.
-NO_MSG_READER =.No message body reader found for request class : {0}.
-
+NO_ROOT_EXC =.No root resource matching request path {0} is found.
\ No newline at end of file
Modified: cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/provider/PrimitiveTextProvider.java
URL: http://svn.apache.org/viewvc/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/provider/PrimitiveTextProvider.java?rev=734772&r1=734771&r2=734772&view=diff
==============================================================================
--- cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/provider/PrimitiveTextProvider.java (original)
+++ cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/provider/PrimitiveTextProvider.java Thu Jan 15 10:18:02 2009
@@ -25,7 +25,6 @@
import java.lang.reflect.Type;
import javax.ws.rs.Consumes;
-import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
@@ -33,8 +32,8 @@
import javax.ws.rs.ext.MessageBodyWriter;
import org.apache.cxf.helpers.IOUtils;
-import org.apache.cxf.jaxrs.utils.AnnotationUtils;
import org.apache.cxf.jaxrs.utils.InjectionUtils;
+import org.apache.cxf.jaxrs.utils.ParameterType;
@Produces("text/plain")
@Consumes("text/plain")
@@ -56,7 +55,7 @@
return InjectionUtils.handleParameter(
IOUtils.readStringFromStream(is).toString(),
type,
- AnnotationUtils.getAnnotation(anns, PathParam.class) != null);
+ ParameterType.REQUEST_BODY, null);
}
public long getSize(Object t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mt) {
Modified: cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/provider/ProviderFactory.java
URL: http://svn.apache.org/viewvc/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/provider/ProviderFactory.java?rev=734772&r1=734771&r2=734772&view=diff
==============================================================================
--- cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/provider/ProviderFactory.java (original)
+++ cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/provider/ProviderFactory.java Thu Jan 15 10:18:02 2009
@@ -38,6 +38,7 @@
import javax.ws.rs.ext.MessageBodyWriter;
import org.apache.cxf.jaxrs.ext.MappingsHandler;
+import org.apache.cxf.jaxrs.ext.ParameterHandler;
import org.apache.cxf.jaxrs.ext.RequestHandler;
import org.apache.cxf.jaxrs.ext.ResponseHandler;
import org.apache.cxf.jaxrs.impl.RequestPreprocessor;
@@ -72,6 +73,8 @@
new ArrayList<ProviderInfo<RequestHandler>>(1);
private List<ProviderInfo<ResponseHandler>> responseHandlers =
new ArrayList<ProviderInfo<ResponseHandler>>(1);
+ private List<ProviderInfo<ParameterHandler>> jaxrsParamHandlers =
+ new ArrayList<ProviderInfo<ParameterHandler>>(1);
private RequestPreprocessor requestPreprocessor;
private ProviderFactory() {
@@ -87,6 +90,7 @@
requestHandlers,
responseHandlers,
defaultExceptionMappers,
+ jaxrsParamHandlers,
new JAXBElementProvider(),
new JSONProvider(),
new BinaryDataProvider(),
@@ -193,6 +197,32 @@
return candidates.get(0);
}
+ @SuppressWarnings("unchecked")
+ public <T> ParameterHandler<T> createParameterHandler(Class<?> paramType) {
+
+ List<ParameterHandler<T>> candidates = new LinkedList<ParameterHandler<T>>();
+
+ for (ProviderInfo<ParameterHandler> em : jaxrsParamHandlers) {
+ Type[] types = em.getProvider().getClass().getGenericInterfaces();
+ for (Type t : types) {
+ if (t instanceof ParameterizedType) {
+ ParameterizedType pt = (ParameterizedType)t;
+ Type[] args = pt.getActualTypeArguments();
+ for (int i = 0; i < args.length; i++) {
+ if (((Class<?>)args[i]).isAssignableFrom(paramType)) {
+ candidates.add(em.getProvider());
+ }
+ }
+ }
+ }
+ }
+ if (candidates.size() == 0) {
+ return null;
+ }
+ Collections.sort(candidates, new ParameterHandlerComparator());
+ return candidates.get(0);
+ }
+
public <T> MessageBodyReader<T> createMessageBodyReader(Class<T> bodyType,
Type parameterType,
Annotation[] parameterAnnotations,
@@ -257,13 +287,14 @@
return mw;
}
-
+//CHECKSTYLE:OFF
private void setProviders(List<ProviderInfo<MessageBodyReader>> readers,
List<ProviderInfo<MessageBodyWriter>> writers,
List<ProviderInfo<ContextResolver>> resolvers,
List<ProviderInfo<RequestHandler>> requestFilters,
List<ProviderInfo<ResponseHandler>> responseFilters,
List<ProviderInfo<ExceptionMapper>> excMappers,
+ List<ProviderInfo<ParameterHandler>> paramHandlers,
Object... providers) {
for (Object o : providers) {
@@ -290,6 +321,10 @@
if (ExceptionMapper.class.isAssignableFrom(o.getClass())) {
excMappers.add(new ProviderInfo<ExceptionMapper>((ExceptionMapper)o));
}
+
+ if (ParameterHandler.class.isAssignableFrom(o.getClass())) {
+ paramHandlers.add(new ProviderInfo<ParameterHandler>((ParameterHandler)o));
+ }
}
sortReaders(readers);
@@ -297,6 +332,7 @@
injectContexts(readers, writers, resolvers, requestFilters, responseFilters, excMappers);
}
+//CHECKSTYLE:ON
void injectContexts(List<?> ... providerLists) {
for (List<?> list : providerLists) {
@@ -458,6 +494,7 @@
requestHandlers,
responseHandlers,
userExceptionMappers,
+ jaxrsParamHandlers,
userProviders.toArray());
}
@@ -531,6 +568,7 @@
userExceptionMappers.clear();
requestHandlers.clear();
responseHandlers.clear();
+ jaxrsParamHandlers.clear();
}
public void setSchemaLocations(List<String> schemas) {
@@ -556,20 +594,34 @@
public int compare(ExceptionMapper<? extends Throwable> em1,
ExceptionMapper<? extends Throwable> em2) {
- Type[] types1 = em1.getClass().getGenericInterfaces();
- Type[] types2 = em2.getClass().getGenericInterfaces();
-
- Class<?> realClass1 = InjectionUtils.getActualType(types1[0]);
- Class<?> realClass2 = InjectionUtils.getActualType(types2[0]);
- if (realClass1 == realClass2) {
- return 0;
- }
- if (realClass1.isAssignableFrom(realClass2)) {
- // subclass should go first
- return 1;
- }
- return -1;
+ return compareClasses(em1.getClass(), em2.getClass());
}
}
+
+ private static class ParameterHandlerComparator implements
+ Comparator<ParameterHandler<? extends Object>> {
+
+ public int compare(ParameterHandler<? extends Object> em1,
+ ParameterHandler<? extends Object> em2) {
+ return compareClasses(em1.getClass(), em2.getClass());
+ }
+
+ }
+
+ private static int compareClasses(Class<?> cl1, Class<?> cl2) {
+ Type[] types1 = cl1.getGenericInterfaces();
+ Type[] types2 = cl2.getGenericInterfaces();
+
+ Class<?> realClass1 = InjectionUtils.getActualType(types1[0]);
+ Class<?> realClass2 = InjectionUtils.getActualType(types2[0]);
+ if (realClass1 == realClass2) {
+ return 0;
+ }
+ if (realClass1.isAssignableFrom(realClass2)) {
+ // subclass should go first
+ return 1;
+ }
+ return -1;
+ }
}
Modified: cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/utils/InjectionUtils.java
URL: http://svn.apache.org/viewvc/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/utils/InjectionUtils.java?rev=734772&r1=734771&r2=734772&view=diff
==============================================================================
--- cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/utils/InjectionUtils.java (original)
+++ cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/utils/InjectionUtils.java Thu Jan 15 10:18:02 2009
@@ -21,6 +21,7 @@
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;
@@ -43,10 +44,13 @@
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.PathSegment;
import javax.ws.rs.core.Request;
+import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.ext.ContextResolver;
@@ -56,6 +60,7 @@
import org.apache.cxf.common.logging.LogUtils;
import org.apache.cxf.common.util.PrimitiveUtils;
import org.apache.cxf.jaxrs.ext.MessageContext;
+import org.apache.cxf.jaxrs.ext.ParameterHandler;
import org.apache.cxf.jaxrs.impl.PathSegmentImpl;
import org.apache.cxf.jaxrs.impl.tl.ThreadLocalContextResolver;
import org.apache.cxf.jaxrs.impl.tl.ThreadLocalHttpHeaders;
@@ -70,6 +75,7 @@
import org.apache.cxf.jaxrs.impl.tl.ThreadLocalServletContext;
import org.apache.cxf.jaxrs.impl.tl.ThreadLocalUriInfo;
import org.apache.cxf.jaxrs.model.AbstractResourceInfo;
+import org.apache.cxf.jaxrs.provider.ProviderFactory;
import org.apache.cxf.message.Message;
public final class InjectionUtils {
@@ -108,9 +114,8 @@
try {
f.set(o, v);
} catch (IllegalAccessException ex) {
- LOG.warning(new org.apache.cxf.common.i18n.Message("FIELD_INJECTION_FAILURE",
- BUNDLE,
- f.getName()).toString());
+ reportServerError("FIELD_ACCESS_FAILURE",
+ f.getType().getName());
}
return null;
}
@@ -133,20 +138,23 @@
try {
Method methodToInvoke = checkProxy(method, requestObject);
methodToInvoke.invoke(requestObject, new Object[]{parameterValue});
+ } catch (IllegalAccessException ex) {
+ reportServerError("METHOD_ACCESS_FAILURE", method.getName());
} catch (Exception ex) {
- LOG.warning(new org.apache.cxf.common.i18n.Message("METHOD_INJECTION_FAILURE",
- BUNDLE,
- method.getName()).toString());
+ reportServerError("METHOD_INJECTION_FAILURE", method.getName());
}
}
- public static Object handleParameter(String value, Class<?> pClass, boolean pathParam) {
+ public static Object handleParameter(String value,
+ Class<?> pClass,
+ ParameterType pType,
+ String basePath) {
if (value == null) {
return null;
}
- if (pathParam) {
+ if (pType == ParameterType.PATH) {
PathSegment ps = new PathSegmentImpl(value, false);
if (PathSegment.class.isAssignableFrom(pClass)) {
return ps;
@@ -161,70 +169,122 @@
// check constructors accepting a single String value
try {
Constructor<?> c = pClass.getConstructor(new Class<?>[]{String.class});
- if (c != null) {
- return c.newInstance(new Object[]{value});
- }
- } catch (Exception ex) {
+ return c.newInstance(new Object[]{value});
+ } catch (NoSuchMethodException ex) {
// try valueOf
+ } catch (Exception ex) {
+ LOG.severe(new org.apache.cxf.common.i18n.Message("CLASS_CONSTRUCTOR_FAILURE",
+ BUNDLE,
+ pClass.getName()).toString());
+ throw new WebApplicationException(ex, getFailureStatus(pType));
}
+
// check for valueOf(String) static methods
+ String[] methodNames = pClass.isEnum()
+ ? new String[] {"fromString", "valueOf"}
+ : new String[] {"valueOf", "fromString"};
+ Object result = evaluateFactoryMethod(value, pClass, pType, methodNames[0]);
+ if (result == null) {
+ result = evaluateFactoryMethod(value, pClass, pType, methodNames[1]);
+ }
+
+ if (basePath != null) {
+ ParameterHandler<?> pm = ProviderFactory.getInstance(basePath)
+ .createParameterHandler(pClass);
+ if (pm != null) {
+ result = pm.fromString(value);
+ }
+ }
+
+ if (result != null) {
+ return result;
+ }
+
+ reportServerError("WRONG_PARAMETER_TYPE", pClass.getName());
+ return null;
+ }
+
+ public static void reportServerError(String messageName, String parameter) {
+ org.apache.cxf.common.i18n.Message errorMessage =
+ new org.apache.cxf.common.i18n.Message(messageName,
+ BUNDLE,
+ parameter);
+ LOG.severe(errorMessage.toString());
+ Response r = Response.status(Response.Status.INTERNAL_SERVER_ERROR)
+ .type(MediaType.TEXT_PLAIN_TYPE)
+ .entity(errorMessage.toString()).build();
+ throw new WebApplicationException(r);
+ }
+
+ private static Object evaluateFactoryMethod(String value,
+ Class<?> pClass,
+ ParameterType pType,
+ String methodName) {
try {
- Method m = pClass.getMethod("valueOf", new Class<?>[]{String.class});
- if (m != null && Modifier.isStatic(m.getModifiers())) {
+ Method m = pClass.getMethod(methodName, new Class<?>[]{String.class});
+ if (Modifier.isStatic(m.getModifiers())) {
return m.invoke(null, new Object[]{value});
}
- } catch (Exception ex) {
+ } catch (NoSuchMethodException ex) {
// no luck
+ } catch (Exception ex) {
+ Throwable t = ex instanceof InvocationTargetException
+ ? ((InvocationTargetException)ex).getTargetException() : ex;
+ LOG.severe(new org.apache.cxf.common.i18n.Message("CLASS_VALUE_OF_FAILURE",
+ BUNDLE,
+ pClass.getName()).toString());
+ throw new WebApplicationException(t, getFailureStatus(pType));
}
-
return null;
}
public static Object handleBean(Class<?> paramType, MultivaluedMap<String, String> values,
- boolean pathParam) {
+ ParameterType pType, String basePath) {
Object bean = null;
try {
bean = paramType.newInstance();
- for (Map.Entry<String, List<String>> entry : values.entrySet()) {
- boolean injected = false;
- for (Method m : paramType.getMethods()) {
- if (m.getName().equalsIgnoreCase("set" + entry.getKey())
- && m.getParameterTypes().length == 1) {
- Object paramValue = handleParameter(entry.getValue().get(0),
- m.getParameterTypes()[0],
- pathParam);
- if (paramValue != null) {
- injectThroughMethod(bean, m, paramValue);
- injected = true;
- break;
- }
+ } catch (IllegalAccessException ex) {
+ reportServerError("CLASS_ACCESS_FAILURE", paramType.getName());
+ } catch (Exception ex) {
+ reportServerError("CLASS_INSTANTIATION_FAILURE", paramType.getName());
+ }
+
+ for (Map.Entry<String, List<String>> entry : values.entrySet()) {
+ boolean injected = false;
+ for (Method m : paramType.getMethods()) {
+ if (m.getName().equalsIgnoreCase("set" + entry.getKey())
+ && m.getParameterTypes().length == 1) {
+ Object paramValue = handleParameter(entry.getValue().get(0),
+ m.getParameterTypes()[0],
+ pType, basePath);
+ if (paramValue != null) {
+ injectThroughMethod(bean, m, paramValue);
+ injected = true;
+ break;
}
}
- if (injected) {
- continue;
- }
- for (Field f : paramType.getFields()) {
- if (f.getName().equalsIgnoreCase(entry.getKey())) {
- Object paramValue = handleParameter(entry.getValue().get(0),
- f.getType(), pathParam);
- if (paramValue != null) {
- injectFieldValue(f, bean, paramValue);
- break;
- }
+ }
+ if (injected) {
+ continue;
+ }
+ for (Field f : paramType.getFields()) {
+ if (f.getName().equalsIgnoreCase(entry.getKey())) {
+ Object paramValue = handleParameter(entry.getValue().get(0),
+ f.getType(), pType, basePath);
+ if (paramValue != null) {
+ injectFieldValue(f, bean, paramValue);
+ break;
}
}
}
- } catch (Exception ex) {
- LOG.warning(new org.apache.cxf.common.i18n.Message("CLASS_INSTANCIATION_FAILURE",
- BUNDLE,
- paramType.getName()).toString());
}
+
return bean;
}
@SuppressWarnings("unchecked")
public static Object injectIntoList(Type genericType, List<String> values,
- boolean decoded, boolean pathParam) {
+ boolean decoded, ParameterType pathParam, String basePath) {
Class<?> realType = InjectionUtils.getActualType(genericType);
values = checkPathSegment(values, realType, pathParam);
List theValues = new ArrayList();
@@ -232,7 +292,7 @@
if (decoded) {
r = JAXRSUtils.uriDecode(r);
}
- Object o = InjectionUtils.handleParameter(r, realType, pathParam);
+ Object o = InjectionUtils.handleParameter(r, realType, pathParam, basePath);
if (o != null) {
theValues.add(o);
}
@@ -244,7 +304,9 @@
@SuppressWarnings("unchecked")
public static Object injectIntoSet(Type genericType, List<String> values,
- boolean sorted, boolean decoded, boolean pathParam) {
+ boolean sorted,
+ boolean decoded,
+ ParameterType pathParam, String basePath) {
Class<?> realType = InjectionUtils.getActualType(genericType);
values = checkPathSegment(values, realType, pathParam);
@@ -254,7 +316,7 @@
if (decoded) {
r = JAXRSUtils.uriDecode(r);
}
- Object o = InjectionUtils.handleParameter(r, realType, pathParam);
+ Object o = InjectionUtils.handleParameter(r, realType, pathParam, basePath);
if (o != null) {
theValues.add(o);
}
@@ -262,8 +324,9 @@
return theValues;
}
- private static List<String> checkPathSegment(List<String> values, Class<?> type, boolean pathParam) {
- if (!pathParam || !PathSegment.class.isAssignableFrom(type)) {
+ private static List<String> checkPathSegment(List<String> values, Class<?> type,
+ ParameterType pathParam) {
+ if (pathParam != ParameterType.PATH || !PathSegment.class.isAssignableFrom(type)) {
return values;
}
List<String> newValues = new ArrayList<String>();
@@ -285,9 +348,9 @@
Class<?> paramType,
Type genericType,
String defaultValue,
- boolean isLast,
boolean decoded,
- boolean pathParam) {
+ ParameterType pathParam,
+ String basePath) {
if (paramValues == null) {
if (defaultValue != null) {
@@ -303,14 +366,18 @@
}
if (List.class.isAssignableFrom(paramType)) {
- return InjectionUtils.injectIntoList(genericType, paramValues, decoded, pathParam);
+ return InjectionUtils.injectIntoList(genericType, paramValues, decoded, pathParam,
+ basePath);
} else if (Set.class.isAssignableFrom(paramType)) {
- return InjectionUtils.injectIntoSet(genericType, paramValues, false, decoded, pathParam);
+ return InjectionUtils.injectIntoSet(genericType, paramValues, false, decoded, pathParam,
+ basePath);
} else if (SortedSet.class.isAssignableFrom(paramType)) {
- return InjectionUtils.injectIntoSet(genericType, paramValues, true, decoded, pathParam);
+ return InjectionUtils.injectIntoSet(genericType, paramValues, true, decoded, pathParam,
+ basePath);
} else {
String result = null;
if (paramValues.size() > 0) {
+ boolean isLast = pathParam == ParameterType.PATH ? true : false;
result = isLast ? paramValues.get(paramValues.size() - 1)
: paramValues.get(0);
}
@@ -318,7 +385,7 @@
if (decoded) {
result = JAXRSUtils.uriDecode(result);
}
- return InjectionUtils.handleParameter(result, paramType, pathParam);
+ return InjectionUtils.handleParameter(result, paramType, pathParam, basePath);
} else {
return null;
}
@@ -433,4 +500,12 @@
InjectionUtils.injectContextField(cri, f, o, value, true);
}
}
+
+ public static Response.Status getFailureStatus(ParameterType pType) {
+ if (pType == ParameterType.MATRIX || pType == ParameterType.PATH
+ || pType == ParameterType.QUERY) {
+ return Response.Status.NOT_FOUND;
+ }
+ return Response.Status.BAD_REQUEST;
+ }
}
Modified: cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/utils/JAXRSUtils.java
URL: http://svn.apache.org/viewvc/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/utils/JAXRSUtils.java?rev=734772&r1=734771&r2=734772&view=diff
==============================================================================
--- cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/utils/JAXRSUtils.java (original)
+++ cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/utils/JAXRSUtils.java Thu Jan 15 10:18:02 2009
@@ -237,7 +237,6 @@
return firstEntry.getKey();
}
-
return null;
}
@@ -252,20 +251,34 @@
new OperationResourceInfoComparator());
MediaType requestType = requestContentType == null
? ALL_TYPES : MediaType.valueOf(requestContentType);
+
+ int pathMatched = 0;
+ int methodMatched = 0;
+ int consumeMatched = 0;
+ int produceMatched = 0;
+
for (MediaType acceptType : acceptContentTypes) {
for (OperationResourceInfo ori : resource.getMethodDispatcher().getOperationResourceInfos()) {
-
URITemplate uriTemplate = ori.getURITemplate();
MultivaluedMap<String, String> map = cloneMap(values);
if (uriTemplate != null && uriTemplate.match(path, map)) {
if (ori.isSubResourceLocator()) {
candidateList.put(ori, map);
- } else if (ori.getHttpMethod().equalsIgnoreCase(httpMethod)
- && matchMimeTypes(requestType, acceptType, ori)) {
+ } else {
String finalGroup = map.getFirst(URITemplate.FINAL_MATCH_GROUP);
if (finalGroup == null || StringUtils.isEmpty(finalGroup)
|| finalGroup.equals("/")) {
- candidateList.put(ori, map);
+ pathMatched++;
+ boolean mMatched = ori.getHttpMethod().equalsIgnoreCase(httpMethod);
+ boolean cMatched = matchConsumeTypes(requestType, ori);
+ boolean pMatched = matchProduceTypes(acceptType, ori);
+ if (mMatched && cMatched && pMatched) {
+ candidateList.put(ori, map);
+ } else {
+ methodMatched = mMatched ? methodMatched + 1 : methodMatched;
+ produceMatched = pMatched ? produceMatched + 1 : produceMatched;
+ consumeMatched = cMatched ? consumeMatched + 1 : consumeMatched;
+ }
}
}
}
@@ -279,10 +292,28 @@
}
}
- return null;
+ int status = pathMatched == 0 ? 404 : methodMatched == 0 ? 405
+ : consumeMatched == 0 ? 415 : produceMatched == 0 ? 406 : 404;
+ String name = resource.isRoot() ? "NO_OP_EXC" : "NO_SUBRESOURCE_METHOD_FOUND";
+ org.apache.cxf.common.i18n.Message errorMsg =
+ new org.apache.cxf.common.i18n.Message(name,
+ BUNDLE,
+ path,
+ requestType.toString(),
+ convertTypesToString(acceptContentTypes));
+ LOG.severe(errorMsg.toString());
+
+ throw new WebApplicationException(status);
+
}
-
+ private static String convertTypesToString(List<MediaType> types) {
+ StringBuilder sb = new StringBuilder();
+ for (MediaType type : types) {
+ sb.append(type.toString()).append(',');
+ }
+ return sb.toString();
+ }
public static List<MediaType> getConsumeTypes(Consumes cm) {
return cm == null ? Collections.singletonList(ALL_TYPES)
@@ -456,12 +487,14 @@
CookieParam cookie = AnnotationUtils.getAnnotation(anns, CookieParam.class);
if (cookie != null) {
- result = processCookieParam(message, cookie.value(), parameterClass, genericParam, defaultValue);
+ result = processCookieParam(message, cookie.value(), parameterClass, genericParam,
+ defaultValue);
}
HeaderParam hp = AnnotationUtils.getAnnotation(anns, HeaderParam.class);
if (hp != null) {
- result = processHeaderParam(message, hp.value(), parameterClass, genericParam, defaultValue);
+ result = processHeaderParam(message, hp.value(), parameterClass, genericParam,
+ defaultValue);
}
return result;
@@ -484,8 +517,13 @@
}
}
+ String basePath = HttpUtils.getOriginalAddress(m);
+
if ("".equals(key)) {
- return InjectionUtils.handleBean(pClass, params, false);
+ return InjectionUtils.handleBean(pClass,
+ params,
+ ParameterType.MATRIX,
+ basePath);
} else {
List<String> values = params.get(key);
return InjectionUtils.createParameterObject(values,
@@ -493,8 +531,8 @@
genericType,
defaultValue,
false,
- false,
- true);
+ ParameterType.MATRIX,
+ basePath);
}
}
@@ -514,8 +552,9 @@
// TODO : this is done per every form parameter hence it needs to be refactored
FormUtils.populateMap(params, body, decode);
+ String basePath = HttpUtils.getOriginalAddress(m);
if ("".equals(key)) {
- return InjectionUtils.handleBean(pClass, params, false);
+ return InjectionUtils.handleBean(pClass, params, ParameterType.FORM, basePath);
} else {
List<String> results = params.get(key);
@@ -524,8 +563,8 @@
genericType,
defaultValue,
false,
- false,
- false);
+ ParameterType.FORM,
+ basePath);
}
}
@@ -544,14 +583,14 @@
String defaultValue) {
List<String> values = new HttpHeadersImpl(m).getRequestHeader(header);
-
+ String basePath = HttpUtils.getOriginalAddress(m);
return InjectionUtils.createParameterObject(values,
pClass,
genericType,
defaultValue,
false,
- false,
- false);
+ ParameterType.HEADER,
+ basePath);
}
@@ -570,7 +609,12 @@
if (pClass.isAssignableFrom(Cookie.class)) {
return Cookie.valueOf(value.length() == 0 ? defaultValue : value);
}
- return value.length() > 0 ? InjectionUtils.handleParameter(value, pClass, false)
+
+ String basePath = HttpUtils.getOriginalAddress(m);
+ return value.length() > 0 ? InjectionUtils.handleParameter(value,
+ pClass,
+ ParameterType.COOKIE,
+ basePath)
: defaultValue;
}
@@ -645,18 +689,19 @@
String defaultValue,
boolean decoded) {
+ String basePath = HttpUtils.getOriginalAddress(m);
String parameterName = uriParamAnnotation.value();
if ("".equals(parameterName)) {
- return InjectionUtils.handleBean(paramType, values, true);
+ return InjectionUtils.handleBean(paramType, values, ParameterType.PATH, basePath);
} else {
List<String> results = values.get(parameterName);
return InjectionUtils.createParameterObject(results,
paramType,
genericType,
defaultValue,
- true,
decoded,
- true);
+ ParameterType.PATH,
+ basePath);
}
}
@@ -671,10 +716,11 @@
boolean decode) {
String queryName = queryParam.value();
+ String basePath = HttpUtils.getOriginalAddress(m);
if ("".equals(queryName)) {
return InjectionUtils.handleBean(paramType,
new UriInfoImpl(m, null).getQueryParameters(),
- false);
+ ParameterType.QUERY, basePath);
} else {
List<String> results = getStructuredParams((String)m.get(Message.QUERY_STRING),
"&",
@@ -685,8 +731,7 @@
genericType,
defaultValue,
false,
- false,
- false);
+ ParameterType.QUERY, basePath);
}
}
@@ -743,7 +788,6 @@
parameterAnnotations,
type,
m);
- // TODO : make the exceptions
if (provider != null) {
try {
HttpHeaders headers = new HttpHeadersImpl(m);
@@ -751,15 +795,19 @@
targetTypeClass, parameterType, parameterAnnotations, contentType,
headers.getRequestHeaders(), is);
} catch (IOException e) {
- e.printStackTrace();
- throw new RuntimeException("Error deserializing input stream into target class "
- + targetTypeClass.getSimpleName()
- + ", content type : " + contentType);
+ String errorMessage = "Error deserializing input stream into target class "
+ + targetTypeClass.getSimpleName()
+ + ", content type : " + contentType;
+ LOG.severe(errorMessage);
+ throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
}
} else {
- throw new RuntimeException("No message body reader found for target class "
- + targetTypeClass.getSimpleName()
- + ", content type : " + contentType);
+ String errorMessage = new org.apache.cxf.common.i18n.Message("NO_MSG_READER",
+ BUNDLE,
+ targetTypeClass.getSimpleName(),
+ contentType).toString();
+ LOG.severe(errorMessage);
+ throw new WebApplicationException(Response.Status.UNSUPPORTED_MEDIA_TYPE);
}
}
@@ -768,6 +816,18 @@
+ public static boolean matchConsumeTypes(MediaType requestContentType,
+ OperationResourceInfo ori) {
+
+ return intersectMimeTypes(ori.getConsumeTypes(), requestContentType).size() != 0;
+ }
+
+ public static boolean matchProduceTypes(MediaType acceptContentType,
+ OperationResourceInfo ori) {
+
+ return intersectMimeTypes(ori.getProduceTypes(), acceptContentType).size() != 0;
+ }
+
public static boolean matchMimeTypes(MediaType requestContentType,
MediaType acceptContentType,
OperationResourceInfo ori) {
Modified: cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/utils/Messages.properties
URL: http://svn.apache.org/viewvc/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/utils/Messages.properties?rev=734772&r1=734771&r2=734772&view=diff
==============================================================================
--- cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/utils/Messages.properties (original)
+++ cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/utils/Messages.properties Thu Jan 15 10:18:02 2009
@@ -20,5 +20,13 @@
#
NO_CONTENT_TYPE_SPECIFIED=No Content-Type specified for HTTP {0}
METHOD_INJECTION_FAILURE=Method {0} injection failure
-FIELD_INJECTION_FAILURE=Field {0} injection failure
-CLASS_INSTANCIATION_FAILURE=Class {0} can not be instanciated
+METHOD_ACCESS_FAILURE=Method {0} can not be accessed due to security manager restrictions
+FIELD_ACCESS_FAILURE=Field of type {0} can not be accessed due to security manager restrictions
+CLASS_INSTANTIATION_FAILURE=Class {0} can not be instantiated
+CLASS_ACCESS_FAILURE=Class {0} can not be instantiated due to security manager restrictions
+CLASS_CONSTRUCTOR_FAILURE=Class {0} can not be instantiated using a constructor with a single String argument
+CLASS_VALUE_OF_FAILURE=Instance of class {0} can not be created using static valueOf(String) or fromString(String) methods
+WRONG_PARAMETER_TYPE=Parameter Class {0} has no constructor with single String parameter, static valueOf(String) or fromString(String) methods
+NO_MSG_READER =.No message body reader found for request class : {0}, ContentType : {1}.
+NO_SUBRESOURCE_METHOD_FOUND=No operation matching request path {0} is found on subresource, ContentType : {1}, Accept : {2}.
+NO_OP_EXC =.No operation matching request path {0} is found, ContentType : {1}, Accept : {2}.
Added: cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/utils/ParameterType.java
URL: http://svn.apache.org/viewvc/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/utils/ParameterType.java?rev=734772&view=auto
==============================================================================
--- cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/utils/ParameterType.java (added)
+++ cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/utils/ParameterType.java Thu Jan 15 10:18:02 2009
@@ -0,0 +1,32 @@
+/**
+ * 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;
+
+public enum ParameterType {
+ PATH,
+ QUERY,
+ MATRIX,
+ HEADER,
+ COOKIE,
+ FORM,
+
+ REQUEST_BODY,
+ UNKNOWN
+}
Propchange: cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/utils/ParameterType.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/utils/ParameterType.java
------------------------------------------------------------------------------
svn:keywords = Rev Date
Modified: cxf/trunk/rt/frontend/jaxrs/src/test/java/org/apache/cxf/jaxrs/Customer.java
URL: http://svn.apache.org/viewvc/cxf/trunk/rt/frontend/jaxrs/src/test/java/org/apache/cxf/jaxrs/Customer.java?rev=734772&r1=734771&r2=734772&view=diff
==============================================================================
--- cxf/trunk/rt/frontend/jaxrs/src/test/java/org/apache/cxf/jaxrs/Customer.java (original)
+++ cxf/trunk/rt/frontend/jaxrs/src/test/java/org/apache/cxf/jaxrs/Customer.java Thu Jan 15 10:18:02 2009
@@ -19,7 +19,9 @@
package org.apache.cxf.jaxrs;
+import java.util.HashMap;
import java.util.List;
+import java.util.UUID;
import javax.annotation.Resource;
import javax.servlet.ServletConfig;
@@ -88,6 +90,15 @@
@QueryParam("b")
private String b;
+ private String name;
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String n) {
+ name = n;
+ }
public String getB() {
return b;
@@ -228,6 +239,24 @@
// complete
}
+ public void testCustomerParam(@QueryParam("p1") Customer c) {
+ // complete
+ }
+
+ public void testFromStringParam(@QueryParam("p1") UUID uuid,
+ @QueryParam("p2") CustomerGender gender,
+ @QueryParam("p3") CustomerGender gender2) {
+ // complete
+ }
+// CHECKSTYLE:OFF
+ public void testWrongType(@QueryParam("p1") HashMap map) {
+ // complete
+ }
+// CHECKSTYLE:ON
+ public void testWrongType2(@QueryParam("p1") CustomerGender g) {
+ // complete
+ }
+
public void testFormParam(@FormParam("p1") String fp1,
@FormParam("p2") List<String> fp2) {
// complete
Added: cxf/trunk/rt/frontend/jaxrs/src/test/java/org/apache/cxf/jaxrs/CustomerGender.java
URL: http://svn.apache.org/viewvc/cxf/trunk/rt/frontend/jaxrs/src/test/java/org/apache/cxf/jaxrs/CustomerGender.java?rev=734772&view=auto
==============================================================================
--- cxf/trunk/rt/frontend/jaxrs/src/test/java/org/apache/cxf/jaxrs/CustomerGender.java (added)
+++ cxf/trunk/rt/frontend/jaxrs/src/test/java/org/apache/cxf/jaxrs/CustomerGender.java Thu Jan 15 10:18:02 2009
@@ -0,0 +1,34 @@
+/**
+ * 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;
+
+public enum CustomerGender {
+ MALE,
+ FEMALE;
+
+ public static CustomerGender fromString(String s) {
+ if ("1".equals(s)) {
+ return FEMALE;
+ } else if ("2".equals(s)) {
+ return MALE;
+ }
+ return valueOf(s);
+ }
+}
Propchange: cxf/trunk/rt/frontend/jaxrs/src/test/java/org/apache/cxf/jaxrs/CustomerGender.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: cxf/trunk/rt/frontend/jaxrs/src/test/java/org/apache/cxf/jaxrs/CustomerGender.java
------------------------------------------------------------------------------
svn:keywords = Rev Date
Added: cxf/trunk/rt/frontend/jaxrs/src/test/java/org/apache/cxf/jaxrs/CustomerParameterHandler.java
URL: http://svn.apache.org/viewvc/cxf/trunk/rt/frontend/jaxrs/src/test/java/org/apache/cxf/jaxrs/CustomerParameterHandler.java?rev=734772&view=auto
==============================================================================
--- cxf/trunk/rt/frontend/jaxrs/src/test/java/org/apache/cxf/jaxrs/CustomerParameterHandler.java (added)
+++ cxf/trunk/rt/frontend/jaxrs/src/test/java/org/apache/cxf/jaxrs/CustomerParameterHandler.java Thu Jan 15 10:18:02 2009
@@ -0,0 +1,32 @@
+/**
+ * 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;
+
+import org.apache.cxf.jaxrs.ext.ParameterHandler;
+
+public class CustomerParameterHandler implements ParameterHandler<Customer> {
+
+ public Customer fromString(String s) {
+ Customer c = new Customer();
+ c.setName(s);
+ return c;
+ }
+
+}
Propchange: cxf/trunk/rt/frontend/jaxrs/src/test/java/org/apache/cxf/jaxrs/CustomerParameterHandler.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: cxf/trunk/rt/frontend/jaxrs/src/test/java/org/apache/cxf/jaxrs/CustomerParameterHandler.java
------------------------------------------------------------------------------
svn:keywords = Rev Date
Modified: cxf/trunk/rt/frontend/jaxrs/src/test/java/org/apache/cxf/jaxrs/provider/ProviderFactoryTest.java
URL: http://svn.apache.org/viewvc/cxf/trunk/rt/frontend/jaxrs/src/test/java/org/apache/cxf/jaxrs/provider/ProviderFactoryTest.java?rev=734772&r1=734771&r2=734772&view=diff
==============================================================================
--- cxf/trunk/rt/frontend/jaxrs/src/test/java/org/apache/cxf/jaxrs/provider/ProviderFactoryTest.java (original)
+++ cxf/trunk/rt/frontend/jaxrs/src/test/java/org/apache/cxf/jaxrs/provider/ProviderFactoryTest.java Thu Jan 15 10:18:02 2009
@@ -47,11 +47,15 @@
import org.apache.abdera.model.Entry;
import org.apache.abdera.model.Feed;
import org.apache.cxf.helpers.IOUtils;
+import org.apache.cxf.jaxrs.Customer;
+import org.apache.cxf.jaxrs.CustomerParameterHandler;
import org.apache.cxf.jaxrs.JAXBContextProvider;
+import org.apache.cxf.jaxrs.ext.ParameterHandler;
import org.apache.cxf.jaxrs.impl.WebApplicationExceptionMapper;
import org.apache.cxf.jaxrs.model.ProviderInfo;
import org.apache.cxf.jaxrs.utils.JAXRSUtils;
import org.apache.cxf.message.MessageImpl;
+
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
@@ -134,6 +138,15 @@
}
@Test
+ public void testParameterHandlerProvider() throws Exception {
+ ProviderFactory pf = ProviderFactory.getInstance();
+ ParameterHandler h = new CustomerParameterHandler();
+ pf.registerUserProvider(h);
+ ParameterHandler h2 = pf.createParameterHandler(Customer.class);
+ assertSame(h2, h);
+ }
+
+ @Test
public void testSortEntityProvidersWithConfig() throws Exception {
ProviderFactory pf = ProviderFactory.getInstance();
JSONProvider json1 = new JSONProvider();
@@ -398,5 +411,5 @@
}
}
-
+
}
Modified: cxf/trunk/rt/frontend/jaxrs/src/test/java/org/apache/cxf/jaxrs/utils/JAXRSUtilsTest.java
URL: http://svn.apache.org/viewvc/cxf/trunk/rt/frontend/jaxrs/src/test/java/org/apache/cxf/jaxrs/utils/JAXRSUtilsTest.java?rev=734772&r1=734771&r2=734772&view=diff
==============================================================================
--- cxf/trunk/rt/frontend/jaxrs/src/test/java/org/apache/cxf/jaxrs/utils/JAXRSUtilsTest.java (original)
+++ cxf/trunk/rt/frontend/jaxrs/src/test/java/org/apache/cxf/jaxrs/utils/JAXRSUtilsTest.java Thu Jan 15 10:18:02 2009
@@ -26,11 +26,13 @@
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
+import java.util.UUID;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
@@ -43,6 +45,8 @@
import javax.xml.bind.JAXBContext;
import org.apache.cxf.jaxrs.Customer;
+import org.apache.cxf.jaxrs.CustomerGender;
+import org.apache.cxf.jaxrs.CustomerParameterHandler;
import org.apache.cxf.jaxrs.JAXBContextProvider;
import org.apache.cxf.jaxrs.JAXRSServiceFactoryBean;
import org.apache.cxf.jaxrs.JAXRSServiceImpl;
@@ -67,6 +71,7 @@
import org.apache.cxf.message.MessageImpl;
import org.apache.cxf.transport.http.AbstractHTTPDestination;
import org.easymock.EasyMock;
+
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
@@ -519,6 +524,77 @@
}
@Test
+ public void testFromStringParameters() throws Exception {
+ Class[] argType = {UUID.class, CustomerGender.class, CustomerGender.class};
+ Method m = Customer.class.getMethod("testFromStringParam", argType);
+ UUID u = UUID.randomUUID();
+ MessageImpl messageImpl = new MessageImpl();
+ messageImpl.put(Message.QUERY_STRING, "p1=" + u.toString() + "&p2=1&p3=2");
+ List<Object> params = JAXRSUtils.processParameters(new OperationResourceInfo(m, null),
+ null,
+ messageImpl);
+ assertEquals(3, params.size());
+ assertEquals("Query UUID Parameter was not matched correctly",
+ u.toString(), params.get(0).toString());
+ assertSame(CustomerGender.FEMALE, params.get(1));
+ assertSame(CustomerGender.MALE, params.get(2));
+ }
+
+ @Test
+ public void testCustomerParameter() throws Exception {
+ ProviderFactory.getInstance().registerUserProvider(
+ new CustomerParameterHandler());
+ Class[] argType = {Customer.class};
+ Method m = Customer.class.getMethod("testCustomerParam", argType);
+ MessageImpl messageImpl = new MessageImpl();
+ messageImpl.put(Message.QUERY_STRING, "p1=Fred");
+ List<Object> params = JAXRSUtils.processParameters(new OperationResourceInfo(m, null),
+ null,
+ messageImpl);
+ assertEquals(1, params.size());
+ Customer c = (Customer)params.get(0);
+ assertEquals("Fred", c.getName());
+ }
+
+ @Test
+ public void testWrongType() throws Exception {
+ Class[] argType = {HashMap.class};
+ Method m = Customer.class.getMethod("testWrongType", argType);
+ MessageImpl messageImpl = new MessageImpl();
+ messageImpl.put(Message.QUERY_STRING, "p1=1");
+ try {
+ JAXRSUtils.processParameters(new OperationResourceInfo(m, null),
+ null,
+ messageImpl);
+ fail("HashMap can not be handled as parameter");
+ } catch (WebApplicationException ex) {
+ assertEquals(500, ex.getResponse().getStatus());
+ assertEquals("Parameter Class java.util.HashMap has no constructor with "
+ + "single String parameter, static valueOf(String) or fromString(String) methods",
+ ex.getResponse().getEntity().toString());
+ }
+
+ }
+
+ @Test
+ public void testExceptionDuringConstruction() throws Exception {
+ Class[] argType = {CustomerGender.class};
+ Method m = Customer.class.getMethod("testWrongType2", argType);
+ MessageImpl messageImpl = new MessageImpl();
+ messageImpl.put(Message.QUERY_STRING, "p1=3");
+ try {
+ JAXRSUtils.processParameters(new OperationResourceInfo(m, null),
+ null,
+ messageImpl);
+ fail("CustomerGender have no instance with name 3");
+ } catch (WebApplicationException ex) {
+ assertEquals(404, ex.getResponse().getStatus());
+ }
+
+ }
+
+
+ @Test
public void testQueryParametersBean() throws Exception {
Class[] argType = {Customer.CustomerBean.class};
Method m = Customer.class.getMethod("testQueryBean", argType);
Modified: cxf/trunk/systests/src/test/java/org/apache/cxf/systest/jaxrs/BookStore.java
URL: http://svn.apache.org/viewvc/cxf/trunk/systests/src/test/java/org/apache/cxf/systest/jaxrs/BookStore.java?rev=734772&r1=734771&r2=734772&view=diff
==============================================================================
--- cxf/trunk/systests/src/test/java/org/apache/cxf/systest/jaxrs/BookStore.java (original)
+++ cxf/trunk/systests/src/test/java/org/apache/cxf/systest/jaxrs/BookStore.java Thu Jan 15 10:18:02 2009
@@ -90,6 +90,25 @@
}
@GET
+ @Path("wrongparametertype")
+ public void wrongParameterType(@QueryParam("p") Map p) {
+ throw new IllegalStateException("This op is not expected to be invoked");
+ }
+
+ @GET
+ @Path("exceptionduringconstruction")
+ public void wrongParameterType(@QueryParam("p") BadBook p) {
+ throw new IllegalStateException("This op is not expected to be invoked");
+ }
+
+ @POST
+ @Path("/unsupportedcontenttype")
+ @Consumes("application/xml")
+ public String unsupportedContentType() {
+ throw new IllegalStateException("This op is not expected to be invoked");
+ }
+
+ @GET
@Path("/bookurl/{URL}/")
public Book getBookByURL(@PathParam("URL") String urlValue) throws Exception {
String url2 = new URL(urlValue).toString();
@@ -419,6 +438,12 @@
}
}
+
+ private static class BadBook {
+ public BadBook(String s) {
+ throw new RuntimeException("The bad book");
+ }
+ }
}
Modified: cxf/trunk/systests/src/test/java/org/apache/cxf/systest/jaxrs/JAXRSClientServerBookTest.java
URL: http://svn.apache.org/viewvc/cxf/trunk/systests/src/test/java/org/apache/cxf/systest/jaxrs/JAXRSClientServerBookTest.java?rev=734772&r1=734771&r2=734772&view=diff
==============================================================================
--- cxf/trunk/systests/src/test/java/org/apache/cxf/systest/jaxrs/JAXRSClientServerBookTest.java (original)
+++ cxf/trunk/systests/src/test/java/org/apache/cxf/systest/jaxrs/JAXRSClientServerBookTest.java Thu Jan 15 10:18:02 2009
@@ -74,18 +74,48 @@
"application/xml", 404);
}
+ @Test
+ public void testNoPathMatch() throws Exception {
+ getAndCompare("http://localhost:9080/bookstore/bookqueries",
+ "",
+ "application/xml", 404);
+ }
+
@Test
public void testAcceptTypeMismatch() throws Exception {
- // TODO : more specific message is needed
- String msg = "<ns1:XMLFault xmlns:ns1=\"http://cxf.apache.org/bindings/xformat\"><ns1:faultstring"
- + " xmlns:ns1=\"http://cxf.apache.org/bindings/xformat\">.No operation matching request path "
- + "/bookstore/booknames/123 is found, ContentType : */*, Accept : foo/bar.</ns1:faultstring>"
- + "</ns1:XMLFault>";
-
getAndCompare("http://localhost:9080/bookstore/booknames/123",
- msg,
- "foo/bar", 500);
+ "",
+ "foo/bar", 406);
+ }
+
+ @Test
+ public void testWrongHttpMethod() throws Exception {
+ getAndCompare("http://localhost:9080/bookstore/unsupportedcontenttype",
+ "",
+ "foo/bar", 405);
+ }
+
+ @Test
+ public void testWrongQueryParameterType() throws Exception {
+ getAndCompare("http://localhost:9080/bookstore/wrongparametertype?p=1",
+ "Parameter Class java.util.Map has no constructor with single String "
+ + "parameter, static valueOf(String) or fromString(String) methods",
+ "*/*", 500);
+ }
+
+ @Test
+ public void testExceptionDuringConstruction() throws Exception {
+ getAndCompare("http://localhost:9080/bookstore/exceptionconstruction?p=1",
+ "",
+ "foo/bar", 404);
+ }
+
+ @Test
+ public void testSubresourceMethodNotFound() throws Exception {
+ getAndCompare("http://localhost:9080/bookstore/interface/thesubresource",
+ "",
+ "foo/bar", 404);
}
@Test
@@ -96,19 +126,12 @@
getAndCompareStrings("http://localhost:9080/bookstore/timetable",
msg1, msg2,
- "*/*", 406);
+ "*/*", 500);
}
@SuppressWarnings("deprecation")
@Test
public void testNoMessageReaderFound() throws Exception {
-// TODO : more specific message is needed
- String msg = "<ns1:XMLFault xmlns:ns1=\"http://cxf.apache.org/bindings/xformat\"><ns1:faultstring"
- + " xmlns:ns1=\"http://cxf.apache.org/bindings/xformat\">"
- + "java.lang.RuntimeException: No message body reader found for target class long[], "
- + "content type : application/octet-stream"
- + "</ns1:faultstring>"
- + "</ns1:XMLFault>";
String endpointAddress =
"http://localhost:9080/bookstore/binarybooks";
@@ -121,8 +144,7 @@
try {
int result = httpclient.executeMethod(post);
- assertEquals(500, result);
- assertEquals(msg, post.getResponseBodyAsString());
+ assertEquals(415, result);
} finally {
// Release current connection to the connection pool once you are done
post.releaseConnection();
@@ -131,14 +153,8 @@
@Test
public void testConsumeTypeMismatch() throws Exception {
- // TODO : more specific message is needed
- String msg = "<ns1:XMLFault xmlns:ns1=\"http://cxf.apache.org/bindings/xformat\"><ns1:faultstring"
- + " xmlns:ns1=\"http://cxf.apache.org/bindings/xformat\">.No operation matching request path "
- + "/bookstore/books is found, ContentType : application/bar, Accept : text/xml."
- + "</ns1:faultstring></ns1:XMLFault>";
-
String endpointAddress =
- "http://localhost:9080/bookstore/books";
+ "http://localhost:9080/bookstore/unsupportedcontenttype";
PostMethod post = new PostMethod(endpointAddress);
post.setRequestHeader("Content-Type", "application/bar");
@@ -147,8 +163,7 @@
try {
int result = httpclient.executeMethod(post);
- assertEquals(500, result);
- assertEquals(msg, post.getResponseBodyAsString());
+ assertEquals(415, result);
} finally {
// Release current connection to the connection pool once you are done
post.releaseConnection();