src/share/classes/com/sun/xml/internal/messaging/saaj/client/p2p/HttpSOAPConnection.java

changeset 1
0961a4a21176
child 45
31822b475baa
equal deleted inserted replaced
-1:000000000000 1:0961a4a21176
1 /*
2 * $Id: HttpSOAPConnection.java,v 1.41 2006/01/27 12:49:17 vj135062 Exp $
3 * $Revision: 1.41 $
4 * $Date: 2006/01/27 12:49:17 $
5 */
6
7 /*
8 * Copyright 2006 Sun Microsystems, Inc. All Rights Reserved.
9 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
10 *
11 * This code is free software; you can redistribute it and/or modify it
12 * under the terms of the GNU General Public License version 2 only, as
13 * published by the Free Software Foundation. Sun designates this
14 * particular file as subject to the "Classpath" exception as provided
15 * by Sun in the LICENSE file that accompanied this code.
16 *
17 * This code is distributed in the hope that it will be useful, but WITHOUT
18 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
19 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
20 * version 2 for more details (a copy is included in the LICENSE file that
21 * accompanied this code).
22 *
23 * You should have received a copy of the GNU General Public License version
24 * 2 along with this work; if not, write to the Free Software Foundation,
25 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
26 *
27 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
28 * CA 95054 USA or visit www.sun.com if you need additional information or
29 * have any questions.
30 */
31 package com.sun.xml.internal.messaging.saaj.client.p2p;
32
33 import java.io.*;
34 import java.lang.reflect.Method;
35 import java.net.*;
36 import java.security.*;
37 import java.util.Iterator;
38 import java.util.StringTokenizer;
39 import java.util.logging.Level;
40 import java.util.logging.Logger;
41
42 import javax.xml.soap.*;
43
44 import com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl;
45 import com.sun.xml.internal.messaging.saaj.util.*;
46
47 /**
48 * This represents a "connection" to the simple HTTP-based provider.
49 *
50 * @author Anil Vijendran (akv@eng.sun.com)
51 * @author Rajiv Mordani (rajiv.mordani@sun.com)
52 * @author Manveen Kaur (manveen.kaur@sun.com)
53 *
54 */
55 public class HttpSOAPConnection extends SOAPConnection {
56
57 protected static Logger log =
58 Logger.getLogger(LogDomainConstants.HTTP_CONN_DOMAIN,
59 "com.sun.xml.internal.messaging.saaj.client.p2p.LocalStrings");
60
61 public static String defaultProxyHost = null;
62 public static int defaultProxyPort = -1;
63
64 MessageFactory messageFactory = null;
65
66 boolean closed = false;
67
68 public HttpSOAPConnection() throws SOAPException {
69 proxyHost = defaultProxyHost;
70 proxyPort = defaultProxyPort;
71
72 try {
73 messageFactory = MessageFactory.newInstance(SOAPConstants.DYNAMIC_SOAP_PROTOCOL);
74 } catch (Exception ex) {
75 log.log(Level.SEVERE, "SAAJ0001.p2p.cannot.create.msg.factory", ex);
76 throw new SOAPExceptionImpl("Unable to create message factory", ex);
77 }
78 }
79
80 public void close() throws SOAPException {
81 if (closed) {
82 log.severe("SAAJ0002.p2p.close.already.closed.conn");
83 throw new SOAPExceptionImpl("Connection already closed");
84 }
85
86 messageFactory = null;
87 closed = true;
88 }
89
90 public SOAPMessage call(SOAPMessage message, Object endPoint)
91 throws SOAPException {
92 if (closed) {
93 log.severe("SAAJ0003.p2p.call.already.closed.conn");
94 throw new SOAPExceptionImpl("Connection is closed");
95 }
96
97 Class urlEndpointClass = null;
98
99 try {
100 urlEndpointClass = Class.forName("javax.xml.messaging.URLEndpoint");
101 } catch (Exception ex) {
102 //Do nothing. URLEndpoint is available only when JAXM is there.
103 log.finest("SAAJ0090.p2p.endpoint.available.only.for.JAXM");
104 }
105
106 if (urlEndpointClass != null) {
107 if (urlEndpointClass.isInstance(endPoint)) {
108 String url = null;
109
110 try {
111 Method m = urlEndpointClass.getMethod("getURL", (Class[])null);
112 url = (String) m.invoke(endPoint, (Object[])null);
113 } catch (Exception ex) {
114 // TBD -- exception chaining
115 log.log(Level.SEVERE,"SAAJ0004.p2p.internal.err",ex);
116 throw new SOAPExceptionImpl(
117 "Internal error: " + ex.getMessage());
118 }
119 try {
120 endPoint = new URL(url);
121 } catch (MalformedURLException mex) {
122 log.log(Level.SEVERE,"SAAJ0005.p2p.", mex);
123 throw new SOAPExceptionImpl("Bad URL: " + mex.getMessage());
124 }
125 }
126 }
127
128 if (endPoint instanceof java.lang.String) {
129 try {
130 endPoint = new URL((String) endPoint);
131 } catch (MalformedURLException mex) {
132 log.log(Level.SEVERE, "SAAJ0006.p2p.bad.URL", mex);
133 throw new SOAPExceptionImpl("Bad URL: " + mex.getMessage());
134 }
135 }
136
137 if (endPoint instanceof URL)
138 try {
139 PriviledgedPost pp =
140 new PriviledgedPost(this, message, (URL) endPoint);
141 SOAPMessage response =
142 (SOAPMessage) AccessController.doPrivileged(pp);
143
144 return response;
145 } catch (Exception ex) {
146 // TBD -- chaining?
147 throw new SOAPExceptionImpl(ex);
148 } else {
149 log.severe("SAAJ0007.p2p.bad.endPoint.type");
150 throw new SOAPExceptionImpl("Bad endPoint type " + endPoint);
151 }
152 }
153
154 static class PriviledgedPost implements PrivilegedExceptionAction {
155
156 HttpSOAPConnection c;
157 SOAPMessage message;
158 URL endPoint;
159
160 PriviledgedPost(
161 HttpSOAPConnection c,
162 SOAPMessage message,
163 URL endPoint) {
164 this.c = c;
165 this.message = message;
166 this.endPoint = endPoint;
167 }
168
169 public Object run() throws Exception {
170 return c.post(message, endPoint);
171 }
172 }
173
174 // TBD
175 // Fix this to do things better.
176
177 private String proxyHost = null;
178
179 static class PriviledgedSetProxyAction implements PrivilegedExceptionAction {
180
181 String proxyHost = null;
182 int proxyPort = 0;
183
184 PriviledgedSetProxyAction(String host, int port) {
185 this.proxyHost = host;
186 this.proxyPort = port;
187 }
188
189 public Object run() throws Exception {
190 System.setProperty("http.proxyHost", proxyHost);
191 System.setProperty("http.proxyPort", new Integer(proxyPort).toString());
192 log.log(Level.FINE, "SAAJ0050.p2p.proxy.host",
193 new String[] { proxyHost });
194 log.log(Level.FINE, "SAAJ0051.p2p.proxy.port",
195 new String[] { new Integer(proxyPort).toString() });
196 return proxyHost;
197 }
198 }
199
200
201 public void setProxy(String host, int port) {
202 try {
203 proxyPort = port;
204 PriviledgedSetProxyAction ps = new PriviledgedSetProxyAction(host, port);
205 proxyHost = (String) AccessController.doPrivileged(ps);
206 } catch (Exception e) {
207 throw new RuntimeException(e);
208 }
209 }
210
211 public String getProxyHost() {
212 return proxyHost;
213 }
214
215 private int proxyPort = -1;
216
217 public int getProxyPort() {
218 return proxyPort;
219 }
220
221 SOAPMessage post(SOAPMessage message, URL endPoint) throws SOAPException {
222 boolean isFailure = false;
223
224 URL url = null;
225 HttpURLConnection httpConnection = null;
226
227 int responseCode = 0;
228 try {
229 if (endPoint.getProtocol().equals("https"))
230 //if(!setHttps)
231 initHttps();
232 // Process the URL
233 JaxmURI uri = new JaxmURI(endPoint.toString());
234 String userInfo = uri.getUserinfo();
235
236 url = endPoint;
237
238 if (dL > 0)
239 d("uri: " + userInfo + " " + url + " " + uri);
240
241 // TBD
242 // Will deal with https later.
243 if (!url.getProtocol().equalsIgnoreCase("http")
244 && !url.getProtocol().equalsIgnoreCase("https")) {
245 log.severe("SAAJ0052.p2p.protocol.mustbe.http.or.https");
246 throw new IllegalArgumentException(
247 "Protocol "
248 + url.getProtocol()
249 + " not supported in URL "
250 + url);
251 }
252 httpConnection = (HttpURLConnection) createConnection(url);
253
254 httpConnection.setRequestMethod("POST");
255
256 httpConnection.setDoOutput(true);
257 httpConnection.setDoInput(true);
258 httpConnection.setUseCaches(false);
259 HttpURLConnection.setFollowRedirects(true);
260
261 if (message.saveRequired())
262 message.saveChanges();
263
264 MimeHeaders headers = message.getMimeHeaders();
265
266 Iterator it = headers.getAllHeaders();
267 boolean hasAuth = false; // true if we find explicit Auth header
268 while (it.hasNext()) {
269 MimeHeader header = (MimeHeader) it.next();
270
271 String[] values = headers.getHeader(header.getName());
272
273 if (values.length == 1)
274 httpConnection.setRequestProperty(
275 header.getName(),
276 header.getValue());
277 else {
278 StringBuffer concat = new StringBuffer();
279 int i = 0;
280 while (i < values.length) {
281 if (i != 0)
282 concat.append(',');
283 concat.append(values[i]);
284 i++;
285 }
286
287 httpConnection.setRequestProperty(
288 header.getName(),
289 concat.toString());
290 }
291
292 if ("Authorization".equals(header.getName())) {
293 hasAuth = true;
294 log.fine("SAAJ0091.p2p.https.auth.in.POST.true");
295 }
296 }
297
298 if (!hasAuth && userInfo != null) {
299 initAuthUserInfo(httpConnection, userInfo);
300 }
301
302 OutputStream out = httpConnection.getOutputStream();
303 message.writeTo(out);
304
305 out.flush();
306 out.close();
307
308 httpConnection.connect();
309
310 try {
311
312 responseCode = httpConnection.getResponseCode();
313
314 // let HTTP_INTERNAL_ERROR (500) through because it is used for SOAP faults
315 if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) {
316 isFailure = true;
317 }
318 //else if (responseCode != HttpURLConnection.HTTP_OK)
319 //else if (!(responseCode >= HttpURLConnection.HTTP_OK && responseCode < 207))
320 else if ((responseCode / 100) != 2) {
321 log.log(Level.SEVERE,
322 "SAAJ0008.p2p.bad.response",
323 new String[] {httpConnection.getResponseMessage()});
324 throw new SOAPExceptionImpl(
325 "Bad response: ("
326 + responseCode
327 + httpConnection.getResponseMessage());
328
329 }
330 } catch (IOException e) {
331 // on JDK1.3.1_01, we end up here, but then getResponseCode() succeeds!
332 responseCode = httpConnection.getResponseCode();
333 if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) {
334 isFailure = true;
335 } else {
336 throw e;
337 }
338
339 }
340
341 } catch (SOAPException ex) {
342 throw ex;
343 } catch (Exception ex) {
344 log.severe("SAAJ0009.p2p.msg.send.failed");
345 throw new SOAPExceptionImpl("Message send failed", ex);
346 }
347
348 SOAPMessage response = null;
349 if (responseCode == HttpURLConnection.HTTP_OK || isFailure) {
350 try {
351 MimeHeaders headers = new MimeHeaders();
352
353 String key, value;
354
355 // Header field 0 is the status line so we skip it.
356
357 int i = 1;
358
359 while (true) {
360 key = httpConnection.getHeaderFieldKey(i);
361 value = httpConnection.getHeaderField(i);
362
363 if (key == null && value == null)
364 break;
365
366 if (key != null) {
367 StringTokenizer values =
368 new StringTokenizer(value, ",");
369 while (values.hasMoreTokens())
370 headers.addHeader(key, values.nextToken().trim());
371 }
372 i++;
373 }
374
375 InputStream httpIn =
376 (isFailure
377 ? httpConnection.getErrorStream()
378 : httpConnection.getInputStream());
379
380 byte[] bytes = readFully(httpIn);
381
382 int length =
383 httpConnection.getContentLength() == -1
384 ? bytes.length
385 : httpConnection.getContentLength();
386
387 // If no reply message is returned,
388 // content-Length header field value is expected to be zero.
389 if (length == 0) {
390 response = null;
391 log.warning("SAAJ0014.p2p.content.zero");
392 } else {
393 ByteInputStream in = new ByteInputStream(bytes, length);
394 response = messageFactory.createMessage(headers, in);
395 }
396
397 httpIn.close();
398 httpConnection.disconnect();
399
400 } catch (SOAPException ex) {
401 throw ex;
402 } catch (Exception ex) {
403 log.log(Level.SEVERE,"SAAJ0010.p2p.cannot.read.resp", ex);
404 throw new SOAPExceptionImpl(
405 "Unable to read response: " + ex.getMessage());
406 }
407 }
408 return response;
409 }
410
411 // Object identifies where the request should be sent.
412 // It is required to support objects of type String and java.net.URL.
413
414 public SOAPMessage get(Object endPoint) throws SOAPException {
415 if (closed) {
416 log.severe("SAAJ0011.p2p.get.already.closed.conn");
417 throw new SOAPExceptionImpl("Connection is closed");
418 }
419 Class urlEndpointClass = null;
420
421 try {
422 urlEndpointClass = Class.forName("javax.xml.messaging.URLEndpoint");
423 } catch (Exception ex) {
424 //Do nothing. URLEndpoint is available only when JAXM is there.
425 }
426
427 if (urlEndpointClass != null) {
428 if (urlEndpointClass.isInstance(endPoint)) {
429 String url = null;
430
431 try {
432 Method m = urlEndpointClass.getMethod("getURL", (Class[])null);
433 url = (String) m.invoke(endPoint, (Object[])null);
434 } catch (Exception ex) {
435 log.severe("SAAJ0004.p2p.internal.err");
436 throw new SOAPExceptionImpl(
437 "Internal error: " + ex.getMessage());
438 }
439 try {
440 endPoint = new URL(url);
441 } catch (MalformedURLException mex) {
442 log.severe("SAAJ0005.p2p.");
443 throw new SOAPExceptionImpl("Bad URL: " + mex.getMessage());
444 }
445 }
446 }
447
448 if (endPoint instanceof java.lang.String) {
449 try {
450 endPoint = new URL((String) endPoint);
451 } catch (MalformedURLException mex) {
452 log.severe("SAAJ0006.p2p.bad.URL");
453 throw new SOAPExceptionImpl("Bad URL: " + mex.getMessage());
454 }
455 }
456
457 if (endPoint instanceof URL)
458 try {
459 PriviledgedGet pg = new PriviledgedGet(this, (URL) endPoint);
460 SOAPMessage response =
461 (SOAPMessage) AccessController.doPrivileged(pg);
462
463 return response;
464 } catch (Exception ex) {
465 throw new SOAPExceptionImpl(ex);
466 } else
467 throw new SOAPExceptionImpl("Bad endPoint type " + endPoint);
468 }
469
470 static class PriviledgedGet implements PrivilegedExceptionAction {
471
472 HttpSOAPConnection c;
473 URL endPoint;
474
475 PriviledgedGet(HttpSOAPConnection c, URL endPoint) {
476 this.c = c;
477 this.endPoint = endPoint;
478 }
479
480 public Object run() throws Exception {
481 return c.get(endPoint);
482 }
483 }
484
485 SOAPMessage get(URL endPoint) throws SOAPException {
486 boolean isFailure = false;
487
488 URL url = null;
489 HttpURLConnection httpConnection = null;
490
491 int responseCode = 0;
492 try {
493 /// Is https GET allowed??
494 if (endPoint.getProtocol().equals("https"))
495 initHttps();
496 // Process the URL
497 JaxmURI uri = new JaxmURI(endPoint.toString());
498 String userInfo = uri.getUserinfo();
499
500 url = endPoint;
501
502 if (dL > 0)
503 d("uri: " + userInfo + " " + url + " " + uri);
504
505 // TBD
506 // Will deal with https later.
507 if (!url.getProtocol().equalsIgnoreCase("http")
508 && !url.getProtocol().equalsIgnoreCase("https")) {
509 log.severe("SAAJ0052.p2p.protocol.mustbe.http.or.https");
510 throw new IllegalArgumentException(
511 "Protocol "
512 + url.getProtocol()
513 + " not supported in URL "
514 + url);
515 }
516 httpConnection = (HttpURLConnection) createConnection(url);
517
518 httpConnection.setRequestMethod("GET");
519
520 httpConnection.setDoOutput(true);
521 httpConnection.setDoInput(true);
522 httpConnection.setUseCaches(false);
523 HttpURLConnection.setFollowRedirects(true);
524
525 httpConnection.connect();
526
527 try {
528
529 responseCode = httpConnection.getResponseCode();
530
531 // let HTTP_INTERNAL_ERROR (500) through because it is used for SOAP faults
532 if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) {
533 isFailure = true;
534 } else if ((responseCode / 100) != 2) {
535 log.log(Level.SEVERE,
536 "SAAJ0008.p2p.bad.response",
537 new String[] { httpConnection.getResponseMessage()});
538 throw new SOAPExceptionImpl(
539 "Bad response: ("
540 + responseCode
541 + httpConnection.getResponseMessage());
542
543 }
544 } catch (IOException e) {
545 // on JDK1.3.1_01, we end up here, but then getResponseCode() succeeds!
546 responseCode = httpConnection.getResponseCode();
547 if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) {
548 isFailure = true;
549 } else {
550 throw e;
551 }
552
553 }
554
555 } catch (SOAPException ex) {
556 throw ex;
557 } catch (Exception ex) {
558 log.severe("SAAJ0012.p2p.get.failed");
559 throw new SOAPExceptionImpl("Get failed", ex);
560 }
561
562 SOAPMessage response = null;
563 if (responseCode == HttpURLConnection.HTTP_OK || isFailure) {
564 try {
565 MimeHeaders headers = new MimeHeaders();
566
567 String key, value;
568
569 // Header field 0 is the status line so we skip it.
570
571 int i = 1;
572
573 while (true) {
574 key = httpConnection.getHeaderFieldKey(i);
575 value = httpConnection.getHeaderField(i);
576
577 if (key == null && value == null)
578 break;
579
580 if (key != null) {
581 StringTokenizer values =
582 new StringTokenizer(value, ",");
583 while (values.hasMoreTokens())
584 headers.addHeader(key, values.nextToken().trim());
585 }
586 i++;
587 }
588
589 InputStream httpIn =
590 (isFailure
591 ? httpConnection.getErrorStream()
592 : httpConnection.getInputStream());
593
594 byte[] bytes = readFully(httpIn);
595
596 int length =
597 httpConnection.getContentLength() == -1
598 ? bytes.length
599 : httpConnection.getContentLength();
600
601 // If no reply message is returned,
602 // content-Length header field value is expected to be zero.
603 if (length == 0) {
604 response = null;
605 log.warning("SAAJ0014.p2p.content.zero");
606 } else {
607
608 ByteInputStream in = new ByteInputStream(bytes, length);
609 response = messageFactory.createMessage(headers, in);
610 }
611
612 httpIn.close();
613 httpConnection.disconnect();
614
615 } catch (SOAPException ex) {
616 throw ex;
617 } catch (Exception ex) {
618 log.log(Level.SEVERE,
619 "SAAJ0010.p2p.cannot.read.resp",
620 ex);
621 throw new SOAPExceptionImpl(
622 "Unable to read response: " + ex.getMessage());
623 }
624 }
625 return response;
626 }
627
628 private byte[] readFully(InputStream istream) throws IOException {
629 ByteArrayOutputStream bout = new ByteArrayOutputStream();
630 byte[] buf = new byte[1024];
631 int num = 0;
632
633 while ((num = istream.read(buf)) != -1) {
634 bout.write(buf, 0, num);
635 }
636
637 byte[] ret = bout.toByteArray();
638
639 return ret;
640 }
641
642 private static String SSL_PKG = "com.sun.net.ssl.internal.www.protocol";
643 private static String SSL_PROVIDER =
644 "com.sun.net.ssl.internal.ssl.Provider";
645 private void initHttps() {
646 //if(!setHttps) {
647 String pkgs = System.getProperty("java.protocol.handler.pkgs");
648 log.log(Level.FINE,
649 "SAAJ0053.p2p.providers",
650 new String[] { pkgs });
651
652 if (pkgs == null || pkgs.indexOf(SSL_PKG) < 0) {
653 if (pkgs == null)
654 pkgs = SSL_PKG;
655 else
656 pkgs = pkgs + "|" + SSL_PKG;
657 System.setProperty("java.protocol.handler.pkgs", pkgs);
658 log.log(Level.FINE,
659 "SAAJ0054.p2p.set.providers",
660 new String[] { pkgs });
661 try {
662 Class c = Class.forName(SSL_PROVIDER);
663 Provider p = (Provider) c.newInstance();
664 Security.addProvider(p);
665 log.log(Level.FINE,
666 "SAAJ0055.p2p.added.ssl.provider",
667 new String[] { SSL_PROVIDER });
668 //System.out.println("Added SSL_PROVIDER " + SSL_PROVIDER);
669 //setHttps = true;
670 } catch (Exception ex) {
671 }
672 }
673 //}
674 }
675
676 private void initAuthUserInfo(HttpURLConnection conn, String userInfo) {
677 String user;
678 String password;
679 if (userInfo != null) { // get the user and password
680 //System.out.println("UserInfo= " + userInfo );
681 int delimiter = userInfo.indexOf(':');
682 if (delimiter == -1) {
683 user = ParseUtil.decode(userInfo);
684 password = null;
685 } else {
686 user = ParseUtil.decode(userInfo.substring(0, delimiter++));
687 password = ParseUtil.decode(userInfo.substring(delimiter));
688 }
689
690 String plain = user + ":";
691 byte[] nameBytes = plain.getBytes();
692 byte[] passwdBytes = password.getBytes();
693
694 // concatenate user name and password bytes and encode them
695 byte[] concat = new byte[nameBytes.length + passwdBytes.length];
696
697 System.arraycopy(nameBytes, 0, concat, 0, nameBytes.length);
698 System.arraycopy(
699 passwdBytes,
700 0,
701 concat,
702 nameBytes.length,
703 passwdBytes.length);
704 String auth = "Basic " + new String(Base64.encode(concat));
705 conn.setRequestProperty("Authorization", auth);
706 if (dL > 0)
707 d("Adding auth " + auth);
708 }
709 }
710
711 private static final int dL = 0;
712 private void d(String s) {
713 log.log(Level.SEVERE,
714 "SAAJ0013.p2p.HttpSOAPConnection",
715 new String[] { s });
716 System.err.println("HttpSOAPConnection: " + s);
717 }
718
719 private java.net.HttpURLConnection createConnection(URL endpoint)
720 throws IOException {
721 return (HttpURLConnection) endpoint.openConnection();
722 }
723
724 }

mercurial