Changeset 9309 in josm for trunk/src/org


Ignore:
Timestamp:
2016-01-04T20:51:45+01:00 (4 years ago)
Author:
simon04
Message:

see #12292 - Allow to disconnect HttpClient in connecting phase

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

Legend:

Unmodified
Added
Removed
  • trunk/src/org/openstreetmap/josm/data/oauth/SignpostAdapters.java

    r9254 r9309  
    4040            if (response != null) {
    4141                ((HttpResponse) response).response.disconnect();
     42            } else if (request != null) {
     43                ((HttpRequest) request).request.disconnect();
    4244            }
    4345        }
  • trunk/src/org/openstreetmap/josm/gui/download/PlaceSelection.java

    r9171 r9309  
    325325
    326326        private final String searchExpression;
    327         private HttpClient.Response connection;
     327        private HttpClient connection;
    328328        private List<SearchResult> data;
    329329        private boolean canceled;
     
    368368                URL url = new URL(urlString);
    369369                synchronized (this) {
    370                     connection = HttpClient.create(url).connect();
    371                 }
    372                 try (Reader reader = connection.getContentReader()) {
     370                    connection = HttpClient.create(url);
     371                    connection.connect();
     372                }
     373                try (Reader reader = connection.getResponse().getContentReader()) {
    373374                    InputSource inputSource = new InputSource(reader);
    374375                    NameFinderResultParser parser = new NameFinderResultParser();
  • trunk/src/org/openstreetmap/josm/gui/io/DownloadFileTask.java

    r9296 r9309  
    6969
    7070    private boolean canceled;
    71     private HttpClient.Response downloadConnection;
     71    private HttpClient downloadConnection;
    7272
    7373    private synchronized void closeConnectionIfNeeded() {
     
    103103            long size;
    104104            synchronized (this) {
    105                 downloadConnection = HttpClient.create(url).useCache(false).connect();
    106                 size = downloadConnection.getContentLength();
     105                downloadConnection = HttpClient.create(url).useCache(false);
     106                downloadConnection.connect();
     107                size = downloadConnection.getResponse().getContentLength();
    107108            }
    108109
     
    111112
    112113            try (
    113                 InputStream in = downloadConnection.getContent();
     114                InputStream in = downloadConnection.getResponse().getContent();
    114115                OutputStream out = new FileOutputStream(file)
    115116            ) {
  • trunk/src/org/openstreetmap/josm/gui/oauth/OsmOAuthAuthorizationClient.java

    r9301 r9309  
    4444    private final OAuthProvider provider;
    4545    private boolean canceled;
    46     private HttpClient.Response connection;
     46    private HttpClient connection;
    4747
    4848    private static class SessionId {
     
    183183
    184184    protected String extractToken() {
    185         try (BufferedReader r = connection.getContentReader()) {
     185        try (BufferedReader r = connection.getResponse().getContentReader()) {
    186186            String c;
    187187            Pattern p = Pattern.compile(".*authenticity_token.*value=\"([^\"]+)\".*");
     
    200200
    201201    protected SessionId extractOsmSession() {
    202         List<String> setCookies = connection.getHeaderFields().get("Set-Cookie");
     202        List<String> setCookies = connection.getResponse().getHeaderFields().get("Set-Cookie");
    203203        if (setCookies == null)
    204204            // no cookies set
     
    293293            URL url = new URL(sb.toString());
    294294            synchronized (this) {
    295                 connection = HttpClient.create(url).connect();
     295                connection = HttpClient.create(url);
     296                connection.connect();
    296297            }
    297298            SessionId sessionId = extractOsmSession();
     
    322323            synchronized (this) {
    323324                connection = HttpClient.create(url)
    324                         .setHeader("Cookie", "_osm_session=" + sessionId.id + "; _osm_username=" + sessionId.userName)
    325                         .connect();
     325                        .setHeader("Cookie", "_osm_session=" + sessionId.id + "; _osm_username=" + sessionId.userName);
     326                connection.connect();
    326327            }
    327328            sessionId.token = extractToken();
     
    357358
    358359            synchronized (this) {
    359                 connection = client.connect();
     360                connection = client;
     361                connection.connect();
    360362            }
    361363
     
    364366            // an error page is sent to back to the user.
    365367            //
    366             int retCode = connection.getResponseCode();
     368            int retCode = connection.getResponse().getResponseCode();
    367369            if (retCode != HttpURLConnection.HTTP_MOVED_TEMP)
    368370                throw new OsmOAuthAuthorizationException(tr("Failed to authenticate user ''{0}'' with password ''***'' as OAuth user",
     
    383385            URL url = new URL(buildOsmLogoutUrl());
    384386            synchronized (this) {
    385                 connection = HttpClient.create(url).setMaxRedirects(-1).connect();
     387                connection = HttpClient.create(url).setMaxRedirects(-1);
     388                connection.connect();
    386389            }
    387390        } catch (IOException e) {
     
    432435
    433436            synchronized (this) {
    434                 connection = client.connect();
    435             }
    436 
    437             int retCode = connection.getResponseCode();
     437                connection = client;
     438                connection.connect();
     439            }
     440
     441            int retCode = connection.getResponse().getResponseCode();
    438442            if (retCode != HttpURLConnection.HTTP_OK)
    439443                throw new OsmOAuthAuthorizationException(tr("Failed to authorize OAuth request  ''{0}''", requestToken.getKey()));
  • trunk/src/org/openstreetmap/josm/gui/oauth/TestAccessTokenTask.java

    r9172 r9309  
    4646    private final Component parent;
    4747    private final String apiUrl;
    48     private HttpClient.Response connection;
     48    private HttpClient connection;
    4949
    5050    /**
     
    107107            sign(client);
    108108            synchronized (this) {
    109                 connection = client.connect();
     109                connection = client;
     110                connection.connect();
    110111            }
    111112
    112             if (connection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED)
     113            if (connection.getResponse().getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED)
    113114                throw new OsmApiException(HttpURLConnection.HTTP_UNAUTHORIZED,
    114115                        tr("Retrieving user details with Access Token Key ''{0}'' was rejected.", token.getKey()), null);
    115116
    116             if (connection.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN)
     117            if (connection.getResponse().getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN)
    117118                throw new OsmApiException(HttpURLConnection.HTTP_FORBIDDEN,
    118119                        tr("Retrieving user details with Access Token Key ''{0}'' was forbidden.", token.getKey()), null);
    119120
    120             if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
    121                 throw new OsmApiException(connection.getResponseCode(), connection.getHeaderField("Error"), null);
    122             Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(connection.getContent());
     121            if (connection.getResponse().getResponseCode() != HttpURLConnection.HTTP_OK)
     122                throw new OsmApiException(connection.getResponse().getResponseCode(),
     123                        connection.getResponse().getHeaderField("Error"), null);
     124            Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(connection.getResponse().getContent());
    123125            return OsmServerUserInfoReader.buildFromXML(d);
    124126        } catch (SAXException | ParserConfigurationException e) {
  • trunk/src/org/openstreetmap/josm/gui/preferences/server/ApiUrlTestTask.java

    r9172 r9309  
    3636    private boolean success;
    3737    private final Component parent;
    38     private HttpClient.Response connection;
     38    private HttpClient connection;
    3939
    4040    /**
     
    177177
    178178            synchronized (this) {
    179                 connection = HttpClient.create(capabilitiesUrl).connect();
    180             }
    181 
    182             if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
    183                 alertInvalidServerResult(connection.getResponseCode());
     179                connection = HttpClient.create(capabilitiesUrl);
     180                connection.connect();
     181            }
     182
     183            if (connection.getResponse().getResponseCode() != HttpURLConnection.HTTP_OK) {
     184                alertInvalidServerResult(connection.getResponse().getResponseCode());
    184185                return;
    185186            }
    186187
    187188            try {
    188                 Capabilities.CapabilitiesParser.parse(new InputSource(connection.getContent()));
     189                Capabilities.CapabilitiesParser.parse(new InputSource(connection.getResponse().getContent()));
    189190            } catch (SAXException | ParserConfigurationException e) {
    190191                Main.warn(e.getMessage());
  • trunk/src/org/openstreetmap/josm/io/OsmApi.java

    r9182 r9309  
    618618                url = new URL(new URL(getBaseUrl()), urlSuffix);
    619619                final HttpClient client = HttpClient.create(url, requestMethod).keepAlive(false);
     620                activeConnection = client;
    620621                if (fastFail) {
    621622                    client.setConnectTimeout(1000);
     
    640641                }
    641642
    642                 activeConnection = client.connect();
    643                 Main.info(activeConnection.getResponseMessage());
    644                 int retCode = activeConnection.getResponseCode();
     643                final HttpClient.Response response = client.connect();
     644                Main.info(response.getResponseMessage());
     645                int retCode = response.getResponseCode();
    645646
    646647                if (retCode >= 500) {
     
    652653                }
    653654
    654                 final String responseBody = activeConnection.fetchContent();
     655                final String responseBody = response.fetchContent();
    655656
    656657                String errorHeader = null;
    657658                // Look for a detailed error message from the server
    658                 if (activeConnection.getHeaderField("Error") != null) {
    659                     errorHeader = activeConnection.getHeaderField("Error");
     659                if (response.getHeaderField("Error") != null) {
     660                    errorHeader = response.getHeaderField("Error");
    660661                    Main.error("Error header: " + errorHeader);
    661662                } else if (retCode != HttpURLConnection.HTTP_OK && responseBody.length() > 0) {
  • trunk/src/org/openstreetmap/josm/io/OsmConnection.java

    r9172 r9309  
    3131public class OsmConnection {
    3232    protected boolean cancel;
    33     protected HttpClient.Response activeConnection;
     33    protected HttpClient activeConnection;
    3434    protected OAuthParameters oauthParameters;
    3535
  • trunk/src/org/openstreetmap/josm/io/OsmServerReader.java

    r9308 r9309  
    123123
    124124            final HttpClient client = HttpClient.create(url);
     125            activeConnection = client;
    125126            client.setReasonForRequest(reason);
    126127            adaptRequest(client);
     
    131132                throw new OsmTransferCanceledException("Operation canceled");
    132133
     134            final HttpClient.Response response;
    133135            try {
    134                 activeConnection = client.connect(progressMonitor);
     136                response = client.connect(progressMonitor);
    135137            } catch (Exception e) {
    136138                Main.error(e);
     
    141143            }
    142144            try {
    143                 if (activeConnection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED)
     145                if (response.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED)
    144146                    throw new OsmApiException(HttpURLConnection.HTTP_UNAUTHORIZED, null, null);
    145147
    146                 if (activeConnection.getResponseCode() == HttpURLConnection.HTTP_PROXY_AUTH)
     148                if (response.getResponseCode() == HttpURLConnection.HTTP_PROXY_AUTH)
    147149                    throw new OsmTransferCanceledException("Proxy Authentication Required");
    148150
    149                 if (activeConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
    150                     String errorHeader = activeConnection.getHeaderField("Error");
     151                if (response.getResponseCode() != HttpURLConnection.HTTP_OK) {
     152                    String errorHeader = response.getHeaderField("Error");
    151153                    String errorBody;
    152154                    try {
    153                         errorBody = activeConnection.fetchContent();
     155                        errorBody = response.fetchContent();
    154156                    } catch (Exception e) {
    155157                        errorBody = tr("Reading error text failed.");
    156158                    }
    157                     throw new OsmApiException(activeConnection.getResponseCode(), errorHeader, errorBody, url.toString());
     159                    throw new OsmApiException(response.getResponseCode(), errorHeader, errorBody, url.toString());
    158160                }
    159161
    160                 activeConnection.uncompressAccordingToContentDisposition(uncompressAccordingToContentDisposition);
    161                 return activeConnection.getContent();
     162                response.uncompressAccordingToContentDisposition(uncompressAccordingToContentDisposition);
     163                return response.getContent();
    162164            } catch (OsmTransferException e) {
    163165                throw e;
  • trunk/src/org/openstreetmap/josm/plugins/PluginDownloadTask.java

    r9280 r9309  
    4444    private final Collection<PluginInformation> downloaded = new LinkedList<>();
    4545    private boolean canceled;
    46     private HttpClient.Response downloadConnection;
     46    private HttpClient downloadConnection;
    4747
    4848    /**
     
    124124            synchronized (this) {
    125125                downloadConnection = HttpClient.create(url)
    126                         .setAccept(PLUGIN_MIME_TYPES)
    127                         .connect();
    128             }
    129             try (InputStream in = downloadConnection.getContent()) {
     126                        .setAccept(PLUGIN_MIME_TYPES);
     127                downloadConnection.connect();
     128            }
     129            try (InputStream in = downloadConnection.getResponse().getContent()) {
    130130                Files.copy(in, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
    131131            }
  • trunk/src/org/openstreetmap/josm/plugins/ReadRemotePluginInformationTask.java

    r9296 r9309  
    5151    private Collection<String> sites;
    5252    private boolean canceled;
    53     private HttpClient.Response connection;
     53    private HttpClient connection;
    5454    private List<PluginInformation> availablePlugins;
    5555    private boolean displayErrMsg;
     
    157157
    158158            URL url = new URL(site);
    159             connection = HttpClient.create(url).useCache(false).connect();
    160             content = connection.fetchContent();
    161             if (connection.getResponseCode() != 200) {
     159            connection = HttpClient.create(url).useCache(false);
     160            final HttpClient.Response response = connection.connect();
     161            content = response.fetchContent();
     162            if (response.getResponseCode() != 200) {
    162163                throw new IOException(tr("Unsuccessful HTTP request"));
    163164            }
  • trunk/src/org/openstreetmap/josm/tools/HttpClient.java

    r9274 r9309  
    4747    private boolean useCache;
    4848    private String reasonForRequest;
     49    private transient HttpURLConnection connection; // to allow disconnecting before `response` is set
     50    private transient Response response;
    4951
    5052    private HttpClient(URL url, String requestMethod) {
     
    7577        }
    7678        final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
     79        this.connection = connection;
    7780        connection.setRequestMethod(requestMethod);
    7881        connection.setRequestProperty("User-Agent", Version.getInstance().getFullAgentString());
     
    148151                }
    149152            }
    150             Response response = new Response(connection, progressMonitor);
     153            response = new Response(connection, progressMonitor);
    151154            successfulConnection = true;
    152155            return response;
     
    156159            }
    157160        }
     161    }
     162
     163    /**
     164     * Returns the HTTP response which is set only after calling {@link #connect()}.
     165     * Calling this method again, returns the identical object (unless another {@link #connect()} is performed).
     166     *
     167     * @return the HTTP response
     168     * @since 9309
     169     */
     170    public Response getResponse() {
     171        return response;
    158172    }
    159173
     
    381395         */
    382396        public void disconnect() {
    383             // TODO is this block necessary for disconnecting?
    384             // Fix upload aborts - see #263
    385             connection.setConnectTimeout(100);
    386             connection.setReadTimeout(100);
    387             try {
    388                 Thread.sleep(100);
    389             } catch (InterruptedException ex) {
    390                 Main.warn("InterruptedException in " + getClass().getSimpleName() + " during cancel");
    391             }
    392 
    393             connection.disconnect();
     397            HttpClient.disconnect(connection);
    394398        }
    395399    }
     
    611615        }
    612616    }
     617
     618    /**
     619     * @see HttpURLConnection#disconnect()
     620     * @since 9309
     621     */
     622    public void disconnect() {
     623        HttpClient.disconnect(connection);
     624    }
     625
     626    private static void disconnect(final HttpURLConnection connection) {
     627        // Fix upload aborts - see #263
     628        connection.setConnectTimeout(100);
     629        connection.setReadTimeout(100);
     630        try {
     631            Thread.sleep(100);
     632        } catch (InterruptedException ex) {
     633            Main.warn("InterruptedException in " + HttpClient.class + " during cancel");
     634        }
     635        connection.disconnect();
     636    }
    613637}
Note: See TracChangeset for help on using the changeset viewer.