001    /*
002     * Sonar, open source software quality management tool.
003     * Copyright (C) 2009 SonarSource SA
004     * mailto:contact AT sonarsource DOT com
005     *
006     * Sonar is free software; you can redistribute it and/or
007     * modify it under the terms of the GNU Lesser General Public
008     * License as published by the Free Software Foundation; either
009     * version 3 of the License, or (at your option) any later version.
010     *
011     * Sonar is distributed in the hope that it will be useful,
012     * but WITHOUT ANY WARRANTY; without even the implied warranty of
013     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
014     * Lesser General Public License for more details.
015     *
016     * You should have received a copy of the GNU Lesser General Public
017     * License along with Sonar; if not, write to the Free Software
018     * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02
019     */
020    package org.sonar.wsclient.connectors;
021    
022    import org.apache.commons.httpclient.*;
023    import org.apache.commons.httpclient.auth.AuthScope;
024    import org.apache.commons.httpclient.methods.GetMethod;
025    import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
026    import org.apache.commons.httpclient.util.URIUtil;
027    import org.sonar.wsclient.Host;
028    import org.sonar.wsclient.services.Query;
029    
030    import java.io.BufferedReader;
031    import java.io.IOException;
032    import java.io.InputStream;
033    import java.io.InputStreamReader;
034    
035    public class HttpClient3Connector implements Connector {
036    
037      private static final int TIMEOUT_MS = 30000;
038      private static final int MAX_TOTAL_CONNECTIONS = 40;
039      private static final int MAX_HOST_CONNECTIONS = 4;
040    
041      private final Host server;
042      private HttpClient httpClient;
043    
044      public HttpClient3Connector(final Host server) {
045        this.server = server;
046        createClient();
047      }
048    
049      public HttpClient3Connector(Host server, HttpClient httpClient) {
050        this.httpClient = httpClient;
051        this.server = server;
052      }
053    
054      private void createClient() {
055        final HttpConnectionManagerParams params = new HttpConnectionManagerParams();
056        params.setConnectionTimeout(TIMEOUT_MS);
057        params.setDefaultMaxConnectionsPerHost(MAX_HOST_CONNECTIONS);
058        params.setMaxTotalConnections(MAX_TOTAL_CONNECTIONS);
059        final MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
060        connectionManager.setParams(params);
061        this.httpClient = new HttpClient(connectionManager);
062        configureCredentials();
063      }
064    
065      private void configureCredentials() {
066        if (server.getUsername() != null) {
067          httpClient.getParams().setAuthenticationPreemptive(true);
068          Credentials defaultcreds = new UsernamePasswordCredentials(server.getUsername(), server.getPassword());
069          httpClient.getState().setCredentials(AuthScope.ANY, defaultcreds);
070        }
071      }
072    
073      public String execute(Query query) {
074        GetMethod method = null;
075        String url = null;
076        String json = null;
077        try {
078          url = server.getHost() + URIUtil.encodeQuery(query.getUrl());
079          method = new GetMethod(url);
080          method.setRequestHeader("Accept", "application/json");
081          httpClient.executeMethod(method);
082          if (method.getStatusCode() == HttpStatus.SC_OK) {
083            json = getResponseBodyAsString(method);
084    
085          } else if (method.getStatusCode() != HttpStatus.SC_NOT_FOUND) {
086            throw new ConnectionException("HTTP error: " + method.getStatusCode() + ", msg: " + method.getStatusText() + ", query: " + url);
087          }
088    
089        } catch (HttpException e) {
090          throw new ConnectionException("Query: " + url, e);
091    
092        } catch (IOException e) {
093          throw new ConnectionException("Query: " + url, e);
094    
095        } finally {
096          if (method != null) {
097            method.releaseConnection();
098          }
099        }
100        return json;
101      }
102    
103      private String getResponseBodyAsString(HttpMethod method) {
104        BufferedReader reader = null;
105        try {
106          final InputStream inputStream = method.getResponseBodyAsStream();
107          reader = new BufferedReader(new InputStreamReader(inputStream));
108          final StringBuilder sb = new StringBuilder();
109          String line;
110    
111          while ((line = reader.readLine()) != null) {
112            sb.append(line).append("\n");
113          }
114          return sb.toString();
115    
116        } catch (IOException e) {
117          throw new ConnectionException("Can not read response", e);
118    
119        } finally {
120          if (reader != null) {
121            try {
122              reader.close();
123    
124            } catch (Exception e) {
125              // TODO
126            }
127          }
128        }
129      }
130    }