cxf-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From cschnei...@apache.org
Subject svn commit: r1042403 - in /cxf/trunk/rt/transports/http/src: main/java/org/apache/cxf/transport/http/ main/java/org/apache/cxf/transport/servlet/ test/java/org/apache/cxf/transport/servlet/
Date Sun, 05 Dec 2010 18:57:57 GMT
Author: cschneider
Date: Sun Dec  5 18:57:57 2010
New Revision: 1042403

URL: http://svn.apache.org/viewvc?rev=1042403&view=rev
Log:
CXF-3160 Reduce Code duplication between http transport variants

Modified:
    cxf/trunk/rt/transports/http/src/main/java/org/apache/cxf/transport/http/AbstractHTTPDestination.java
    cxf/trunk/rt/transports/http/src/main/java/org/apache/cxf/transport/http/HTTPConduit.java
    cxf/trunk/rt/transports/http/src/main/java/org/apache/cxf/transport/http/Headers.java
    cxf/trunk/rt/transports/http/src/main/java/org/apache/cxf/transport/http/HttpServletRequestSnapshot.java
    cxf/trunk/rt/transports/http/src/main/java/org/apache/cxf/transport/servlet/AbstractServletController.java
    cxf/trunk/rt/transports/http/src/main/java/org/apache/cxf/transport/servlet/ServletController.java
    cxf/trunk/rt/transports/http/src/main/java/org/apache/cxf/transport/servlet/ServletDestination.java
    cxf/trunk/rt/transports/http/src/test/java/org/apache/cxf/transport/servlet/ServletControllerTest.java

Modified: cxf/trunk/rt/transports/http/src/main/java/org/apache/cxf/transport/http/AbstractHTTPDestination.java
URL: http://svn.apache.org/viewvc/cxf/trunk/rt/transports/http/src/main/java/org/apache/cxf/transport/http/AbstractHTTPDestination.java?rev=1042403&r1=1042402&r2=1042403&view=diff
==============================================================================
--- cxf/trunk/rt/transports/http/src/main/java/org/apache/cxf/transport/http/AbstractHTTPDestination.java
(original)
+++ cxf/trunk/rt/transports/http/src/main/java/org/apache/cxf/transport/http/AbstractHTTPDestination.java
Sun Dec  5 18:57:57 2010
@@ -26,14 +26,8 @@ import java.net.HttpURLConnection;
 import java.net.ServerSocket;
 import java.net.URL;
 import java.security.Principal;
-import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collection;
-import java.util.Collections;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
 import java.util.Map;
 import java.util.logging.Level;
 import java.util.logging.Logger;
@@ -54,7 +48,6 @@ import org.apache.cxf.common.util.String
 import org.apache.cxf.configuration.Configurable;
 import org.apache.cxf.configuration.security.AuthorizationPolicy;
 import org.apache.cxf.continuations.ContinuationProvider;
-import org.apache.cxf.helpers.CastUtils;
 import org.apache.cxf.helpers.HttpHeaderHelper;
 import org.apache.cxf.interceptor.Fault;
 import org.apache.cxf.interceptor.Interceptor;
@@ -62,7 +55,9 @@ import org.apache.cxf.io.AbstractWrapped
 import org.apache.cxf.io.DelegatingInputStream;
 import org.apache.cxf.message.Attachment;
 import org.apache.cxf.message.Exchange;
+import org.apache.cxf.message.ExchangeImpl;
 import org.apache.cxf.message.Message;
+import org.apache.cxf.message.MessageImpl;
 import org.apache.cxf.message.MessageUtils;
 import org.apache.cxf.security.SecurityContext;
 import org.apache.cxf.service.model.EndpointInfo;
@@ -90,14 +85,11 @@ public abstract class AbstractHTTPDestin
     public static final String HTTP_RESPONSE = "HTTP.RESPONSE";
     public static final String HTTP_CONTEXT = "HTTP.CONTEXT";
     public static final String HTTP_CONFIG = "HTTP.CONFIG";
-    public static final String PROTOCOL_HEADERS_CONTENT_TYPE = Message.CONTENT_TYPE.toLowerCase();
         
     public static final String RESPONSE_COMMITED = "http.response.done";
     public static final String REQUEST_REDIRECTED = "http.request.redirected";
     public static final String CXF_CONTINUATION_MESSAGE = "cxf.continuation.message";
-    
-    private static final String HTTP_HEADERS_SETCOOKIE = "Set-Cookie";
-    
+
     private static final Logger LOG = LogUtils.getL7dLogger(AbstractHTTPDestination.class);
     
     private static final long serialVersionUID = 1L;
@@ -138,58 +130,29 @@ public abstract class AbstractHTTPDestin
         initConfig();
     }
     
-    
-
-    /**
-     * Cache HTTP headers in message.
-     * 
-     * @param message the current message
-     */
-    protected void setHeaders(Message message) {
-        Map<String, List<String>> requestHeaders = new HashMap<String, List<String>>();
-        copyRequestHeaders(message, requestHeaders);
-        message.put(Message.PROTOCOL_HEADERS, requestHeaders);
-
-        if (requestHeaders.containsKey("Authorization")) {
-            List<String> authorizationLines = requestHeaders.get("Authorization");

-            String credentials = authorizationLines.get(0);
-            if (credentials != null && !StringUtils.isEmpty(credentials.trim()))
{
-                String authType = credentials.split(" ")[0];
-                if ("Basic".equals(authType)) {
-                    String authEncoded = credentials.split(" ")[1];
-                    try {
-                        String authDecoded = new String(Base64Utility.decode(authEncoded));
-                        String authInfo[] = authDecoded.split(":");
-                        String username = (authInfo.length > 0) ? authInfo[0] : "";
-                        // Below line for systems that blank out password after authentication;
-                        // see CXF-1495 for more info
-                        String password = (authInfo.length > 1) ? authInfo[1] : "";
-                        AuthorizationPolicy policy = new AuthorizationPolicy();
-                        policy.setUserName(username);
-                        policy.setPassword(password);
-                        
-                        message.put(AuthorizationPolicy.class, policy);
-                    } catch (Base64Exception ex) {
-                        //ignore, we'll leave things alone.  They can try decoding it themselves
-                    }
-                }
-            }
-        }
-        
-        if (LOG.isLoggable(Level.FINE)) {
-            LOG.log(Level.FINE, "Request Headers: " + requestHeaders.toString());
+    private AuthorizationPolicy getAuthorizationPolicyFromMessage(String credentials) {
+        if (credentials == null || StringUtils.isEmpty(credentials.trim())) {
+            return null;
         }
-           
-    }
-    
-    protected void updateResponseHeaders(Message message) {
-        Map<String, List<String>> responseHeaders =
-            CastUtils.cast((Map)message.get(Message.PROTOCOL_HEADERS));
-        if (responseHeaders == null) {
-            responseHeaders = new HashMap<String, List<String>>();
-            message.put(Message.PROTOCOL_HEADERS, responseHeaders);         
+        String authType = credentials.split(" ")[0];
+        if ("Basic".equals(authType)) {
+            String authEncoded = credentials.split(" ")[1];
+            try {
+                String authDecoded = new String(Base64Utility.decode(authEncoded));
+                String authInfo[] = authDecoded.split(":");
+                String username = (authInfo.length > 0) ? authInfo[0] : "";
+                // Below line for systems that blank out password after authentication;
+                // see CXF-1495 for more info
+                String password = (authInfo.length > 1) ? authInfo[1] : "";
+                AuthorizationPolicy policy = new AuthorizationPolicy();
+                policy.setUserName(username);
+                policy.setPassword(password);
+                return policy;
+            } catch (Base64Exception ex) {
+                // Invalid authentication => treat as not authenticated
+            }
         }
-        setPolicies(responseHeaders);
+        return null;
     }
     
     /** 
@@ -201,83 +164,33 @@ public abstract class AbstractHTTPDestin
         return ex == null ? false : ex.isOneWay();
     }
     
-    /**
-     * Copy the request headers into the message.
-     * 
-     * @param message the current message
-     * @param headers the current set of headers
-     */
-    protected void copyRequestHeaders(Message message, Map<String, List<String>>
headers) {
-        HttpServletRequest req = (HttpServletRequest)message.get(HTTP_REQUEST);
-        
-        //TODO how to deal with the fields        
-        for (Enumeration e = req.getHeaderNames(); e.hasMoreElements();) {
-            String fname = (String)e.nextElement();
-            String mappedName = HttpHeaderHelper.getHeaderKey(fname);
-            List<String> values;
-            if (headers.containsKey(mappedName)) {
-                values = headers.get(mappedName);
-            } else {
-                values = new ArrayList<String>();
-                headers.put(mappedName, values);
-            }
-            for (Enumeration e2 = req.getHeaders(fname); e2.hasMoreElements();) {
-                String val = (String)e2.nextElement();
-                values.add(val);
-            }
-        }
-        headers.put(Message.CONTENT_TYPE, Collections.singletonList(req.getContentType()));
-    }
+    public void invoke(final ServletContext context, 
+                       final HttpServletRequest req, 
+                       final HttpServletResponse resp) throws IOException {
+        invoke(null, context, req, resp);
+    }
+    
+    public void invoke(final ServletConfig config,
+                       final ServletContext context, 
+                       final HttpServletRequest req, 
+                       final HttpServletResponse resp) throws IOException {
+        
+        MessageImpl inMessage = new MessageImpl();
+        setupMessage(inMessage,
+                     config,
+                     context,
+                     req,
+                     resp);
+
+        ExchangeImpl exchange = new ExchangeImpl();
+        exchange.setInMessage(inMessage);
+        exchange.setSession(new HTTPSession(req));
+        inMessage.setDestination(this);
 
-    /**
-     * Copy the response headers into the response.
-     * 
-     * @param message the current message
-     * @param headers the current set of headers
-     */
-    protected void copyResponseHeaders(Message message, HttpServletResponse response) {
-        String ct  = (String)message.get(Message.CONTENT_TYPE);
-        String enc = (String)message.get(Message.ENCODING);
-        
-        if (null != ct 
-            && null != enc
-            && ct.indexOf("charset=") == -1
-            && !ct.toLowerCase().contains("multipart/related")) {
-            ct = ct + "; charset=" + enc;
-        }
-
-        Map<?, ?> headers = (Map<?, ?>)message.get(Message.PROTOCOL_HEADERS);
-        if (null != headers) {
-            
-            if (!headers.containsKey(Message.CONTENT_TYPE)) {
-                response.setContentType(ct);
-            }
-            
-            for (Iterator<?> iter = headers.keySet().iterator(); iter.hasNext();) {
-                String header = (String)iter.next();
-                List<?> headerList = (List<?>)headers.get(header);
-                StringBuilder sb = new StringBuilder();
-
-                if (HTTP_HEADERS_SETCOOKIE.equals(header)) {
-                    for (int i = 0; i < headerList.size(); i++) {
-                        response.addHeader(header, headerList.get(i).toString());
-                    }
-                } else {
-                    for (int i = 0; i < headerList.size(); i++) {
-                        sb.append(headerList.get(i));
-                        if (i + 1 < headerList.size()) {
-                            sb.append(',');
-                        }
-                    }
-                }
-
-                response.addHeader(header, sb.toString());
-            }
-        } else {
-            response.setContentType(ct);
-        }
+        incomingObserver.onMessage(inMessage);
+ 
     }
-    
+
     protected void setupMessage(Message inMessage,
                                 final ServletContext context, 
                                 final HttpServletRequest req, 
@@ -319,31 +232,12 @@ public abstract class AbstractHTTPDestin
             contextPath = "";
         }
         inMessage.put(Message.PATH_INFO, contextPath + req.getPathInfo());
-        
         String contentType = req.getContentType();
-        String enc = HttpHeaderHelper.findCharset(contentType);
-        if (enc == null) {
-            enc = req.getCharacterEncoding();
-        }
-        // work around a bug with Jetty which results in the character
-        // encoding not being trimmed correctly.
-        if (enc != null && enc.endsWith("\"")) {
-            enc = enc.substring(0, enc.length() - 1);
-        }
-        if (enc != null || "POST".equals(req.getMethod()) || "PUT".equals(req.getMethod()))
{
-            //allow gets/deletes/options to not specify an encoding
-            String normalizedEncoding = HttpHeaderHelper.mapCharset(enc);
-            if (normalizedEncoding == null) {
-                String m = new org.apache.cxf.common.i18n.Message("INVALID_ENCODING_MSG",
-                                                                  LOG, enc).toString();
-                LOG.log(Level.WARNING, m);
-                throw new IOException(m);   
-            }
-            inMessage.put(Message.ENCODING, normalizedEncoding);
-        }
-        
-        inMessage.put(Message.QUERY_STRING, req.getQueryString());
         inMessage.put(Message.CONTENT_TYPE, contentType);
+        setEncoding(inMessage, req, contentType);
+
+        inMessage.put(Message.QUERY_STRING, req.getQueryString());
+
         inMessage.put(Message.ACCEPT_CONTENT_TYPE, req.getHeader("Accept"));
         String basePath = getBasePath(contextPath);
         if (!StringUtils.isEmpty(basePath)) {
@@ -360,7 +254,11 @@ public abstract class AbstractHTTPDestin
             }
         });
         
-        setHeaders(inMessage);
+        Headers headers = new Headers(inMessage);
+        headers.copyFromRequest(req);
+        String credentials = headers.getAuthorization();
+        AuthorizationPolicy authPolicy = getAuthorizationPolicyFromMessage(credentials);
+        inMessage.put(AuthorizationPolicy.class, authPolicy);
         
         SSLUtils.propogateSecureSession(req, inMessage);
 
@@ -369,6 +267,33 @@ public abstract class AbstractHTTPDestin
                 Arrays.asList(new Interceptor[] {CertConstraintsInterceptor.INSTANCE}));
 
     }
+
+    private String setEncoding(final Message inMessage, 
+                               final HttpServletRequest req, 
+                               final String contentType) throws IOException {
+        
+        String enc = HttpHeaderHelper.findCharset(contentType);
+        if (enc == null) {
+            enc = req.getCharacterEncoding();
+        }
+        // work around a bug with Jetty which results in the character
+        // encoding not being trimmed correctly.
+        if (enc != null && enc.endsWith("\"")) {
+            enc = enc.substring(0, enc.length() - 1);
+        }
+        if (enc != null || "POST".equals(req.getMethod()) || "PUT".equals(req.getMethod()))
{
+            //allow gets/deletes/options to not specify an encoding
+            String normalizedEncoding = HttpHeaderHelper.mapCharset(enc);
+            if (normalizedEncoding == null) {
+                String m = new org.apache.cxf.common.i18n.Message("INVALID_ENCODING_MSG",
+                                                                  LOG, enc).toString();
+                LOG.log(Level.WARNING, m);
+                throw new IOException(m);   
+            }
+            inMessage.put(Message.ENCODING, normalizedEncoding);
+        }
+        return contentType;
+    }
     protected Message retrieveFromContinuation(HttpServletRequest req) {
         if (!isServlet3) {
             return null;
@@ -445,48 +370,7 @@ public abstract class AbstractHTTPDestin
                     new HTTPServerPolicy(), HTTPServerPolicy.class);
         }
     }
-    private static List<String> createMutableList(String val) {
-        return new ArrayList<String>(Arrays.asList(new String[] {val}));
-    }
-    void setPolicies(Map<String, List<String>> headers) {
-        HTTPServerPolicy policy = server; 
-        if (policy.isSetCacheControl()) {
-            headers.put("Cache-Control",
-                        createMutableList(policy.getCacheControl().value()));
-        }
-        if (policy.isSetContentLocation()) {
-            headers.put("Content-Location",
-                        createMutableList(policy.getContentLocation()));
-        }
-        if (policy.isSetContentEncoding()) {
-            headers.put("Content-Encoding",
-                        createMutableList(policy.getContentEncoding()));
-        }
-        if (policy.isSetContentType()) {
-            headers.put(HttpHeaderHelper.CONTENT_TYPE,
-                        createMutableList(policy.getContentType()));
-        }
-        if (policy.isSetServerType()) {
-            headers.put("Server",
-                        createMutableList(policy.getServerType()));
-        }
-        if (policy.isSetHonorKeepAlive() && !policy.isHonorKeepAlive()) {
-            headers.put("Connection",
-                        createMutableList("close"));
-        } else if (policy.isSetKeepAliveParameters()) {
-            headers.put("Keep-Alive", createMutableList(policy.getKeepAliveParameters()));
-        }
-        
-    
-        
-    /*
-     * TODO - hook up these policies
-    <xs:attribute name="SuppressClientSendErrors" type="xs:boolean" use="optional" default="false">
-    <xs:attribute name="SuppressClientReceiveErrors" type="xs:boolean" use="optional"
default="false">
-    */
-    }
-  
-   
+
     /**
      * On first write, we need to make sure any attachments and such that are still on the
incoming stream 
      * are read in.  Otherwise we can get into a deadlock where the client is still trying
to send the 
@@ -527,47 +411,58 @@ public abstract class AbstractHTTPDestin
         if (isResponseRedirected(outMessage)) {
             return null;
         }
-        
+
         cacheInput(outMessage);
-        
-        updateResponseHeaders(outMessage);
-        Object responseObj = outMessage.get(HTTP_RESPONSE);
+
+        new Headers(outMessage).setFromServerPolicy(server);
+
         OutputStream responseStream = null;
         boolean oneWay = isOneWay(outMessage);
-        if (responseObj instanceof HttpServletResponse) {
-            HttpServletResponse response = (HttpServletResponse)responseObj;
 
-            Integer i = (Integer)outMessage.get(Message.RESPONSE_CODE);
-            if (i != null) {
-                int status = i.intValue();  
-                if (HttpURLConnection.HTTP_INTERNAL_ERROR == i) {
-                    Map<Object, Object> pHeaders = 
-                        CastUtils.cast((Map)outMessage.get(Message.PROTOCOL_HEADERS));
-                    if (null != pHeaders && pHeaders.containsKey(PROTOCOL_HEADERS_CONTENT_TYPE))
{
-                        pHeaders.remove(PROTOCOL_HEADERS_CONTENT_TYPE);
-                    }
-                }
-                response.setStatus(status);
-            } else if (oneWay && !MessageUtils.isPartialResponse(outMessage)) {
-                response.setStatus(HttpURLConnection.HTTP_ACCEPTED);
-            } else {
-                response.setStatus(HttpURLConnection.HTTP_OK);
-            }
+        HttpServletResponse response = getHttpResponseFromMessage(outMessage);
+
+        int responseCode = getReponseCodeFromMessage(outMessage);
+        response.setStatus(responseCode);
+        if (HttpURLConnection.HTTP_INTERNAL_ERROR == responseCode) {
+            new Headers(outMessage).removeContentType();
+        }
+        new Headers(outMessage).copyToResponse(response);
+
+        if (oneWay && !MessageUtils.isPartialResponse(outMessage)) {
+            response.setContentLength(0);
+            response.flushBuffer();
+            response.getOutputStream().close();
+        } else if (!getStream) {
+            response.getOutputStream().close();
+        } else {
+            responseStream = response.getOutputStream();                
+        }
 
-            copyResponseHeaders(outMessage, response);
+        if (oneWay) {
+            outMessage.remove(HTTP_RESPONSE);
+        }
+        return responseStream;
+    }
 
-            if (oneWay && !MessageUtils.isPartialResponse(outMessage)) {
-                response.setContentLength(0);
-                response.flushBuffer();
-                response.getOutputStream().close();
-            } else if (!getStream) {
-                response.getOutputStream().close();
-            } else {
-                responseStream = response.getOutputStream();                
-            }
+    private int getReponseCodeFromMessage(Message message) {
+        Integer i = (Integer)message.get(Message.RESPONSE_CODE);
+        if (i != null) {
+            return i.intValue();  
+        } else if (isOneWay(message) && !MessageUtils.isPartialResponse(message))
{
+            return HttpURLConnection.HTTP_ACCEPTED;
+        } else {
+            return HttpURLConnection.HTTP_OK;
+        }
+    }
+
+    
+    private HttpServletResponse getHttpResponseFromMessage(Message message) throws IOException
{
+        Object responseObj = message.get(HTTP_RESPONSE);
+        if (responseObj instanceof HttpServletResponse) {
+            return (HttpServletResponse)responseObj;
         } else if (null != responseObj) {
             String m = (new org.apache.cxf.common.i18n.Message("UNEXPECTED_RESPONSE_TYPE_MSG",
-                LOG, responseObj.getClass())).toString();
+                    LOG, responseObj.getClass())).toString();
             LOG.log(Level.WARNING, m);
             throw new IOException(m);   
         } else {
@@ -575,17 +470,12 @@ public abstract class AbstractHTTPDestin
             LOG.log(Level.WARNING, m);
             throw new IOException(m);
         }
-
-        if (oneWay) {
-            outMessage.remove(HTTP_RESPONSE);
-        }
-        return responseStream;
     }
-    
+
     private boolean isResponseRedirected(Message outMessage) {
         return Boolean.TRUE.equals(outMessage.get(REQUEST_REDIRECTED));
     }
-    
+
     /**
      * Backchannel conduit.
      */
@@ -738,6 +628,7 @@ public abstract class AbstractHTTPDestin
      * 
      * @see org.apache.cxf.transport.AbstractMultiplexDestination#getId(java.util.Map)
      */
+    @SuppressWarnings("rawtypes")
     public String getId(Map context) {
         String id = null;
 
@@ -799,5 +690,5 @@ public abstract class AbstractHTTPDestin
     public boolean canAssert(QName type) {
         return PolicyUtils.HTTPSERVERPOLICY_ASSERTION_QNAME.equals(type); 
     }
-    
+
 }

Modified: cxf/trunk/rt/transports/http/src/main/java/org/apache/cxf/transport/http/HTTPConduit.java
URL: http://svn.apache.org/viewvc/cxf/trunk/rt/transports/http/src/main/java/org/apache/cxf/transport/http/HTTPConduit.java?rev=1042403&r1=1042402&r2=1042403&view=diff
==============================================================================
--- cxf/trunk/rt/transports/http/src/main/java/org/apache/cxf/transport/http/HTTPConduit.java
(original)
+++ cxf/trunk/rt/transports/http/src/main/java/org/apache/cxf/transport/http/HTTPConduit.java
Sun Dec  5 18:57:57 2010
@@ -523,7 +523,7 @@ public class HTTPConduit 
         }
 
         setHeadersByAuthorizationPolicy(message, currentURL);
-        new Headers(message).setHeadersByClientPolicy(getClient(message));
+        new Headers(message).setFromClientPolicy(getClient(message));
 
         message.setContent(OutputStream.class, 
                            new WrappedOutputStream(

Modified: cxf/trunk/rt/transports/http/src/main/java/org/apache/cxf/transport/http/Headers.java
URL: http://svn.apache.org/viewvc/cxf/trunk/rt/transports/http/src/main/java/org/apache/cxf/transport/http/Headers.java?rev=1042403&r1=1042402&r2=1042403&view=diff
==============================================================================
--- cxf/trunk/rt/transports/http/src/main/java/org/apache/cxf/transport/http/Headers.java
(original)
+++ cxf/trunk/rt/transports/http/src/main/java/org/apache/cxf/transport/http/Headers.java
Sun Dec  5 18:57:57 2010
@@ -23,7 +23,10 @@ import java.net.HttpURLConnection;
 import java.net.URLConnection;
 import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.Collections;
+import java.util.Enumeration;
 import java.util.HashMap;
+import java.util.Iterator;
 import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
@@ -31,11 +34,15 @@ import java.util.Map;
 import java.util.logging.Level;
 import java.util.logging.Logger;
 
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
 import org.apache.cxf.common.logging.LogUtils;
 import org.apache.cxf.helpers.CastUtils;
 import org.apache.cxf.helpers.HttpHeaderHelper;
 import org.apache.cxf.message.Message;
 import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;
+import org.apache.cxf.transports.http.configuration.HTTPServerPolicy;
 import org.apache.cxf.version.Version;
 
 public class Headers {
@@ -44,6 +51,9 @@ public class Headers {
      *  is used to get the response.
      */
     public static final String KEY_HTTP_CONNECTION = "http.connection";
+    public static final String PROTOCOL_HEADERS_CONTENT_TYPE = Message.CONTENT_TYPE.toLowerCase();
+    private static final String HTTP_HEADERS_SETCOOKIE = "Set-Cookie";
+
     private static final Logger LOG = LogUtils.getL7dLogger(Headers.class);
     private final Message message;
     private final Map<String, List<String>> headers;
@@ -78,7 +88,7 @@ public class Headers {
      * 
      * REVISIT: A cookie is set statically from configuration? 
      */
-    void setHeadersByClientPolicy(HTTPClientPolicy policy) {
+    void setFromClientPolicy(HTTPClientPolicy policy) {
         if (policy == null) {
             return;
         }
@@ -124,6 +134,43 @@ public class Headers {
                     createMutableList(policy.getReferer()));
         }
     }
+    
+    void setFromServerPolicy(HTTPServerPolicy policy) {
+        if (policy.isSetCacheControl()) {
+            headers.put("Cache-Control",
+                        createMutableList(policy.getCacheControl().value()));
+        }
+        if (policy.isSetContentLocation()) {
+            headers.put("Content-Location",
+                        createMutableList(policy.getContentLocation()));
+        }
+        if (policy.isSetContentEncoding()) {
+            headers.put("Content-Encoding",
+                        createMutableList(policy.getContentEncoding()));
+        }
+        if (policy.isSetContentType()) {
+            headers.put(HttpHeaderHelper.CONTENT_TYPE,
+                        createMutableList(policy.getContentType()));
+        }
+        if (policy.isSetServerType()) {
+            headers.put("Server",
+                        createMutableList(policy.getServerType()));
+        }
+        if (policy.isSetHonorKeepAlive() && !policy.isHonorKeepAlive()) {
+            headers.put("Connection",
+                        createMutableList("close"));
+        } else if (policy.isSetKeepAliveParameters()) {
+            headers.put("Keep-Alive", createMutableList(policy.getKeepAliveParameters()));
+        }
+        
+    
+        
+    /*
+     * TODO - hook up these policies
+    <xs:attribute name="SuppressClientSendErrors" type="xs:boolean" use="optional" default="false">
+    <xs:attribute name="SuppressClientReceiveErrors" type="xs:boolean" use="optional"
default="false">
+    */
+    }
 
     public void removeAuthorizationHeaders() {
         headers.remove("Authorization");
@@ -161,7 +208,7 @@ public class Headers {
         message.put(Message.PROTOCOL_HEADERS, headers);
         return headers;
     }
-    
+
     public void readFromConnection(HttpURLConnection connection) {
         Map<String, List<String>> origHeaders = connection.getHeaderFields();
         headers.clear();
@@ -265,5 +312,99 @@ public class Headers {
             connection.addRequestProperty("User-Agent", Version.getCompleteVersionString());
         }
     }
+    
+    /**
+     * Copy the request headers into the message.
+     * 
+     * @param message the current message
+     * @param headers the current set of headers
+     */
+    protected void copyFromRequest(HttpServletRequest req) {
+
+        //TODO how to deal with the fields        
+        for (Enumeration<String> e = req.getHeaderNames(); e.hasMoreElements();) {
+            String fname = (String)e.nextElement();
+            String mappedName = HttpHeaderHelper.getHeaderKey(fname);
+            List<String> values;
+            if (headers.containsKey(mappedName)) {
+                values = headers.get(mappedName);
+            } else {
+                values = new ArrayList<String>();
+                headers.put(mappedName, values);
+            }
+            for (Enumeration<String> e2 = req.getHeaders(fname); e2.hasMoreElements();)
{
+                String val = (String)e2.nextElement();
+                values.add(val);
+            }
+        }
+        headers.put(Message.CONTENT_TYPE, Collections.singletonList(req.getContentType()));
+        if (LOG.isLoggable(Level.FINE)) {
+            LOG.log(Level.FINE, "Request Headers: " + headers.toString());
+        }
+    }
+
+    private String getContentTypeFromMessage() {
+        final String ct  = (String)message.get(Message.CONTENT_TYPE);
+        final String enc = (String)message.get(Message.ENCODING);
+        
+        if (null != ct 
+            && null != enc
+            && ct.indexOf("charset=") == -1
+            && !ct.toLowerCase().contains("multipart/related")) {
+            return ct + "; charset=" + enc;
+        } else {
+            return ct;
+        }
+    }
+    
+    /**
+     * Copy the response headers into the response.
+     * 
+     * @param message the current message
+     * @param headers the current set of headers
+     */
+    protected void copyToResponse(HttpServletResponse response) {
+        String contentType = getContentTypeFromMessage();
+ 
+        if (!headers.containsKey(Message.CONTENT_TYPE)) {
+            response.setContentType(contentType);
+        }
+
+        for (Iterator<?> iter = headers.keySet().iterator(); iter.hasNext();) {
+            String header = (String)iter.next();
+            List<?> headerList = (List<?>)headers.get(header);
+            StringBuilder sb = new StringBuilder();
+
+            if (HTTP_HEADERS_SETCOOKIE.equals(header)) {
+                for (int i = 0; i < headerList.size(); i++) {
+                    response.addHeader(header, headerList.get(i).toString());
+                }
+            } else {
+                for (int i = 0; i < headerList.size(); i++) {
+                    sb.append(headerList.get(i));
+                    if (i + 1 < headerList.size()) {
+                        sb.append(',');
+                    }
+                }
+            }
+
+            response.addHeader(header, sb.toString());
+        }
+    }
+    
+    void removeContentType() {
+        if (headers.containsKey(PROTOCOL_HEADERS_CONTENT_TYPE)) {
+            headers.remove(PROTOCOL_HEADERS_CONTENT_TYPE);
+        }
+    }
+
+    public String getAuthorization() {
+        if (headers.containsKey("Authorization")) {
+            List<String> authorizationLines = headers.get("Authorization"); 
+            return authorizationLines.get(0);
+        } else {
+            return null;
+        }
+    }
 
 }

Modified: cxf/trunk/rt/transports/http/src/main/java/org/apache/cxf/transport/http/HttpServletRequestSnapshot.java
URL: http://svn.apache.org/viewvc/cxf/trunk/rt/transports/http/src/main/java/org/apache/cxf/transport/http/HttpServletRequestSnapshot.java?rev=1042403&r1=1042402&r2=1042403&view=diff
==============================================================================
--- cxf/trunk/rt/transports/http/src/main/java/org/apache/cxf/transport/http/HttpServletRequestSnapshot.java
(original)
+++ cxf/trunk/rt/transports/http/src/main/java/org/apache/cxf/transport/http/HttpServletRequestSnapshot.java
Sun Dec  5 18:57:57 2010
@@ -37,6 +37,7 @@ public class HttpServletRequestSnapshot 
     private Cookie[] cookies;
     private String localAddr;
     private Locale local;
+    @SuppressWarnings("rawtypes")
     private Enumeration locals;
     private String localName;
     private int localPort = -1;
@@ -125,13 +126,17 @@ public class HttpServletRequestSnapshot 
         return null;
     }
 
-    @SuppressWarnings("unchecked")
+    @SuppressWarnings({
+        "unchecked", "rawtypes"
+    })
     @Override
     public Enumeration getHeaderNames() {
         return this.requestHeaderNames;
     }
 
-    @SuppressWarnings("unchecked")
+    @SuppressWarnings({
+        "unchecked", "rawtypes"
+    })
     @Override
     public Enumeration getHeaders(String name) {
         return headersMap.get(name);
@@ -227,7 +232,9 @@ public class HttpServletRequestSnapshot 
         return this.local;
     }
 
-    @SuppressWarnings("unchecked")
+    @SuppressWarnings({
+        "unchecked", "rawtypes"
+    })
     @Override
     public Enumeration getLocales() {
         return this.locals;

Modified: cxf/trunk/rt/transports/http/src/main/java/org/apache/cxf/transport/servlet/AbstractServletController.java
URL: http://svn.apache.org/viewvc/cxf/trunk/rt/transports/http/src/main/java/org/apache/cxf/transport/servlet/AbstractServletController.java?rev=1042403&r1=1042402&r2=1042403&view=diff
==============================================================================
--- cxf/trunk/rt/transports/http/src/main/java/org/apache/cxf/transport/servlet/AbstractServletController.java
(original)
+++ cxf/trunk/rt/transports/http/src/main/java/org/apache/cxf/transport/servlet/AbstractServletController.java
Sun Dec  5 18:57:57 2010
@@ -19,27 +19,38 @@
 
 package org.apache.cxf.transport.servlet;
 
+import java.io.IOException;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
 import javax.servlet.ServletConfig;
+import javax.servlet.ServletException;
 import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
 
+import org.apache.cxf.common.logging.LogUtils;
 import org.apache.cxf.common.util.UrlUtils;
+import org.apache.cxf.transport.http.AbstractHTTPDestination;
 
 public abstract class AbstractServletController {
-    
     protected static final String DEFAULT_LISTINGS_CLASSIFIER = "/services";
+    private static final Logger LOG = LogUtils.getL7dLogger(ServletController.class);
+    
     protected boolean isHideServiceList;
     protected boolean disableAddressUpdates;
     protected String forcedBaseAddress;
     protected String serviceListStyleSheet;
     protected String title;
     protected String serviceListRelativePath = DEFAULT_LISTINGS_CLASSIFIER;
+    protected ServletConfig servletConfig;
     
     protected AbstractServletController() {
         
     }
     
     protected AbstractServletController(ServletConfig config) {
-        init(config);
+        this.servletConfig = config;
+        init();
     }
     
     public void setHideServiceList(boolean generate) {
@@ -63,7 +74,7 @@ public abstract class AbstractServletCon
         title = t;
     }
     
-    private void init(ServletConfig servletConfig) {
+    private void init() {
         if (servletConfig == null) {
             return;
         }
@@ -127,5 +138,23 @@ public abstract class AbstractServletCon
         }
         return lastIndex;
     }
-   
+    
+    public void invokeDestination(final HttpServletRequest request, HttpServletResponse response,
+                                  AbstractHTTPDestination d) throws ServletException {
+        if (LOG.isLoggable(Level.FINE)) {
+            LOG.fine("Service http request on thread: " + Thread.currentThread());
+        }
+
+        try {
+            d.invoke(servletConfig, servletConfig.getServletContext(), request, response);
+        } catch (IOException e) {
+            throw new ServletException(e);
+        } finally {
+            if (LOG.isLoggable(Level.FINE)) {
+                LOG.fine("Finished servicing http request on thread: " + Thread.currentThread());
+            }
+        }
+
+    }
+
 }

Modified: cxf/trunk/rt/transports/http/src/main/java/org/apache/cxf/transport/servlet/ServletController.java
URL: http://svn.apache.org/viewvc/cxf/trunk/rt/transports/http/src/main/java/org/apache/cxf/transport/servlet/ServletController.java?rev=1042403&r1=1042402&r2=1042403&view=diff
==============================================================================
--- cxf/trunk/rt/transports/http/src/main/java/org/apache/cxf/transport/servlet/ServletController.java
(original)
+++ cxf/trunk/rt/transports/http/src/main/java/org/apache/cxf/transport/servlet/ServletController.java
Sun Dec  5 18:57:57 2010
@@ -54,8 +54,6 @@ public class ServletController extends A
     private static final Logger LOG = LogUtils.getL7dLogger(ServletController.class);
     
     private ServletTransportFactory transport;
-    private ServletContext servletContext;
-    private ServletConfig servletConfig;
     private Bus bus;
     private volatile String lastBase = "";
     
@@ -65,10 +63,8 @@ public class ServletController extends A
                              Bus b) {
         super(config);
         this.transport = df;
-        this.servletConfig = config;
-        this.servletContext = context;
         this.bus = b;
-        init();
+        this.transport.setServletController(this);
     }
     
     ServletController() {
@@ -451,26 +447,4 @@ public class ServletController extends A
         res.getWriter().write("<html><body>No service was found.</body></html>");
     }
 
-    public void invokeDestination(final HttpServletRequest request, HttpServletResponse response,
-                                  ServletDestination d) throws ServletException {
-        if (LOG.isLoggable(Level.FINE)) {
-            LOG.fine("Service http request on thread: " + Thread.currentThread());
-        }
-
-        try {
-            d.invoke(servletConfig, servletContext, request, response);
-        } catch (IOException e) {
-            throw new ServletException(e);
-        } finally {
-            if (LOG.isLoggable(Level.FINE)) {
-                LOG.fine("Finished servicing http request on thread: " + Thread.currentThread());
-            }
-        }
-
-    }
-    
-    private void init() {
-        transport.setServletController(this);
-    }
-    
 }

Modified: cxf/trunk/rt/transports/http/src/main/java/org/apache/cxf/transport/servlet/ServletDestination.java
URL: http://svn.apache.org/viewvc/cxf/trunk/rt/transports/http/src/main/java/org/apache/cxf/transport/servlet/ServletDestination.java?rev=1042403&r1=1042402&r2=1042403&view=diff
==============================================================================
--- cxf/trunk/rt/transports/http/src/main/java/org/apache/cxf/transport/servlet/ServletDestination.java
(original)
+++ cxf/trunk/rt/transports/http/src/main/java/org/apache/cxf/transport/servlet/ServletDestination.java
Sun Dec  5 18:57:57 2010
@@ -23,18 +23,10 @@ import java.io.IOException;
 import java.net.URI;
 import java.util.logging.Logger;
 
-import javax.servlet.ServletConfig;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
 import org.apache.cxf.Bus;
 import org.apache.cxf.common.logging.LogUtils;
-import org.apache.cxf.message.ExchangeImpl;
-import org.apache.cxf.message.MessageImpl;
 import org.apache.cxf.service.model.EndpointInfo;
 import org.apache.cxf.transport.http.AbstractHTTPDestination;
-import org.apache.cxf.transport.http.HTTPSession;
 
 
 public class ServletDestination extends AbstractHTTPDestination {
@@ -71,32 +63,6 @@ public class ServletDestination extends 
         return LOG;
     }
 
-    public void invoke(final ServletContext context, 
-                       final HttpServletRequest req, 
-                       final HttpServletResponse resp) throws IOException {
-        invoke(null, context, req, resp);
-    }
-    
-    public void invoke(final ServletConfig config,
-                       final ServletContext context, 
-                       final HttpServletRequest req, 
-                       final HttpServletResponse resp) throws IOException {
-        
-        MessageImpl inMessage = new MessageImpl();
-        setupMessage(inMessage,
-                     config,
-                     context,
-                     req,
-                     resp);
-
-        ExchangeImpl exchange = new ExchangeImpl();
-        exchange.setInMessage(inMessage);
-        exchange.setSession(new HTTPSession(req));
-        inMessage.setDestination(this);
-
-        incomingObserver.onMessage(inMessage);
- 
-    }
     protected String getBasePath(String contextPath) throws IOException {
         
         String address = getAddress().getAddress().getValue();

Modified: cxf/trunk/rt/transports/http/src/test/java/org/apache/cxf/transport/servlet/ServletControllerTest.java
URL: http://svn.apache.org/viewvc/cxf/trunk/rt/transports/http/src/test/java/org/apache/cxf/transport/servlet/ServletControllerTest.java?rev=1042403&r1=1042402&r2=1042403&view=diff
==============================================================================
--- cxf/trunk/rt/transports/http/src/test/java/org/apache/cxf/transport/servlet/ServletControllerTest.java
(original)
+++ cxf/trunk/rt/transports/http/src/test/java/org/apache/cxf/transport/servlet/ServletControllerTest.java
Sun Dec  5 18:57:57 2010
@@ -25,6 +25,7 @@ import javax.servlet.http.HttpServletReq
 import javax.servlet.http.HttpServletResponse;
 
 import org.apache.cxf.transport.MessageObserver;
+import org.apache.cxf.transport.http.AbstractHTTPDestination;
 import org.easymock.classextension.EasyMock;
 
 import org.junit.Assert;
@@ -215,7 +216,7 @@ public class ServletControllerTest exten
         
         @Override
         public void invokeDestination(final HttpServletRequest request, HttpServletResponse
response,
-                                      ServletDestination d) throws ServletException {
+                                      AbstractHTTPDestination d) throws ServletException
{
             invokeDestinationCalled = true;
         }
         



Mime
View raw message