-
Notifications
You must be signed in to change notification settings - Fork 15
/
HttpSOAPConnection.java
576 lines (482 loc) · 20.1 KB
/
HttpSOAPConnection.java
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
/*
* Copyright (c) 1997, 2022 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Distribution License v. 1.0, which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
package com.sun.xml.messaging.saaj.client.p2p;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.Iterator;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import jakarta.xml.soap.MessageFactory;
import jakarta.xml.soap.MimeHeader;
import jakarta.xml.soap.MimeHeaders;
import jakarta.xml.soap.SOAPConnection;
import jakarta.xml.soap.SOAPConstants;
import jakarta.xml.soap.SOAPException;
import jakarta.xml.soap.SOAPMessage;
import com.sun.xml.messaging.saaj.SOAPExceptionImpl;
import com.sun.xml.messaging.saaj.util.Base64;
import com.sun.xml.messaging.saaj.util.ByteInputStream;
import com.sun.xml.messaging.saaj.util.LogDomainConstants;
import com.sun.xml.messaging.saaj.util.ParseUtil;
import com.sun.xml.messaging.saaj.util.SAAJUtil;
/**
* This represents a "connection" to the simple HTTP-based provider.
*
* @author Anil Vijendran (akv@eng.sun.com)
* @author Rajiv Mordani (rajiv.mordani@sun.com)
* @author Manveen Kaur (manveen.kaur@sun.com)
*
*/
class HttpSOAPConnection extends SOAPConnection {
private static final Logger log =
Logger.getLogger(LogDomainConstants.HTTP_CONN_DOMAIN,
"com.sun.xml.messaging.saaj.client.p2p.LocalStrings");
/**
* URLConnection connect timeout
*/
private static int CONNECT_TIMEOUT = Integer.MIN_VALUE;
/**
* URLConnection read timeout
*/
private static int READ_TIMEOUT = Integer.MIN_VALUE;
static {
Integer i = SAAJUtil.getSystemInteger("saaj.connect.timeout");
if (i != null) {
CONNECT_TIMEOUT = i;
}
i = SAAJUtil.getSystemInteger("saaj.read.timeout");
if (i != null) {
READ_TIMEOUT = i;
}
}
MessageFactory messageFactory = null;
boolean closed = false;
public HttpSOAPConnection() throws SOAPException {
try {
messageFactory = MessageFactory.newInstance(SOAPConstants.DYNAMIC_SOAP_PROTOCOL);
} catch (NoSuchMethodError ex) {
//fallback to default SOAP 1.1 in this case for backward compatibility
messageFactory = MessageFactory.newInstance();
} catch (Exception ex) {
log.log(Level.SEVERE, "SAAJ0001.p2p.cannot.create.msg.factory", ex);
throw new SOAPExceptionImpl("Unable to create message factory", ex);
}
}
@Override
public void close() throws SOAPException {
if (closed) {
log.severe("SAAJ0002.p2p.close.already.closed.conn");
throw new SOAPExceptionImpl("Connection already closed");
}
messageFactory = null;
closed = true;
}
@Override
public int getConnectTimeout() {
if (Integer.MIN_VALUE != CONNECT_TIMEOUT) {
return CONNECT_TIMEOUT;
}
return super.getConnectTimeout();
}
@Override
public int getReadTimeout() {
if (Integer.MIN_VALUE != READ_TIMEOUT) {
return READ_TIMEOUT;
}
return super.getReadTimeout();
}
@Override
public SOAPMessage call(SOAPMessage message, Object endPoint)
throws SOAPException {
if (closed) {
log.severe("SAAJ0003.p2p.call.already.closed.conn");
throw new SOAPExceptionImpl("Connection is closed");
}
if (endPoint instanceof java.lang.String) {
try {
endPoint = new URL((String) endPoint);
} catch (MalformedURLException mex) {
log.log(Level.SEVERE, "SAAJ0006.p2p.bad.URL", mex);
throw new SOAPExceptionImpl("Bad URL: " + mex.getMessage());
}
}
if (endPoint instanceof URL)
try {
SOAPMessage response = post(message, (URL)endPoint);
return response;
} catch (Exception ex) {
// TBD -- chaining?
throw new SOAPExceptionImpl(ex);
} else {
log.severe("SAAJ0007.p2p.bad.endPoint.type");
throw new SOAPExceptionImpl("Bad endPoint type " + endPoint);
}
}
SOAPMessage post(SOAPMessage message, URL endPoint) throws SOAPException, IOException {
boolean isFailure = false;
URL url = null;
HttpURLConnection httpConnection = null;
int responseCode = 0;
try {
// Process the URL
URI uri = new URI(endPoint.toString());
String userInfo = uri.getRawUserInfo();
url = endPoint;
if (dL > 0)
d("uri: " + userInfo + " " + url + " " + uri);
// TBD
// Will deal with https later.
if (!url.getProtocol().equalsIgnoreCase("http")
&& !url.getProtocol().equalsIgnoreCase("https")) {
log.severe("SAAJ0052.p2p.protocol.mustbe.http.or.https");
throw new IllegalArgumentException(
"Protocol "
+ url.getProtocol()
+ " not supported in URL "
+ url);
}
httpConnection = createConnection(url);
httpConnection.setRequestMethod("POST");
httpConnection.setDoOutput(true);
httpConnection.setDoInput(true);
httpConnection.setUseCaches(false);
httpConnection.setInstanceFollowRedirects(true);
httpConnection.setConnectTimeout(getConnectTimeout());
httpConnection.setReadTimeout(getReadTimeout());
if (message.saveRequired())
message.saveChanges();
MimeHeaders headers = message.getMimeHeaders();
Iterator<?> it = headers.getAllHeaders();
boolean hasAuth = false; // true if we find explicit Auth header
while (it.hasNext()) {
MimeHeader header = (MimeHeader) it.next();
String[] values = headers.getHeader(header.getName());
if (values.length == 1)
httpConnection.setRequestProperty(
header.getName(),
header.getValue());
else {
StringBuilder concat = new StringBuilder();
int i = 0;
while (i < values.length) {
if (i != 0)
concat.append(',');
concat.append(values[i]);
i++;
}
httpConnection.setRequestProperty(
header.getName(),
concat.toString());
}
if ("Authorization".equals(header.getName())) {
hasAuth = true;
if (log.isLoggable(Level.FINE))
log.fine("SAAJ0091.p2p.https.auth.in.POST.true");
}
}
if (!hasAuth && userInfo != null) {
initAuthUserInfo(httpConnection, userInfo);
}
OutputStream out = httpConnection.getOutputStream();
try {
message.writeTo(out);
out.flush();
} finally {
out.close();
}
httpConnection.connect();
try {
responseCode = httpConnection.getResponseCode();
// let HTTP_INTERNAL_ERROR (500) and HTTP_BAD_REQUEST (400) through because it is used for SOAP faults
if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR || responseCode == HttpURLConnection.HTTP_BAD_REQUEST) {
isFailure = true;
}
//else if (responseCode != HttpURLConnection.HTTP_OK)
//else if (!(responseCode >= HttpURLConnection.HTTP_OK && responseCode < 207))
else if ((responseCode / 100) != 2) {
log.log(Level.SEVERE,
"SAAJ0008.p2p.bad.response",
new String[] {httpConnection.getResponseMessage().replaceAll("[\r\n]","")});
throw new SOAPExceptionImpl(
"Bad response: ("
+ responseCode
+ httpConnection.getResponseMessage());
}
} catch (IOException e) {
// on JDK1.3.1_01, we end up here, but then getResponseCode() succeeds!
responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR || responseCode == HttpURLConnection.HTTP_BAD_REQUEST) {
isFailure = true;
} else {
throw e;
}
}
} catch (SOAPException ex) {
throw ex;
} catch (Exception ex) {
log.severe("SAAJ0009.p2p.msg.send.failed");
throw new SOAPExceptionImpl("Message send failed", ex);
}
SOAPMessage response = null;
InputStream httpIn = null;
if (responseCode == HttpURLConnection.HTTP_OK || isFailure) {
try {
MimeHeaders headers = new MimeHeaders();
String key, value;
// Header field 0 is the status line so we skip it.
int i = 1;
while (true) {
key = httpConnection.getHeaderFieldKey(i);
value = httpConnection.getHeaderField(i);
if (key == null && value == null)
break;
if (key != null) {
StringTokenizer values =
new StringTokenizer(value, ",");
while (values.hasMoreTokens())
headers.addHeader(key, values.nextToken().trim());
}
i++;
}
httpIn =
(isFailure
? httpConnection.getErrorStream()
: httpConnection.getInputStream());
byte[] bytes = readFully(httpIn);
int length =
httpConnection.getContentLength() == -1
? bytes.length
: httpConnection.getContentLength();
// If no reply message is returned,
// content-Length header field value is expected to be zero.
if (length == 0) {
response = null;
log.warning("SAAJ0014.p2p.content.zero");
} else {
ByteInputStream in = new ByteInputStream(bytes, length);
response = messageFactory.createMessage(headers, in);
}
} catch (SOAPException ex) {
throw ex;
} catch (Exception ex) {
log.log(Level.SEVERE,"SAAJ0010.p2p.cannot.read.resp", ex);
throw new SOAPExceptionImpl(
"Unable to read response: " + ex.getMessage());
} finally {
if (httpIn != null)
httpIn.close();
httpConnection.disconnect();
}
}
return response;
}
// Object identifies where the request should be sent.
// It is required to support objects of type String and java.net.URL.
@Override
public SOAPMessage get(Object endPoint) throws SOAPException {
if (closed) {
log.severe("SAAJ0011.p2p.get.already.closed.conn");
throw new SOAPExceptionImpl("Connection is closed");
}
if (endPoint instanceof java.lang.String) {
try {
endPoint = new URL((String) endPoint);
} catch (MalformedURLException mex) {
log.severe("SAAJ0006.p2p.bad.URL");
throw new SOAPExceptionImpl("Bad URL: " + mex.getMessage());
}
}
if (endPoint instanceof URL)
try {
SOAPMessage response = doGet((URL)endPoint);
return response;
} catch (Exception ex) {
throw new SOAPExceptionImpl(ex);
} else
throw new SOAPExceptionImpl("Bad endPoint type " + endPoint);
}
SOAPMessage doGet(URL endPoint) throws SOAPException, IOException {
boolean isFailure = false;
URL url = null;
HttpURLConnection httpConnection = null;
int responseCode = 0;
try {
// Process the URL
URI uri = new URI(endPoint.toString());
url = endPoint;
if (dL > 0) {
String userInfo = uri.getRawUserInfo();
d("uri: " + userInfo + " " + url + " " + uri);
}
// TBD
// Will deal with https later.
if (!url.getProtocol().equalsIgnoreCase("http")
&& !url.getProtocol().equalsIgnoreCase("https")) {
log.severe("SAAJ0052.p2p.protocol.mustbe.http.or.https");
throw new IllegalArgumentException(
"Protocol "
+ url.getProtocol()
+ " not supported in URL "
+ url);
}
httpConnection = createConnection(url);
httpConnection.setRequestMethod("GET");
httpConnection.setDoOutput(true);
httpConnection.setDoInput(true);
httpConnection.setUseCaches(false);
httpConnection.setInstanceFollowRedirects(true);
httpConnection.setConnectTimeout(getConnectTimeout());
httpConnection.setReadTimeout(getReadTimeout());
httpConnection.connect();
try {
responseCode = httpConnection.getResponseCode();
// let HTTP_INTERNAL_ERROR (500) and HTTP_BAD_REQUEST (400) through because it is used for SOAP faults
if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR || responseCode == HttpURLConnection.HTTP_BAD_REQUEST) {
isFailure = true;
} else if ((responseCode / 100) != 2) {
log.log(Level.SEVERE,
"SAAJ0008.p2p.bad.response",
new String[] { httpConnection.getResponseMessage().replaceAll("[\r\n]","")});
throw new SOAPExceptionImpl(
"Bad response: ("
+ responseCode
+ httpConnection.getResponseMessage());
}
} catch (IOException e) {
// on JDK1.3.1_01, we end up here, but then getResponseCode() succeeds!
responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR || responseCode == HttpURLConnection.HTTP_BAD_REQUEST) {
isFailure = true;
} else {
throw e;
}
}
} catch (SOAPException ex) {
throw ex;
} catch (Exception ex) {
log.severe("SAAJ0012.p2p.get.failed");
throw new SOAPExceptionImpl("Get failed", ex);
}
SOAPMessage response = null;
InputStream httpIn = null;
if (responseCode == HttpURLConnection.HTTP_OK || isFailure) {
try {
MimeHeaders headers = new MimeHeaders();
String key, value;
// Header field 0 is the status line so we skip it.
int i = 1;
while (true) {
key = httpConnection.getHeaderFieldKey(i);
value = httpConnection.getHeaderField(i);
if (key == null && value == null)
break;
if (key != null) {
StringTokenizer values =
new StringTokenizer(value, ",");
while (values.hasMoreTokens())
headers.addHeader(key, values.nextToken().trim());
}
i++;
}
httpIn =
(isFailure
? httpConnection.getErrorStream()
: httpConnection.getInputStream());
// If no reply message is returned,
// content-Length header field value is expected to be zero.
// java SE 6 documentation says :
// available() : an estimate of the number of bytes that can be read
//(or skipped over) from this input stream without blocking
//or 0 when it reaches the end of the input stream.
if ((httpIn == null )
|| (httpConnection.getContentLength() == 0)
|| (httpIn.available() == 0)) {
response = null;
log.warning("SAAJ0014.p2p.content.zero");
} else {
response = messageFactory.createMessage(headers, httpIn);
}
} catch (SOAPException ex) {
throw ex;
} catch (Exception ex) {
log.log(Level.SEVERE,
"SAAJ0010.p2p.cannot.read.resp",
ex);
throw new SOAPExceptionImpl(
"Unable to read response: " + ex.getMessage());
} finally {
if (httpIn != null)
httpIn.close();
httpConnection.disconnect();
}
}
return response;
}
private byte[] readFully(InputStream istream) throws IOException {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int num = 0;
while ((num = istream.read(buf)) != -1) {
bout.write(buf, 0, num);
}
byte[] ret = bout.toByteArray();
return ret;
}
private void initAuthUserInfo(HttpURLConnection conn, String userInfo) {
String user;
String password;
if (userInfo != null) { // get the user and password
//System.out.println("UserInfo= " + userInfo );
int delimiter = userInfo.indexOf(':');
if (delimiter == -1) {
user = ParseUtil.decode(userInfo);
password = null;
} else {
user = ParseUtil.decode(userInfo.substring(0, delimiter++));
password = ParseUtil.decode(userInfo.substring(delimiter));
}
String plain = user + ":";
byte[] nameBytes = plain.getBytes();
byte[] passwdBytes = (password == null ? new byte[0] : password
.getBytes());
// concatenate user name and password bytes and encode them
byte[] concat = new byte[nameBytes.length + passwdBytes.length];
System.arraycopy(nameBytes, 0, concat, 0, nameBytes.length);
System.arraycopy(
passwdBytes,
0,
concat,
nameBytes.length,
passwdBytes.length);
String auth = "Basic " + new String(Base64.encode(concat));
conn.setRequestProperty("Authorization", auth);
if (dL > 0)
d("Adding auth " + auth);
}
}
private static final int dL = 0;
private void d(String s) {
log.log(Level.SEVERE,
"SAAJ0013.p2p.HttpSOAPConnection",
new String[] { s.replaceAll("[\r\n]","") });
System.err.println("HttpSOAPConnection: " + s);
}
private java.net.HttpURLConnection createConnection(URL endpoint)
throws IOException {
return (HttpURLConnection) endpoint.openConnection();
}
}