wink-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From b...@apache.org
Subject svn commit: r819229 - in /incubator/wink/trunk/wink-server/src: main/java/org/apache/wink/server/handlers/ main/java/org/apache/wink/server/internal/ main/java/org/apache/wink/server/internal/handlers/ test/java/org/apache/wink/server/internal/handlers...
Date Sat, 26 Sep 2009 23:37:53 GMT
Author: bluk
Date: Sat Sep 26 23:37:52 2009
New Revision: 819229

URL: http://svn.apache.org/viewvc?rev=819229&view=rev
Log:
Make MediaTypeMapperFactory public

See [WINK-206]

Added:
    incubator/wink/trunk/wink-server/src/main/java/org/apache/wink/server/handlers/MediaTypeMapperFactory.java
  (with props)
    incubator/wink/trunk/wink-server/src/main/java/org/apache/wink/server/handlers/MediaTypeMappingRecord.java
  (with props)
    incubator/wink/trunk/wink-server/src/test/java/org/apache/wink/server/internal/handlers/MediaTypeMapping2Test.java
  (with props)
    incubator/wink/trunk/wink-server/src/test/java/org/apache/wink/server/internal/handlers/MediaTypeMappingTest.java
  (with props)
    incubator/wink/trunk/wink-server/src/test/resources/org/apache/wink/server/internal/handlers/MediaTypeMapping2Test.properties
  (with props)
    incubator/wink/trunk/wink-server/src/test/resources/org/apache/wink/server/internal/handlers/MediaTypeMappingTest.properties
  (with props)
Modified:
    incubator/wink/trunk/wink-server/src/main/java/org/apache/wink/server/internal/DeploymentConfiguration.java
    incubator/wink/trunk/wink-server/src/main/java/org/apache/wink/server/internal/MediaTypeMapper.java
    incubator/wink/trunk/wink-server/src/main/java/org/apache/wink/server/internal/handlers/ServerMessageContext.java

Added: incubator/wink/trunk/wink-server/src/main/java/org/apache/wink/server/handlers/MediaTypeMapperFactory.java
URL: http://svn.apache.org/viewvc/incubator/wink/trunk/wink-server/src/main/java/org/apache/wink/server/handlers/MediaTypeMapperFactory.java?rev=819229&view=auto
==============================================================================
--- incubator/wink/trunk/wink-server/src/main/java/org/apache/wink/server/handlers/MediaTypeMapperFactory.java
(added)
+++ incubator/wink/trunk/wink-server/src/main/java/org/apache/wink/server/handlers/MediaTypeMapperFactory.java
Sat Sep 26 23:37:52 2009
@@ -0,0 +1,44 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.wink.server.handlers;
+
+import java.util.List;
+
+/**
+ * <p>
+ * MediaTypeMapperFactory is responsible to provide media type mappings from an
+ * application's response media type to a preferred media type. The use case is
+ * when certain user agents do not know how to handle a specific response media
+ * type (such as an application/*+xml) and must use another media type (such as
+ * text/xml).
+ * <p>
+ * The user should extend this class and override the relevant methods.
+ * <p>
+ * The sub-classes MUST have the public default constructor.
+ */
+public abstract class MediaTypeMapperFactory {
+
+    /**
+     * Returns a list of media type mappings that will be called to map response
+     * media types to preferred media types.
+     * 
+     * @return set of media type mapping records
+     */
+    public abstract List<? extends MediaTypeMappingRecord> getMediaTypeMappings();
+}

Propchange: incubator/wink/trunk/wink-server/src/main/java/org/apache/wink/server/handlers/MediaTypeMapperFactory.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/wink/trunk/wink-server/src/main/java/org/apache/wink/server/handlers/MediaTypeMappingRecord.java
URL: http://svn.apache.org/viewvc/incubator/wink/trunk/wink-server/src/main/java/org/apache/wink/server/handlers/MediaTypeMappingRecord.java?rev=819229&view=auto
==============================================================================
--- incubator/wink/trunk/wink-server/src/main/java/org/apache/wink/server/handlers/MediaTypeMappingRecord.java
(added)
+++ incubator/wink/trunk/wink-server/src/main/java/org/apache/wink/server/handlers/MediaTypeMappingRecord.java
Sat Sep 26 23:37:52 2009
@@ -0,0 +1,40 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.wink.server.handlers;
+
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+
+/**
+ * MediaTypeMappingRecords can map response media types to a different response
+ * media type if necessary.
+ */
+public interface MediaTypeMappingRecord {
+
+    /**
+     * Maps response media types to a different response media type if
+     * necessary. If the match does not apply, return null.
+     * 
+     * @param requestHeaders the current request headers
+     * @param responseMediaType the response media type
+     * @return the media type to use instead
+     */
+    MediaType match(HttpHeaders requestHeaders, MediaType responseMediaType);
+
+}

Propchange: incubator/wink/trunk/wink-server/src/main/java/org/apache/wink/server/handlers/MediaTypeMappingRecord.java
------------------------------------------------------------------------------
    svn:eol-style = native

Modified: incubator/wink/trunk/wink-server/src/main/java/org/apache/wink/server/internal/DeploymentConfiguration.java
URL: http://svn.apache.org/viewvc/incubator/wink/trunk/wink-server/src/main/java/org/apache/wink/server/internal/DeploymentConfiguration.java?rev=819229&r1=819228&r2=819229&view=diff
==============================================================================
--- incubator/wink/trunk/wink-server/src/main/java/org/apache/wink/server/internal/DeploymentConfiguration.java
(original)
+++ incubator/wink/trunk/wink-server/src/main/java/org/apache/wink/server/internal/DeploymentConfiguration.java
Sat Sep 26 23:37:52 2009
@@ -35,7 +35,6 @@
 import javax.servlet.ServletContext;
 import javax.ws.rs.WebApplicationException;
 import javax.ws.rs.core.Application;
-import javax.ws.rs.core.MediaType;
 
 import org.apache.wink.common.internal.application.ApplicationValidator;
 import org.apache.wink.common.internal.i18n.Messages;
@@ -44,9 +43,9 @@
 import org.apache.wink.common.internal.registry.InjectableFactory;
 import org.apache.wink.common.internal.registry.ProvidersRegistry;
 import org.apache.wink.common.internal.utils.FileLoader;
-import org.apache.wink.common.internal.utils.MediaTypeUtils;
 import org.apache.wink.server.handlers.Handler;
 import org.apache.wink.server.handlers.HandlersFactory;
+import org.apache.wink.server.handlers.MediaTypeMapperFactory;
 import org.apache.wink.server.handlers.RequestHandler;
 import org.apache.wink.server.handlers.RequestHandlersChain;
 import org.apache.wink.server.handlers.ResponseHandler;
@@ -79,17 +78,19 @@
  */
 public class DeploymentConfiguration {
 
-    private static final Logger       logger                            =
-                                                                            LoggerFactory
-                                                                                .getLogger(DeploymentConfiguration.class);
-    private static final String       ALTERNATIVE_SHORTCUTS             =
-                                                                            "META-INF/wink-alternate-shortcuts.properties";
-    private static final String       HTTP_METHOD_OVERRIDE_HEADERS_PROP =
-                                                                            "wink.httpMethodOverrideHeaders";
-    private static final String       HANDLERS_FACTORY_CLASS_PROP       =
-                                                                            "wink.handlersFactoryClass";
-    private static final String       VALIDATE_LOCATION_HEADER          =
-                                                                            "wink.validateLocationHeader";
+    private static final Logger       logger                              =
+                                                                              LoggerFactory
+                                                                                  .getLogger(DeploymentConfiguration.class);
+    private static final String       ALTERNATIVE_SHORTCUTS               =
+                                                                              "META-INF/wink-alternate-shortcuts.properties";
+    private static final String       HTTP_METHOD_OVERRIDE_HEADERS_PROP   =
+                                                                              "wink.httpMethodOverrideHeaders";
+    private static final String       HANDLERS_FACTORY_CLASS_PROP         =
+                                                                              "wink.handlersFactoryClass";
+    private static final String       MEDIATYPE_MAPPER_FACTORY_CLASS_PROP =
+                                                                              "wink.mediaTypeMapperFactoryClass";
+    private static final String       VALIDATE_LOCATION_HEADER            =
+                                                                              "wink.validateLocationHeader";
     // handler chains
     private RequestHandlersChain      requestHandlersChain;
     private ResponseHandlersChain     responseHandlersChain;
@@ -317,16 +318,33 @@
      * Initializes the MediaTypeMapper. Override it to provide a custom
      * MediaTypeMapper.
      */
+    @SuppressWarnings("unchecked")
     protected void initMediaTypeMapper() {
         if (mediaTypeMapper == null) {
             mediaTypeMapper = new MediaTypeMapper();
-            mediaTypeMapper.addMapping("Mozilla/",
-                                       MediaType.APPLICATION_ATOM_XML,
-                                       MediaType.TEXT_XML);
-            mediaTypeMapper.addMapping("Mozilla/",
-                                       MediaTypeUtils.ATOM_SERVICE_DOCUMENT,
-                                       MediaType.TEXT_XML);
-            mediaTypeMapper.addMapping("Mozilla/", MediaTypeUtils.OPENSEARCH, MediaType.TEXT_XML);
+
+            String mediaTypeMapperFactoryClassName =
+                properties.getProperty(MEDIATYPE_MAPPER_FACTORY_CLASS_PROP);
+            if (mediaTypeMapperFactoryClassName != null) {
+                try {
+                    logger.debug("MediaTypeMappingFactory Class is: {}",
+                                 mediaTypeMapperFactoryClassName);
+                    Class<MediaTypeMapperFactory> handlerFactoryClass =
+                        (Class<MediaTypeMapperFactory>)Class
+                            .forName(mediaTypeMapperFactoryClassName);
+                    MediaTypeMapperFactory handlersFactory = handlerFactoryClass.newInstance();
+                    mediaTypeMapper.addMappings(handlersFactory.getMediaTypeMappings());
+                } catch (ClassNotFoundException e) {
+                    logger.error(Messages
+                        .getMessage("isNotAClass", mediaTypeMapperFactoryClassName), e);
+                } catch (InstantiationException e) {
+                    logger.error(Messages.getMessage("classInstantiationException",
+                                                     mediaTypeMapperFactoryClassName), e);
+                } catch (IllegalAccessException e) {
+                    logger.error(Messages.getMessage("classIllegalAccess",
+                                                     mediaTypeMapperFactoryClassName), e);
+                }
+            }
         }
     }
 

Modified: incubator/wink/trunk/wink-server/src/main/java/org/apache/wink/server/internal/MediaTypeMapper.java
URL: http://svn.apache.org/viewvc/incubator/wink/trunk/wink-server/src/main/java/org/apache/wink/server/internal/MediaTypeMapper.java?rev=819229&r1=819228&r2=819229&view=diff
==============================================================================
--- incubator/wink/trunk/wink-server/src/main/java/org/apache/wink/server/internal/MediaTypeMapper.java
(original)
+++ incubator/wink/trunk/wink-server/src/main/java/org/apache/wink/server/internal/MediaTypeMapper.java
Sat Sep 26 23:37:52 2009
@@ -22,14 +22,13 @@
 
 import java.util.ArrayList;
 import java.util.List;
-import java.util.Map;
 
+import javax.ws.rs.core.HttpHeaders;
 import javax.ws.rs.core.MediaType;
 
+import org.apache.wink.server.handlers.MediaTypeMappingRecord;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.apache.wink.common.internal.i18n.Messages;
-import org.apache.wink.common.internal.utils.MediaTypeUtils;
 
 /**
  * Allows to map response media types to other media types based on user agent.
@@ -37,59 +36,17 @@
  */
 public final class MediaTypeMapper {
 
-    private static final Logger logger = LoggerFactory.getLogger(MediaTypeMapper.class);
+    private static final Logger          logger   = LoggerFactory.getLogger(MediaTypeMapper.class);
 
-    private interface MappingRecord {
+    private List<MediaTypeMappingRecord> mappings = new ArrayList<MediaTypeMappingRecord>();
 
-        boolean match(String userAgent, MediaType responseMediaType);
-
-        MediaType getReplacement();
-
-    }
-
-    private static class AgentStartsWith implements MappingRecord {
-
-        private String    userAgentStartsWith;
-        private MediaType responseType;
-        private MediaType replacementType;
-
-        public AgentStartsWith(String userAgentStartsWith,
-                               String responseType,
-                               String replacementType) {
-            if (userAgentStartsWith == null)
-                throw new NullPointerException();
-            this.userAgentStartsWith = userAgentStartsWith;
-            this.responseType = MediaType.valueOf(responseType);
-            this.replacementType = MediaType.valueOf(replacementType);
-        }
-
-        public boolean match(String userAgent, MediaType responseMediaType) {
-            return userAgent.startsWith(userAgentStartsWith) && MediaTypeUtils
-                .equalsIgnoreParameters(responseMediaType, responseType);
-        }
-
-        public MediaType getReplacement() {
-            return replacementType;
-        }
-    }
-
-    private List<MappingRecord> mappings = new ArrayList<MappingRecord>();
-
-    public void setMappings(List<Map<String, String>> mappings) {
-        for (Map<String, String> record : mappings) {
-            String userAgent = record.get("userAgentStartsWith"); //$NON-NLS-1$
-            String resultMimeType = record.get("resultMediaType"); //$NON-NLS-1$
-            String typeToSend = record.get("typeToSend"); //$NON-NLS-1$
-            addMapping(userAgent, resultMimeType, typeToSend);
-        }
-    }
-
-    public void addMapping(String userAgent, String resultMimeType, String typeToSend) {
-        if (userAgent == null || resultMimeType == null || typeToSend == null) {
-            logger.warn(Messages.getMessage("mediaTypeMapperIncompleteRecord"), userAgent);
+    public void addMappings(List<? extends MediaTypeMappingRecord> records) {
+        if (records == null) {
+            logger.debug("No media type mapping records to add");
             return;
         }
-        this.mappings.add(new AgentStartsWith(userAgent, resultMimeType, typeToSend));
+        logger.debug("Media type mapping records to add: {}", records);
+        this.mappings.addAll(records);
     }
 
     /**
@@ -100,14 +57,19 @@
      * @param userAgent User-Agent header; null is allowed
      * @return responseMediaType parameter or some non-null value
      */
-    public MediaType mapOutputMediaType(MediaType responseMediaType, String userAgent) {
-        if (userAgent != null) {
-            for (MappingRecord mappingRecord : mappings) {
-                if (mappingRecord.match(userAgent, responseMediaType)) {
-                    return mappingRecord.getReplacement();
-                }
+    public MediaType mapOutputMediaType(MediaType responseMediaType, HttpHeaders requestHeaders)
{
+        for (MediaTypeMappingRecord mappingRecord : mappings) {
+            logger.debug("Attempting to map media type using mapping record: {}", mappingRecord);
+            MediaType replacement = mappingRecord.match(requestHeaders, responseMediaType);
+            if (replacement != null) {
+                logger.debug("Mapped user media type to: {} using mapping record: {}",
+                             replacement,
+                             mappingRecord);
+                return replacement;
             }
         }
+        logger.debug("Did not find a mapping record so returning original response media
type: {}",
+                     responseMediaType);
         return responseMediaType; // returning the same
     }
 

Modified: incubator/wink/trunk/wink-server/src/main/java/org/apache/wink/server/internal/handlers/ServerMessageContext.java
URL: http://svn.apache.org/viewvc/incubator/wink/trunk/wink-server/src/main/java/org/apache/wink/server/internal/handlers/ServerMessageContext.java?rev=819229&r1=819228&r2=819229&view=diff
==============================================================================
--- incubator/wink/trunk/wink-server/src/main/java/org/apache/wink/server/internal/handlers/ServerMessageContext.java
(original)
+++ incubator/wink/trunk/wink-server/src/main/java/org/apache/wink/server/internal/handlers/ServerMessageContext.java
Sat Sep 26 23:37:52 2009
@@ -41,6 +41,7 @@
 import org.apache.wink.common.internal.contexts.ProvidersImpl;
 import org.apache.wink.common.internal.registry.ProvidersRegistry;
 import org.apache.wink.common.internal.runtime.AbstractRuntimeContext;
+import org.apache.wink.common.internal.runtime.RuntimeContextTLS;
 import org.apache.wink.server.handlers.MessageContext;
 import org.apache.wink.server.internal.DeploymentConfiguration;
 import org.apache.wink.server.internal.MediaTypeMapper;
@@ -231,9 +232,8 @@
         }
 
         private MediaType getRealResponseMimeType(String responseMimeType) {
-            String userAgent = servletRequest.getHeader(HttpHeaders.USER_AGENT);
             return mediaTypeMapper.mapOutputMediaType(MediaType.valueOf(responseMimeType),
-                                                      userAgent);
+                                                      getHttpHeaders());
         }
     }
 }

Added: incubator/wink/trunk/wink-server/src/test/java/org/apache/wink/server/internal/handlers/MediaTypeMapping2Test.java
URL: http://svn.apache.org/viewvc/incubator/wink/trunk/wink-server/src/test/java/org/apache/wink/server/internal/handlers/MediaTypeMapping2Test.java?rev=819229&view=auto
==============================================================================
--- incubator/wink/trunk/wink-server/src/test/java/org/apache/wink/server/internal/handlers/MediaTypeMapping2Test.java
(added)
+++ incubator/wink/trunk/wink-server/src/test/java/org/apache/wink/server/internal/handlers/MediaTypeMapping2Test.java
Sat Sep 26 23:37:52 2009
@@ -0,0 +1,128 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.wink.server.internal.handlers;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+
+import org.apache.wink.common.internal.utils.MediaTypeUtils;
+import org.apache.wink.server.handlers.MediaTypeMapperFactory;
+import org.apache.wink.server.handlers.MediaTypeMappingRecord;
+import org.apache.wink.server.internal.servlet.MockServletInvocationTest;
+import org.apache.wink.test.mock.MockRequestConstructor;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.springframework.mock.web.MockHttpServletResponse;
+
+public class MediaTypeMapping2Test extends MockServletInvocationTest {
+
+    @Path("/resource1")
+    public static class Resource {
+
+        @GET
+        public Response get() {
+            return Response.ok("Hello world!").type("custom/type").build();
+        }
+    }
+
+    private static class AgentStartsWith implements MediaTypeMappingRecord {
+
+        private String    userAgentStartsWith;
+        private MediaType responseType;
+        private MediaType replacementType;
+
+        public AgentStartsWith(String userAgentStartsWith,
+                               String responseType,
+                               String replacementType) {
+            if (userAgentStartsWith == null)
+                throw new NullPointerException();
+            this.userAgentStartsWith = userAgentStartsWith;
+            this.responseType = MediaType.valueOf(responseType);
+            this.replacementType = MediaType.valueOf(replacementType);
+        }
+
+        public MediaType match(HttpHeaders requestHeaders, MediaType responseMediaType) {
+            if (!MediaTypeUtils.equalsIgnoreParameters(responseMediaType, responseType))
{
+                return null;
+            }
+            String userAgent = requestHeaders.getRequestHeaders().getFirst(HttpHeaders.USER_AGENT);
+            if (userAgent != null && userAgent.startsWith(userAgentStartsWith)) {
+                return replacementType;
+            }
+            return null;
+        }
+    }
+
+    public static class UserMediaTypeMapperFactory extends MediaTypeMapperFactory {
+
+        @Override
+        public List<? extends MediaTypeMappingRecord> getMediaTypeMappings() {
+            List<MediaTypeMappingRecord> records = new ArrayList<MediaTypeMappingRecord>();
+            records.add(new AgentStartsWith("Agent123/", "custom/type", MediaType.TEXT_XML));
+            records.add(new MediaTypeMappingRecord() {
+
+                public MediaType match(HttpHeaders requestHeaders, MediaType responseMediaType)
{
+                    return MediaType.valueOf("my/type");
+                }
+            });
+            return records;
+        }
+
+    }
+
+    @Override
+    protected Class<?>[] getClasses() {
+        return new Class<?>[] {Resource.class};
+    }
+
+    public void testMediaTypeMapping() throws Exception {
+        MockHttpServletRequest mockRequest =
+            MockRequestConstructor.constructMockRequest("GET", "/resource1", MediaType.WILDCARD);
+        MockHttpServletResponse response = invoke(mockRequest);
+        assertEquals(200, response.getStatus());
+        assertEquals("Hello world!", response.getContentAsString());
+        assertEquals("my/type", response.getContentType());
+
+        mockRequest =
+            MockRequestConstructor.constructMockRequest("GET", "/resource1", MediaType.WILDCARD);
+        mockRequest.addHeader(HttpHeaders.USER_AGENT, "Agent123/abcd");
+        response = invoke(mockRequest);
+        assertEquals(200, response.getStatus());
+        assertEquals("Hello world!", response.getContentAsString());
+        assertEquals(MediaType.TEXT_XML, response.getContentType());
+
+        mockRequest =
+            MockRequestConstructor.constructMockRequest("GET", "/resource1", MediaType.WILDCARD);
+        mockRequest.addHeader(HttpHeaders.USER_AGENT, "Agent123abcd");
+        response = invoke(mockRequest);
+        assertEquals(200, response.getStatus());
+        assertEquals("Hello world!", response.getContentAsString());
+        assertEquals("my/type", response.getContentType());
+    }
+
+    @Override
+    protected String getPropertiesFile() {
+        return getClass().getName().replaceAll("\\.", "/") + ".properties";
+    }
+}

Propchange: incubator/wink/trunk/wink-server/src/test/java/org/apache/wink/server/internal/handlers/MediaTypeMapping2Test.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/wink/trunk/wink-server/src/test/java/org/apache/wink/server/internal/handlers/MediaTypeMappingTest.java
URL: http://svn.apache.org/viewvc/incubator/wink/trunk/wink-server/src/test/java/org/apache/wink/server/internal/handlers/MediaTypeMappingTest.java?rev=819229&view=auto
==============================================================================
--- incubator/wink/trunk/wink-server/src/test/java/org/apache/wink/server/internal/handlers/MediaTypeMappingTest.java
(added)
+++ incubator/wink/trunk/wink-server/src/test/java/org/apache/wink/server/internal/handlers/MediaTypeMappingTest.java
Sat Sep 26 23:37:52 2009
@@ -0,0 +1,122 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.wink.server.internal.handlers;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+
+import org.apache.wink.common.internal.utils.MediaTypeUtils;
+import org.apache.wink.server.handlers.MediaTypeMapperFactory;
+import org.apache.wink.server.handlers.MediaTypeMappingRecord;
+import org.apache.wink.server.internal.servlet.MockServletInvocationTest;
+import org.apache.wink.test.mock.MockRequestConstructor;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.springframework.mock.web.MockHttpServletResponse;
+
+public class MediaTypeMappingTest extends MockServletInvocationTest {
+
+    @Path("/resource1")
+    public static class Resource {
+
+        @GET
+        public Response get() {
+            return Response.ok("Hello world!").type("custom/type").build();
+        }
+    }
+
+    private static class AgentStartsWith implements MediaTypeMappingRecord {
+
+        private String    userAgentStartsWith;
+        private MediaType responseType;
+        private MediaType replacementType;
+
+        public AgentStartsWith(String userAgentStartsWith,
+                               String responseType,
+                               String replacementType) {
+            if (userAgentStartsWith == null)
+                throw new NullPointerException();
+            this.userAgentStartsWith = userAgentStartsWith;
+            this.responseType = MediaType.valueOf(responseType);
+            this.replacementType = MediaType.valueOf(replacementType);
+        }
+
+        public MediaType match(HttpHeaders requestHeaders, MediaType responseMediaType) {
+            if (!MediaTypeUtils.equalsIgnoreParameters(responseMediaType, responseType))
{
+                return null;
+            }
+            String userAgent = requestHeaders.getRequestHeaders().getFirst(HttpHeaders.USER_AGENT);
+            if (userAgent != null && userAgent.startsWith(userAgentStartsWith)) {
+                return replacementType;
+            }
+            return null;
+        }
+    }
+
+    public static class UserMediaTypeMapperFactory extends MediaTypeMapperFactory {
+
+        @Override
+        public List<? extends MediaTypeMappingRecord> getMediaTypeMappings() {
+            List<MediaTypeMappingRecord> records = new ArrayList<MediaTypeMappingRecord>();
+            records.add(new AgentStartsWith("Agent123/", "custom/type", MediaType.TEXT_XML));
+            return records;
+        }
+
+    }
+
+    @Override
+    protected Class<?>[] getClasses() {
+        return new Class<?>[] {Resource.class};
+    }
+
+    public void testMediaTypeMapping() throws Exception {
+        MockHttpServletRequest mockRequest =
+            MockRequestConstructor.constructMockRequest("GET", "/resource1", MediaType.WILDCARD);
+        MockHttpServletResponse response = invoke(mockRequest);
+        assertEquals(200, response.getStatus());
+        assertEquals("Hello world!", response.getContentAsString());
+        assertEquals("custom/type", response.getContentType());
+
+        mockRequest =
+            MockRequestConstructor.constructMockRequest("GET", "/resource1", MediaType.WILDCARD);
+        mockRequest.addHeader(HttpHeaders.USER_AGENT, "Agent123/abcd");
+        response = invoke(mockRequest);
+        assertEquals(200, response.getStatus());
+        assertEquals("Hello world!", response.getContentAsString());
+        assertEquals(MediaType.TEXT_XML, response.getContentType());
+
+        mockRequest =
+            MockRequestConstructor.constructMockRequest("GET", "/resource1", MediaType.WILDCARD);
+        mockRequest.addHeader(HttpHeaders.USER_AGENT, "Agent123abcd");
+        response = invoke(mockRequest);
+        assertEquals(200, response.getStatus());
+        assertEquals("Hello world!", response.getContentAsString());
+        assertEquals("custom/type", response.getContentType());
+    }
+
+    @Override
+    protected String getPropertiesFile() {
+        return getClass().getName().replaceAll("\\.", "/") + ".properties";
+    }
+}

Propchange: incubator/wink/trunk/wink-server/src/test/java/org/apache/wink/server/internal/handlers/MediaTypeMappingTest.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/wink/trunk/wink-server/src/test/resources/org/apache/wink/server/internal/handlers/MediaTypeMapping2Test.properties
URL: http://svn.apache.org/viewvc/incubator/wink/trunk/wink-server/src/test/resources/org/apache/wink/server/internal/handlers/MediaTypeMapping2Test.properties?rev=819229&view=auto
==============================================================================
--- incubator/wink/trunk/wink-server/src/test/resources/org/apache/wink/server/internal/handlers/MediaTypeMapping2Test.properties
(added)
+++ incubator/wink/trunk/wink-server/src/test/resources/org/apache/wink/server/internal/handlers/MediaTypeMapping2Test.properties
Sat Sep 26 23:37:52 2009
@@ -0,0 +1,19 @@
+###############################################################################
+#     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.
+###############################################################################
+wink.mediaTypeMapperFactoryClass=org.apache.wink.server.internal.handlers.MediaTypeMapping2Test$UserMediaTypeMapperFactory
\ No newline at end of file

Propchange: incubator/wink/trunk/wink-server/src/test/resources/org/apache/wink/server/internal/handlers/MediaTypeMapping2Test.properties
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/wink/trunk/wink-server/src/test/resources/org/apache/wink/server/internal/handlers/MediaTypeMappingTest.properties
URL: http://svn.apache.org/viewvc/incubator/wink/trunk/wink-server/src/test/resources/org/apache/wink/server/internal/handlers/MediaTypeMappingTest.properties?rev=819229&view=auto
==============================================================================
--- incubator/wink/trunk/wink-server/src/test/resources/org/apache/wink/server/internal/handlers/MediaTypeMappingTest.properties
(added)
+++ incubator/wink/trunk/wink-server/src/test/resources/org/apache/wink/server/internal/handlers/MediaTypeMappingTest.properties
Sat Sep 26 23:37:52 2009
@@ -0,0 +1,19 @@
+###############################################################################
+#     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.
+###############################################################################
+wink.mediaTypeMapperFactoryClass=org.apache.wink.server.internal.handlers.MediaTypeMappingTest$UserMediaTypeMapperFactory
\ No newline at end of file

Propchange: incubator/wink/trunk/wink-server/src/test/resources/org/apache/wink/server/internal/handlers/MediaTypeMappingTest.properties
------------------------------------------------------------------------------
    svn:eol-style = native



Mime
View raw message