source: josm/trunk/src/org/openstreetmap/josm/tools/HttpClient.java@ 14496

Last change on this file since 14496 was 14496, checked in by Don-vip, 5 years ago

fix #17060, see #16073 - Support Internationalized domain names (IDN)

This allows JOSM to accesss https://öpnvkarte.de

File size: 27.1 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.tools;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.io.BufferedOutputStream;
7import java.io.BufferedReader;
8import java.io.ByteArrayInputStream;
9import java.io.IOException;
10import java.io.InputStream;
11import java.io.OutputStream;
12import java.net.CookieHandler;
13import java.net.CookieManager;
14import java.net.HttpURLConnection;
15import java.net.MalformedURLException;
16import java.net.URL;
17import java.nio.charset.StandardCharsets;
18import java.util.Collections;
19import java.util.List;
20import java.util.Locale;
21import java.util.Map;
22import java.util.Map.Entry;
23import java.util.NoSuchElementException;
24import java.util.Optional;
25import java.util.Scanner;
26import java.util.TreeMap;
27import java.util.concurrent.TimeUnit;
28import java.util.regex.Matcher;
29import java.util.regex.Pattern;
30import java.util.zip.GZIPInputStream;
31
32import org.openstreetmap.josm.data.Version;
33import org.openstreetmap.josm.data.validation.routines.DomainValidator;
34import org.openstreetmap.josm.gui.progress.NullProgressMonitor;
35import org.openstreetmap.josm.gui.progress.ProgressMonitor;
36import org.openstreetmap.josm.io.Compression;
37import org.openstreetmap.josm.io.NetworkManager;
38import org.openstreetmap.josm.io.ProgressInputStream;
39import org.openstreetmap.josm.io.ProgressOutputStream;
40import org.openstreetmap.josm.io.UTFInputStreamReader;
41import org.openstreetmap.josm.io.auth.DefaultAuthenticator;
42import org.openstreetmap.josm.spi.preferences.Config;
43
44/**
45 * Provides a uniform access for a HTTP/HTTPS server. This class should be used in favour of {@link HttpURLConnection}.
46 * @since 9168
47 */
48public final class HttpClient {
49
50 private URL url;
51 private final String requestMethod;
52 private int connectTimeout = (int) TimeUnit.SECONDS.toMillis(Config.getPref().getInt("socket.timeout.connect", 15));
53 private int readTimeout = (int) TimeUnit.SECONDS.toMillis(Config.getPref().getInt("socket.timeout.read", 30));
54 private byte[] requestBody;
55 private long ifModifiedSince;
56 private final Map<String, String> headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
57 private int maxRedirects = Config.getPref().getInt("socket.maxredirects", 5);
58 private boolean useCache;
59 private String reasonForRequest;
60 private String outputMessage = tr("Uploading data ...");
61 private HttpURLConnection connection; // to allow disconnecting before `response` is set
62 private Response response;
63 private boolean finishOnCloseOutput = true;
64
65 // Pattern to detect Tomcat error message. Be careful with change of format:
66 // CHECKSTYLE.OFF: LineLength
67 // https://svn.apache.org/viewvc/tomcat/trunk/java/org/apache/catalina/valves/ErrorReportValve.java?r1=1740707&r2=1779641&pathrev=1779641&diff_format=h
68 // CHECKSTYLE.ON: LineLength
69 private static final Pattern TOMCAT_ERR_MESSAGE = Pattern.compile(
70 ".*<p><b>[^<]+</b>[^<]+</p><p><b>[^<]+</b> (?:<u>)?([^<]*)(?:</u>)?</p><p><b>[^<]+</b> (?:<u>)?[^<]*(?:</u>)?</p>.*",
71 Pattern.CASE_INSENSITIVE);
72
73 static {
74 try {
75 CookieHandler.setDefault(new CookieManager());
76 } catch (SecurityException e) {
77 Logging.log(Logging.LEVEL_ERROR, "Unable to set default cookie handler", e);
78 }
79 }
80
81 private HttpClient(URL url, String requestMethod) {
82 try {
83 String host = url.getHost();
84 String asciiHost = DomainValidator.unicodeToASCII(host);
85 this.url = asciiHost.equals(host) ? url : new URL(url.getProtocol(), asciiHost, url.getPort(), url.getFile());
86 } catch (MalformedURLException e) {
87 throw new JosmRuntimeException(e);
88 }
89 this.requestMethod = requestMethod;
90 this.headers.put("Accept-Encoding", "gzip");
91 }
92
93 /**
94 * Opens the HTTP connection.
95 * @return HTTP response
96 * @throws IOException if any I/O error occurs
97 */
98 public Response connect() throws IOException {
99 return connect(null);
100 }
101
102 /**
103 * Opens the HTTP connection.
104 * @param progressMonitor progress monitor
105 * @return HTTP response
106 * @throws IOException if any I/O error occurs
107 * @since 9179
108 */
109 public Response connect(ProgressMonitor progressMonitor) throws IOException {
110 if (progressMonitor == null) {
111 progressMonitor = NullProgressMonitor.INSTANCE;
112 }
113 final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
114 this.connection = connection;
115 connection.setRequestMethod(requestMethod);
116 connection.setRequestProperty("User-Agent", Version.getInstance().getFullAgentString());
117 connection.setConnectTimeout(connectTimeout);
118 connection.setReadTimeout(readTimeout);
119 connection.setInstanceFollowRedirects(false); // we do that ourselves
120 if (ifModifiedSince > 0) {
121 connection.setIfModifiedSince(ifModifiedSince);
122 }
123 connection.setUseCaches(useCache);
124 if (!useCache) {
125 connection.setRequestProperty("Cache-Control", "no-cache");
126 }
127 for (Map.Entry<String, String> header : headers.entrySet()) {
128 if (header.getValue() != null) {
129 connection.setRequestProperty(header.getKey(), header.getValue());
130 }
131 }
132
133 progressMonitor.beginTask(tr("Contacting Server..."), 1);
134 progressMonitor.indeterminateSubTask(null);
135
136 if ("PUT".equals(requestMethod) || "POST".equals(requestMethod) || "DELETE".equals(requestMethod)) {
137 Logging.info("{0} {1} ({2}) ...", requestMethod, url, Utils.getSizeString(requestBody.length, Locale.getDefault()));
138 if (Logging.isTraceEnabled() && requestBody.length > 0) {
139 Logging.trace("BODY: {0}", new String(requestBody, StandardCharsets.UTF_8));
140 }
141 connection.setFixedLengthStreamingMode(requestBody.length);
142 connection.setDoOutput(true);
143 try (OutputStream out = new BufferedOutputStream(
144 new ProgressOutputStream(connection.getOutputStream(), requestBody.length,
145 progressMonitor, outputMessage, finishOnCloseOutput))) {
146 out.write(requestBody);
147 }
148 }
149
150 boolean successfulConnection = false;
151 try {
152 try {
153 connection.connect();
154 final boolean hasReason = reasonForRequest != null && !reasonForRequest.isEmpty();
155 Logging.info("{0} {1}{2} -> {3}{4}",
156 requestMethod, url, hasReason ? (" (" + reasonForRequest + ')') : "",
157 connection.getResponseCode(),
158 connection.getContentLengthLong() > 0
159 ? (" (" + Utils.getSizeString(connection.getContentLengthLong(), Locale.getDefault()) + ')')
160 : ""
161 );
162 if (Logging.isDebugEnabled()) {
163 Logging.debug("RESPONSE: {0}", connection.getHeaderFields());
164 }
165 if (DefaultAuthenticator.getInstance().isEnabled() && connection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
166 DefaultAuthenticator.getInstance().addFailedCredentialHost(url.getHost());
167 }
168 } catch (IOException | IllegalArgumentException | NoSuchElementException e) {
169 Logging.info("{0} {1} -> !!!", requestMethod, url);
170 Logging.warn(e);
171 //noinspection ThrowableResultOfMethodCallIgnored
172 NetworkManager.addNetworkError(url, Utils.getRootCause(e));
173 throw e;
174 }
175 if (isRedirect(connection.getResponseCode())) {
176 final String redirectLocation = connection.getHeaderField("Location");
177 if (redirectLocation == null) {
178 /* I18n: argument is HTTP response code */
179 throw new IOException(tr("Unexpected response from HTTP server. Got {0} response without ''Location'' header." +
180 " Can''t redirect. Aborting.", connection.getResponseCode()));
181 } else if (maxRedirects > 0) {
182 url = new URL(url, redirectLocation);
183 maxRedirects--;
184 Logging.info(tr("Download redirected to ''{0}''", redirectLocation));
185 return connect();
186 } else if (maxRedirects == 0) {
187 String msg = tr("Too many redirects to the download URL detected. Aborting.");
188 throw new IOException(msg);
189 }
190 }
191 response = new Response(connection, progressMonitor);
192 successfulConnection = true;
193 return response;
194 } finally {
195 if (!successfulConnection) {
196 connection.disconnect();
197 }
198 }
199 }
200
201 /**
202 * Returns the HTTP response which is set only after calling {@link #connect()}.
203 * Calling this method again, returns the identical object (unless another {@link #connect()} is performed).
204 *
205 * @return the HTTP response
206 * @since 9309
207 */
208 public Response getResponse() {
209 return response;
210 }
211
212 /**
213 * A wrapper for the HTTP response.
214 */
215 public static final class Response {
216 private final HttpURLConnection connection;
217 private final ProgressMonitor monitor;
218 private final int responseCode;
219 private final String responseMessage;
220 private boolean uncompress;
221 private boolean uncompressAccordingToContentDisposition;
222 private String responseData;
223
224 private Response(HttpURLConnection connection, ProgressMonitor monitor) throws IOException {
225 CheckParameterUtil.ensureParameterNotNull(connection, "connection");
226 CheckParameterUtil.ensureParameterNotNull(monitor, "monitor");
227 this.connection = connection;
228 this.monitor = monitor;
229 this.responseCode = connection.getResponseCode();
230 this.responseMessage = connection.getResponseMessage();
231 if (this.responseCode >= 300) {
232 String contentType = getContentType();
233 if (contentType == null || (
234 contentType.contains("text") ||
235 contentType.contains("html") ||
236 contentType.contains("xml"))
237 ) {
238 String content = this.fetchContent();
239 if (content.isEmpty()) {
240 Logging.debug("Server did not return any body");
241 } else {
242 Logging.debug("Response body: ");
243 Logging.debug(this.fetchContent());
244 }
245 } else {
246 Logging.debug("Server returned content: {0} of length: {1}. Not printing.", contentType, this.getContentLength());
247 }
248 }
249 }
250
251 /**
252 * Sets whether {@link #getContent()} should uncompress the input stream if necessary.
253 *
254 * @param uncompress whether the input stream should be uncompressed if necessary
255 * @return {@code this}
256 */
257 public Response uncompress(boolean uncompress) {
258 this.uncompress = uncompress;
259 return this;
260 }
261
262 /**
263 * Sets whether {@link #getContent()} should uncompress the input stream according to {@code Content-Disposition}
264 * HTTP header.
265 * @param uncompressAccordingToContentDisposition whether the input stream should be uncompressed according to
266 * {@code Content-Disposition}
267 * @return {@code this}
268 * @since 9172
269 */
270 public Response uncompressAccordingToContentDisposition(boolean uncompressAccordingToContentDisposition) {
271 this.uncompressAccordingToContentDisposition = uncompressAccordingToContentDisposition;
272 return this;
273 }
274
275 /**
276 * Returns the URL.
277 * @return the URL
278 * @see HttpURLConnection#getURL()
279 * @since 9172
280 */
281 public URL getURL() {
282 return connection.getURL();
283 }
284
285 /**
286 * Returns the request method.
287 * @return the HTTP request method
288 * @see HttpURLConnection#getRequestMethod()
289 * @since 9172
290 */
291 public String getRequestMethod() {
292 return connection.getRequestMethod();
293 }
294
295 /**
296 * Returns an input stream that reads from this HTTP connection, or,
297 * error stream if the connection failed but the server sent useful data.
298 * <p>
299 * Note: the return value can be null, if both the input and the error stream are null.
300 * Seems to be the case if the OSM server replies a 401 Unauthorized, see #3887
301 * @return input or error stream
302 * @throws IOException if any I/O error occurs
303 *
304 * @see HttpURLConnection#getInputStream()
305 * @see HttpURLConnection#getErrorStream()
306 */
307 @SuppressWarnings("resource")
308 public InputStream getContent() throws IOException {
309 InputStream in;
310 try {
311 in = connection.getInputStream();
312 } catch (IOException ioe) {
313 Logging.debug(ioe);
314 in = Optional.ofNullable(connection.getErrorStream()).orElseGet(() -> new ByteArrayInputStream(new byte[]{}));
315 }
316 in = new ProgressInputStream(in, getContentLength(), monitor);
317 in = "gzip".equalsIgnoreCase(getContentEncoding()) ? new GZIPInputStream(in) : in;
318 Compression compression = Compression.NONE;
319 if (uncompress) {
320 final String contentType = getContentType();
321 Logging.debug("Uncompressing input stream according to Content-Type header: {0}", contentType);
322 compression = Compression.forContentType(contentType);
323 }
324 if (uncompressAccordingToContentDisposition && Compression.NONE == compression) {
325 final String contentDisposition = getHeaderField("Content-Disposition");
326 final Matcher matcher = Pattern.compile("filename=\"([^\"]+)\"").matcher(
327 contentDisposition != null ? contentDisposition : "");
328 if (matcher.find()) {
329 Logging.debug("Uncompressing input stream according to Content-Disposition header: {0}", contentDisposition);
330 compression = Compression.byExtension(matcher.group(1));
331 }
332 }
333 in = compression.getUncompressedInputStream(in);
334 return in;
335 }
336
337 /**
338 * Returns {@link #getContent()} wrapped in a buffered reader.
339 *
340 * Detects Unicode charset in use utilizing {@link UTFInputStreamReader}.
341 * @return buffered reader
342 * @throws IOException if any I/O error occurs
343 */
344 public BufferedReader getContentReader() throws IOException {
345 return new BufferedReader(
346 UTFInputStreamReader.create(getContent())
347 );
348 }
349
350 /**
351 * Fetches the HTTP response as String.
352 * @return the response
353 * @throws IOException if any I/O error occurs
354 */
355 public synchronized String fetchContent() throws IOException {
356 if (responseData == null) {
357 try (Scanner scanner = new Scanner(getContentReader()).useDelimiter("\\A")) { // \A - beginning of input
358 responseData = scanner.hasNext() ? scanner.next() : "";
359 }
360 }
361 return responseData;
362 }
363
364 /**
365 * Gets the response code from this HTTP connection.
366 * @return HTTP response code
367 *
368 * @see HttpURLConnection#getResponseCode()
369 */
370 public int getResponseCode() {
371 return responseCode;
372 }
373
374 /**
375 * Gets the response message from this HTTP connection.
376 * @return HTTP response message
377 *
378 * @see HttpURLConnection#getResponseMessage()
379 * @since 9172
380 */
381 public String getResponseMessage() {
382 return responseMessage;
383 }
384
385 /**
386 * Returns the {@code Content-Encoding} header.
387 * @return {@code Content-Encoding} HTTP header
388 * @see HttpURLConnection#getContentEncoding()
389 */
390 public String getContentEncoding() {
391 return connection.getContentEncoding();
392 }
393
394 /**
395 * Returns the {@code Content-Type} header.
396 * @return {@code Content-Type} HTTP header
397 */
398 public String getContentType() {
399 return connection.getHeaderField("Content-Type");
400 }
401
402 /**
403 * Returns the {@code Expire} header.
404 * @return {@code Expire} HTTP header
405 * @see HttpURLConnection#getExpiration()
406 * @since 9232
407 */
408 public long getExpiration() {
409 return connection.getExpiration();
410 }
411
412 /**
413 * Returns the {@code Last-Modified} header.
414 * @return {@code Last-Modified} HTTP header
415 * @see HttpURLConnection#getLastModified()
416 * @since 9232
417 */
418 public long getLastModified() {
419 return connection.getLastModified();
420 }
421
422 /**
423 * Returns the {@code Content-Length} header.
424 * @return {@code Content-Length} HTTP header
425 * @see HttpURLConnection#getContentLengthLong()
426 */
427 public long getContentLength() {
428 return connection.getContentLengthLong();
429 }
430
431 /**
432 * Returns the value of the named header field.
433 * @param name the name of a header field
434 * @return the value of the named header field, or {@code null} if there is no such field in the header
435 * @see HttpURLConnection#getHeaderField(String)
436 * @since 9172
437 */
438 public String getHeaderField(String name) {
439 return connection.getHeaderField(name);
440 }
441
442 /**
443 * Returns an unmodifiable Map mapping header keys to a List of header values.
444 * As per RFC 2616, section 4.2 header names are case insensitive, so returned map is also case insensitive
445 * @return unmodifiable Map mapping header keys to a List of header values
446 * @see HttpURLConnection#getHeaderFields()
447 * @since 9232
448 */
449 public Map<String, List<String>> getHeaderFields() {
450 // returned map from HttpUrlConnection is case sensitive, use case insensitive TreeMap to conform to RFC 2616
451 Map<String, List<String>> ret = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
452 for (Entry<String, List<String>> e: connection.getHeaderFields().entrySet()) {
453 if (e.getKey() != null) {
454 ret.put(e.getKey(), e.getValue());
455 }
456 }
457 return Collections.unmodifiableMap(ret);
458 }
459
460 /**
461 * @see HttpURLConnection#disconnect()
462 */
463 public void disconnect() {
464 HttpClient.disconnect(connection);
465 }
466 }
467
468 /**
469 * Creates a new instance for the given URL and a {@code GET} request
470 *
471 * @param url the URL
472 * @return a new instance
473 */
474 public static HttpClient create(URL url) {
475 return create(url, "GET");
476 }
477
478 /**
479 * Creates a new instance for the given URL and a {@code GET} request
480 *
481 * @param url the URL
482 * @param requestMethod the HTTP request method to perform when calling
483 * @return a new instance
484 */
485 public static HttpClient create(URL url, String requestMethod) {
486 return new HttpClient(url, requestMethod);
487 }
488
489 /**
490 * Returns the URL set for this connection.
491 * @return the URL
492 * @see #create(URL)
493 * @see #create(URL, String)
494 * @since 9172
495 */
496 public URL getURL() {
497 return url;
498 }
499
500 /**
501 * Returns the request method set for this connection.
502 * @return the HTTP request method
503 * @see #create(URL, String)
504 * @since 9172
505 */
506 public String getRequestMethod() {
507 return requestMethod;
508 }
509
510 /**
511 * Returns the set value for the given {@code header}.
512 * @param header HTTP header name
513 * @return HTTP header value
514 * @since 9172
515 */
516 public String getRequestHeader(String header) {
517 return headers.get(header);
518 }
519
520 /**
521 * Sets whether not to set header {@code Cache-Control=no-cache}
522 *
523 * @param useCache whether not to set header {@code Cache-Control=no-cache}
524 * @return {@code this}
525 * @see HttpURLConnection#setUseCaches(boolean)
526 */
527 public HttpClient useCache(boolean useCache) {
528 this.useCache = useCache;
529 return this;
530 }
531
532 /**
533 * Sets whether not to set header {@code Connection=close}
534 * <p>
535 * This might fix #7640, see
536 * <a href='https://web.archive.org/web/20140118201501/http://www.tikalk.com/java/forums/httpurlconnection-disable-keep-alive'>here</a>.
537 *
538 * @param keepAlive whether not to set header {@code Connection=close}
539 * @return {@code this}
540 */
541 public HttpClient keepAlive(boolean keepAlive) {
542 return setHeader("Connection", keepAlive ? null : "close");
543 }
544
545 /**
546 * Sets a specified timeout value, in milliseconds, to be used when opening a communications link to the resource referenced
547 * by this URLConnection. If the timeout expires before the connection can be established, a
548 * {@link java.net.SocketTimeoutException} is raised. A timeout of zero is interpreted as an infinite timeout.
549 * @param connectTimeout an {@code int} that specifies the connect timeout value in milliseconds
550 * @return {@code this}
551 * @see HttpURLConnection#setConnectTimeout(int)
552 */
553 public HttpClient setConnectTimeout(int connectTimeout) {
554 this.connectTimeout = connectTimeout;
555 return this;
556 }
557
558 /**
559 * Sets the read timeout to a specified timeout, in milliseconds. A non-zero value specifies the timeout when reading from
560 * input stream when a connection is established to a resource. If the timeout expires before there is data available for
561 * read, a {@link java.net.SocketTimeoutException} is raised. A timeout of zero is interpreted as an infinite timeout.
562 * @param readTimeout an {@code int} that specifies the read timeout value in milliseconds
563 * @return {@code this}
564 * @see HttpURLConnection#setReadTimeout(int)
565 */
566 public HttpClient setReadTimeout(int readTimeout) {
567 this.readTimeout = readTimeout;
568 return this;
569 }
570
571 /**
572 * Sets the {@code Accept} header.
573 * @param accept header value
574 *
575 * @return {@code this}
576 */
577 public HttpClient setAccept(String accept) {
578 return setHeader("Accept", accept);
579 }
580
581 /**
582 * Sets the request body for {@code PUT}/{@code POST} requests.
583 * @param requestBody request body
584 *
585 * @return {@code this}
586 */
587 public HttpClient setRequestBody(byte[] requestBody) {
588 this.requestBody = Utils.copyArray(requestBody);
589 return this;
590 }
591
592 /**
593 * Sets the {@code If-Modified-Since} header.
594 * @param ifModifiedSince header value
595 *
596 * @return {@code this}
597 */
598 public HttpClient setIfModifiedSince(long ifModifiedSince) {
599 this.ifModifiedSince = ifModifiedSince;
600 return this;
601 }
602
603 /**
604 * Sets the maximum number of redirections to follow.
605 *
606 * Set {@code maxRedirects} to {@code -1} in order to ignore redirects, i.e.,
607 * to not throw an {@link IOException} in {@link #connect()}.
608 * @param maxRedirects header value
609 *
610 * @return {@code this}
611 */
612 public HttpClient setMaxRedirects(int maxRedirects) {
613 this.maxRedirects = maxRedirects;
614 return this;
615 }
616
617 /**
618 * Sets an arbitrary HTTP header.
619 * @param key header name
620 * @param value header value
621 *
622 * @return {@code this}
623 */
624 public HttpClient setHeader(String key, String value) {
625 this.headers.put(key, value);
626 return this;
627 }
628
629 /**
630 * Sets arbitrary HTTP headers.
631 * @param headers HTTP headers
632 *
633 * @return {@code this}
634 */
635 public HttpClient setHeaders(Map<String, String> headers) {
636 this.headers.putAll(headers);
637 return this;
638 }
639
640 /**
641 * Sets a reason to show on console. Can be {@code null} if no reason is given.
642 * @param reasonForRequest Reason to show
643 * @return {@code this}
644 * @since 9172
645 */
646 public HttpClient setReasonForRequest(String reasonForRequest) {
647 this.reasonForRequest = reasonForRequest;
648 return this;
649 }
650
651 /**
652 * Sets the output message to be displayed in progress monitor for {@code PUT}, {@code POST} and {@code DELETE} methods.
653 * Defaults to "Uploading data ..." (translated). Has no effect for {@code GET} or any other method.
654 * @param outputMessage message to be displayed in progress monitor
655 * @return {@code this}
656 * @since 12711
657 */
658 public HttpClient setOutputMessage(String outputMessage) {
659 this.outputMessage = outputMessage;
660 return this;
661 }
662
663 /**
664 * Sets whether the progress monitor task will be finished when the output stream is closed. This is {@code true} by default.
665 * @param finishOnCloseOutput whether the progress monitor task will be finished when the output stream is closed
666 * @return {@code this}
667 * @since 10302
668 */
669 public HttpClient setFinishOnCloseOutput(boolean finishOnCloseOutput) {
670 this.finishOnCloseOutput = finishOnCloseOutput;
671 return this;
672 }
673
674 private static boolean isRedirect(final int statusCode) {
675 switch (statusCode) {
676 case HttpURLConnection.HTTP_MOVED_PERM: // 301
677 case HttpURLConnection.HTTP_MOVED_TEMP: // 302
678 case HttpURLConnection.HTTP_SEE_OTHER: // 303
679 case 307: // TEMPORARY_REDIRECT:
680 case 308: // PERMANENT_REDIRECT:
681 return true;
682 default:
683 return false;
684 }
685 }
686
687 /**
688 * @see HttpURLConnection#disconnect()
689 * @since 9309
690 */
691 public void disconnect() {
692 HttpClient.disconnect(connection);
693 }
694
695 private static void disconnect(final HttpURLConnection connection) {
696 if (connection != null) {
697 // Fix upload aborts - see #263
698 connection.setConnectTimeout(100);
699 connection.setReadTimeout(100);
700 try {
701 Thread.sleep(100);
702 } catch (InterruptedException ex) {
703 Logging.warn("InterruptedException in " + HttpClient.class + " during cancel");
704 Thread.currentThread().interrupt();
705 }
706 connection.disconnect();
707 }
708 }
709
710 /**
711 * Returns a {@link Matcher} against predefined Tomcat error messages.
712 * If it matches, error message can be extracted from {@code group(1)}.
713 * @param data HTML contents to check
714 * @return a {@link Matcher} against predefined Tomcat error messages
715 * @since 13358
716 */
717 public static Matcher getTomcatErrorMatcher(String data) {
718 return data != null ? TOMCAT_ERR_MESSAGE.matcher(data) : null;
719 }
720}
Note: See TracBrowser for help on using the repository browser.