Changeset 5587 in josm


Ignore:
Timestamp:
2012-11-18T00:44:10+01:00 (9 years ago)
Author:
Don-vip
Message:

Single entry point in Utils to open HTTP connections

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

Legend:

Unmodified
Added
Removed
  • trunk/src/org/openstreetmap/josm/gui/dialogs/properties/PropertiesDialog.java

    r5520 r5587  
    14121412                            HttpURLConnection conn;
    14131413                            for (URI u : uris) {
    1414                                 conn = (HttpURLConnection) u.toURL().openConnection();
     1414                                conn = Utils.openHttpConnection(u.toURL());
    14151415                                conn.setConnectTimeout(Main.pref.getInteger("socket.timeout.connect",15)*1000);
    14161416
     
    14221422                                    conn.disconnect();
    14231423
    1424                                     conn = (HttpURLConnection) new URI(u.toString()
     1424                                    conn = Utils.openHttpConnection(new URI(u.toString()
    14251425                                            .replace("=", "%3D") /* do not URLencode whole string! */
    14261426                                            .replaceFirst("/wiki/", "/w/index.php?redirect=no&title=")
    1427                                             ).toURL().openConnection();
     1427                                            ).toURL());
    14281428                                    conn.setConnectTimeout(Main.pref.getInteger("socket.timeout.connect",15)*1000);
    14291429
  • trunk/src/org/openstreetmap/josm/gui/download/PlaceSelection.java

    r5429 r5587  
    5656import org.openstreetmap.josm.tools.ImageProvider;
    5757import org.openstreetmap.josm.tools.OsmUrlToBounds;
     58import org.openstreetmap.josm.tools.Utils;
    5859import org.xml.sax.Attributes;
    5960import org.xml.sax.InputSource;
     
    362363                URL url = new URL(urlString);
    363364                synchronized(this) {
    364                     connection = (HttpURLConnection)url.openConnection();
     365                    connection = Utils.openHttpConnection(url);
    365366                }
    366367                connection.setConnectTimeout(Main.pref.getInteger("socket.timeout.connect",15)*1000);
  • trunk/src/org/openstreetmap/josm/gui/help/HelpContentReader.java

    r5266 r5587  
    99import java.net.URL;
    1010
     11import org.openstreetmap.josm.tools.Utils;
    1112import org.openstreetmap.josm.tools.WikiReader;
    1213
     
    4647     */
    4748    public String fetchHelpTopicContent(String helpTopicUrl, boolean dotest) throws HelpContentReaderException {
    48         URL url = null;
    4949        HttpURLConnection con = null;
    5050        BufferedReader in = null;
    5151        try {
    52             url = new URL(helpTopicUrl);
    53             con = (HttpURLConnection)url.openConnection();
     52            con = Utils.openHttpConnection(new URL(helpTopicUrl));
    5453            con.connect();
    5554            in = new BufferedReader(new InputStreamReader(con.getInputStream(),"utf-8"));
  • trunk/src/org/openstreetmap/josm/gui/io/DownloadFileTask.java

    r5266 r5587  
     1// License: GPL. For details, see LICENSE file.
    12package org.openstreetmap.josm.gui.io;
    2 
    3 
    4 
    5 // License: GPL. For details, see LICENSE file.
    63
    74import static org.openstreetmap.josm.tools.I18n.tr;
     
    1714import java.net.MalformedURLException;
    1815import java.net.URL;
    19 
    20 import java.net.URLConnection;
    2116import java.util.Enumeration;
    22 
    2317import java.util.zip.ZipEntry;
    2418import java.util.zip.ZipFile;
    25 import org.openstreetmap.josm.data.Version;
     19
    2620import org.openstreetmap.josm.gui.PleaseWaitDialog;
    2721import org.openstreetmap.josm.gui.PleaseWaitRunnable;
     
    3125
    3226/**
    33  * Asynchronous task for downloading andnd unpacking arbitrary file lists
    34  * Shows progress bar when donloading
     27 * Asynchronous task for downloading and unpacking arbitrary file lists
     28 * Shows progress bar when downloading
    3529 */
    3630public class DownloadFileTask extends PleaseWaitRunnable{
     
    6357
    6458    private boolean canceled;
    65     private URLConnection downloadConnection;
     59    private HttpURLConnection downloadConnection;
    6660
    6761    private synchronized void closeConnectionIfNeeded() {
    68         if (downloadConnection != null && downloadConnection instanceof HttpURLConnection) {
    69             HttpURLConnection conn = ((HttpURLConnection) downloadConnection);
    70             conn.disconnect();
     62        if (downloadConnection != null) {
     63            downloadConnection.disconnect();
    7164        }
    7265        downloadConnection = null;
     
    9790            int size;
    9891            synchronized(this) {
    99                 downloadConnection = url.openConnection();
     92                downloadConnection = Utils.openHttpConnection(url);
    10093                downloadConnection.setRequestProperty("Cache-Control", "no-cache");
    101                 downloadConnection.setRequestProperty("User-Agent",Version.getInstance().getAgentString());
    102                 downloadConnection.setRequestProperty("Host", url.getHost());
    10394                downloadConnection.connect();
    10495                size = downloadConnection.getContentLength();
     
    176167        try {
    177168            zf = new ZipFile(file);
    178             Enumeration es = zf.entries();
     169            Enumeration<?> es = zf.entries();
    179170            ZipEntry ze;
    180171            while (es.hasMoreElements()) {
  • trunk/src/org/openstreetmap/josm/gui/oauth/OsmOAuthAuthorizationClient.java

    r5422 r5587  
    3030
    3131import org.openstreetmap.josm.Main;
    32 import org.openstreetmap.josm.data.Version;
    3332import org.openstreetmap.josm.data.oauth.OAuthParameters;
    3433import org.openstreetmap.josm.data.oauth.OAuthToken;
     
    3837import org.openstreetmap.josm.io.OsmTransferCanceledException;
    3938import org.openstreetmap.josm.tools.CheckParameterUtil;
     39import org.openstreetmap.josm.tools.Utils;
    4040
    4141/**
     
    325325            URL url = new URL(sb.toString());
    326326            synchronized(this) {
    327                 connection = (HttpURLConnection)url.openConnection();
     327                connection = Utils.openHttpConnection(url);
    328328            }
    329329            connection.setRequestMethod("GET");
    330330            connection.setDoInput(true);
    331331            connection.setDoOutput(false);
    332             setHttpRequestParameters(connection);
    333332            connection.connect();
    334333            SessionId sessionId = extractOsmSession(connection);
     
    355354            URL url = new URL(getAuthoriseUrl(requestToken));
    356355            synchronized(this) {
    357                 connection = (HttpURLConnection)url.openConnection();
     356                connection = Utils.openHttpConnection(url);
    358357            }
    359358            connection.setRequestMethod("GET");
     
    361360            connection.setDoOutput(false);
    362361            connection.setRequestProperty("Cookie", "_osm_session=" + sessionId.id + "; _osm_username=" + sessionId.userName);
    363             setHttpRequestParameters(connection);
    364362            connection.connect();
    365363            sessionId.token = extractToken(connection);
     
    380378            URL url = new URL(buildOsmLoginUrl());
    381379            synchronized(this) {
    382                 connection = (HttpURLConnection)url.openConnection();
     380                connection = Utils.openHttpConnection(url);
    383381            }
    384382            connection.setRequestMethod("POST");
     
    401399            // make sure we can catch 302 Moved Temporarily below
    402400            connection.setInstanceFollowRedirects(false);
    403             setHttpRequestParameters(connection);
    404401
    405402            connection.connect();
     
    437434            URL url = new URL(buildOsmLogoutUrl());
    438435            synchronized(this) {
    439                 connection = (HttpURLConnection)url.openConnection();
     436                connection = Utils.openHttpConnection(url);
    440437            }
    441438            connection.setRequestMethod("GET");
    442439            connection.setDoInput(true);
    443440            connection.setDoOutput(false);
    444             setHttpRequestParameters(connection);
    445441            connection.connect();
    446         }catch(MalformedURLException e) {
     442        } catch(MalformedURLException e) {
    447443            throw new OsmOAuthAuthorizationException(e);
    448444        } catch(IOException e) {
     
    484480            URL url = new URL(oauthProviderParameters.getAuthoriseUrl());
    485481            synchronized(this) {
    486                 connection = (HttpURLConnection)url.openConnection();
     482                connection = Utils.openHttpConnection(url);
    487483            }
    488484            connection.setRequestMethod("POST");
     
    494490            connection.setRequestProperty("Cookie", "_osm_session=" + sessionId.id + "; _osm_username=" + sessionId.userName);
    495491            connection.setInstanceFollowRedirects(false);
    496             setHttpRequestParameters(connection);
    497492
    498493            connection.connect();
     
    520515            }
    521516        }
    522     }
    523 
    524     protected void setHttpRequestParameters(HttpURLConnection connection) {
    525         connection.setRequestProperty("User-Agent", Version.getInstance().getAgentString());
    526         connection.setRequestProperty("Host", connection.getURL().getHost());
    527517    }
    528518
  • trunk/src/org/openstreetmap/josm/gui/oauth/TestAccessTokenTask.java

    r5411 r5587  
    1717import oauth.signpost.exception.OAuthException;
    1818
    19 import org.openstreetmap.josm.data.Version;
    2019import org.openstreetmap.josm.data.oauth.OAuthParameters;
    2120import org.openstreetmap.josm.data.oauth.OAuthToken;
     
    3029import org.openstreetmap.josm.io.auth.DefaultAuthenticator;
    3130import org.openstreetmap.josm.tools.CheckParameterUtil;
     31import org.openstreetmap.josm.tools.Utils;
    3232import org.w3c.dom.Document;
    3333import org.xml.sax.SAXException;
     
    104104            DefaultAuthenticator.getInstance().setEnabled(false);
    105105            synchronized(this) {
    106                 connection = (HttpURLConnection)url.openConnection();
     106                connection = Utils.openHttpConnection(url);
    107107            }
    108108
    109109            connection.setDoOutput(true);
    110110            connection.setRequestMethod("GET");
    111             connection.setRequestProperty("User-Agent", Version.getInstance().getAgentString());
    112             connection.setRequestProperty("Host", connection.getURL().getHost());
    113111            sign(connection);
    114112            connection.connect();
  • trunk/src/org/openstreetmap/josm/gui/preferences/imagery/AddWMSLayerPanel.java

    r5461 r5587  
    6060import org.openstreetmap.josm.io.UTFInputStreamReader;
    6161import org.openstreetmap.josm.tools.GBC;
     62import org.openstreetmap.josm.tools.Utils;
    6263import org.w3c.dom.Document;
    6364import org.w3c.dom.Element;
     
    342343        try {
    343344            System.out.println("GET "+getCapabilitiesUrl.toString());
    344             URLConnection openConnection = getCapabilitiesUrl.openConnection();
     345            URLConnection openConnection = Utils.openHttpConnection(getCapabilitiesUrl);
    345346            InputStream inputStream = openConnection.getInputStream();
    346347            BufferedReader br = new BufferedReader(UTFInputStreamReader.create(inputStream, "UTF-8"));
  • trunk/src/org/openstreetmap/josm/gui/preferences/server/ApiUrlTestTask.java

    r5266 r5587  
    2020import org.openstreetmap.josm.io.OsmTransferException;
    2121import org.openstreetmap.josm.tools.CheckParameterUtil;
     22import org.openstreetmap.josm.tools.Utils;
    2223import org.xml.sax.SAXException;
    2324
     
    182183
    183184            synchronized(this) {
    184                 connection = (HttpURLConnection)capabilitiesUrl.openConnection();
     185                connection = Utils.openHttpConnection(capabilitiesUrl);
    185186            }
    186187            connection.setDoInput(true);
    187188            connection.setDoOutput(false);
    188189            connection.setRequestMethod("GET");
    189             connection.setRequestProperty("User-Agent", Version.getInstance().getAgentString());
    190             connection.setRequestProperty("Host", connection.getURL().getHost());
    191190            connection.connect();
    192191
  • trunk/src/org/openstreetmap/josm/io/MirroredInputStream.java

    r4812 r5587  
    269269        int numRedirects = 0;
    270270        while(true) {
    271             con = (HttpURLConnection)downloadUrl.openConnection();
     271            con = Utils.openHttpConnection(downloadUrl);
    272272            con.setInstanceFollowRedirects(false);
    273273            con.setConnectTimeout(Main.pref.getInteger("socket.timeout.connect",15)*1000);
  • trunk/src/org/openstreetmap/josm/io/OsmApi.java

    r5422 r5587  
    3636import org.openstreetmap.josm.gui.progress.ProgressMonitor;
    3737import org.openstreetmap.josm.tools.CheckParameterUtil;
     38import org.openstreetmap.josm.tools.Utils;
    3839import org.xml.sax.Attributes;
    3940import org.xml.sax.InputSource;
     
    585586                URL url = new URL(new URL(getBaseUrl()), urlSuffix);
    586587                System.out.print(requestMethod + " " + url + "... ");
    587                 activeConnection = (HttpURLConnection)url.openConnection();
    588588                // fix #5369, see http://www.tikalk.com/java/forums/httpurlconnection-disable-keep-alive
    589                 activeConnection.setRequestProperty("Connection", "close");
     589                activeConnection = Utils.openHttpConnection(url, false);
    590590                activeConnection.setConnectTimeout(fastFail ? 1000 : Main.pref.getInteger("socket.timeout.connect",15)*1000);
    591591                if (fastFail) {
  • trunk/src/org/openstreetmap/josm/io/OsmServerReader.java

    r5584 r5587  
    1919import org.openstreetmap.josm.data.osm.DataSet;
    2020import org.openstreetmap.josm.gui.progress.ProgressMonitor;
     21import org.openstreetmap.josm.tools.Utils;
    2122
    2223/**
     
    6465            }
    6566            try {
    66                 activeConnection = (HttpURLConnection)url.openConnection();
    6767                // fix #7640, see http://www.tikalk.com/java/forums/httpurlconnection-disable-keep-alive
    68                 activeConnection.setRequestProperty("Connection", "close");
     68                activeConnection = Utils.openHttpConnection(url, false);
    6969            } catch(Exception e) {
    7070                throw new OsmTransferException(tr("Failed to open connection to API {0}.", url.toExternalForm()), e);
  • trunk/src/org/openstreetmap/josm/io/imagery/OsmosnimkiOffsetServer.java

    r4869 r5587  
    1414import org.openstreetmap.josm.data.imagery.ImageryInfo;
    1515import org.openstreetmap.josm.data.preferences.StringProperty;
     16import org.openstreetmap.josm.tools.Utils;
    1617
    1718public class OsmosnimkiOffsetServer implements OffsetServer {
     
    2829            URL url = new URL(this.url + "action=CheckAvailability&id=" + URLEncoder.encode(info.getUrl(), "UTF-8"));
    2930            System.out.println(tr("Querying offset availability: {0}", url));
    30             final BufferedReader rdr = new BufferedReader(new InputStreamReader(url.openConnection().getInputStream(), "UTF-8"));
     31            final BufferedReader rdr = new BufferedReader(new InputStreamReader(Utils.openHttpConnection(url).getInputStream(), "UTF-8"));
    3132            String response = rdr.readLine();
    3233            System.out.println(tr("Offset server response: {0}", response));
     
    4647            URL url = new URL(this.url + "action=GetOffsetForPoint&lat=" + ll.lat() + "&lon=" + ll.lon() + "&id=" + URLEncoder.encode(info.getUrl(), "UTF-8"));
    4748            System.out.println(tr("Querying offset: {0}", url.toString()));
    48             final BufferedReader rdr = new BufferedReader(new InputStreamReader(url.openConnection().getInputStream(), "UTF-8"));
     49            final BufferedReader rdr = new BufferedReader(new InputStreamReader(Utils.openHttpConnection(url).getInputStream(), "UTF-8"));
    4950            String s = rdr.readLine();
    5051            if (s == null)
  • trunk/src/org/openstreetmap/josm/io/imagery/WMSGrabber.java

    r5017 r5587  
    162162        System.out.println("Grabbing WMS " + (attempt > 1? "(attempt " + attempt + ") ":"") + url);
    163163
    164         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
     164        HttpURLConnection conn = Utils.openHttpConnection(url);
    165165        for(Entry<String, String> e : props.entrySet()) {
    166166            conn.setRequestProperty(e.getKey(), e.getValue());
  • trunk/src/org/openstreetmap/josm/plugins/PluginDownloadTask.java

    r5266 r5587  
    119119            URL url = new URL(pi.downloadlink);
    120120            synchronized(this) {
    121                 downloadConnection = (HttpURLConnection)url.openConnection();
     121                downloadConnection = Utils.openHttpConnection(url);
    122122                downloadConnection.setRequestProperty("Cache-Control", "no-cache");
    123                 downloadConnection.setRequestProperty("User-Agent",Version.getInstance().getAgentString());
    124                 downloadConnection.setRequestProperty("Host", url.getHost());
    125123                downloadConnection.connect();
    126124            }
  • trunk/src/org/openstreetmap/josm/plugins/ReadRemotePluginInformationTask.java

    r5266 r5587  
    162162            URL url = new URL(site);
    163163            synchronized(this) {
    164                 connection = (HttpURLConnection)url.openConnection();
     164                connection = Utils.openHttpConnection(url);
    165165                connection.setRequestProperty("Cache-Control", "no-cache");
    166                 connection.setRequestProperty("User-Agent",Version.getInstance().getAgentString());
    167                 connection.setRequestProperty("Host", url.getHost());
    168166                connection.setRequestProperty("Accept-Charset", "utf-8");
    169167            }
     
    211209            URL url = new URL(site);
    212210            synchronized(this) {
    213                 connection = (HttpURLConnection)url.openConnection();
     211                connection = Utils.openHttpConnection(url);
    214212                connection.setRequestProperty("Cache-Control", "no-cache");
    215                 connection.setRequestProperty("User-Agent",Version.getInstance().getAgentString());
    216                 connection.setRequestProperty("Host", url.getHost());
    217213            }
    218214            in = connection.getInputStream();
  • trunk/src/org/openstreetmap/josm/tools/Utils.java

    r5578 r5587  
    1616import java.io.Reader;
    1717import java.io.UnsupportedEncodingException;
     18import java.net.HttpURLConnection;
     19import java.net.URL;
    1820import java.security.MessageDigest;
    1921import java.security.NoSuchAlgorithmException;
     
    2527import java.util.Iterator;
    2628import java.util.List;
     29
     30import org.openstreetmap.josm.data.Version;
    2731
    2832/**
     
    533537        return new Color(Integer.parseInt(clr, 16));
    534538    }
    535 
     539   
     540    /**
     541     * Opens a HTTP connection to the given URL and sets the User-Agent property to JOSM's one.
     542     * @param httpURL The HTTP url to open (must use http:// or https://)
     543     * @return An open HTTP connection to the given URL
     544     * @throws IOException if an I/O exception occurs.
     545     * @since 5587
     546     */
     547    public static HttpURLConnection openHttpConnection(URL httpURL) throws IOException {
     548        if (httpURL == null || !httpURL.getProtocol().matches("https?")) {
     549            throw new IllegalArgumentException("Invalid HTTP url");
     550        }
     551        HttpURLConnection connection = (HttpURLConnection) httpURL.openConnection();
     552        connection.setRequestProperty("User-Agent", Version.getInstance().getAgentString());
     553        return connection;
     554    }
     555   
     556    /**
     557     * Opens a HTTP connection to the given URL, sets the User-Agent property to JOSM's one and optionnaly disables Keep-Alive.
     558     * @param httpURL The HTTP url to open (must use http:// or https://)
     559     * @param keepAlive
     560     * @return An open HTTP connection to the given URL
     561     * @throws IOException if an I/O exception occurs.
     562     * @since 5587
     563     */
     564    public static HttpURLConnection openHttpConnection(URL httpURL, boolean keepAlive) throws IOException {
     565        HttpURLConnection connection = openHttpConnection(httpURL);
     566        if (!keepAlive) {
     567            connection.setRequestProperty("Connection", "close");
     568        }
     569        return connection;
     570    }
    536571}
Note: See TracChangeset for help on using the changeset viewer.