KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > axis2 > transport > http > CommonsHTTPTransportSender


1 package org.apache.axis2.transport.http;
2
3 import org.apache.axis2.Constants;
4 import org.apache.axis2.addressing.AddressingConstants;
5 import org.apache.axis2.addressing.EndpointReference;
6 import org.apache.axis2.context.ConfigurationContext;
7 import org.apache.axis2.context.MessageContext;
8 import org.apache.axis2.description.Parameter;
9 import org.apache.axis2.description.TransportOutDescription;
10 import org.apache.axis2.engine.AxisFault;
11 import org.apache.axis2.handlers.AbstractHandler;
12 import org.apache.axis2.om.OMElement;
13 import org.apache.axis2.om.OMOutput;
14 import org.apache.axis2.transport.TransportSender;
15 import org.apache.commons.httpclient.*;
16 import org.apache.commons.httpclient.methods.PostMethod;
17 import org.apache.commons.httpclient.methods.RequestEntity;
18
19 import javax.xml.stream.FactoryConfigurationError;
20 import javax.xml.stream.XMLOutputFactory;
21 import javax.xml.stream.XMLStreamException;
22 import javax.xml.stream.XMLStreamWriter;
23 import java.io.ByteArrayOutputStream JavaDoc;
24 import java.io.IOException JavaDoc;
25 import java.io.InputStream JavaDoc;
26 import java.io.OutputStream JavaDoc;
27 import java.net.MalformedURLException JavaDoc;
28 import java.net.URL JavaDoc;
29
30 public class CommonsHTTPTransportSender extends AbstractHandler implements TransportSender {
31     private boolean chuncked = false;
32
33     private String JavaDoc httpVersion = HTTPConstants.HEADER_PROTOCOL_10;
34     public static final String JavaDoc HTTP_METHOD = "HTTP_METHOD";
35
36     
37     protected HttpClient httpClient;
38     protected OMElement outputMessage;
39
40     public CommonsHTTPTransportSender() {
41     } //default
42

43     public void invoke(MessageContext msgContext) throws AxisFault {
44         try {
45             //Check for the REST behaviour, if you desire rest beahaviour
46
//put a <parameter name="doREST" value="true"/> at the server.xml/client.xml file
47

48             EndpointReference epr = null;
49             if (msgContext.getTo() != null
50                 && !AddressingConstants.Submission.WSA_ANONYMOUS_URL.equals(
51                     msgContext.getTo().getAddress())
52                 && !AddressingConstants.Final.WSA_ANONYMOUS_URL.equals(
53                     msgContext.getTo().getAddress())) {
54                 epr = msgContext.getTo();
55             }
56
57             OMElement dataOut = null;
58             if (msgContext.isDoingREST()) {
59                 dataOut = msgContext.getEnvelope().getFirstElement();
60             } else {
61                 dataOut = msgContext.getEnvelope();
62             }
63
64             //TODO timeout, configuration
65
if (epr != null) {
66                 writeMessageWithCommons(msgContext, epr, dataOut);
67             } else {
68                 OutputStream JavaDoc out =
69                     (OutputStream JavaDoc) msgContext.getProperty(MessageContext.TRANSPORT_OUT);
70                 OMOutput output = new OMOutput(out, false);
71                 dataOut.serialize(output);
72             }
73             msgContext.getOperationContext().setProperty(
74                 Constants.RESPONSE_WRITTEN,
75                 Constants.VALUE_TRUE);
76         } catch (XMLStreamException e) {
77             throw new AxisFault(e);
78         } catch (FactoryConfigurationError e) {
79             throw new AxisFault(e);
80         }
81     }
82
83     public void writeMessageWithToOutPutStream(MessageContext msgContext, OutputStream JavaDoc out) {
84
85     }
86
87     public void writeMessageWithCommons(
88         MessageContext msgContext,
89         EndpointReference toURL,
90         OMElement dataout)
91         throws AxisFault {
92         try {
93             URL JavaDoc url = new URL JavaDoc(toURL.getAddress());
94             //Configure the transport
95
String JavaDoc soapAction = msgContext.getWSAAction();
96             //settign soapAction
97
String JavaDoc soapActionString = soapAction == null ? "" : soapAction.toString();
98
99             PostMethod postMethod = new PostMethod();
100             postMethod.setPath(url.getFile());
101             msgContext.setProperty(HTTP_METHOD,postMethod);
102             postMethod.setRequestEntity(new AxisRequestEntity(dataout, chuncked));
103             if (!httpVersion.equals(HTTPConstants.HEADER_PROTOCOL_10) && chuncked) {
104                 ((PostMethod) postMethod).setContentChunked(true);
105             }
106
107             postMethod.setRequestHeader(
108                 HTTPConstants.HEADER_CONTENT_TYPE,
109                 "text/xml; charset=utf-8");
110             postMethod.setRequestHeader(
111                 HTTPConstants.HEADER_ACCEPT,
112                 HTTPConstants.HEADER_ACCEPT_APPL_SOAP
113                     + HTTPConstants.HEADER_ACCEPT_APPLICATION_DIME
114                     + HTTPConstants.HEADER_ACCEPT_MULTIPART_RELATED
115                     + HTTPConstants.HEADER_ACCEPT_TEXT_ALL);
116             postMethod.setRequestHeader(HTTPConstants.HEADER_HOST, url.getHost());
117             postMethod.setRequestHeader(HTTPConstants.HEADER_CACHE_CONTROL, "no-cache");
118             postMethod.setRequestHeader(HTTPConstants.HEADER_PRAGMA, "no-cache");
119             //content length is not set yet
120
//setting HTTP vesion
121

122             if (httpVersion != null) {
123                 if (httpVersion.equals(HTTPConstants.HEADER_PROTOCOL_10)) {
124                     //postMethod.setHttp11(false); todo method to findout the transport version...
125
//allowing keep-alive for 1.0
126
postMethod.setRequestHeader(
127                         HTTPConstants.HEADER_CONNECTION,
128                         HTTPConstants.HEADER_CONNECTION_KEEPALIVE);
129                 } else {
130                     // allowing keep-alive for 1.1
131
postMethod.setRequestHeader(
132                         HTTPConstants.HEADER_CONNECTION,
133                         HTTPConstants.HEADER_CONNECTION_KEEPALIVE);
134                 }
135             }
136             // othervise assumes HTTP 1.1 and keep-alive is default.
137
if (!msgContext.isDoingREST()) {
138                 postMethod.setRequestHeader(HTTPConstants.HEADER_SOAP_ACTION, soapActionString);
139             }
140
141             //execuite the HtttpMethodBase - a connection manager can be given for handle multiple
142
httpClient = new HttpClient();
143             //hostConfig handles the socket functions..
144
HostConfiguration hostConfig = getHostConfiguration(msgContext, url);
145
146             //code that wirte the stream to the wire
147

148             this.httpClient.executeMethod(hostConfig, postMethod);
149             if(postMethod.getStatusCode() == HttpStatus.SC_OK){
150                 InputStream JavaDoc in = postMethod.getResponseBodyAsStream();
151                 if(in == null){
152                     throw new AxisFault("Input Stream can not be Null");
153                 }
154                 msgContext.getOperationContext().setProperty(MessageContext.TRANSPORT_IN,in);
155             }else if(postMethod.getStatusCode() == HttpStatus.SC_ACCEPTED){
156                 return;
157             }else{
158                 throw new AxisFault("Error "+ postMethod.getStatusCode() + " Error Message is "+postMethod.getResponseBodyAsString());
159             }
160         } catch (MalformedURLException JavaDoc e) {
161             throw new AxisFault(e);
162         } catch (HttpException e) {
163             throw new AxisFault(e);
164         } catch (IOException JavaDoc e) {
165             throw new AxisFault(e);
166         }
167
168     }
169
170     protected HostConfiguration getHostConfiguration(MessageContext context, URL JavaDoc targetURL) {
171         //TODO cheaking wheather the host is a proxy
172
HostConfiguration config = new HostConfiguration();
173         config.setHost(targetURL.getHost(), targetURL.getPort() == -1 ? 80 : targetURL.getPort());
174         return config;
175     }
176     //get the contentLength...
177
public class AxisRequestEntity implements RequestEntity {
178         private OMElement element;
179         private boolean chuncked;
180         private byte[] bytes;
181
182         public AxisRequestEntity(OMElement element, boolean chuncked) {
183             this.element = element;
184             this.chuncked = chuncked;
185         }
186         public boolean isRepeatable() {
187             return false;
188         }
189
190         public byte[] writeBytes() throws AxisFault {
191             try {
192                 ByteArrayOutputStream JavaDoc bytesOut = new ByteArrayOutputStream JavaDoc();
193                 XMLStreamWriter outputWriter =
194                     XMLOutputFactory.newInstance().createXMLStreamWriter(bytesOut);
195                 OMOutput output = new OMOutput(outputWriter);
196                 element.serialize(output);
197                 outputWriter.flush();
198                 return bytesOut.toByteArray();
199             } catch (XMLStreamException e) {
200                 throw new AxisFault(e);
201             } catch (FactoryConfigurationError e) {
202                 throw new AxisFault(e);
203             }
204         }
205
206         public void writeRequest(OutputStream JavaDoc out) throws IOException JavaDoc {
207             try {
208                 if (chuncked) {
209                     XMLStreamWriter outputWriter = null;
210                     outputWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(out);
211                     OMOutput output = new OMOutput(outputWriter);
212                     element.serialize(output);
213                     outputWriter.flush();
214                     out.flush();
215                 } else {
216                     if (bytes == null) {
217                         bytes = writeBytes();
218                     }
219                     out.write(bytes);
220                 }
221             } catch (XMLStreamException e) {
222                 throw new AxisFault(e);
223             } catch (FactoryConfigurationError e) {
224                 throw new AxisFault(e);
225             } catch (IOException JavaDoc e) {
226                 throw new AxisFault(e);
227             }
228         }
229
230         public long getContentLength() {
231             try {
232                 if (chuncked) {
233                     return -1;
234                 } else {
235                     if (bytes == null) {
236                         bytes = writeBytes();
237                     }
238                     return bytes.length;
239                 }
240             } catch (AxisFault e) {
241                 return -1;
242             }
243         }
244
245         public String JavaDoc getContentType() {
246             return "text/xml; charset=utf-8";
247         }
248     }
249
250     /* (non-Javadoc)
251      * @see org.apache.axis2.transport.TransportSender#cleanUp(org.apache.axis2.context.MessageContext)
252      */

253     public void cleanUp(MessageContext msgContext) throws AxisFault {
254         HttpMethod httpMethod = (HttpMethod)msgContext.getProperty(HTTP_METHOD);
255         if(httpMethod != null){
256             httpMethod.releaseConnection();
257         }
258
259     }
260
261     public void init(ConfigurationContext confContext, TransportOutDescription transportOut)
262         throws AxisFault {
263         //<parameter name="PROTOCOL" locked="xsd:false">HTTP/1.0</parameter> or
264
//<parameter name="PROTOCOL" locked="xsd:false">HTTP/1.1</parameter> is checked
265
Parameter version = transportOut.getParameter(HTTPConstants.PROTOCOL_VERSION);
266         if (version != null) {
267             if (HTTPConstants.HEADER_PROTOCOL_11.equals(version.getValue())) {
268                 this.httpVersion = HTTPConstants.HEADER_PROTOCOL_11;
269                 Parameter transferEncoding =
270                     transportOut.getParameter(HTTPConstants.HEADER_TRANSFER_ENCODING);
271                 if (transferEncoding != null
272                     && HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED.equals(
273                         transferEncoding.getValue())) {
274                     this.chuncked = true;
275                 }
276             } else if (HTTPConstants.HEADER_PROTOCOL_10.equals(version.getValue())) {
277                 //TODO HTTP1.0 specific parameters
278
} else {
279                 throw new AxisFault(
280                     "Parameter "
281                         + HTTPConstants.PROTOCOL_VERSION
282                         + " Can have values only HTTP/1.0 or HTTP/1.1");
283             }
284         }
285
286     }
287
288 }
289
Popular Tags