Save This Page
Home » axis2-1.5-src » org.apache » axis2 » transport » http » [javadoc | source]
    1   /*
    2    * Licensed to the Apache Software Foundation (ASF) under one
    3    * or more contributor license agreements. See the NOTICE file
    4    * distributed with this work for additional information
    5    * regarding copyright ownership. The ASF licenses this file
    6    * to you under the Apache License, Version 2.0 (the
    7    * "License"); you may not use this file except in compliance
    8    * with the License. You may obtain a copy of the License at
    9    *
   10    * http://www.apache.org/licenses/LICENSE-2.0
   11    *
   12    * Unless required by applicable law or agreed to in writing,
   13    * software distributed under the License is distributed on an
   14    * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
   15    * KIND, either express or implied. See the License for the
   16    * specific language governing permissions and limitations
   17    * under the License.
   18    */
   19   
   20   package org.apache.axis2.transport.http;
   21   
   22   import org.apache.axiom.om.OMAttribute;
   23   import org.apache.axiom.om.OMElement;
   24   import org.apache.axiom.om.OMOutputFormat;
   25   import org.apache.axis2.AxisFault;
   26   import org.apache.axis2.Constants;
   27   import org.apache.axis2.context.MessageContext;
   28   import org.apache.axis2.context.OperationContext;
   29   import org.apache.axis2.description.TransportOutDescription;
   30   import org.apache.axis2.i18n.Messages;
   31   import org.apache.axis2.transport.MessageFormatter;
   32   import org.apache.axis2.transport.TransportUtils;
   33   import org.apache.axis2.util.JavaUtils;
   34   import org.apache.axis2.wsdl.WSDLConstants;
   35   import org.apache.commons.httpclient.Credentials;
   36   import org.apache.commons.httpclient.Header;
   37   import org.apache.commons.httpclient.HeaderElement;
   38   import org.apache.commons.httpclient.HostConfiguration;
   39   import org.apache.commons.httpclient.HttpClient;
   40   import org.apache.commons.httpclient.HttpConnectionManager;
   41   import org.apache.commons.httpclient.HttpMethod;
   42   import org.apache.commons.httpclient.HttpMethodBase;
   43   import org.apache.commons.httpclient.HttpVersion;
   44   import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
   45   import org.apache.commons.httpclient.NTCredentials;
   46   import org.apache.commons.httpclient.NameValuePair;
   47   import org.apache.commons.httpclient.UsernamePasswordCredentials;
   48   import org.apache.commons.httpclient.auth.AuthPolicy;
   49   import org.apache.commons.httpclient.auth.AuthScope;
   50   import org.apache.commons.httpclient.params.HttpMethodParams;
   51   import org.apache.commons.httpclient.protocol.Protocol;
   52   import org.apache.commons.logging.Log;
   53   import org.apache.commons.logging.LogFactory;
   54   
   55   import javax.xml.namespace.QName;
   56   import java.io.IOException;
   57   import java.io.InputStream;
   58   import java.net.URL;
   59   import java.util.ArrayList;
   60   import java.util.HashMap;
   61   import java.util.Iterator;
   62   import java.util.List;
   63   import java.util.Map;
   64   import java.util.zip.GZIPInputStream;
   65   
   66   public abstract class AbstractHTTPSender {
   67       protected static final String ANONYMOUS = "anonymous";
   68       protected static final String PROXY_HOST_NAME = "proxy_host";
   69       protected static final String PROXY_PORT = "proxy_port";
   70       protected boolean chunked = false;
   71       protected String httpVersion = HTTPConstants.HEADER_PROTOCOL_11;
   72       private static final Log log = LogFactory.getLog(AbstractHTTPSender.class);
   73   
   74       protected static final String PROTOCOL_HTTP = "http";
   75       protected static final String PROTOCOL_HTTPS = "https";
   76   
   77       /**
   78        * proxydiscription
   79        */
   80       protected TransportOutDescription proxyOutSetting = null;
   81       protected OMOutputFormat format = new OMOutputFormat();
   82   
   83       /**
   84        * isAllowedRetry will be using to check where the
   85        * retry should be allowed or not.
   86        */
   87       protected boolean isAllowedRetry = false;
   88   
   89       public void setChunked(boolean chunked) {
   90           this.chunked = chunked;
   91       }
   92   
   93       public void setHttpVersion(String version) throws AxisFault {
   94           if (version != null) {
   95               if (HTTPConstants.HEADER_PROTOCOL_11.equals(version)) {
   96                   this.httpVersion = HTTPConstants.HEADER_PROTOCOL_11;
   97               } else if (HTTPConstants.HEADER_PROTOCOL_10.equals(version)) {
   98                   this.httpVersion = HTTPConstants.HEADER_PROTOCOL_10;
   99                   // chunked is not possible with HTTP/1.0
  100                   this.chunked = false;
  101               } else {
  102                   throw new AxisFault(
  103                           "Parameter " + HTTPConstants.PROTOCOL_VERSION
  104                                   + " Can have values only HTTP/1.0 or HTTP/1.1");
  105               }
  106           }
  107       }
  108   
  109       /**
  110        * Collect the HTTP header information and set them in the message context
  111        *
  112        * @param method HttpMethodBase from which to get information
  113        * @param msgContext the MessageContext in which to place the information... OR NOT!
  114        * @throws AxisFault if problems occur
  115        */
  116       protected void obtainHTTPHeaderInformation(HttpMethodBase method,
  117                                                  MessageContext msgContext) throws AxisFault {
  118           // Set RESPONSE properties onto the REQUEST message context.  They will need to be copied off the request context onto
  119           // the response context elsewhere, for example in the OutInOperationClient.
  120           Map transportHeaders = new CommonsTransportHeaders(method.getResponseHeaders());
  121           msgContext.setProperty(MessageContext.TRANSPORT_HEADERS, transportHeaders);
  122           msgContext.setProperty(HTTPConstants.MC_HTTP_STATUS_CODE, new Integer(method.getStatusCode()));
  123           Header header = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_TYPE);
  124   
  125           if (header != null) {
  126               HeaderElement[] headers = header.getElements();
  127               MessageContext inMessageContext = msgContext.getOperationContext().getMessageContext(
  128                       WSDLConstants.MESSAGE_LABEL_IN_VALUE);
  129   
  130               Object contentType = header.getValue();
  131               Object charSetEnc = null;
  132   
  133               for (int i = 0; i < headers.length; i++) {
  134                   NameValuePair charsetEnc = headers[i].getParameterByName(
  135                           HTTPConstants.CHAR_SET_ENCODING);
  136                   if (charsetEnc != null) {
  137                       charSetEnc = charsetEnc.getValue();
  138                   }
  139               }
  140   
  141               if (inMessageContext != null) {
  142                   inMessageContext
  143                           .setProperty(Constants.Configuration.CONTENT_TYPE, contentType);
  144                   inMessageContext
  145                           .setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, charSetEnc);
  146               } else {
  147   
  148                   // Transport details will be stored in a HashMap so that anybody interested can
  149                   // retrieve them
  150                   HashMap transportInfoMap = new HashMap();
  151                   transportInfoMap.put(Constants.Configuration.CONTENT_TYPE, contentType);
  152                   transportInfoMap.put(Constants.Configuration.CHARACTER_SET_ENCODING, charSetEnc);
  153   
  154                   //the HashMap is stored in the outgoing message.
  155                   msgContext.setProperty(Constants.Configuration.TRANSPORT_INFO_MAP,
  156                                          transportInfoMap);
  157               }
  158           }
  159   
  160           String sessionCookie = null;
  161           // Process old style headers first
  162           Header[] cookieHeaders = method.getResponseHeaders(HTTPConstants.HEADER_SET_COOKIE);
  163           String customCoookiId = (String) msgContext.getProperty(Constants.CUSTOM_COOKIE_ID);
  164           for (int i = 0; i < cookieHeaders.length; i++) {
  165               HeaderElement[] elements = cookieHeaders[i].getElements();
  166               for (int e = 0; e < elements.length; e++) {
  167                   HeaderElement element = elements[e];
  168                   if (Constants.SESSION_COOKIE.equalsIgnoreCase(element.getName()) ||
  169                           Constants.SESSION_COOKIE_JSESSIONID.equalsIgnoreCase(element.getName())) {
  170                       sessionCookie = processCookieHeader(element);
  171                   }
  172                   if (customCoookiId != null && customCoookiId.equalsIgnoreCase(element.getName())) {
  173                       sessionCookie = processCookieHeader(element);
  174                   }
  175               }
  176           }
  177           // Overwrite old style cookies with new style ones if present
  178           cookieHeaders = method.getResponseHeaders(HTTPConstants.HEADER_SET_COOKIE2);
  179           for (int i = 0; i < cookieHeaders.length; i++) {
  180               HeaderElement[] elements = cookieHeaders[i].getElements();
  181               for (int e = 0; e < elements.length; e++) {
  182                   HeaderElement element = elements[e];
  183                   if (Constants.SESSION_COOKIE.equalsIgnoreCase(element.getName()) ||
  184                           Constants.SESSION_COOKIE_JSESSIONID.equalsIgnoreCase(element.getName())) {
  185                       sessionCookie = processCookieHeader(element);
  186                   }
  187                   if(customCoookiId!=null&&customCoookiId.equalsIgnoreCase(element.getName())){
  188                       sessionCookie = processCookieHeader(element);
  189                   }
  190               }
  191           }
  192   
  193           if (sessionCookie != null) {
  194               msgContext.getServiceContext().setProperty(HTTPConstants.COOKIE_STRING, sessionCookie);
  195           }
  196       }
  197   
  198       private String processCookieHeader(HeaderElement element) {
  199           String cookie = element.getName() + "=" + element.getValue();
  200           NameValuePair[] parameters =  element.getParameters();
  201           for (int j = 0; parameters != null && j < parameters.length; j++) {
  202               NameValuePair parameter = parameters[j];
  203               cookie = cookie + "; " + parameter.getName() + "=" + parameter.getValue();
  204           }
  205           return cookie;
  206       }
  207   
  208       protected void processResponse(HttpMethodBase httpMethod,
  209                                      MessageContext msgContext)
  210               throws IOException {
  211           obtainHTTPHeaderInformation(httpMethod, msgContext);
  212   
  213           InputStream in = httpMethod.getResponseBodyAsStream();
  214           if (in == null) {
  215               throw new AxisFault(Messages.getMessage("canNotBeNull", "InputStream"));
  216           }
  217           Header contentEncoding =
  218                   httpMethod.getResponseHeader(HTTPConstants.HEADER_CONTENT_ENCODING);
  219           if (contentEncoding != null) {
  220               if (contentEncoding.getValue().
  221                       equalsIgnoreCase(HTTPConstants.COMPRESSION_GZIP)) {
  222                   in = new GZIPInputStream(in);
  223                   // If the content-encoding is identity we can basically ignore it.
  224               } else if (!"identity".equalsIgnoreCase(contentEncoding.getValue())) {
  225                   throw new AxisFault("HTTP :" + "unsupported content-encoding of '"
  226                           + contentEncoding.getValue() + "' found");
  227               }
  228           }
  229   
  230           OperationContext opContext = msgContext.getOperationContext();
  231           if (opContext != null) {
  232               opContext.setProperty(MessageContext.TRANSPORT_IN, in);
  233           }
  234       }
  235   
  236       public abstract void send(MessageContext msgContext, URL url, String soapActionString)
  237               throws IOException;
  238   
  239       /**
  240        * getting host configuration to support standard http/s, proxy and NTLM support
  241        *
  242        * @param client active HttpClient
  243        * @param msgCtx active MessageContext
  244        * @param targetURL the target URL
  245        * @return a HostConfiguration set up with proxy information
  246        * @throws AxisFault if problems occur
  247        */
  248       protected HostConfiguration getHostConfiguration(HttpClient client,
  249                                                        MessageContext msgCtx,
  250                                                        URL targetURL)throws AxisFault {
  251   
  252           boolean isAuthenticationEnabled = isAuthenticationEnabled(msgCtx);
  253           int port = targetURL.getPort();
  254   
  255           String protocol = targetURL.getProtocol();
  256           if (port == -1) {
  257               if (PROTOCOL_HTTP.equals(protocol)) {
  258                   port = 80;
  259               } else if (PROTOCOL_HTTPS.equals(protocol)) {
  260                   port = 443;
  261               }
  262   
  263           }
  264   
  265           // to see the host is a proxy and in the proxy list - available in axis2.xml
  266           HostConfiguration config = new HostConfiguration();
  267   
  268           // one might need to set his own socket factory. Let's allow that case as well.
  269           Protocol protocolHandler =
  270                   (Protocol)msgCtx.getOptions().getProperty(HTTPConstants.CUSTOM_PROTOCOL_HANDLER);
  271   
  272           // setting the real host configuration
  273           // I assume the 90% case, or even 99% case will be no protocol handler case.
  274           if (protocolHandler == null) {
  275               config.setHost(targetURL.getHost(), port, targetURL.getProtocol());
  276           } else {
  277               config.setHost(targetURL.getHost(), port, protocolHandler);
  278           }
  279   
  280           if (isAuthenticationEnabled) {
  281               // Basic, Digest, NTLM and custom authentications.
  282               this.setAuthenticationInfo(client, msgCtx, config);
  283           }
  284           // proxy configuration
  285   
  286           if (ProxyConfiguration.isProxyEnabled(msgCtx,targetURL)) {
  287               log.debug("ProxyConfiguration");
  288               ProxyConfiguration proxyConfiguration = new ProxyConfiguration();
  289               proxyConfiguration.configure(msgCtx,client,config);
  290           }
  291   
  292           return config;
  293       }
  294   
  295       protected boolean isAuthenticationEnabled(MessageContext msgCtx) {
  296           return (msgCtx.getProperty(HTTPConstants.AUTHENTICATE) != null);
  297       }
  298   
  299       /*
  300       This will handle server Authentication, It could be either NTLM, Digest or Basic Authentication.
  301       Apart from that user can change the priory or add a custom authentication scheme.
  302       */
  303       protected void setAuthenticationInfo(HttpClient agent,
  304                                            MessageContext msgCtx,
  305                                            HostConfiguration config) throws AxisFault {
  306           HttpTransportProperties.Authenticator authenticator;
  307           Object obj = msgCtx.getProperty(HTTPConstants.AUTHENTICATE);
  308           if (obj != null) {
  309               if (obj instanceof HttpTransportProperties.Authenticator) {
  310                   authenticator = (HttpTransportProperties.Authenticator) obj;
  311   
  312                   String username = authenticator.getUsername();
  313                   String password = authenticator.getPassword();
  314                   String host = authenticator.getHost();
  315                   String domain = authenticator.getDomain();
  316   
  317                   int port = authenticator.getPort();
  318                   String realm = authenticator.getRealm();
  319   
  320                   /* If retrying is available set it first */
  321                   isAllowedRetry = authenticator.isAllowedRetry();
  322   
  323                   Credentials creds;
  324   
  325                   agent.getParams()
  326                           .setAuthenticationPreemptive(authenticator.getPreemptiveAuthentication());
  327   
  328                   if (host != null) {
  329                       if (domain != null) {
  330                           /*Credentials for NTLM Authentication*/
  331                           creds = new NTCredentials(username, password, host, domain);
  332                       } else {
  333                           /*Credentials for Digest and Basic Authentication*/
  334                           creds = new UsernamePasswordCredentials(username, password);
  335                       }
  336                       agent.getState().setCredentials(new AuthScope(host, port, realm), creds);
  337                   } else {
  338                       if (domain != null) {
  339                           /*Credentials for NTLM Authentication when host is ANY_HOST*/
  340                           creds = new NTCredentials(username, password, AuthScope.ANY_HOST, domain);
  341                           agent.getState().setCredentials(
  342                                   new AuthScope(AuthScope.ANY_HOST, port, realm), creds);
  343                       } else {
  344                           /*Credentials only for Digest and Basic Authentication*/
  345                           creds = new UsernamePasswordCredentials(username, password);
  346                           agent.getState().setCredentials(new AuthScope(AuthScope.ANY), creds);
  347                       }
  348                   }
  349                   /* Customizing the priority Order */
  350                   List schemes = authenticator.getAuthSchemes();
  351                   if (schemes != null && schemes.size() > 0) {
  352                       List authPrefs = new ArrayList(3);
  353                       for (int i = 0; i < schemes.size(); i++) {
  354                           if (schemes.get(i) instanceof AuthPolicy) {
  355                               authPrefs.add(schemes.get(i));
  356                               continue;
  357                           }
  358                           String scheme = (String) schemes.get(i);
  359                           if (HttpTransportProperties.Authenticator.BASIC.equals(scheme)) {
  360                               authPrefs.add(AuthPolicy.BASIC);
  361                           } else if (HttpTransportProperties.Authenticator.NTLM.equals(scheme)) {
  362                               authPrefs.add(AuthPolicy.NTLM);
  363                           } else if (HttpTransportProperties.Authenticator.DIGEST.equals(scheme)) {
  364                               authPrefs.add(AuthPolicy.DIGEST);
  365                           }
  366                       }
  367                       agent.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY,
  368                               authPrefs);
  369                   }
  370   
  371               } else {
  372                   throw new AxisFault("HttpTransportProperties.Authenticator class cast exception");
  373               }
  374           }
  375   
  376       }
  377   
  378       /**
  379        * Method used to copy all the common properties
  380        *
  381        * @param msgContext       - The messageContext of the request message
  382        * @param url              - The target URL
  383        * @param httpMethod       - The http method used to send the request
  384        * @param httpClient       - The httpclient used to send the request
  385        * @param soapActionString - The soap action atring of the request message
  386        * @return MessageFormatter - The messageFormatter for the relavent request message
  387        * @throws AxisFault - Thrown in case an exception occurs
  388        */
  389       protected MessageFormatter populateCommonProperties(MessageContext msgContext, URL url,
  390                                                         HttpMethodBase httpMethod,
  391                                                         HttpClient httpClient,
  392                                                         String soapActionString)
  393               throws AxisFault {
  394   
  395           if (isAuthenticationEnabled(msgContext)) {
  396               httpMethod.setDoAuthentication(true);
  397           }
  398   
  399           MessageFormatter messageFormatter = TransportUtils.getMessageFormatter(
  400                   msgContext);
  401   
  402           url = messageFormatter.getTargetAddress(msgContext, format, url);
  403   
  404           httpMethod.setPath(url.getPath());
  405   
  406           httpMethod.setQueryString(url.getQuery());
  407   
  408           httpMethod.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE,
  409                                       messageFormatter.getContentType(msgContext, format,
  410                                                                       soapActionString));
  411   
  412           httpMethod.setRequestHeader(HTTPConstants.HEADER_HOST, url.getHost());
  413   
  414           if (msgContext.getOptions() != null && msgContext.getOptions().isManageSession()) {
  415               // setting the cookie in the out path
  416               Object cookieString = msgContext.getProperty(HTTPConstants.COOKIE_STRING);
  417   
  418               if (cookieString != null) {
  419                   StringBuffer buffer = new StringBuffer();
  420                   buffer.append(cookieString);
  421                   httpMethod.setRequestHeader(HTTPConstants.HEADER_COOKIE, buffer.toString());
  422               }
  423           }
  424   
  425           if (httpVersion.equals(HTTPConstants.HEADER_PROTOCOL_10)) {
  426               httpClient.getParams().setVersion(HttpVersion.HTTP_1_0);
  427           }
  428           return messageFormatter;
  429       }
  430   
  431       /**
  432        * This is used to get the dynamically set time out values from the
  433        * message context. If the values are not available or invalid then
  434        * the default values or the values set by the configuration will be used
  435        *
  436        * @param msgContext the active MessageContext
  437        * @param httpClient
  438        */
  439       protected void initializeTimeouts(MessageContext msgContext, HttpClient httpClient) {
  440           // If the SO_TIMEOUT of CONNECTION_TIMEOUT is set by dynamically the
  441           // override the static config
  442           Integer tempSoTimeoutProperty =
  443                   (Integer) msgContext.getProperty(HTTPConstants.SO_TIMEOUT);
  444           Integer tempConnTimeoutProperty =
  445                   (Integer) msgContext
  446                           .getProperty(HTTPConstants.CONNECTION_TIMEOUT);
  447           long timeout = msgContext.getOptions().getTimeOutInMilliSeconds();
  448   
  449           if (tempConnTimeoutProperty != null) {
  450               int connectionTimeout = tempConnTimeoutProperty.intValue();
  451               // timeout for initial connection
  452               httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);
  453           } else {
  454               // set timeout in client
  455               if (timeout > 0) {
  456                   httpClient.getHttpConnectionManager().getParams().setConnectionTimeout((int) timeout);
  457               }
  458           }
  459   
  460           if (tempSoTimeoutProperty != null) {
  461               int soTimeout = tempSoTimeoutProperty.intValue();
  462               // SO_TIMEOUT -- timeout for blocking reads
  463               httpClient.getHttpConnectionManager().getParams().setSoTimeout(soTimeout);
  464               httpClient.getParams().setSoTimeout(soTimeout);
  465           } else {
  466               // set timeout in client
  467               if (timeout > 0) {
  468                   httpClient.getHttpConnectionManager().getParams().setSoTimeout((int) timeout);
  469                   httpClient.getParams().setSoTimeout((int) timeout);
  470               }
  471           }
  472       }
  473   
  474       public void setFormat(OMOutputFormat format) {
  475           this.format = format;
  476       }
  477   
  478       protected HttpClient getHttpClient(MessageContext msgContext) {
  479           HttpClient httpClient;
  480           Object reuse = msgContext.getOptions().getProperty(HTTPConstants.REUSE_HTTP_CLIENT);
  481           if (reuse == null) {
  482               reuse = msgContext.getConfigurationContext().getProperty(HTTPConstants.REUSE_HTTP_CLIENT);
  483           }
  484           if (reuse != null && JavaUtils.isTrueExplicitly(reuse)) {
  485               httpClient = (HttpClient) msgContext.getOptions().getProperty(HTTPConstants.CACHED_HTTP_CLIENT);
  486               if (httpClient == null) {
  487                   httpClient = (HttpClient) msgContext.getConfigurationContext()
  488                           .getProperty(HTTPConstants.CACHED_HTTP_CLIENT);
  489               }
  490               if (httpClient != null)
  491                   return httpClient;
  492               MultiThreadedHttpConnectionManager connectionManager =
  493                   new MultiThreadedHttpConnectionManager();
  494               httpClient = new HttpClient(connectionManager);
  495               msgContext.getConfigurationContext()
  496                   .setProperty(HTTPConstants.CACHED_HTTP_CLIENT, httpClient);
  497           } else {
  498               HttpConnectionManager connManager =
  499                       (HttpConnectionManager) msgContext.getProperty(
  500                               HTTPConstants.MULTITHREAD_HTTP_CONNECTION_MANAGER);
  501               if (connManager == null) {
  502                   connManager =
  503                           (HttpConnectionManager) msgContext.getProperty(
  504                                   HTTPConstants.MUTTITHREAD_HTTP_CONNECTION_MANAGER);
  505               }
  506               if(connManager != null){
  507                   httpClient = new HttpClient(connManager);
  508               } else {
  509                   //Multi threaded http connection manager has set as the default 
  510                   connManager = new MultiThreadedHttpConnectionManager();
  511                   httpClient = new HttpClient(connManager);
  512               }
  513           }
  514   
  515           // Get the timeout values set in the runtime
  516           initializeTimeouts(msgContext, httpClient);
  517           return httpClient;
  518       }
  519   
  520       protected void executeMethod(HttpClient httpClient, MessageContext msgContext, URL url,
  521                                    HttpMethod method) throws IOException {
  522           HostConfiguration config = this.getHostConfiguration(httpClient, msgContext, url);
  523   
  524           msgContext.setProperty(HTTPConstants.HTTP_METHOD, method);
  525   
  526           // set the custom headers, if available
  527           addCustomHeaders(method, msgContext);
  528   
  529           // add compression headers if needed
  530           if (msgContext.isPropertyTrue(HTTPConstants.MC_ACCEPT_GZIP)) {
  531               method.addRequestHeader(HTTPConstants.HEADER_ACCEPT_ENCODING,
  532                       HTTPConstants.COMPRESSION_GZIP);
  533           }
  534   
  535           if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
  536               method.addRequestHeader(HTTPConstants.HEADER_CONTENT_ENCODING,
  537                       HTTPConstants.COMPRESSION_GZIP);
  538           }
  539           
  540           if (msgContext.getProperty(HTTPConstants.HTTP_METHOD_PARAMS) != null) {
  541               HttpMethodParams params = (HttpMethodParams)msgContext
  542                       .getProperty(HTTPConstants.HTTP_METHOD_PARAMS);
  543               method.setParams(params);
  544           }
  545   
  546           String cookiePolicy = (String) msgContext.getProperty(HTTPConstants.COOKIE_POLICY);
  547           if (cookiePolicy != null) {
  548               method.getParams().setCookiePolicy(cookiePolicy);   
  549           }
  550           httpClient.executeMethod(config, method);
  551       }
  552   
  553       public void addCustomHeaders(HttpMethod method, MessageContext msgContext) {
  554   
  555           boolean isCustomUserAgentSet = false;
  556           // set the custom headers, if available
  557           Object httpHeadersObj = msgContext.getProperty(HTTPConstants.HTTP_HEADERS);
  558           if (httpHeadersObj != null) {
  559               if (httpHeadersObj instanceof ArrayList) {
  560                   ArrayList httpHeaders = (ArrayList) httpHeadersObj;
  561                   Header header;
  562                   for (int i = 0; i < httpHeaders.size(); i++) {
  563                       header = (Header) httpHeaders.get(i);
  564                       if (HTTPConstants.HEADER_USER_AGENT.equals(header.getName())) {
  565                           isCustomUserAgentSet = true;
  566                       }
  567                       method.addRequestHeader(header);
  568                   }
  569       
  570               }
  571               if (httpHeadersObj instanceof Map) {
  572                   Map httpHeaders = (Map) httpHeadersObj;
  573                   for (Iterator iterator = httpHeaders.entrySet().iterator(); iterator.hasNext();) {
  574                       Map.Entry entry  = (Map.Entry) iterator.next();
  575                       String key = (String) entry.getKey();
  576                       String value = (String) entry.getValue();
  577                       if (HTTPConstants.HEADER_USER_AGENT.equals(key)) {
  578                           isCustomUserAgentSet = true;
  579                       }
  580                       method.addRequestHeader(key, value);
  581                   }
  582               }
  583           }
  584   
  585           if (!isCustomUserAgentSet) {
  586               String userAgentString = getUserAgent(msgContext);
  587               method.setRequestHeader(HTTPConstants.HEADER_USER_AGENT, userAgentString);
  588           }
  589   
  590       }
  591   
  592       private String getUserAgent(MessageContext messageContext) {
  593           String userAgentString = "Axis2";
  594           boolean locked = false;
  595           if (messageContext.getParameter(HTTPConstants.USER_AGENT) != null) {
  596               OMElement userAgentElement =
  597                       messageContext.getParameter(HTTPConstants.USER_AGENT).getParameterElement();
  598               userAgentString = userAgentElement.getText().trim();
  599               OMAttribute lockedAttribute = userAgentElement.getAttribute(new QName("locked"));
  600               if (lockedAttribute != null) {
  601                   if (lockedAttribute.getAttributeValue().equalsIgnoreCase("true")) {
  602                       locked = true;
  603                   }
  604               }
  605           }
  606           // Runtime overing part
  607           if (!locked) {
  608               if (messageContext.getProperty(HTTPConstants.USER_AGENT) != null) {
  609                   userAgentString = (String) messageContext.getProperty(HTTPConstants.USER_AGENT);
  610               }
  611           }
  612   
  613           return userAgentString;
  614       }
  615       
  616   }

Save This Page
Home » axis2-1.5-src » org.apache » axis2 » transport » http » [javadoc | source]