001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.tools;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.io.BufferedOutputStream;
007import java.io.BufferedReader;
008import java.io.ByteArrayInputStream;
009import java.io.IOException;
010import java.io.InputStream;
011import java.io.OutputStream;
012import java.net.CookieHandler;
013import java.net.CookieManager;
014import java.net.HttpURLConnection;
015import java.net.MalformedURLException;
016import java.net.URL;
017import java.nio.charset.StandardCharsets;
018import java.util.Collections;
019import java.util.List;
020import java.util.Locale;
021import java.util.Map;
022import java.util.Map.Entry;
023import java.util.NoSuchElementException;
024import java.util.Optional;
025import java.util.Scanner;
026import java.util.TreeMap;
027import java.util.concurrent.TimeUnit;
028import java.util.regex.Matcher;
029import java.util.regex.Pattern;
030import java.util.zip.GZIPInputStream;
031
032import org.openstreetmap.josm.data.Version;
033import org.openstreetmap.josm.data.validation.routines.DomainValidator;
034import org.openstreetmap.josm.gui.progress.NullProgressMonitor;
035import org.openstreetmap.josm.gui.progress.ProgressMonitor;
036import org.openstreetmap.josm.io.Compression;
037import org.openstreetmap.josm.io.NetworkManager;
038import org.openstreetmap.josm.io.ProgressInputStream;
039import org.openstreetmap.josm.io.ProgressOutputStream;
040import org.openstreetmap.josm.io.UTFInputStreamReader;
041import org.openstreetmap.josm.io.auth.DefaultAuthenticator;
042import org.openstreetmap.josm.spi.preferences.Config;
043
044/**
045 * Provides a uniform access for a HTTP/HTTPS server. This class should be used in favour of {@link HttpURLConnection}.
046 * @since 9168
047 */
048public final class HttpClient {
049
050    private URL url;
051    private final String requestMethod;
052    private int connectTimeout = (int) TimeUnit.SECONDS.toMillis(Config.getPref().getInt("socket.timeout.connect", 15));
053    private int readTimeout = (int) TimeUnit.SECONDS.toMillis(Config.getPref().getInt("socket.timeout.read", 30));
054    private byte[] requestBody;
055    private long ifModifiedSince;
056    private final Map<String, String> headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
057    private int maxRedirects = Config.getPref().getInt("socket.maxredirects", 5);
058    private boolean useCache;
059    private String reasonForRequest;
060    private String outputMessage = tr("Uploading data ...");
061    private HttpURLConnection connection; // to allow disconnecting before `response` is set
062    private Response response;
063    private boolean finishOnCloseOutput = true;
064
065    // Pattern to detect Tomcat error message. Be careful with change of format:
066    // CHECKSTYLE.OFF: LineLength
067    // https://svn.apache.org/viewvc/tomcat/trunk/java/org/apache/catalina/valves/ErrorReportValve.java?r1=1740707&r2=1779641&pathrev=1779641&diff_format=h
068    // CHECKSTYLE.ON: LineLength
069    private static final Pattern TOMCAT_ERR_MESSAGE = Pattern.compile(
070        ".*<p><b>[^<]+</b>[^<]+</p><p><b>[^<]+</b> (?:<u>)?([^<]*)(?:</u>)?</p><p><b>[^<]+</b> (?:<u>)?[^<]*(?:</u>)?</p>.*",
071        Pattern.CASE_INSENSITIVE);
072
073    static {
074        try {
075            CookieHandler.setDefault(new CookieManager());
076        } catch (SecurityException e) {
077            Logging.log(Logging.LEVEL_ERROR, "Unable to set default cookie handler", e);
078        }
079    }
080
081    private HttpClient(URL url, String requestMethod) {
082        try {
083            String host = url.getHost();
084            String asciiHost = DomainValidator.unicodeToASCII(host);
085            this.url = asciiHost.equals(host) ? url : new URL(url.getProtocol(), asciiHost, url.getPort(), url.getFile());
086        } catch (MalformedURLException e) {
087            throw new JosmRuntimeException(e);
088        }
089        this.requestMethod = requestMethod;
090        this.headers.put("Accept-Encoding", "gzip");
091    }
092
093    /**
094     * Opens the HTTP connection.
095     * @return HTTP response
096     * @throws IOException if any I/O error occurs
097     */
098    public Response connect() throws IOException {
099        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                    try {
164                        Logging.debug("RESPONSE: {0}", connection.getHeaderFields());
165                    } catch (IllegalArgumentException e) {
166                        Logging.warn(e);
167                    }
168                }
169                if (DefaultAuthenticator.getInstance().isEnabled() && connection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
170                    DefaultAuthenticator.getInstance().addFailedCredentialHost(url.getHost());
171                }
172            } catch (IOException | IllegalArgumentException | NoSuchElementException e) {
173                Logging.info("{0} {1} -> !!!", requestMethod, url);
174                Logging.warn(e);
175                //noinspection ThrowableResultOfMethodCallIgnored
176                NetworkManager.addNetworkError(url, Utils.getRootCause(e));
177                throw e;
178            }
179            if (isRedirect(connection.getResponseCode())) {
180                final String redirectLocation = connection.getHeaderField("Location");
181                if (redirectLocation == null) {
182                    /* I18n: argument is HTTP response code */
183                    throw new IOException(tr("Unexpected response from HTTP server. Got {0} response without ''Location'' header." +
184                            " Can''t redirect. Aborting.", connection.getResponseCode()));
185                } else if (maxRedirects > 0) {
186                    url = new URL(url, redirectLocation);
187                    maxRedirects--;
188                    Logging.info(tr("Download redirected to ''{0}''", redirectLocation));
189                    return connect();
190                } else if (maxRedirects == 0) {
191                    String msg = tr("Too many redirects to the download URL detected. Aborting.");
192                    throw new IOException(msg);
193                }
194            }
195            response = new Response(connection, progressMonitor);
196            successfulConnection = true;
197            return response;
198        } finally {
199            if (!successfulConnection) {
200                connection.disconnect();
201            }
202        }
203    }
204
205    /**
206     * Returns the HTTP response which is set only after calling {@link #connect()}.
207     * Calling this method again, returns the identical object (unless another {@link #connect()} is performed).
208     *
209     * @return the HTTP response
210     * @since 9309
211     */
212    public Response getResponse() {
213        return response;
214    }
215
216    /**
217     * A wrapper for the HTTP response.
218     */
219    public static final class Response {
220        private final HttpURLConnection connection;
221        private final ProgressMonitor monitor;
222        private final int responseCode;
223        private final String responseMessage;
224        private boolean uncompress;
225        private boolean uncompressAccordingToContentDisposition;
226        private String responseData;
227
228        private Response(HttpURLConnection connection, ProgressMonitor monitor) throws IOException {
229            CheckParameterUtil.ensureParameterNotNull(connection, "connection");
230            CheckParameterUtil.ensureParameterNotNull(monitor, "monitor");
231            this.connection = connection;
232            this.monitor = monitor;
233            this.responseCode = connection.getResponseCode();
234            this.responseMessage = connection.getResponseMessage();
235            if (this.responseCode >= 300) {
236                String contentType = getContentType();
237                if (contentType == null || (
238                        contentType.contains("text") ||
239                        contentType.contains("html") ||
240                        contentType.contains("xml"))
241                        ) {
242                    String content = this.fetchContent();
243                    if (content.isEmpty()) {
244                        Logging.debug("Server did not return any body");
245                    } else {
246                        Logging.debug("Response body: ");
247                        Logging.debug(this.fetchContent());
248                    }
249                } else {
250                    Logging.debug("Server returned content: {0} of length: {1}. Not printing.", contentType, this.getContentLength());
251                }
252            }
253        }
254
255        /**
256         * Sets whether {@link #getContent()} should uncompress the input stream if necessary.
257         *
258         * @param uncompress whether the input stream should be uncompressed if necessary
259         * @return {@code this}
260         */
261        public Response uncompress(boolean uncompress) {
262            this.uncompress = uncompress;
263            return this;
264        }
265
266        /**
267         * Sets whether {@link #getContent()} should uncompress the input stream according to {@code Content-Disposition}
268         * HTTP header.
269         * @param uncompressAccordingToContentDisposition whether the input stream should be uncompressed according to
270         * {@code Content-Disposition}
271         * @return {@code this}
272         * @since 9172
273         */
274        public Response uncompressAccordingToContentDisposition(boolean uncompressAccordingToContentDisposition) {
275            this.uncompressAccordingToContentDisposition = uncompressAccordingToContentDisposition;
276            return this;
277        }
278
279        /**
280         * Returns the URL.
281         * @return the URL
282         * @see HttpURLConnection#getURL()
283         * @since 9172
284         */
285        public URL getURL() {
286            return connection.getURL();
287        }
288
289        /**
290         * Returns the request method.
291         * @return the HTTP request method
292         * @see HttpURLConnection#getRequestMethod()
293         * @since 9172
294         */
295        public String getRequestMethod() {
296            return connection.getRequestMethod();
297        }
298
299        /**
300         * Returns an input stream that reads from this HTTP connection, or,
301         * error stream if the connection failed but the server sent useful data.
302         * <p>
303         * Note: the return value can be null, if both the input and the error stream are null.
304         * Seems to be the case if the OSM server replies a 401 Unauthorized, see #3887
305         * @return input or error stream
306         * @throws IOException if any I/O error occurs
307         *
308         * @see HttpURLConnection#getInputStream()
309         * @see HttpURLConnection#getErrorStream()
310         */
311        @SuppressWarnings("resource")
312        public InputStream getContent() throws IOException {
313            InputStream in;
314            try {
315                in = connection.getInputStream();
316            } catch (IOException ioe) {
317                Logging.debug(ioe);
318                in = Optional.ofNullable(connection.getErrorStream()).orElseGet(() -> new ByteArrayInputStream(new byte[]{}));
319            }
320            in = new ProgressInputStream(in, getContentLength(), monitor);
321            in = "gzip".equalsIgnoreCase(getContentEncoding()) ? new GZIPInputStream(in) : in;
322            Compression compression = Compression.NONE;
323            if (uncompress) {
324                final String contentType = getContentType();
325                Logging.debug("Uncompressing input stream according to Content-Type header: {0}", contentType);
326                compression = Compression.forContentType(contentType);
327            }
328            if (uncompressAccordingToContentDisposition && Compression.NONE == compression) {
329                final String contentDisposition = getHeaderField("Content-Disposition");
330                final Matcher matcher = Pattern.compile("filename=\"([^\"]+)\"").matcher(
331                        contentDisposition != null ? contentDisposition : "");
332                if (matcher.find()) {
333                    Logging.debug("Uncompressing input stream according to Content-Disposition header: {0}", contentDisposition);
334                    compression = Compression.byExtension(matcher.group(1));
335                }
336            }
337            in = compression.getUncompressedInputStream(in);
338            return in;
339        }
340
341        /**
342         * Returns {@link #getContent()} wrapped in a buffered reader.
343         *
344         * Detects Unicode charset in use utilizing {@link UTFInputStreamReader}.
345         * @return buffered reader
346         * @throws IOException if any I/O error occurs
347         */
348        public BufferedReader getContentReader() throws IOException {
349            return new BufferedReader(
350                    UTFInputStreamReader.create(getContent())
351            );
352        }
353
354        /**
355         * Fetches the HTTP response as String.
356         * @return the response
357         * @throws IOException if any I/O error occurs
358         */
359        public synchronized String fetchContent() throws IOException {
360            if (responseData == null) {
361                try (Scanner scanner = new Scanner(getContentReader()).useDelimiter("\\A")) { // \A - beginning of input
362                    responseData = scanner.hasNext() ? scanner.next() : "";
363                }
364            }
365            return responseData;
366        }
367
368        /**
369         * Gets the response code from this HTTP connection.
370         * @return HTTP response code
371         *
372         * @see HttpURLConnection#getResponseCode()
373         */
374        public int getResponseCode() {
375            return responseCode;
376        }
377
378        /**
379         * Gets the response message from this HTTP connection.
380         * @return HTTP response message
381         *
382         * @see HttpURLConnection#getResponseMessage()
383         * @since 9172
384         */
385        public String getResponseMessage() {
386            return responseMessage;
387        }
388
389        /**
390         * Returns the {@code Content-Encoding} header.
391         * @return {@code Content-Encoding} HTTP header
392         * @see HttpURLConnection#getContentEncoding()
393         */
394        public String getContentEncoding() {
395            return connection.getContentEncoding();
396        }
397
398        /**
399         * Returns the {@code Content-Type} header.
400         * @return {@code Content-Type} HTTP header
401         */
402        public String getContentType() {
403            return connection.getHeaderField("Content-Type");
404        }
405
406        /**
407         * Returns the {@code Expire} header.
408         * @return {@code Expire} HTTP header
409         * @see HttpURLConnection#getExpiration()
410         * @since 9232
411         */
412        public long getExpiration() {
413            return connection.getExpiration();
414        }
415
416        /**
417         * Returns the {@code Last-Modified} header.
418         * @return {@code Last-Modified} HTTP header
419         * @see HttpURLConnection#getLastModified()
420         * @since 9232
421         */
422        public long getLastModified() {
423            return connection.getLastModified();
424        }
425
426        /**
427         * Returns the {@code Content-Length} header.
428         * @return {@code Content-Length} HTTP header
429         * @see HttpURLConnection#getContentLengthLong()
430         */
431        public long getContentLength() {
432            return connection.getContentLengthLong();
433        }
434
435        /**
436         * Returns the value of the named header field.
437         * @param name the name of a header field
438         * @return the value of the named header field, or {@code null} if there is no such field in the header
439         * @see HttpURLConnection#getHeaderField(String)
440         * @since 9172
441         */
442        public String getHeaderField(String name) {
443            return connection.getHeaderField(name);
444        }
445
446        /**
447         * Returns an unmodifiable Map mapping header keys to a List of header values.
448         * As per RFC 2616, section 4.2 header names are case insensitive, so returned map is also case insensitive
449         * @return unmodifiable Map mapping header keys to a List of header values
450         * @see HttpURLConnection#getHeaderFields()
451         * @since 9232
452         */
453        public Map<String, List<String>> getHeaderFields() {
454            // returned map from HttpUrlConnection is case sensitive, use case insensitive TreeMap to conform to RFC 2616
455            Map<String, List<String>> ret = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
456            for (Entry<String, List<String>> e: connection.getHeaderFields().entrySet()) {
457                if (e.getKey() != null) {
458                    ret.put(e.getKey(), e.getValue());
459                }
460            }
461            return Collections.unmodifiableMap(ret);
462        }
463
464        /**
465         * @see HttpURLConnection#disconnect()
466         */
467        public void disconnect() {
468            HttpClient.disconnect(connection);
469        }
470    }
471
472    /**
473     * Creates a new instance for the given URL and a {@code GET} request
474     *
475     * @param url the URL
476     * @return a new instance
477     */
478    public static HttpClient create(URL url) {
479        return create(url, "GET");
480    }
481
482    /**
483     * Creates a new instance for the given URL and a {@code GET} request
484     *
485     * @param url the URL
486     * @param requestMethod the HTTP request method to perform when calling
487     * @return a new instance
488     */
489    public static HttpClient create(URL url, String requestMethod) {
490        return new HttpClient(url, requestMethod);
491    }
492
493    /**
494     * Returns the URL set for this connection.
495     * @return the URL
496     * @see #create(URL)
497     * @see #create(URL, String)
498     * @since 9172
499     */
500    public URL getURL() {
501        return url;
502    }
503
504    /**
505     * Returns the request method set for this connection.
506     * @return the HTTP request method
507     * @see #create(URL, String)
508     * @since 9172
509     */
510    public String getRequestMethod() {
511        return requestMethod;
512    }
513
514    /**
515     * Returns the set value for the given {@code header}.
516     * @param header HTTP header name
517     * @return HTTP header value
518     * @since 9172
519     */
520    public String getRequestHeader(String header) {
521        return headers.get(header);
522    }
523
524    /**
525     * Sets whether not to set header {@code Cache-Control=no-cache}
526     *
527     * @param useCache whether not to set header {@code Cache-Control=no-cache}
528     * @return {@code this}
529     * @see HttpURLConnection#setUseCaches(boolean)
530     */
531    public HttpClient useCache(boolean useCache) {
532        this.useCache = useCache;
533        return this;
534    }
535
536    /**
537     * Sets whether not to set header {@code Connection=close}
538     * <p>
539     * This might fix #7640, see
540     * <a href='https://web.archive.org/web/20140118201501/http://www.tikalk.com/java/forums/httpurlconnection-disable-keep-alive'>here</a>.
541     *
542     * @param keepAlive whether not to set header {@code Connection=close}
543     * @return {@code this}
544     */
545    public HttpClient keepAlive(boolean keepAlive) {
546        return setHeader("Connection", keepAlive ? null : "close");
547    }
548
549    /**
550     * Sets a specified timeout value, in milliseconds, to be used when opening a communications link to the resource referenced
551     * by this URLConnection. If the timeout expires before the connection can be established, a
552     * {@link java.net.SocketTimeoutException} is raised. A timeout of zero is interpreted as an infinite timeout.
553     * @param connectTimeout an {@code int} that specifies the connect timeout value in milliseconds
554     * @return {@code this}
555     * @see HttpURLConnection#setConnectTimeout(int)
556     */
557    public HttpClient setConnectTimeout(int connectTimeout) {
558        this.connectTimeout = connectTimeout;
559        return this;
560    }
561
562    /**
563     * Sets the read timeout to a specified timeout, in milliseconds. A non-zero value specifies the timeout when reading from
564     * input stream when a connection is established to a resource. If the timeout expires before there is data available for
565     * read, a {@link java.net.SocketTimeoutException} is raised. A timeout of zero is interpreted as an infinite timeout.
566     * @param readTimeout an {@code int} that specifies the read timeout value in milliseconds
567     * @return {@code this}
568     * @see HttpURLConnection#setReadTimeout(int)
569     */
570    public HttpClient setReadTimeout(int readTimeout) {
571        this.readTimeout = readTimeout;
572        return this;
573    }
574
575    /**
576     * Sets the {@code Accept} header.
577     * @param accept header value
578     *
579     * @return {@code this}
580     */
581    public HttpClient setAccept(String accept) {
582        return setHeader("Accept", accept);
583    }
584
585    /**
586     * Sets the request body for {@code PUT}/{@code POST} requests.
587     * @param requestBody request body
588     *
589     * @return {@code this}
590     */
591    public HttpClient setRequestBody(byte[] requestBody) {
592        this.requestBody = Utils.copyArray(requestBody);
593        return this;
594    }
595
596    /**
597     * Sets the {@code If-Modified-Since} header.
598     * @param ifModifiedSince header value
599     *
600     * @return {@code this}
601     */
602    public HttpClient setIfModifiedSince(long ifModifiedSince) {
603        this.ifModifiedSince = ifModifiedSince;
604        return this;
605    }
606
607    /**
608     * Sets the maximum number of redirections to follow.
609     *
610     * Set {@code maxRedirects} to {@code -1} in order to ignore redirects, i.e.,
611     * to not throw an {@link IOException} in {@link #connect()}.
612     * @param maxRedirects header value
613     *
614     * @return {@code this}
615     */
616    public HttpClient setMaxRedirects(int maxRedirects) {
617        this.maxRedirects = maxRedirects;
618        return this;
619    }
620
621    /**
622     * Sets an arbitrary HTTP header.
623     * @param key header name
624     * @param value header value
625     *
626     * @return {@code this}
627     */
628    public HttpClient setHeader(String key, String value) {
629        this.headers.put(key, value);
630        return this;
631    }
632
633    /**
634     * Sets arbitrary HTTP headers.
635     * @param headers HTTP headers
636     *
637     * @return {@code this}
638     */
639    public HttpClient setHeaders(Map<String, String> headers) {
640        this.headers.putAll(headers);
641        return this;
642    }
643
644    /**
645     * Sets a reason to show on console. Can be {@code null} if no reason is given.
646     * @param reasonForRequest Reason to show
647     * @return {@code this}
648     * @since 9172
649     */
650    public HttpClient setReasonForRequest(String reasonForRequest) {
651        this.reasonForRequest = reasonForRequest;
652        return this;
653    }
654
655    /**
656     * Sets the output message to be displayed in progress monitor for {@code PUT}, {@code POST} and {@code DELETE} methods.
657     * Defaults to "Uploading data ..." (translated). Has no effect for {@code GET} or any other method.
658     * @param outputMessage message to be displayed in progress monitor
659     * @return {@code this}
660     * @since 12711
661     */
662    public HttpClient setOutputMessage(String outputMessage) {
663        this.outputMessage = outputMessage;
664        return this;
665    }
666
667    /**
668     * Sets whether the progress monitor task will be finished when the output stream is closed. This is {@code true} by default.
669     * @param finishOnCloseOutput whether the progress monitor task will be finished when the output stream is closed
670     * @return {@code this}
671     * @since 10302
672     */
673    public HttpClient setFinishOnCloseOutput(boolean finishOnCloseOutput) {
674        this.finishOnCloseOutput = finishOnCloseOutput;
675        return this;
676    }
677
678    private static boolean isRedirect(final int statusCode) {
679        switch (statusCode) {
680            case HttpURLConnection.HTTP_MOVED_PERM: // 301
681            case HttpURLConnection.HTTP_MOVED_TEMP: // 302
682            case HttpURLConnection.HTTP_SEE_OTHER: // 303
683            case 307: // TEMPORARY_REDIRECT:
684            case 308: // PERMANENT_REDIRECT:
685                return true;
686            default:
687                return false;
688        }
689    }
690
691    /**
692     * @see HttpURLConnection#disconnect()
693     * @since 9309
694     */
695    public void disconnect() {
696        HttpClient.disconnect(connection);
697    }
698
699    private static void disconnect(final HttpURLConnection connection) {
700        if (connection != null) {
701            // Fix upload aborts - see #263
702            connection.setConnectTimeout(100);
703            connection.setReadTimeout(100);
704            try {
705                Thread.sleep(100);
706            } catch (InterruptedException ex) {
707                Logging.warn("InterruptedException in " + HttpClient.class + " during cancel");
708                Thread.currentThread().interrupt();
709            }
710            connection.disconnect();
711        }
712    }
713
714    /**
715     * Returns a {@link Matcher} against predefined Tomcat error messages.
716     * If it matches, error message can be extracted from {@code group(1)}.
717     * @param data HTML contents to check
718     * @return a {@link Matcher} against predefined Tomcat error messages
719     * @since 13358
720     */
721    public static Matcher getTomcatErrorMatcher(String data) {
722        return data != null ? TOMCAT_ERR_MESSAGE.matcher(data) : null;
723    }
724}