File: HTTPRemotingConnection.java

package info (click to toggle)
libjboss-web-services-java 0.0%2Bsvn5660%2Bdak2-3
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 7,276 kB
  • sloc: java: 79,207; xml: 29; makefile: 19; sh: 16
file content (407 lines) | stat: -rw-r--r-- 14,293 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
/*
 * JBoss, Home of Professional Open Source
 * Copyright 2005, JBoss Inc., and individual contributors as indicated
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.jboss.ws.core.client;

// $Id$

import java.io.IOException;
import java.lang.reflect.Field;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

import javax.xml.rpc.Stub;
import javax.xml.soap.MimeHeader;
import javax.xml.soap.MimeHeaders;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.addressing.EndpointReference;

import org.jboss.logging.Logger;
import org.jboss.remoting.Client;
import org.jboss.remoting.InvokerLocator;
import org.jboss.remoting.Version;
import org.jboss.remoting.marshal.MarshalFactory;
import org.jboss.remoting.marshal.Marshaller;
import org.jboss.remoting.marshal.UnMarshaller;
import org.jboss.ws.core.CommonMessageContext;
import org.jboss.ws.core.MessageAbstraction;
import org.jboss.ws.core.MessageTrace;
import org.jboss.ws.core.StubExt;
import org.jboss.ws.core.WSTimeoutException;
import org.jboss.ws.core.soap.MessageContextAssociation;
import org.jboss.ws.metadata.config.EndpointProperty;

import org.jboss.ws.extensions.wsrm.transport.RMChannel;
import org.jboss.ws.extensions.wsrm.transport.RMTransportHelper;
import org.jboss.ws.extensions.wsrm.transport.RMMetadata;

/**
 * SOAPConnection implementation.
 * <p/>
 *
 * Per default HTTP 1.1 chunked encoding is used.
 * This may be ovverriden through {@link org.jboss.ws.metadata.config.EndpointProperty#CHUNKED_ENCODING_SIZE}.
 * A chunksize value of zero disables chunked encoding.
 *
 * @author Thomas.Diesler@jboss.org
 * @author <a href="mailto:jason@stacksmash.com">Jason T. Greene</a>
 *
 * @since 02-Feb-2005
 */
public abstract class HTTPRemotingConnection implements RemoteConnection
{
   // provide logging
   private static Logger log = Logger.getLogger(HTTPRemotingConnection.class);

   private Map<String, Object> clientConfig = new HashMap<String, Object>();

   private static Map<String, String> metadataMap = new HashMap<String, String>();
   static
   {
      metadataMap.put(Stub.USERNAME_PROPERTY, "http.basic.username");
      metadataMap.put(Stub.PASSWORD_PROPERTY, "http.basic.password");
      metadataMap.put(BindingProvider.USERNAME_PROPERTY, "http.basic.username");
      metadataMap.put(BindingProvider.PASSWORD_PROPERTY, "http.basic.password");
   }
   private static Map<String, String> configMap = new HashMap<String, String>();
   static
   {
      configMap.put(StubExt.PROPERTY_KEY_STORE, "org.jboss.remoting.keyStore");
      configMap.put(StubExt.PROPERTY_KEY_STORE_PASSWORD, "org.jboss.remoting.keyStorePassword");
      configMap.put(StubExt.PROPERTY_KEY_STORE_TYPE, "org.jboss.remoting.keyStoreType");
      configMap.put(StubExt.PROPERTY_TRUST_STORE, "org.jboss.remoting.trustStore");
      configMap.put(StubExt.PROPERTY_TRUST_STORE_PASSWORD, "org.jboss.remoting.trustStorePassword");
      configMap.put(StubExt.PROPERTY_TRUST_STORE_TYPE, "org.jboss.remoting.trustStoreType");
   }

   private boolean closed;
   
   private static final RMChannel RM_CHANNEL = RMChannel.getInstance();
   
   public HTTPRemotingConnection()
   {
      // HTTPClientInvoker conect sends gratuitous POST
      // http://jira.jboss.com/jira/browse/JBWS-711
      clientConfig.put(Client.ENABLE_LEASE, false);
   }

   public boolean isClosed()
   {
      return closed;
   }

   public void setClosed(boolean closed)
   {
      this.closed = closed;
   }

   /** 
    * Sends the given message to the specified endpoint. 
    * 
    * A null reqMessage signifies a HTTP GET request.
    */
   public MessageAbstraction invoke(MessageAbstraction reqMessage, Object endpoint, boolean oneway) throws IOException
   {
      if (endpoint == null)
         throw new IllegalArgumentException("Given endpoint cannot be null");

      if (closed)
         throw new IOException("Connection is already closed");

      Object timeout = null;
      String targetAddress;
      Map<String, Object> callProps = new HashMap<String, Object>();

      if (endpoint instanceof EndpointInfo)
      {
         EndpointInfo epInfo = (EndpointInfo)endpoint;
         targetAddress = epInfo.getTargetAddress();
         callProps = epInfo.getProperties();

         if (callProps.containsKey(StubExt.PROPERTY_CLIENT_TIMEOUT))
         {
            timeout = callProps.get(StubExt.PROPERTY_CLIENT_TIMEOUT);
            targetAddress = addURLParameter(targetAddress, "timeout", timeout.toString());
         }

      }
      else if (endpoint instanceof EndpointReference)
      {
         EndpointReference epr = (EndpointReference)endpoint;
         targetAddress = epr.getAddress().toString();
      }
      else
      {
         targetAddress = endpoint.toString();
      }

      // setup remoting client            
      Map<String, Object> metadata = createRemotingMetaData(reqMessage, callProps);
      Marshaller marshaller = getMarshaller();
      UnMarshaller unmarshaller = getUnmarshaller();
      InvokerLocator locator = null;
      try
      {
         // Get the invoker from Remoting for a given endpoint address
         log.debug("Get locator for: " + endpoint);
         
         /** 
          * [JBWS-1704] The Use Of Remoting Causes An Additional 'datatype' Parameter To Be Sent On All Requests
          * 
          * An HTTPClientInvoker may disconnect from the server and recreated by the remoting layer.
          * In that case the new invoker does not inherit the marshaller/unmarshaller from the disconnected invoker.
          * We therefore explicitly specify the invoker locator datatype and register the SOAP marshaller/unmarshaller
          * with the MarshalFactory. 
          * 
          * This applies to remoting-1.4.5 and less
          */
         String version = getRemotingVersion();
         if (version.startsWith("1.4"))
         {
            targetAddress = addURLParameter(targetAddress, InvokerLocator.DATATYPE, "JBossWSMessage");
            MarshalFactory.addMarshaller("JBossWSMessage", marshaller, unmarshaller);
         }

         locator = new InvokerLocator(targetAddress);
      }
      catch (MalformedURLException e)
      {
         throw new IllegalArgumentException("Malformed endpoint address", e);
      }

      try
      {
         if (RMTransportHelper.isRMMessage(callProps))
         {
            RMMetadata rmMetadata = new RMMetadata(getRemotingVersion(), targetAddress, marshaller, unmarshaller, callProps, metadata, clientConfig);
            return RM_CHANNEL.send(reqMessage, rmMetadata);
         }
         else 
         {
            Client client = new Client(locator, "jbossws", clientConfig);
            client.connect();

            client.setMarshaller(marshaller);

            if (oneway == false)  
               client.setUnMarshaller(unmarshaller);
         
            if (log.isDebugEnabled())
               log.debug("Remoting metadata: " + metadata);

            // debug the outgoing message
            MessageTrace.traceMessage("Outgoing Request Message", reqMessage);

            MessageAbstraction resMessage = null;

            if (oneway == true)
            {
               client.invokeOneway(reqMessage, metadata, false);
            }
            else
            {
               resMessage = (MessageAbstraction)client.invoke(reqMessage, metadata);
            }

            // Disconnect the remoting client
            client.disconnect();
 
            callProps.clear();
            callProps.putAll(metadata);

            // trace the incomming response message
            MessageTrace.traceMessage("Incoming Response Message", resMessage);

            return resMessage;
         }
      }
      catch (Throwable th)
      {
         if (timeout != null && (th.getCause() instanceof SocketTimeoutException))
         {
            throw new WSTimeoutException("Timeout after: " + timeout + "ms", new Long(timeout.toString()));
         }

         IOException io = new IOException("Could not transmit message");
         io.initCause(th);
         throw io;
      }
   }
   
   private String addURLParameter(String urlStr, String key, String value) throws MalformedURLException
   {
      URL url = new URL(urlStr);
      urlStr += (url.getQuery() == null ? "?" : "&") + key + "=" + value;
      return urlStr;
   }

   private String getRemotingVersion()
   {
      String version = null; 
      try
      {
         // Access the constant dynamically, otherwise it will be the compile time value
         Field field = Version.class.getDeclaredField("VERSION");
         version = (String)field.get(null);
      }
      catch (Exception ex)
      {
         throw new RuntimeException("Cannot obtain remoting version", ex);
      }
      
      if (version == null)
      {
         URL codeURL = Version.class.getProtectionDomain().getCodeSource().getLocation();
         throw new RuntimeException("Cannot obtain remoting version from: " + codeURL);
      }
      return version;
   }

   private Map<String, Object> createRemotingMetaData(MessageAbstraction reqMessage, Map callProps)
   {
      CommonMessageContext msgContext = MessageContextAssociation.peekMessageContext();

      Map<String, Object> metadata = new HashMap<String, Object>();

      // We need to unmarshall faults (HTTP 500)
      // metadata.put(HTTPMetadataConstants.NO_THROW_ON_ERROR, "true"); // since 2.0.0.GA
      metadata.put("NoThrowOnError", "true");

      if (reqMessage != null)
      {
         populateHeaders(reqMessage, metadata);

         // Enable chunked encoding. This is the default size. 
         clientConfig.put("chunkedLength", "1024");
         
         // May be overridden through endpoint config
         if (msgContext != null)
         {
            Properties epmdProps = msgContext.getEndpointMetaData().getProperties();

            // chunksize settings
            String chunkSizeValue = epmdProps.getProperty(EndpointProperty.CHUNKED_ENCODING_SIZE);
            int chunkSize = chunkSizeValue != null ? Integer.valueOf(chunkSizeValue) : -1;
            if (chunkSize > 0)
            {
               clientConfig.put(EndpointProperty.CHUNKED_ENCODING_SIZE, chunkSizeValue);
            }
            else
            {
               clientConfig.remove("chunkedLength");
            }
         }
      }
      else
      {
         metadata.put("TYPE", "GET");
      }

      if (callProps != null)
      {
         Iterator it = callProps.entrySet().iterator();

         // Get authentication type, default to BASIC authetication
         String authType = (String)callProps.get(StubExt.PROPERTY_AUTH_TYPE);
         if (authType == null)
            authType = StubExt.PROPERTY_AUTH_TYPE_BASIC;

         while (it.hasNext())
         {
            Map.Entry entry = (Map.Entry)it.next();
            String key = (String)entry.getKey();
            Object val = entry.getValue();

            // pass properties to remoting meta data
            if (metadataMap.containsKey(key))
            {
               String remotingKey = metadataMap.get(key);
               if ("http.basic.username".equals(remotingKey) || "http.basic.password".equals(remotingKey))
               {
                  if (authType.equals(StubExt.PROPERTY_AUTH_TYPE_BASIC))
                  {
                     metadata.put(remotingKey, val);
                  }
                  else
                  {
                     log.warn("Ignore '" + key + "' with auth typy: " + authType);
                  }
               }
               else
               {
                  metadata.put(remotingKey, val);
               }
            }

            // pass properties to remoting client config
            if (configMap.containsKey(key))
            {
               String remotingKey = configMap.get(key);
               clientConfig.put(remotingKey, val);
            }
         }
      }

      return metadata;
   }

   protected void populateHeaders(MessageAbstraction reqMessage, Map<String, Object> metadata)
   {
      MimeHeaders mimeHeaders = reqMessage.getMimeHeaders();

      Properties props = new Properties();
      metadata.put("HEADER", props);

      Iterator i = mimeHeaders.getAllHeaders();
      while (i.hasNext())
      {
         MimeHeader header = (MimeHeader)i.next();
         String currentValue = props.getProperty(header.getName());

         /*
          * Coalesce multiple headers into one
          *
          * From HTTP/1.1 RFC 2616:
          *
          * Multiple message-header fields with the same field-name MAY be
          * present in a message if and only if the entire field-value for that
          * header field is defined as a comma-separated list [i.e., #(values)].
          * It MUST be possible to combine the multiple header fields into one
          * "field-name: field-value" pair, without changing the semantics of
          * the message, by appending each subsequent field-value to the first,
          * each separated by a comma.
          */
         if (currentValue != null)
         {
            props.put(header.getName(), currentValue + "," + header.getValue());
         }
         else
         {
            props.put(header.getName(), header.getValue());
         }
      }
   }
}