KickJava   Java API By Example, From Geeks To Geeks.

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


1 /*
2  * Copyright 2004,2005 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package org.apache.axis2.transport.http;
17
18 import org.apache.axis2.context.ConfigurationContext;
19 import org.apache.axis2.description.OperationDescription;
20 import org.apache.axis2.description.ServiceDescription;
21 import org.apache.axis2.engine.AxisFault;
22
23 import java.io.IOException JavaDoc;
24 import java.io.InputStream JavaDoc;
25 import java.util.*;
26
27 /**
28  * Class HTTPTransportReceiver
29  */

30 public class HTTPTransportReceiver {
31     /**
32      * Field END
33      */

34     private static final int END = 1;
35
36     /**
37      * Field END_OF_LINE
38      */

39     private static final int END_OF_LINE = 2;
40
41     /**
42      * Field BEFORE_SEPERATOR
43      */

44     private static final int BEFORE_SEPERATOR = 3;
45
46     /**
47      * Field AFTER_SEPERATOR
48      */

49     private static final int AFTER_SEPERATOR = 4;
50
51     /**
52      * Field lastRead
53      */

54     private int lastRead = -1;
55
56     /**
57      * Field buf
58      */

59     private byte[] buf = new byte[1024];
60
61     /**
62      * Field index
63      */

64     int index = 0;
65
66     /**
67      * Field length
68      */

69     int length = 0;
70
71     /**
72      * Field done
73      */

74     private boolean done = false;
75
76 //
77
// /**
78
// * Method invoke
79
// *
80
// * @param msgContext
81
// * @throws AxisFault
82
// */
83
// public SOAPEnvelope handleHTTPRequest(
84
// MessageContext msgContext,InputStream inStream, Map map)
85
// throws AxisFault {
86
// SOAPEnvelope soapEnvelope = null;
87
//
88
//
89
//
90
// msgContext.setWSAAction(
91
// (String) map.get(HTTPConstants.HEADER_SOAP_ACTION));
92
// Utils.configureMessageContextForHTTP(
93
// (String) map.get(HTTPConstants.HEADER_CONTENT_TYPE),
94
// msgContext.getWSAAction(),
95
// msgContext);
96
//
97
// String requestURI = (String) map.get(HTTPConstants.REQUEST_URI);
98
// msgContext.setTo(
99
// new EndpointReference(AddressingConstants.WSA_TO, requestURI));
100
//
101
// if (HTTPConstants
102
// .RESPONSE_ACK_CODE_VAL
103
// .equals(map.get(HTTPConstants.RESPONSE_CODE))) {
104
// msgContext.setProperty(
105
// MessageContext.TRANSPORT_SUCCEED,
106
// HTTPConstants.RESPONSE_ACK_CODE_VAL);
107
// return null;
108
// } else if (
109
// HTTPConstants.HEADER_GET.equals(
110
// map.get(HTTPConstants.HTTP_REQ_TYPE))) {
111
// SOAPEnvelope envelope =
112
// HTTPTransportUtils.createEnvelopeFromGetRequest(
113
// requestURI,
114
// getGetRequestParameters(requestURI));
115
// if (envelope == null) {
116
// this.handleGETRequest(
117
// requestURI,
118
// (OutputStream) map.get(MessageContext.TRANSPORT_OUT),
119
// msgContext.getSystemContext());
120
// return null;
121
// } else {
122
// msgContext.setProperty(
123
// Constants.Configuration.DO_REST,
124
// Constants.VALUE_TRUE);
125
// return envelope;
126
// }
127
//
128
// } else {
129
// return TransportUtils.createSOAPMessage(msgContext,inStream);
130
// }
131
// }
132

133
134     /**
135      * parses following two styles of HTTP stuff
136      * Server Side
137      * POST /axis2/services/echo HTTP/1.0
138      * Content-Type: text/xml; charset=utf-8
139      * Accept: application/soap+xml, application/dime, multipart/related, text
140      * User-Agent: Axis/1.2RC1
141      * Host: 127.0.0.1:8081
142      * Cache-Control: no-cache
143      * Pragma: no-cache
144      * SOAPAction: ""
145      * Content-Length: 73507
146      * HTTP/1.1 200 OK
147      * Content-Type: text/xml;charset=utf-8
148      * Date: Sat, 12 Feb 2005 10:39:39 GMT
149      * Server: Apache-Coyote/1.1
150      * Connection: close
151      *
152      * @param reader
153      * @param serverSide
154      * @return
155      * @throws AxisFault
156      */

157     public HashMap parseTheHeaders(InputStream JavaDoc in, boolean serverSide)
158         throws AxisFault {
159         HashMap map = new HashMap();
160         try {
161             StringBuffer JavaDoc str = new StringBuffer JavaDoc();
162             int state = BEFORE_SEPERATOR;
163             String JavaDoc key = null;
164             String JavaDoc value = null;
165             int start = 0;
166             length = readLine(in, buf);
167             if (serverSide) {
168                 if ((buf[0] == 'P')
169                     && (buf[1] == 'O')
170                     && (buf[2] == 'S')
171                     && (buf[3] == 'T')) {
172                     map.put(
173                         HTTPConstants.HTTP_REQ_TYPE,
174                         HTTPConstants.HEADER_POST);
175                     index = 5;
176
177                 } else if (
178                     (buf[0] == 'G') && (buf[1] == 'E') && (buf[2] == 'T')) {
179                     map.put(
180                         HTTPConstants.HTTP_REQ_TYPE,
181                         HTTPConstants.HEADER_GET);
182                     index = 4;
183
184                 } else {
185                     throw new AxisFault("Unsupported HTTP request type: Only GET and POST is supported");
186                 }
187
188                 value = readFirstLineArg(' ');
189                 map.put(HTTPConstants.REQUEST_URI, value);
190                 value = readFirstLineArg('\n');
191                 map.put(HTTPConstants.PROTOCOL_VERSION, value);
192             } else {
193                 index = 0;
194                 value = readFirstLineArg(' ');
195                 if (value != null && value.indexOf("HTTP") >= 0) {
196                     map.put(HTTPConstants.PROTOCOL_VERSION, value);
197                     value = readFirstLineArg(' ');
198                     map.put(HTTPConstants.RESPONSE_CODE, value);
199                 } else {
200                     map.put(HTTPConstants.RESPONSE_CODE, value);
201                 }
202
203                 value = readFirstLineArg('\n');
204                 map.put(HTTPConstants.RESPONSE_WORD, value);
205             }
206             state = BEFORE_SEPERATOR;
207             while (!done) {
208                 length = readLine(in, buf);
209                 if (length <= 0) {
210                     throw new AxisFault("Premature end of steam");
211                 }
212                 for (int i = 0; i < length; i++) {
213                     switch (state) {
214                         case BEFORE_SEPERATOR :
215                             if (buf[i] == ':') {
216                                 key = str.toString();
217                                 str = new StringBuffer JavaDoc();
218                                 state = AFTER_SEPERATOR;
219                                 if (buf[i + 1] == ' ') {
220                                     i++; // ignore next space
221
}
222                             } else {
223                                 str.append((char) buf[i]);
224                             }
225                             break;
226                         case AFTER_SEPERATOR :
227                             if (buf[i] == '\n') {
228                                 value = str.toString();
229                                 map.put(key, value);
230                                 str = new StringBuffer JavaDoc();
231                                 i = length;
232                             } else {
233                                 str.append((char) buf[i]);
234                             }
235                             break;
236
237                             // case END_OF_LINE :
238
// if (buf[i] == '\n') {
239
// state = END;
240
// break;
241
// } else {
242
// state = BEFORE_SEPERATOR;
243
// str.append(buf[i]);
244
// }
245
// break;
246
// case END:
247
// break;
248
default :
249                             throw new AxisFault(
250                                 "Error Occured Unknown state " + state);
251                     }
252                 }
253                 state = BEFORE_SEPERATOR;
254             }
255         } catch (IOException JavaDoc e) {
256             throw new AxisFault(e.getMessage(), e);
257         }
258         return map;
259     }
260
261     // public HashMap parseTheHeaders(Reader reader, boolean serverSide)
262
// throws AxisFault {
263
// HashMap map = new HashMap();
264
// try {
265
//
266
// StringBuffer str = new StringBuffer();
267
//
268
// int state = BEFORE_SEPERATOR;
269
//
270
// String key = null;
271
// String value = null;
272
//
273
// int start = 0;
274
//
275
// length = readLine(reader,buf);
276
//
277
//
278
//
279
// if (serverSide) {
280
// if (buf[0] == 'P'
281
// && buf[1] == 'O'
282
// && buf[2] == 'S'
283
// && buf[3] == 'T') {
284
// index = 5;
285
// value = readFirstLineArg(' ');
286
// map.put(HTTPConstants.REQUEST_URI,value );
287
// value = readFirstLineArg('\n');
288
// map.put(
289
// HTTPConstants.PROTOCOL_VERSION,value);
290
// start = index;
291
// } else {
292
// throw new AxisFault("Only the POST requests are supported");
293
// }
294
// } else {
295
// index = 0;
296
// value = readFirstLineArg(' ');
297
// map.put(HTTPConstants.PROTOCOL_VERSION, value);
298
// value = readFirstLineArg(' ');
299
// map.put(HTTPConstants.RESPONSE_CODE,value);
300
// value = readFirstLineArg('\n');
301
// map.put(HTTPConstants.RESPONSE_WORD, value);
302
// start = index;
303
// }
304
//
305
// while (state != END) {
306
// if(length <= 0){
307
// throw new AxisFault("Premature end of steam");
308
// }
309
// for (int i = start; i < length; i++) {
310
// System.out.println(state);
311
// switch (state) {
312
// case BEFORE_SEPERATOR :
313
// if (buf[i] == ':') {
314
// key = str.toString();
315
// str = new StringBuffer();
316
// state = AFTER_SEPERATOR;
317
//
318
// if(buf[i+1] == ' '){
319
// i++;//ignore next space
320
// }
321
// } else {
322
// str.append(buf[i]);
323
// }
324
// break;
325
// case AFTER_SEPERATOR :
326
// if (buf[i] == '\n') {
327
// value = str.toString();
328
// map.put(key, value);
329
// str = new StringBuffer();
330
// state = END_OF_LINE;
331
// } else {
332
// str.append(buf[i]);
333
// }
334
// break;
335
// case END_OF_LINE :
336
// if (buf[i] == '\n') {
337
// state = END;
338
// break;
339
// } else {
340
// state = BEFORE_SEPERATOR;
341
// str.append(buf[i]);
342
// }
343
// break;
344
// case END:
345
// break;
346
// default :
347
// throw new AxisFault(
348
// "Error Occured Unknown state " + state);
349
//
350
// }
351
// }
352
// start = 0;
353
// if(state != END){
354
// length = reader.read(buf);
355
// }
356
//
357
//
358
// }
359
// } catch (IOException e) {
360
// throw new AxisFault(e.getMessage(), e);
361
// }
362
// return map;
363
// }
364

365     /**
366      * Method readFirstLineArg
367      *
368      * @param terminal
369      * @return
370      * @throws AxisFault
371      */

372     private String JavaDoc readFirstLineArg(char terminal) throws AxisFault {
373         StringBuffer JavaDoc str = new StringBuffer JavaDoc();
374         try {
375             while ((buf[index] != terminal) && (index < length)) {
376                 str.append((char) buf[index]);
377                 index++;
378             }
379             index++;
380             return str.toString();
381         } catch (Exception JavaDoc e) {
382             throw new AxisFault(e.getMessage(), e);
383         }
384     }
385
386     /**
387          * Read a single line from the input stream
388          *
389          * @param is inputstream to read from
390          * @param b byte array to read into
391          * @param off starting offset into the byte array
392          * @param len maximum number of bytes to read
393          * @return
394          * @throws java.io.IOException
395          */

396     protected int readLine(InputStream JavaDoc is, byte[] b)
397         throws java.io.IOException JavaDoc {
398         int count = 0, c;
399
400         // System.out.println("inside here");
401
if (lastRead == -1) {
402             c = is.read();
403         } else {
404             c = lastRead;
405         }
406         int off = 0;
407         while (c != -1) {
408             if ((c != '\n') && (c != '\r')) {
409                 b[off++] = (byte) c;
410                 count++;
411                 c = is.read();
412             } else {
413                 if ('\n' == c) {
414                     c = is.read();
415                     if (c == '\r') {
416                         c = is.read();
417                     }
418
419                     // If the next line begins with tab or space then this is a continuation.
420
if ((c != ' ') && (c != '\t')) {
421                         if (c == '\n') {
422                             done = true;
423                         }
424                         lastRead = c;
425                         b[off++] = '\n';
426                         count++;
427                         break;
428                     }
429                 } else {
430                     c = is.read();
431                 }
432             }
433         }
434         if (c == -1) {
435             throw new AxisFault("Every line should ends with the \\n, unexpected End of stream");
436         } else {
437             return (count > 0) ? count : -1;
438         }
439     }
440
441  
442
443     /**
444      * Returns the HTML text for the list of services deployed
445      * This can be delegated to another Class as well
446      * where it will handle more options of GET messages :-?
447      * @return
448      */

449     public static String JavaDoc getServicesHTML(ConfigurationContext configurationContext) {
450         String JavaDoc temp = "";
451         Map services =
452             configurationContext.getAxisConfiguration().getServices();
453         Hashtable erroneousServices =
454             configurationContext.getAxisConfiguration().getFaulytServices();
455         boolean status = false;
456
457         if (services != null && !services.isEmpty()) {
458             status = true;
459             Collection serviceCollection = services.values();
460             temp += "<h2>" + "Deployed services" + "</h2>";
461             for (Iterator it = serviceCollection.iterator(); it.hasNext();) {
462                 Map operations;
463                 Collection operationsList;
464                 ServiceDescription axisService = (ServiceDescription) it.next();
465                 operations = axisService.getOperations();
466                 operationsList = operations.values();
467
468                 temp += "<h3>" + axisService.getName().getLocalPart() + "</h3>";
469                 if (operationsList.size() > 0) {
470                     temp += "Available operations <ul>";
471                     for (Iterator iterator1 = operationsList.iterator();
472                         iterator1.hasNext();
473                         ) {
474                         OperationDescription axisOperation =
475                             (OperationDescription) iterator1.next();
476                         temp += "<li>"
477                             + axisOperation.getName().getLocalPart()
478                             + "</li>";
479                     }
480                     temp += "</ul>";
481                 } else {
482                     temp += "No operations speficied for this service";
483                 }
484             }
485         }
486
487         if (erroneousServices != null && !erroneousServices.isEmpty()) {
488
489             temp += "<hr><h2><font color=\"blue\">Faulty Services</font></h2>";
490             status = true;
491             Enumeration faultyservices = erroneousServices.keys();
492             while (faultyservices.hasMoreElements()) {
493                 String JavaDoc faultyserviceName =
494                     (String JavaDoc) faultyservices.nextElement();
495                 temp += "<h3><font color=\"blue\">"
496                     + faultyserviceName
497                     + "</font></h3>";
498             }
499         }
500
501         if (!status) {
502             temp = "<h2>There are no services deployed</h2>";
503         }
504
505         temp =
506             "<html><head><title>Axis2: Services</title></head>"
507                 + "<body>"
508                 + temp
509                 + "</body></html>";
510
511         return temp;
512     }
513
514     public static Map getGetRequestParameters(String JavaDoc requestURI) {
515         Map map = new HashMap();
516
517         char[] chars = requestURI.toCharArray();
518         final int NOT_BEGUN = 1500;
519         final int INSIDE_NAME = 1501;
520         final int INSIDE_VALUE = 1502;
521
522         int state = NOT_BEGUN;
523         StringBuffer JavaDoc name = new StringBuffer JavaDoc();
524         StringBuffer JavaDoc value = new StringBuffer JavaDoc();
525
526         for (int index = 0; index < chars.length; index++) {
527             if (state == NOT_BEGUN) {
528                 if (chars[index] == '?') {
529                     state = INSIDE_NAME;
530                 }
531             } else if (state == INSIDE_NAME) {
532                 if (chars[index] == '=') {
533                     state = INSIDE_VALUE;
534                 } else {
535                     name.append(chars[index]);
536                 }
537             } else if (state == INSIDE_VALUE) {
538                 if (chars[index] == ',') {
539                     state = INSIDE_NAME;
540                     map.put(name.toString(), value.toString());
541                     name.delete(0, name.length());
542                     value.delete(0, value.length());
543                 } else {
544                     value.append(chars[index]);
545                 }
546             }
547         }
548         if (name.length() + value.length() > 0) {
549             map.put(name.toString(), value.toString());
550         }
551         return map;
552     }
553
554 }
555
Popular Tags