Changeset 9171 in josm for trunk/src


Ignore:
Timestamp:
2015-12-26T23:42:00+01:00 (8 years ago)
Author:
simon04
Message:

see #12231 - Use HttpClient instead of some Utils.openHttpConnection usages

Location:
trunk/src/org/openstreetmap/josm
Files:
9 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/org/openstreetmap/josm/actions/downloadtasks/DownloadSessionTask.java

    r8921 r9171  
    1313import org.openstreetmap.josm.data.Bounds;
    1414import org.openstreetmap.josm.gui.progress.ProgressMonitor;
    15 import org.openstreetmap.josm.tools.Utils;
     15import org.openstreetmap.josm.tools.HttpClient;
    1616
    1717/**
     
    4545            try {
    4646                URL u = new URL(url);
    47                 loader = new Loader(Utils.openURL(u), u.toURI(), url.endsWith(".joz"));
     47                loader = new Loader(HttpClient.create(u).connect().getContent(), u.toURI(), url.endsWith(".joz"));
    4848                return Main.worker.submit(loader);
    4949            } catch (URISyntaxException | IOException e) {
  • trunk/src/org/openstreetmap/josm/data/imagery/CachedAttributionBingAerialTileSource.java

    r8836 r9171  
    66import java.net.URL;
    77import java.util.List;
    8 import java.util.Scanner;
    98import java.util.concurrent.Callable;
    109
     
    1413import org.openstreetmap.josm.gui.util.GuiHelper;
    1514import org.openstreetmap.josm.io.CacheCustomContent;
    16 import org.openstreetmap.josm.io.UTFInputStreamReader;
    17 import org.openstreetmap.josm.tools.Utils;
     15import org.openstreetmap.josm.tools.HttpClient;
    1816import org.xml.sax.InputSource;
    1917
     
    5553        protected byte[] updateData() throws IOException {
    5654            URL u = getAttributionUrl();
    57             try (Scanner scanner = new Scanner(UTFInputStreamReader.create(Utils.openURL(u)))) {
    58                 String r = scanner.useDelimiter("\\A").next();
    59                 Main.info("Successfully loaded Bing attribution data.");
    60                 return r.getBytes("UTF-8");
    61             }
     55            final String r = HttpClient.create(u).connect().fetchContent();
     56            Main.info("Successfully loaded Bing attribution data.");
     57            return r.getBytes("UTF-8");
    6258        }
    6359    }
  • trunk/src/org/openstreetmap/josm/gui/MainApplication.java

    r8870 r9171  
    6565import org.openstreetmap.josm.tools.BugReportExceptionHandler;
    6666import org.openstreetmap.josm.tools.FontsManager;
     67import org.openstreetmap.josm.tools.HttpClient;
    6768import org.openstreetmap.josm.tools.I18n;
    6869import org.openstreetmap.josm.tools.ImageProvider;
     
    392393            for (String i : args.get(Option.LOAD_PREFERENCES)) {
    393394                info("Reading preferences from " + i);
    394                 try (InputStream is = Utils.openURL(new URL(i))) {
     395                try (InputStream is = HttpClient.create(new URL(i)).connect().getContent()) {
    395396                    config.openAndReadXML(is);
    396397                } catch (Exception ex) {
  • trunk/src/org/openstreetmap/josm/gui/dialogs/properties/PropertiesDialog.java

    r9149 r9171  
    1616import java.beans.PropertyChangeEvent;
    1717import java.beans.PropertyChangeListener;
    18 import java.net.HttpURLConnection;
    1918import java.net.URI;
    2019import java.net.URISyntaxException;
     
    101100import org.openstreetmap.josm.tools.AlphanumComparator;
    102101import org.openstreetmap.josm.tools.GBC;
     102import org.openstreetmap.josm.tools.HttpClient;
    103103import org.openstreetmap.josm.tools.ImageProvider;
    104104import org.openstreetmap.josm.tools.InputMapUtils;
     
    11711171                        try {
    11721172                            // find a page that actually exists in the wiki
    1173                             HttpURLConnection conn;
     1173                            HttpClient.Response conn;
    11741174                            for (URI u : uris) {
    1175                                 conn = Utils.openHttpConnection(u.toURL());
    1176                                 conn.setConnectTimeout(Main.pref.getInteger("socket.timeout.connect", 15)*1000);
     1175                                conn = HttpClient.create(u.toURL(), "HEAD").connect();
    11771176
    11781177                                if (conn.getResponseCode() != 200) {
    1179                                     Main.info("{0} does not exist", u);
    11801178                                    conn.disconnect();
    11811179                                } else {
    1182                                     int osize = conn.getContentLength();
     1180                                    long osize = conn.getContentLength();
    11831181                                    if (osize > -1) {
    11841182                                        conn.disconnect();
    11851183
    1186                                         conn = Utils.openHttpConnection(new URI(u.toString()
     1184                                        final URI newURI = new URI(u.toString()
    11871185                                                .replace("=", "%3D") /* do not URLencode whole string! */
    11881186                                                .replaceFirst("/wiki/", "/w/index.php?redirect=no&title=")
    1189                                                 ).toURL());
    1190                                         conn.setConnectTimeout(Main.pref.getInteger("socket.timeout.connect", 15)*1000);
     1187                                        );
     1188                                        conn = HttpClient.create(newURI.toURL(), "HEAD").connect();
    11911189                                    }
    11921190
     
    11991197                                        conn.disconnect();
    12001198                                    } else {
    1201                                         Main.info("browsing to {0}", u);
    12021199                                        conn.disconnect();
    12031200
  • trunk/src/org/openstreetmap/josm/gui/download/PlaceSelection.java

    r9078 r9171  
    1313import java.awt.event.MouseEvent;
    1414import java.io.IOException;
    15 import java.io.InputStream;
    16 import java.io.InputStreamReader;
    1715import java.io.Reader;
    18 import java.net.HttpURLConnection;
    1916import java.net.URL;
    20 import java.nio.charset.StandardCharsets;
    2117import java.text.DecimalFormat;
    2218import java.util.ArrayList;
     
    5753import org.openstreetmap.josm.io.OsmTransferException;
    5854import org.openstreetmap.josm.tools.GBC;
     55import org.openstreetmap.josm.tools.HttpClient;
    5956import org.openstreetmap.josm.tools.ImageProvider;
    6057import org.openstreetmap.josm.tools.OsmUrlToBounds;
     
    328325
    329326        private final String searchExpression;
    330         private HttpURLConnection connection;
     327        private HttpClient.Response connection;
    331328        private List<SearchResult> data;
    332329        private boolean canceled;
     
    371368                URL url = new URL(urlString);
    372369                synchronized (this) {
    373                     connection = Utils.openHttpConnection(url);
    374                 }
    375                 connection.setConnectTimeout(Main.pref.getInteger("socket.timeout.connect", 15)*1000);
    376                 try (
    377                     InputStream inputStream = connection.getInputStream();
    378                     Reader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
    379                 ) {
     370                    connection = HttpClient.create(url).connect();
     371                }
     372                try (Reader reader = connection.getContentReader()) {
    380373                    InputSource inputSource = new InputSource(reader);
    381374                    NameFinderResultParser parser = new NameFinderResultParser();
  • trunk/src/org/openstreetmap/josm/gui/io/DownloadFileTask.java

    r9059 r9171  
    1111import java.io.InputStream;
    1212import java.io.OutputStream;
    13 import java.net.HttpURLConnection;
    1413import java.net.MalformedURLException;
    1514import java.net.URL;
     
    2221import org.openstreetmap.josm.gui.PleaseWaitDialog;
    2322import org.openstreetmap.josm.gui.PleaseWaitRunnable;
    24 import org.openstreetmap.josm.tools.Utils;
     23import org.openstreetmap.josm.tools.HttpClient;
    2524import org.xml.sax.SAXException;
    2625
     
    6867
    6968    private boolean canceled;
    70     private HttpURLConnection downloadConnection;
     69    private HttpClient.Response downloadConnection;
    7170
    7271    private synchronized void closeConnectionIfNeeded() {
     
    10099
    101100            URL url = new URL(address);
    102             int size;
     101            long size;
    103102            synchronized (this) {
    104                 downloadConnection = Utils.openHttpConnection(url);
    105                 downloadConnection.setRequestProperty("Cache-Control", "no-cache");
    106                 downloadConnection.connect();
     103                downloadConnection = HttpClient.create(url).useCache(false).connect();
    107104                size = downloadConnection.getContentLength();
    108105            }
     
    112109
    113110            try (
    114                 InputStream in = downloadConnection.getInputStream();
     111                InputStream in = downloadConnection.getContent();
    115112                OutputStream out = new FileOutputStream(file)
    116113            ) {
    117114                byte[] buffer = new byte[32768];
    118115                int count = 0;
    119                 int p1 = 0, p2 = 0;
     116                long p1 = 0, p2 = 0;
    120117                for (int read = in.read(buffer); read != -1; read = in.read(buffer)) {
    121118                    out.write(buffer, 0, read);
     
    124121                    p2 = 100 * count / size;
    125122                    if (p2 != p1) {
    126                         progressMonitor.setTicks(p2);
     123                        progressMonitor.setTicks((int) p2);
    127124                        p1 = p2;
    128125                    }
  • trunk/src/org/openstreetmap/josm/io/imagery/WMSImagery.java

    r9108 r9171  
    33
    44import java.awt.HeadlessException;
    5 import java.io.BufferedReader;
    65import java.io.IOException;
    7 import java.io.InputStream;
    86import java.io.StringReader;
    97import java.net.MalformedURLException;
    108import java.net.URL;
    11 import java.net.URLConnection;
    129import java.util.ArrayList;
    1310import java.util.Collection;
     
    2724import org.openstreetmap.josm.data.imagery.ImageryInfo;
    2825import org.openstreetmap.josm.data.projection.Projections;
    29 import org.openstreetmap.josm.io.UTFInputStreamReader;
     26import org.openstreetmap.josm.tools.HttpClient;
    3027import org.openstreetmap.josm.tools.Predicate;
    3128import org.openstreetmap.josm.tools.Utils;
     
    137134
    138135        Main.info("GET " + getCapabilitiesUrl);
    139         URLConnection openConnection = Utils.openHttpConnection(getCapabilitiesUrl, false, true);
    140         StringBuilder ba = new StringBuilder();
    141 
    142         try (
    143             InputStream inputStream = openConnection.getInputStream();
    144             BufferedReader br = new BufferedReader(UTFInputStreamReader.create(inputStream))
    145         ) {
    146             String line;
    147             while ((line = br.readLine()) != null) {
    148                 ba.append(line);
    149                 ba.append('\n');
    150             }
    151         }
    152         String incomingData = ba.toString();
     136        final String incomingData = HttpClient.create(getCapabilitiesUrl).connect().fetchContent();
    153137        Main.debug("Server response to Capabilities request:");
    154138        Main.debug(incomingData);
  • trunk/src/org/openstreetmap/josm/plugins/ReadRemotePluginInformationTask.java

    r9062 r9171  
    66import java.awt.Dimension;
    77import java.awt.GridBagLayout;
    8 import java.io.BufferedReader;
    98import java.io.ByteArrayInputStream;
    109import java.io.File;
     
    1312import java.io.IOException;
    1413import java.io.InputStream;
    15 import java.io.InputStreamReader;
    1614import java.io.OutputStreamWriter;
    1715import java.io.PrintWriter;
    18 import java.net.HttpURLConnection;
    1916import java.net.MalformedURLException;
    2017import java.net.URL;
     
    4239import org.openstreetmap.josm.io.OsmTransferException;
    4340import org.openstreetmap.josm.tools.GBC;
     41import org.openstreetmap.josm.tools.HttpClient;
    4442import org.openstreetmap.josm.tools.Utils;
    4543import org.xml.sax.SAXException;
     
    5351    private Collection<String> sites;
    5452    private boolean canceled;
    55     private HttpURLConnection connection;
     53    private HttpClient.Response connection;
    5654    private List<PluginInformation> availablePlugins;
    5755    private boolean displayErrMsg;
     
    153151        }
    154152
     153        String content = null;
    155154        try {
    156155            monitor.beginTask("");
     
    158157
    159158            URL url = new URL(site);
    160             synchronized (this) {
    161                 connection = Utils.openHttpConnection(url);
    162                 connection.setRequestProperty("Cache-Control", "no-cache");
    163                 connection.setRequestProperty("Accept-Charset", "utf-8");
    164             }
    165             try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
    166                 StringBuilder sb = new StringBuilder();
    167                 String line;
    168                 while ((line = in.readLine()) != null) {
    169                     sb.append(line).append('\n');
    170                 }
    171                 return sb.toString();
    172             }
     159            connection = HttpClient.create(url).useCache(false).connect();
     160            content = connection.fetchContent();
     161            if (connection.getResponseCode() != 200) {
     162                throw new IOException(tr("Unsuccessful HTTP request"));
     163            }
     164            return content;
    173165        } catch (MalformedURLException e) {
    174166            if (canceled) return null;
     
    177169        } catch (IOException e) {
    178170            if (canceled) return null;
    179             Main.addNetworkError(site, e);
    180             handleIOException(monitor, e, tr("Plugin list download error"), tr("JOSM failed to download plugin list:"), displayErrMsg);
     171            handleIOException(monitor, e, content);
    181172            return null;
    182173        } finally {
     
    191182    }
    192183
    193     private void handleIOException(final ProgressMonitor monitor, IOException e, final String title, final String firstMessage,
    194             boolean displayMsg) {
    195         StringBuilder sb = new StringBuilder();
    196         try (InputStream errStream = connection.getErrorStream()) {
    197             if (errStream != null) {
    198                 try (BufferedReader err = new BufferedReader(new InputStreamReader(errStream, StandardCharsets.UTF_8))) {
    199                     String line;
    200                     while ((line = err.readLine()) != null) {
    201                         sb.append(line).append('\n');
    202                     }
    203                 } catch (Exception ex) {
    204                     Main.error(e);
    205                     Main.error(ex);
    206                 }
    207             }
    208         } catch (IOException ex) {
    209             Main.warn(ex);
    210         }
     184    private void handleIOException(final ProgressMonitor monitor, IOException e, String details) {
    211185        final String msg = e.getMessage();
    212         final String details = sb.toString();
    213186        if (details.isEmpty()) {
    214187            Main.error(e.getClass().getSimpleName()+": " + msg);
     
    217190        }
    218191
    219         if (displayMsg) {
    220             displayErrorMessage(monitor, msg, details, title, firstMessage);
     192        if (displayErrMsg) {
     193            displayErrorMessage(monitor, msg, details, tr("Plugin list download error"), tr("JOSM failed to download plugin list:"));
    221194        }
    222195    }
  • trunk/src/org/openstreetmap/josm/tools/HttpClient.java

    r9169 r9171  
    88import java.io.IOException;
    99import java.io.InputStream;
    10 import java.io.InputStreamReader;
    1110import java.io.OutputStream;
    1211import java.net.HttpURLConnection;
    1312import java.net.URL;
    14 import java.nio.charset.StandardCharsets;
    1513import java.util.Map;
     14import java.util.Scanner;
    1615import java.util.concurrent.ConcurrentHashMap;
    1716import java.util.zip.GZIPInputStream;
     
    2019import org.openstreetmap.josm.data.Version;
    2120import org.openstreetmap.josm.io.Compression;
     21import org.openstreetmap.josm.io.UTFInputStreamReader;
    2222
    2323/**
     
    3838    private final Map<String, String> headers = new ConcurrentHashMap<>();
    3939    private int maxRedirects = Main.pref.getInteger("socket.maxredirects", 5);
     40    private boolean useCache;
     41    private boolean keepAlive;
    4042
    4143    private HttpClient(URL url, String requestMethod) {
     
    7072            connection.setIfModifiedSince(ifModifiedSince);
    7173        }
     74        connection.setUseCaches(useCache);
     75        if (!useCache) {
     76            connection.setRequestProperty("Cache-Control", "no-cache");
     77        }
     78        if (!keepAlive) {
     79            connection.setRequestProperty("Connection", "close");
     80        }
    7281        for (Map.Entry<String, String> header : headers.entrySet()) {
    7382            connection.setRequestProperty(header.getKey(), header.getValue());
     
    7887            try {
    7988                connection.connect();
     89                Main.info("{0} {1} => {2}", requestMethod, url, connection.getResponseCode());
    8090            } catch (IOException e) {
    8191                //noinspection ThrowableResultOfMethodCallIgnored
     
    157167
    158168        /**
    159          * Returns {@link #getContent()} wrapped in a buffered reader
     169         * Returns {@link #getContent()} wrapped in a buffered reader.
     170         *
     171         * Detects Unicode charset in use utilizing {@link UTFInputStreamReader}.
    160172         */
    161173        public BufferedReader getContentReader() throws IOException {
    162             return new BufferedReader(new InputStreamReader(getContent(), StandardCharsets.UTF_8));
     174            return new BufferedReader(
     175                    UTFInputStreamReader.create(getContent())
     176            );
     177        }
     178
     179        /**
     180         * Fetches the HTTP response as String.
     181         * @return the response
     182         * @throws IOException
     183         */
     184        public String fetchContent() throws IOException {
     185            try (Scanner scanner = new Scanner(getContentReader())) {
     186                return scanner.useDelimiter("\\A").next();
     187            }
    163188        }
    164189
     
    187212
    188213        /**
     214         * Returns the {@code Content-Length} header.
     215         */
     216        public long getContentLength() {
     217            return connection.getContentLengthLong();
     218        }
     219
     220        /**
    189221         * @see HttpURLConnection#disconnect()
    190222         */
     
    213245    public static HttpClient create(URL url, String requestMethod) {
    214246        return new HttpClient(url, requestMethod);
     247    }
     248
     249    /**
     250     * Sets whether not to set header {@code Cache-Control=no-cache}
     251     *
     252     * @param useCache whether not to set header {@code Cache-Control=no-cache}
     253     * @return {@code this}
     254     * @see HttpURLConnection#setUseCaches(boolean)
     255     */
     256    public HttpClient useCache(boolean useCache) {
     257        this.useCache = useCache;
     258        return this;
     259    }
     260
     261    /**
     262     * Sets whether not to set header {@code Connection=close}
     263     * <p/>
     264     * This might fix #7640, see <a href='https://web.archive.org/web/20140118201501/http://www.tikalk.com/java/forums/httpurlconnection-disable-keep-alive'>here</a>.
     265     *
     266     * @param keepAlive whether not to set header {@code Connection=close}
     267     * @return {@code this}
     268     */
     269    public HttpClient keepAlive(boolean keepAlive) {
     270        this.keepAlive = keepAlive;
     271        return this;
    215272    }
    216273
Note: See TracChangeset for help on using the changeset viewer.