]> source.dussan.org Git - sonarqube.git/commitdiff
Remove coupling of sonar-plugin-api on Guava 10
authorSimon Brandhof <simon.brandhof@sonarsource.com>
Thu, 16 Apr 2015 15:51:29 +0000 (17:51 +0200)
committerSimon Brandhof <simon.brandhof@sonarsource.com>
Thu, 16 Apr 2015 16:38:13 +0000 (18:38 +0200)
in order to prepare upgrade to Guava 18 in core codebase

46 files changed:
server/sonar-server/src/main/java/org/sonar/server/platform/ServerComponents.java
server/sonar-server/src/main/java/org/sonar/server/plugins/PluginDownloader.java
sonar-batch/src/main/java/org/sonar/batch/bootstrap/GlobalContainer.java
sonar-batch/src/main/java/org/sonar/batch/bootstrap/ServerClient.java
sonar-batch/src/main/java/org/sonar/batch/qualitygate/QualityGateProvider.java
sonar-batch/src/main/java/org/sonar/batch/repository/DefaultServerIssuesLoader.java
sonar-batch/src/test/java/org/sonar/batch/issue/tracking/DefaultServerLineHashesLoaderTest.java
sonar-batch/src/test/java/org/sonar/batch/qualitygate/QualityGateProviderTest.java
sonar-core/pom.xml
sonar-core/src/main/java/org/sonar/core/util/DefaultHttpDownloader.java [new file with mode: 0644]
sonar-core/src/main/java/org/sonar/core/util/HttpsTrust.java [new file with mode: 0644]
sonar-core/src/test/java/org/sonar/core/util/DefaultHttpDownloaderTest.java [new file with mode: 0644]
sonar-core/src/test/java/org/sonar/core/util/HttpsTrustTest.java [new file with mode: 0644]
sonar-plugin-api/pom.xml
sonar-plugin-api/src/main/java/org/sonar/api/batch/DefaultFormulaData.java
sonar-plugin-api/src/main/java/org/sonar/api/batch/ProjectClasspath.java
sonar-plugin-api/src/main/java/org/sonar/api/batch/TimeMachineQuery.java
sonar-plugin-api/src/main/java/org/sonar/api/batch/bootstrap/ProjectDefinition.java
sonar-plugin-api/src/main/java/org/sonar/api/batch/rule/Checks.java
sonar-plugin-api/src/main/java/org/sonar/api/batch/rule/internal/ActiveRulesBuilder.java
sonar-plugin-api/src/main/java/org/sonar/api/config/License.java
sonar-plugin-api/src/main/java/org/sonar/api/config/PropertyDefinition.java
sonar-plugin-api/src/main/java/org/sonar/api/config/PropertyDefinitions.java
sonar-plugin-api/src/main/java/org/sonar/api/config/PropertyFieldDefinition.java
sonar-plugin-api/src/main/java/org/sonar/api/config/Settings.java
sonar-plugin-api/src/main/java/org/sonar/api/issue/action/Actions.java
sonar-plugin-api/src/main/java/org/sonar/api/issue/internal/DefaultIssue.java
sonar-plugin-api/src/main/java/org/sonar/api/measures/CoreMetrics.java
sonar-plugin-api/src/main/java/org/sonar/api/measures/CoverageMeasuresBuilder.java
sonar-plugin-api/src/main/java/org/sonar/api/profiles/RulesProfile.java
sonar-plugin-api/src/main/java/org/sonar/api/resources/InputFileUtils.java
sonar-plugin-api/src/main/java/org/sonar/api/resources/ResourceTypeTree.java
sonar-plugin-api/src/main/java/org/sonar/api/scan/filesystem/FileExclusions.java
sonar-plugin-api/src/main/java/org/sonar/api/scan/filesystem/PathResolver.java
sonar-plugin-api/src/main/java/org/sonar/api/server/ws/Request.java
sonar-plugin-api/src/main/java/org/sonar/api/server/ws/internal/ValidatingRequest.java
sonar-plugin-api/src/main/java/org/sonar/api/utils/FieldUtils2.java
sonar-plugin-api/src/main/java/org/sonar/api/utils/HttpDownloader.java
sonar-plugin-api/src/main/java/org/sonar/api/utils/HttpsTrust.java [deleted file]
sonar-plugin-api/src/main/java/org/sonar/api/utils/UriReader.java
sonar-plugin-api/src/main/java/org/sonar/api/utils/command/Command.java
sonar-plugin-api/src/main/java/org/sonar/api/utils/dag/DirectAcyclicGraph.java
sonar-plugin-api/src/main/java/org/sonar/api/web/Filter.java
sonar-plugin-api/src/test/java/org/sonar/api/utils/DateUtilsTest.java
sonar-plugin-api/src/test/java/org/sonar/api/utils/HttpDownloaderTest.java [deleted file]
sonar-plugin-api/src/test/java/org/sonar/api/utils/HttpsTrustTest.java [deleted file]

index 7085d2a46a2a806cd23c6f2afe6f7250ba4f11b3..796372498fda9262a9673f5329344dd40fb5e02b 100644 (file)
@@ -32,7 +32,7 @@ import org.sonar.api.rules.AnnotationRuleParser;
 import org.sonar.api.rules.XMLRuleParser;
 import org.sonar.api.server.rule.RulesDefinitionXmlLoader;
 import org.sonar.api.utils.Durations;
-import org.sonar.api.utils.HttpDownloader;
+import org.sonar.core.util.DefaultHttpDownloader;
 import org.sonar.api.utils.System2;
 import org.sonar.api.utils.UriReader;
 import org.sonar.api.utils.internal.TempFolderCleaner;
@@ -331,7 +331,7 @@ class ServerComponents {
       ThreadLocalDatabaseSessionFactory.class,
       new DatabaseSessionProvider(),
       ServerMetadataPersister.class,
-      HttpDownloader.class,
+      DefaultHttpDownloader.class,
       UriReader.class,
       ServerIdGenerator.class
       );
index 18de6b9e09c1e7a30445444a4a8dc4c7c1f8cb84..295a58a916a6a336683c9aac1e802119e8d1b2aa 100644 (file)
@@ -22,10 +22,10 @@ package org.sonar.server.plugins;
 import org.apache.commons.io.FileUtils;
 import org.apache.commons.lang.StringUtils;
 import org.picocontainer.Startable;
-import org.sonar.api.utils.HttpDownloader;
 import org.sonar.api.utils.SonarException;
 import org.sonar.api.utils.log.Logger;
 import org.sonar.api.utils.log.Loggers;
+import org.sonar.api.utils.HttpDownloader;
 import org.sonar.server.platform.DefaultServerFileSystem;
 import org.sonar.updatecenter.common.Release;
 import org.sonar.updatecenter.common.Version;
index bffee518e54ed62d12abb0c20436dc3171a16610..7aaf0f6be3237ceb1d368f691c954d0585d26ebc 100644 (file)
@@ -24,7 +24,7 @@ import org.sonar.api.config.EmailSettings;
 import org.sonar.api.platform.ComponentContainer;
 import org.sonar.api.platform.PluginMetadata;
 import org.sonar.api.utils.Durations;
-import org.sonar.api.utils.HttpDownloader;
+import org.sonar.core.util.DefaultHttpDownloader;
 import org.sonar.api.utils.System2;
 import org.sonar.api.utils.UriReader;
 import org.sonar.api.utils.internal.TempFolderCleaner;
@@ -88,7 +88,7 @@ public class GlobalContainer extends ComponentContainer {
       DefaultServer.class,
       new TempFolderProvider(),
       TempFolderCleaner.class,
-      HttpDownloader.class,
+      DefaultHttpDownloader.class,
       UriReader.class,
       new FileCacheProvider(),
       System2.INSTANCE,
index faeef8385d845634d44f785c965bad4feeb82e53..91eac2e7ebe4148d7770689af2023f68e7d2ae5c 100644 (file)
@@ -33,8 +33,9 @@ import org.apache.commons.lang.StringEscapeUtils;
 import org.apache.commons.lang.StringUtils;
 import org.sonar.api.BatchComponent;
 import org.sonar.api.CoreProperties;
-import org.sonar.api.utils.HttpDownloader;
+import org.sonar.core.util.DefaultHttpDownloader;
 import org.sonar.batch.bootstrapper.EnvironmentInformation;
+import org.sonar.api.utils.HttpDownloader;
 
 import javax.annotation.Nullable;
 
@@ -57,11 +58,11 @@ public class ServerClient implements BatchComponent {
 
   private static final String GET = "GET";
   private BootstrapProperties props;
-  private HttpDownloader.BaseHttpDownloader downloader;
+  private DefaultHttpDownloader.BaseHttpDownloader downloader;
 
   public ServerClient(BootstrapProperties settings, EnvironmentInformation env) {
     this.props = settings;
-    this.downloader = new HttpDownloader.BaseHttpDownloader(settings.properties(), env.toString());
+    this.downloader = new DefaultHttpDownloader.BaseHttpDownloader(settings.properties(), env.toString());
   }
 
   public String getURL() {
index 4ede40d4ed9c0c62b70856e6cae9b99817cd104d..83be230b314c72eda8559515e0e2ac0f744c143e 100644 (file)
@@ -28,9 +28,9 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.sonar.api.config.Settings;
 import org.sonar.api.measures.MetricFinder;
-import org.sonar.api.utils.HttpDownloader;
 import org.sonar.api.utils.MessageException;
 import org.sonar.batch.bootstrap.ServerClient;
+import org.sonar.api.utils.HttpDownloader;
 
 import java.net.HttpURLConnection;
 
index 8f32995522ad130d1f6458f610f163b26850e9b3..8193d3a3ebede2e1bd5dca342a9202e4e7f30da8 100644 (file)
@@ -21,9 +21,9 @@ package org.sonar.batch.repository;
 
 import com.google.common.base.Function;
 import com.google.common.io.InputSupplier;
-import org.sonar.api.utils.HttpDownloader;
 import org.sonar.batch.bootstrap.ServerClient;
 import org.sonar.batch.protocol.input.BatchInput.ServerIssue;
+import org.sonar.api.utils.HttpDownloader;
 
 import java.io.IOException;
 import java.io.InputStream;
index 28d9b251ec9baa190022d746e4773185148c0290..2986564bbb05a9fec01fa19892c1f5a18fe58239 100644 (file)
@@ -23,8 +23,8 @@ import org.junit.Before;
 import org.junit.Rule;
 import org.junit.Test;
 import org.junit.rules.ExpectedException;
-import org.sonar.api.utils.HttpDownloader;
 import org.sonar.batch.bootstrap.ServerClient;
+import org.sonar.api.utils.HttpDownloader;
 
 import java.net.URI;
 import java.net.URISyntaxException;
index 6c9b252f33df18fae05a0bf43ef566da3d62be69..12a9976207b1119a950842a741355978e2b43403 100644 (file)
@@ -26,9 +26,9 @@ import org.mockito.runners.MockitoJUnitRunner;
 import org.slf4j.Logger;
 import org.sonar.api.config.Settings;
 import org.sonar.api.measures.MetricFinder;
-import org.sonar.api.utils.HttpDownloader;
 import org.sonar.api.utils.MessageException;
 import org.sonar.batch.bootstrap.ServerClient;
+import org.sonar.api.utils.HttpDownloader;
 
 import java.net.HttpURLConnection;
 import java.net.URI;
index 98cc5cb001703a34fae3bed763c153dbc0cacdf0..41ae4b71bffc24d011423cf81aa0e0ce6d1b0dd4 100644 (file)
       <artifactId>bean-matchers</artifactId>
       <scope>test</scope>
     </dependency>
+    <dependency>
+      <groupId>org.simpleframework</groupId>
+      <artifactId>simple</artifactId>
+      <version>4.1.21</version>
+      <scope>test</scope>
+    </dependency>
+
 
 
     <!--
diff --git a/sonar-core/src/main/java/org/sonar/core/util/DefaultHttpDownloader.java b/sonar-core/src/main/java/org/sonar/core/util/DefaultHttpDownloader.java
new file mode 100644 (file)
index 0000000..d7a311a
--- /dev/null
@@ -0,0 +1,343 @@
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ */
+package org.sonar.core.util;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Joiner;
+import com.google.common.base.Strings;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Lists;
+import com.google.common.io.ByteStreams;
+import com.google.common.io.CharStreams;
+import com.google.common.io.Files;
+import com.google.common.io.InputSupplier;
+import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.io.Charsets;
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.io.IOUtils;
+import org.sonar.api.config.Settings;
+import org.sonar.api.platform.Server;
+import org.sonar.api.utils.HttpDownloader;
+import org.sonar.api.utils.SonarException;
+import org.sonar.api.utils.log.Loggers;
+
+import javax.annotation.Nullable;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.Authenticator;
+import java.net.HttpURLConnection;
+import java.net.PasswordAuthentication;
+import java.net.Proxy;
+import java.net.ProxySelector;
+import java.net.URI;
+import java.nio.charset.Charset;
+import java.util.List;
+import java.util.Map;
+import java.util.zip.GZIPInputStream;
+
+/**
+ * This component downloads HTTP files
+ *
+ * @since 2.2
+ */
+public class DefaultHttpDownloader extends HttpDownloader {
+  public static final int TIMEOUT_MILLISECONDS = 20 * 1000;
+
+  private final BaseHttpDownloader downloader;
+  private final Integer readTimeout;
+
+  public DefaultHttpDownloader(Server server, Settings settings) {
+    this(server, settings, null);
+  }
+
+  public DefaultHttpDownloader(Server server, Settings settings, @Nullable Integer readTimeout) {
+    this.readTimeout = readTimeout;
+    downloader = new BaseHttpDownloader(settings.getProperties(), server.getVersion());
+  }
+
+  public DefaultHttpDownloader(Settings settings) {
+    this(settings, null);
+  }
+
+  public DefaultHttpDownloader(Settings settings, @Nullable Integer readTimeout) {
+    this.readTimeout = readTimeout;
+    downloader = new BaseHttpDownloader(settings.getProperties(), null);
+  }
+
+  @Override
+  protected String description(URI uri) {
+    return String.format("%s (%s)", uri.toString(), getProxySynthesis(uri));
+  }
+
+  @Override
+  protected String[] getSupportedSchemes() {
+    return new String[] {"http", "https"};
+  }
+
+  @Override
+  protected byte[] readBytes(URI uri) {
+    return download(uri);
+  }
+
+  @Override
+  protected String readString(URI uri, Charset charset) {
+    try {
+      return CharStreams.toString(CharStreams.newReaderSupplier(downloader.newInputSupplier(uri, this.readTimeout), charset));
+    } catch (IOException e) {
+      throw failToDownload(uri, e);
+    }
+  }
+
+  @Override
+  public String downloadPlainText(URI uri, String encoding) {
+    return readString(uri, Charset.forName(encoding));
+  }
+
+  @Override
+  public byte[] download(URI uri) {
+    try {
+      return ByteStreams.toByteArray(downloader.newInputSupplier(uri, this.readTimeout));
+    } catch (IOException e) {
+      throw failToDownload(uri, e);
+    }
+  }
+
+  public String getProxySynthesis(URI uri) {
+    return downloader.getProxySynthesis(uri);
+  }
+
+  @Override
+  public InputStream openStream(URI uri) {
+    try {
+      return downloader.newInputSupplier(uri, this.readTimeout).getInput();
+    } catch (IOException e) {
+      throw failToDownload(uri, e);
+    }
+  }
+
+  @Override
+  public void download(URI uri, File toFile) {
+    try {
+      Files.copy(downloader.newInputSupplier(uri, this.readTimeout), toFile);
+    } catch (IOException e) {
+      FileUtils.deleteQuietly(toFile);
+      throw failToDownload(uri, e);
+    }
+  }
+
+  private SonarException failToDownload(URI uri, IOException e) {
+    throw new SonarException(String.format("Fail to download: %s (%s)", uri, getProxySynthesis(uri)), e);
+  }
+
+  public static class BaseHttpDownloader {
+
+    private static final String GET = "GET";
+    private static final String HTTP_PROXY_USER = "http.proxyUser";
+    private static final String HTTP_PROXY_PASSWORD = "http.proxyPassword";
+
+    private static final List<String> PROXY_SETTINGS = ImmutableList.of(
+      "http.proxyHost", "http.proxyPort", "http.nonProxyHosts",
+      "http.auth.ntlm.domain", "socksProxyHost", "socksProxyPort");
+
+    private String userAgent;
+
+    public BaseHttpDownloader(Map<String, String> settings, @Nullable String userAgent) {
+      initProxy(settings);
+      initUserAgent(userAgent);
+    }
+
+    private void initProxy(Map<String, String> settings) {
+      propagateProxySystemProperties(settings);
+      if (requiresProxyAuthentication(settings)) {
+        registerProxyCredentials(settings);
+      }
+    }
+
+    private void initUserAgent(@Nullable String sonarVersion) {
+      userAgent = (sonarVersion == null ? "SonarQube" : String.format("SonarQube %s", sonarVersion));
+      System.setProperty("http.agent", userAgent);
+    }
+
+    private String getProxySynthesis(URI uri) {
+      return getProxySynthesis(uri, ProxySelector.getDefault());
+    }
+
+    @VisibleForTesting
+    static String getProxySynthesis(URI uri, ProxySelector proxySelector) {
+      List<Proxy> proxies = proxySelector.select(uri);
+      if (proxies.size() == 1 && proxies.get(0).type().equals(Proxy.Type.DIRECT)) {
+        return "no proxy";
+      }
+
+      List<String> descriptions = Lists.newArrayList();
+      for (Proxy proxy : proxies) {
+        if (proxy.type() != Proxy.Type.DIRECT) {
+          descriptions.add(proxy.type() + " proxy: " + proxy.address());
+        }
+      }
+
+      return Joiner.on(", ").join(descriptions);
+    }
+
+    private void registerProxyCredentials(Map<String, String> settings) {
+      Authenticator.setDefault(new ProxyAuthenticator(
+        settings.get(HTTP_PROXY_USER),
+        settings.get(HTTP_PROXY_PASSWORD)));
+    }
+
+    private boolean requiresProxyAuthentication(Map<String, String> settings) {
+      return settings.containsKey(HTTP_PROXY_USER);
+    }
+
+    private void propagateProxySystemProperties(Map<String, String> settings) {
+      for (String key : PROXY_SETTINGS) {
+        if (settings.containsKey(key)) {
+          System.setProperty(key, settings.get(key));
+        }
+      }
+    }
+
+    public InputSupplier<InputStream> newInputSupplier(URI uri) {
+      return new HttpInputSupplier(uri, GET, userAgent, null, null, TIMEOUT_MILLISECONDS);
+    }
+
+    public InputSupplier<InputStream> newInputSupplier(URI uri, @Nullable Integer readTimeoutMillis) {
+      return newInputSupplier(uri, GET, readTimeoutMillis);
+    }
+
+    public InputSupplier<InputStream> newInputSupplier(URI uri, String requestMethod, @Nullable Integer readTimeoutMillis) {
+      if (readTimeoutMillis != null) {
+        return new HttpInputSupplier(uri, requestMethod, userAgent, null, null, readTimeoutMillis);
+      }
+      return new HttpInputSupplier(uri, requestMethod, userAgent, null, null, TIMEOUT_MILLISECONDS);
+    }
+
+    public InputSupplier<InputStream> newInputSupplier(URI uri, String login, String password) {
+      return newInputSupplier(uri, GET, login, password);
+    }
+
+    /**
+     * @since 5.0
+     */
+    public InputSupplier<InputStream> newInputSupplier(URI uri, String requestMethod, String login, String password) {
+      return new HttpInputSupplier(uri, requestMethod, userAgent, login, password, TIMEOUT_MILLISECONDS);
+    }
+
+    public InputSupplier<InputStream> newInputSupplier(URI uri, String login, String password, @Nullable Integer readTimeoutMillis) {
+      return newInputSupplier(uri, GET, login, password, readTimeoutMillis);
+    }
+
+    /**
+     * @since 5.0
+     */
+    public InputSupplier<InputStream> newInputSupplier(URI uri, String requestMethod, String login, String password, @Nullable Integer readTimeoutMillis) {
+      if (readTimeoutMillis != null) {
+        return new HttpInputSupplier(uri, requestMethod, userAgent, login, password, readTimeoutMillis);
+      }
+      return new HttpInputSupplier(uri, requestMethod, userAgent, login, password, TIMEOUT_MILLISECONDS);
+    }
+
+    private static class HttpInputSupplier implements InputSupplier<InputStream> {
+      private final String login;
+      private final String password;
+      private final URI uri;
+      private final String userAgent;
+      private final int readTimeoutMillis;
+      private final String requestMethod;
+
+      HttpInputSupplier(URI uri, String requestMethod, String userAgent, String login, String password, int readTimeoutMillis) {
+        this.uri = uri;
+        this.requestMethod = requestMethod;
+        this.userAgent = userAgent;
+        this.login = login;
+        this.password = password;
+        this.readTimeoutMillis = readTimeoutMillis;
+      }
+
+      @Override
+      public InputStream getInput() throws IOException {
+        Loggers.get(getClass()).debug("Download: " + uri + " (" + getProxySynthesis(uri, ProxySelector.getDefault()) + ")");
+
+        HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection();
+        connection.setRequestMethod(requestMethod);
+        HttpsTrust.INSTANCE.trust(connection);
+
+        // allow both GZip and Deflate (ZLib) encodings
+        connection.setRequestProperty("Accept-Encoding", "gzip");
+        if (!Strings.isNullOrEmpty(login)) {
+          String encoded = Base64.encodeBase64String((login + ":" + password).getBytes(Charsets.UTF_8));
+          connection.setRequestProperty("Authorization", "Basic " + encoded);
+        }
+        connection.setConnectTimeout(TIMEOUT_MILLISECONDS);
+        connection.setReadTimeout(readTimeoutMillis);
+        connection.setUseCaches(true);
+        connection.setInstanceFollowRedirects(true);
+        connection.setRequestProperty("User-Agent", userAgent);
+
+        // establish connection, get response headers
+        connection.connect();
+
+        // obtain the encoding returned by the server
+        String encoding = connection.getContentEncoding();
+
+        int responseCode = connection.getResponseCode();
+        if (responseCode >= 400) {
+          InputStream errorResponse = null;
+          try {
+            errorResponse = connection.getErrorStream();
+            if (errorResponse != null) {
+              String errorResponseContent = IOUtils.toString(errorResponse);
+              throw new HttpException(uri, responseCode, errorResponseContent);
+            }
+            throw new HttpException(uri, responseCode);
+
+          } finally {
+            IOUtils.closeQuietly(errorResponse);
+          }
+        }
+
+        InputStream resultingInputStream;
+        // create the appropriate stream wrapper based on the encoding type
+        if (encoding != null && "gzip".equalsIgnoreCase(encoding)) {
+          resultingInputStream = new GZIPInputStream(connection.getInputStream());
+        } else {
+          resultingInputStream = connection.getInputStream();
+        }
+        return resultingInputStream;
+      }
+    }
+
+    private static class ProxyAuthenticator extends Authenticator {
+      private final PasswordAuthentication auth;
+
+      ProxyAuthenticator(String user, String password) {
+        auth = new PasswordAuthentication(user, password == null ? new char[0] : password.toCharArray());
+      }
+
+      @Override
+      protected PasswordAuthentication getPasswordAuthentication() {
+        return auth;
+      }
+    }
+  }
+
+}
diff --git a/sonar-core/src/main/java/org/sonar/core/util/HttpsTrust.java b/sonar-core/src/main/java/org/sonar/core/util/HttpsTrust.java
new file mode 100644 (file)
index 0000000..aee9784
--- /dev/null
@@ -0,0 +1,99 @@
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ */
+package org.sonar.core.util;
+
+import javax.net.ssl.*;
+import java.net.HttpURLConnection;
+import java.security.KeyManagementException;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
+import java.security.cert.X509Certificate;
+
+/**
+ * @since 4.0
+ */
+class HttpsTrust {
+
+  static HttpsTrust INSTANCE = new HttpsTrust(new Ssl());
+
+  static class Ssl {
+    SSLSocketFactory newFactory(TrustManager... managers) throws NoSuchAlgorithmException, KeyManagementException {
+      SSLContext context = SSLContext.getInstance("TLS");
+      context.init(null, managers, new SecureRandom());
+      return context.getSocketFactory();
+    }
+  }
+
+  private final SSLSocketFactory socketFactory;
+  private final HostnameVerifier hostnameVerifier;
+
+  HttpsTrust(Ssl context) {
+    this.socketFactory = createSocketFactory(context);
+    this.hostnameVerifier = createHostnameVerifier();
+  }
+
+  void trust(HttpURLConnection connection) {
+    if (connection instanceof HttpsURLConnection) {
+      HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
+      httpsConnection.setSSLSocketFactory(socketFactory);
+      httpsConnection.setHostnameVerifier(hostnameVerifier);
+    }
+  }
+
+  /**
+   * Trust all certificates
+   */
+  private SSLSocketFactory createSocketFactory(Ssl context) {
+    try {
+      return context.newFactory(new AlwaysTrustManager());
+    } catch (Exception e) {
+      throw new IllegalStateException("Fail to build SSL factory", e);
+    }
+  }
+
+  /**
+   * Trust all hosts
+   */
+  private HostnameVerifier createHostnameVerifier() {
+    return new HostnameVerifier() {
+      @Override
+      public boolean verify(String hostname, SSLSession session) {
+        return true;
+      }
+    };
+  }
+
+  static class AlwaysTrustManager implements X509TrustManager {
+    @Override
+    public X509Certificate[] getAcceptedIssuers() {
+      return new X509Certificate[0];
+    }
+
+    @Override
+    public void checkClientTrusted(X509Certificate[] chain, String authType) {
+      // Do not check
+    }
+
+    @Override
+    public void checkServerTrusted(X509Certificate[] chain, String authType) {
+      // Do not check
+    }
+  }
+}
diff --git a/sonar-core/src/test/java/org/sonar/core/util/DefaultHttpDownloaderTest.java b/sonar-core/src/test/java/org/sonar/core/util/DefaultHttpDownloaderTest.java
new file mode 100644 (file)
index 0000000..06dcded
--- /dev/null
@@ -0,0 +1,238 @@
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ */
+package org.sonar.core.util;
+
+import com.google.common.base.Charsets;
+import org.hamcrest.BaseMatcher;
+import org.hamcrest.Description;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.DisableOnDebug;
+import org.junit.rules.ExpectedException;
+import org.junit.rules.TemporaryFolder;
+import org.junit.rules.TestRule;
+import org.junit.rules.Timeout;
+import org.simpleframework.http.Request;
+import org.simpleframework.http.Response;
+import org.simpleframework.http.core.Container;
+import org.simpleframework.transport.connect.SocketConnection;
+import org.sonar.api.config.Settings;
+import org.sonar.api.platform.Server;
+import org.sonar.api.utils.SonarException;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.InetSocketAddress;
+import java.net.Proxy;
+import java.net.ProxySelector;
+import java.net.SocketAddress;
+import java.net.SocketTimeoutException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.Arrays;
+import java.util.Properties;
+import java.util.zip.GZIPOutputStream;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+public class DefaultHttpDownloaderTest {
+
+  @Rule
+  public TemporaryFolder temporaryFolder = new TemporaryFolder();
+
+  @Rule
+  public ExpectedException thrown = ExpectedException.none();
+
+  @Rule
+  public TestRule timeout = new DisableOnDebug(Timeout.seconds(5));
+
+  private static SocketConnection socketConnection;
+  private static String baseUrl;
+
+  @BeforeClass
+  public static void startServer() throws IOException {
+    socketConnection = new SocketConnection(new Container() {
+      public void handle(Request req, Response resp) {
+        try {
+          if (req.getPath().getPath().contains("/redirect/")) {
+            resp.setCode(303);
+            resp.add("Location", "/");
+          }
+          else {
+            if (req.getPath().getPath().contains("/timeout/")) {
+              try {
+                Thread.sleep(500);
+              } catch (InterruptedException e) {
+                throw new IllegalStateException(e);
+              }
+            }
+            if (req.getPath().getPath().contains("/gzip/")) {
+              if (!"gzip".equals(req.getValue("Accept-Encoding"))) {
+                throw new IllegalStateException("Should accept gzip");
+              }
+              resp.set("Content-Encoding", "gzip");
+              GZIPOutputStream gzipOutputStream = new GZIPOutputStream(resp.getOutputStream());
+              gzipOutputStream.write("GZIP response".getBytes());
+              gzipOutputStream.close();
+            }
+            else {
+              resp.getPrintStream().append("agent=" + req.getValues("User-Agent").get(0));
+            }
+          }
+        } catch (IOException e) {
+          throw new IllegalStateException(e);
+        } finally {
+          try {
+            resp.close();
+          } catch (IOException ignored) {
+          }
+        }
+      }
+    });
+    SocketAddress address = socketConnection.connect(new InetSocketAddress(0));
+
+    baseUrl = "http://0.0.0.0:" + ((InetSocketAddress) address).getPort();
+  }
+
+  @AfterClass
+  public static void stopServer() throws IOException {
+    if (null != socketConnection) {
+      socketConnection.close();
+    }
+  }
+
+  @Test
+  public void downloadBytes() throws URISyntaxException {
+    byte[] bytes = new DefaultHttpDownloader(new Settings()).readBytes(new URI(baseUrl));
+    assertThat(bytes.length).isGreaterThan(10);
+  }
+
+  @Test
+  public void readString() throws URISyntaxException {
+    String text = new DefaultHttpDownloader(new Settings()).readString(new URI(baseUrl), Charsets.UTF_8);
+    assertThat(text.length()).isGreaterThan(10);
+  }
+
+  @Test
+  public void readGzipString() throws URISyntaxException {
+    String text = new DefaultHttpDownloader(new Settings()).readString(new URI(baseUrl + "/gzip/"), Charsets.UTF_8);
+    assertThat(text).isEqualTo("GZIP response");
+  }
+
+  @Test
+  public void readStringWithDefaultTimeout() throws URISyntaxException {
+    String text = new DefaultHttpDownloader(new Settings()).readString(new URI(baseUrl + "/timeout/"), Charsets.UTF_8);
+    assertThat(text.length()).isGreaterThan(10);
+  }
+
+  @Test
+  public void readStringWithTimeout() throws URISyntaxException {
+    thrown.expect(new BaseMatcher<Exception>() {
+      @Override
+      public boolean matches(Object ex) {
+        return ex instanceof SonarException && ((SonarException) ex).getCause() instanceof SocketTimeoutException;
+      }
+
+      @Override
+      public void describeTo(Description arg0) {
+      }
+    });
+    new DefaultHttpDownloader(new Settings(), 50).readString(new URI(baseUrl + "/timeout/"), Charsets.UTF_8);
+  }
+
+  @Test
+  public void downloadToFile() throws URISyntaxException, IOException {
+    File toDir = temporaryFolder.newFolder();
+    File toFile = new File(toDir, "downloadToFile.txt");
+
+    new DefaultHttpDownloader(new Settings()).download(new URI(baseUrl), toFile);
+    assertThat(toFile).exists();
+    assertThat(toFile.length()).isGreaterThan(10l);
+  }
+
+  @Test
+  public void shouldNotCreateFileIfFailToDownload() throws Exception {
+    File toDir = temporaryFolder.newFolder();
+    File toFile = new File(toDir, "downloadToFile.txt");
+
+    try {
+      int port = new InetSocketAddress(0).getPort();
+      new DefaultHttpDownloader(new Settings()).download(new URI("http://localhost:" + port), toFile);
+    } catch (SonarException e) {
+      assertThat(toFile).doesNotExist();
+    }
+  }
+
+  @Test
+  public void userAgentIsSonarVersion() throws URISyntaxException, IOException {
+    Server server = mock(Server.class);
+    when(server.getVersion()).thenReturn("2.2");
+
+    InputStream stream = new DefaultHttpDownloader(server, new Settings()).openStream(new URI(baseUrl));
+    Properties props = new Properties();
+    props.load(stream);
+    stream.close();
+
+    assertThat(props.getProperty("agent")).isEqualTo("SonarQube 2.2");
+  }
+
+  @Test
+  public void followRedirect() throws URISyntaxException {
+    String content = new DefaultHttpDownloader(new Settings()).readString(new URI(baseUrl + "/redirect/"), Charsets.UTF_8);
+    assertThat(content).contains("agent");
+  }
+
+  @Test
+  public void shouldGetDirectProxySynthesis() throws URISyntaxException {
+    ProxySelector proxySelector = mock(ProxySelector.class);
+    when(proxySelector.select(any(URI.class))).thenReturn(Arrays.asList(Proxy.NO_PROXY));
+    assertThat(DefaultHttpDownloader.BaseHttpDownloader.getProxySynthesis(new URI("http://an_url"), proxySelector)).isEqualTo("no proxy");
+  }
+
+  @Test
+  public void shouldGetProxySynthesis() throws URISyntaxException {
+    ProxySelector proxySelector = mock(ProxySelector.class);
+    when(proxySelector.select(any(URI.class))).thenReturn(Arrays.<Proxy>asList(new FakeProxy()));
+    assertThat(DefaultHttpDownloader.BaseHttpDownloader.getProxySynthesis(new URI("http://an_url"), proxySelector)).isEqualTo("HTTP proxy: /123.45.67.89:4040");
+  }
+
+  @Test
+  public void supported_schemes() {
+    assertThat(new DefaultHttpDownloader(new Settings()).getSupportedSchemes()).contains("http");
+  }
+
+  @Test
+  public void uri_description() throws URISyntaxException {
+    String description = new DefaultHttpDownloader(new Settings()).description(new URI("http://sonarsource.org"));
+    assertThat(description).matches("http://sonarsource.org \\(.*\\)");
+  }
+}
+
+class FakeProxy extends Proxy {
+  public FakeProxy() {
+    super(Type.HTTP, new InetSocketAddress("123.45.67.89", 4040));
+  }
+}
diff --git a/sonar-core/src/test/java/org/sonar/core/util/HttpsTrustTest.java b/sonar-core/src/test/java/org/sonar/core/util/HttpsTrustTest.java
new file mode 100644 (file)
index 0000000..689c5e3
--- /dev/null
@@ -0,0 +1,102 @@
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ */
+package org.sonar.core.util;
+
+import org.junit.Test;
+
+import javax.net.ssl.HttpsURLConnection;
+import javax.net.ssl.TrustManager;
+import java.io.IOException;
+import java.net.URL;
+import java.security.KeyManagementException;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.Assert.fail;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+public class HttpsTrustTest {
+  @Test
+  public void trustAllHosts() throws Exception {
+    HttpsURLConnection connection = newHttpsConnection();
+    HttpsTrust.INSTANCE.trust(connection);
+
+    assertThat(connection.getHostnameVerifier()).isNotNull();
+    assertThat(connection.getHostnameVerifier().verify("foo", null)).isTrue();
+  }
+
+  @Test
+  public void singleHostnameVerifier() throws Exception {
+    HttpsURLConnection connection1 = newHttpsConnection();
+    HttpsTrust.INSTANCE.trust(connection1);
+    HttpsURLConnection connection2 = newHttpsConnection();
+    HttpsTrust.INSTANCE.trust(connection2);
+
+    assertThat(connection1.getHostnameVerifier()).isSameAs(connection2.getHostnameVerifier());
+  }
+
+  @Test
+  public void trustAllCerts() throws Exception {
+    HttpsURLConnection connection1 = newHttpsConnection();
+    HttpsTrust.INSTANCE.trust(connection1);
+
+    assertThat(connection1.getSSLSocketFactory()).isNotNull();
+    assertThat(connection1.getSSLSocketFactory().getDefaultCipherSuites()).isNotEmpty();
+  }
+
+  @Test
+  public void singleSslFactory() throws Exception {
+    HttpsURLConnection connection1 = newHttpsConnection();
+    HttpsTrust.INSTANCE.trust(connection1);
+    HttpsURLConnection connection2 = newHttpsConnection();
+    HttpsTrust.INSTANCE.trust(connection2);
+
+    assertThat(connection1.getSSLSocketFactory()).isSameAs(connection2.getSSLSocketFactory());
+  }
+
+  @Test
+  public void testAlwaysTrustManager() throws Exception {
+    HttpsTrust.AlwaysTrustManager manager = new HttpsTrust.AlwaysTrustManager();
+    assertThat(manager.getAcceptedIssuers()).isEmpty();
+    // does nothing
+    manager.checkClientTrusted(null, null);
+    manager.checkServerTrusted(null, null);
+  }
+
+  @Test
+  public void failOnError() throws Exception {
+    HttpsTrust.Ssl context = mock(HttpsTrust.Ssl.class);
+    KeyManagementException cause = new KeyManagementException("foo");
+    when(context.newFactory(any(TrustManager.class))).thenThrow(cause);
+
+    try {
+      new HttpsTrust(context);
+      fail();
+    } catch (IllegalStateException e) {
+      assertThat(e.getMessage()).isEqualTo("Fail to build SSL factory");
+      assertThat(e.getCause()).isSameAs(cause);
+    }
+  }
+
+  private HttpsURLConnection newHttpsConnection() throws IOException {
+    return (HttpsURLConnection) new URL("https://localhost").openConnection();
+  }
+}
index c8ad930e77664d9d6fb4e6dba2c7fa5c45a864e6..039aba7b84a33834b482cf2ad69449115e9a9ba3 100644 (file)
       <artifactId>dbunit</artifactId>
       <scope>test</scope>
     </dependency>
-    <dependency>
-      <groupId>org.simpleframework</groupId>
-      <artifactId>simple</artifactId>
-      <version>4.1.21</version>
-      <scope>test</scope>
-    </dependency>
   </dependencies>
 
   <build>
index 6cff32c4d1ad299d419ade9521f9b89fc0739bd4..1aa4bc24193ef7fc7861619d1377235c4f3ccc95 100644 (file)
  */
 package org.sonar.api.batch;
 
-import com.google.common.collect.Lists;
 import org.sonar.api.measures.FormulaData;
 import org.sonar.api.measures.Measure;
 import org.sonar.api.measures.MeasuresFilter;
 import org.sonar.api.measures.Metric;
 
+import java.util.ArrayList;
 import java.util.Collection;
 import java.util.List;
 
@@ -61,7 +61,7 @@ public class DefaultFormulaData implements FormulaData {
 
   @Override
   public Collection<FormulaData> getChildren() {
-    List<FormulaData> result = Lists.newArrayList();
+    List<FormulaData> result = new ArrayList<>();
     for (DecoratorContext childContext : decoratorContext.getChildren()) {
       result.add(new DefaultFormulaData(childContext));
     }
index f7d55073bc50eeda226aeb7b81bc5d8c37b35021..98502636ad27537958a84f692b2c78d5407b1800 100644 (file)
@@ -19,7 +19,6 @@
  */
 package org.sonar.api.batch;
 
-import com.google.common.collect.Lists;
 import org.apache.maven.artifact.DependencyResolutionRequiredException;
 import org.apache.maven.project.MavenProject;
 import org.sonar.api.BatchComponent;
@@ -29,6 +28,7 @@ import java.io.File;
 import java.net.MalformedURLException;
 import java.net.URL;
 import java.net.URLClassLoader;
+import java.util.ArrayList;
 import java.util.List;
 
 /**
@@ -65,7 +65,7 @@ public class ProjectClasspath implements BatchComponent {
 
   protected URLClassLoader createClassLoader() {
     try {
-      List<URL> urls = Lists.newArrayList();
+      List<URL> urls = new ArrayList<>();
       for (File file : getElements()) {
         urls.add(file.toURI().toURL());
       }
@@ -78,7 +78,7 @@ public class ProjectClasspath implements BatchComponent {
 
   protected List<File> createElements() {
     try {
-      List<File> files = Lists.newArrayList();
+      List<File> files = new ArrayList<>();
       if (pom.getCompileClasspathElements() != null) {
         for (String classPathString : pom.getCompileClasspathElements()) {
           files.add(new File(classPathString));
index 4ac061e3bedccdad3eb9dd130c416aef8dbd8c46..e4d5482ad5ff276614ee4d4a8c505ff6f5ec9190 100644 (file)
  */
 package org.sonar.api.batch;
 
-import com.google.common.collect.Lists;
 import org.apache.commons.lang.builder.ToStringBuilder;
 import org.sonar.api.measures.Metric;
 import org.sonar.api.resources.Resource;
 
 import java.util.Arrays;
 import java.util.Date;
+import java.util.LinkedList;
 import java.util.List;
 
 /**
@@ -91,7 +91,7 @@ public class TimeMachineQuery {
    */
   public TimeMachineQuery setMetrics(List<Metric> metrics) {
     this.metrics = metrics;
-    this.metricKeys = Lists.newLinkedList();
+    this.metricKeys = new LinkedList<>();
     for (Metric metric : this.metrics) {
       this.metricKeys.add(metric.getKey());
     }
@@ -120,7 +120,7 @@ public class TimeMachineQuery {
    */
   public TimeMachineQuery setMetrics(Metric... metrics) {
     this.metrics = Arrays.asList(metrics);
-    this.metricKeys = Lists.newLinkedList();
+    this.metricKeys = new LinkedList<>();
     for (Metric metric : this.metrics) {
       this.metricKeys.add(metric.getKey());
     }
@@ -225,10 +225,10 @@ public class TimeMachineQuery {
   @Override
   public String toString() {
     return new ToStringBuilder(this)
-        .append("resource", resource)
-        .append("metrics", metrics)
-        .append("from", from)
-        .append("to", to)
-        .toString();
+      .append("resource", resource)
+      .append("metrics", metrics)
+      .append("from", from)
+      .append("to", to)
+      .toString();
   }
 }
index afc120524a551fbdf3f07db492465e15c78c4a37..9f123486313b8681d96037e1414929049c1a0a58 100644 (file)
@@ -19,7 +19,6 @@
  */
 package org.sonar.api.batch.bootstrap;
 
-import com.google.common.collect.Lists;
 import org.apache.commons.lang.ObjectUtils;
 import org.apache.commons.lang.StringUtils;
 import org.sonar.api.CoreProperties;
@@ -80,8 +79,8 @@ public class ProjectDefinition {
   private File baseDir, workDir, buildDir;
   private Map<String, String> properties = new HashMap<String, String>();
   private ProjectDefinition parent = null;
-  private List<ProjectDefinition> subProjects = Lists.newArrayList();
-  private List<Object> containerExtensions = Lists.newArrayList();
+  private List<ProjectDefinition> subProjects = new ArrayList<>();
+  private List<Object> containerExtensions = new ArrayList<>();
 
   private ProjectDefinition(Properties p) {
     for (Entry<Object, Object> entry : p.entrySet()) {
@@ -603,7 +602,7 @@ public class ProjectDefinition {
   }
 
   private static List<String> trim(String[] strings) {
-    List<String> result = Lists.newArrayList();
+    List<String> result = new ArrayList<>();
     for (String s : strings) {
       result.add(StringUtils.trim(s));
     }
index 5cdc2aba2b3455e20465d21815a6bb411cf0ac35..b755da6f5b56a1924349238554c024d0eb3fc612 100644 (file)
@@ -32,6 +32,8 @@ import javax.annotation.CheckForNull;
 import java.lang.reflect.Field;
 import java.util.Arrays;
 import java.util.Collection;
+import java.util.HashMap;
+import java.util.IdentityHashMap;
 import java.util.List;
 import java.util.Map;
 
@@ -82,8 +84,8 @@ import java.util.Map;
 public class Checks<C> {
   private final ActiveRules activeRules;
   private final String repository;
-  private final Map<RuleKey, C> checkByRule = Maps.newHashMap();
-  private final Map<C, RuleKey> ruleByCheck = Maps.newIdentityHashMap();
+  private final Map<RuleKey, C> checkByRule = new HashMap<>();
+  private final Map<C, RuleKey> ruleByCheck = new IdentityHashMap<>();
 
   Checks(ActiveRules activeRules, String repository) {
     this.activeRules = activeRules;
index 24edaa4e76331ddd5503e2b78fb4a40706d657d3..6e23900143b938fc62aa2d21ae787c78be055cbe 100644 (file)
  */
 package org.sonar.api.batch.rule.internal;
 
-import com.google.common.collect.Maps;
 import org.sonar.api.batch.rule.ActiveRules;
 import org.sonar.api.rule.RuleKey;
 
+import java.util.LinkedHashMap;
 import java.util.Map;
 
 /**
@@ -33,7 +33,7 @@ import java.util.Map;
  */
 public class ActiveRulesBuilder {
 
-  private final Map<RuleKey, NewActiveRule> map = Maps.newLinkedHashMap();
+  private final Map<RuleKey, NewActiveRule> map = new LinkedHashMap<>();
 
   public NewActiveRule create(RuleKey ruleKey) {
     return new NewActiveRule(this, ruleKey);
index d0f53d44024346ab5736c24b6cf0a35faf071166..8760b8f8d2e6e7a11a4703cf460dafb723bcdca0 100644 (file)
@@ -33,6 +33,7 @@ import java.io.IOException;
 import java.io.StringReader;
 import java.util.Calendar;
 import java.util.Date;
+import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 
@@ -51,7 +52,7 @@ public final class License {
   private Map<String, String> additionalProperties;
 
   private License(Map<String, String> properties) {
-    this.additionalProperties = Maps.newHashMap(properties);
+    this.additionalProperties = new HashMap<>(properties);
     product = StringUtils.defaultString(get("Product", properties), get("Plugin", properties));
     organization = StringUtils.defaultString(get("Organisation", properties), get("Name", properties));
     expirationDate = StringUtils.defaultString(get("Expiration", properties), get("Expires", properties));
index 8e9b3d5df103ba7855092041554cfa456535a7b9..c8c73bde7e5261d786dcf4a75e7050f346a87819 100644 (file)
@@ -33,11 +33,10 @@ import org.sonar.api.resources.Qualifiers;
 
 import javax.annotation.Nullable;
 
+import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
 
-import static com.google.common.collect.Lists.newArrayList;
-
 /**
  * Declare a plugin property. Values are available at runtime through the component {@link Settings}.
  * <p/>
@@ -127,7 +126,7 @@ public final class PropertyDefinition implements BatchExtension, ServerExtension
       .propertySetKey(annotation.propertySetKey())
       .fields(PropertyFieldDefinition.create(annotation.fields()))
       .deprecatedKey(annotation.deprecatedKey());
-    List<String> qualifiers = newArrayList();
+    List<String> qualifiers = new ArrayList<>();
     if (annotation.project()) {
       qualifiers.add(Qualifiers.PROJECT);
     }
@@ -322,14 +321,14 @@ public final class PropertyDefinition implements BatchExtension, ServerExtension
      * @see PropertyDefinition.Builder#subCategory(String)
      */
     private String subCategory = "";
-    private List<String> onQualifiers = newArrayList();
-    private List<String> onlyOnQualifiers = newArrayList();
+    private List<String> onQualifiers = new ArrayList<>();
+    private List<String> onlyOnQualifiers = new ArrayList<>();
     private boolean global = true;
     private PropertyType type = PropertyType.STRING;
-    private List<String> options = newArrayList();
+    private List<String> options = new ArrayList<>();
     private boolean multiValues = false;
     private String propertySetKey = "";
-    private List<PropertyFieldDefinition> fields = newArrayList();
+    private List<PropertyFieldDefinition> fields = new ArrayList<>();
     private String deprecatedKey = "";
     private boolean hidden = false;
     private int index = 999;
index 02c86f060238366fa0cdbe0e57a897ea10aaf682..b44f6696d277af5197a5601c506b6775271c3909 100644 (file)
@@ -20,7 +20,6 @@
 package org.sonar.api.config;
 
 import com.google.common.base.Strings;
-import com.google.common.collect.Maps;
 import org.apache.commons.lang.StringUtils;
 import org.sonar.api.BatchComponent;
 import org.sonar.api.CoreProperties;
@@ -44,12 +43,12 @@ import java.util.Map;
  */
 public final class PropertyDefinitions implements BatchComponent, ServerComponent {
 
-  private final Map<String, PropertyDefinition> definitions = Maps.newHashMap();
-  private final Map<String, Category> categories = Maps.newHashMap();
-  private final Map<String, SubCategory> subcategories = Maps.newHashMap();
+  private final Map<String, PropertyDefinition> definitions = new HashMap<>();
+  private final Map<String, Category> categories = new HashMap<>();
+  private final Map<String, SubCategory> subcategories = new HashMap<>();
 
   // deprecated key -> new key
-  private final Map<String, String> deprecatedKeys = Maps.newHashMap();
+  private final Map<String, String> deprecatedKeys = new HashMap<>();
 
   public PropertyDefinitions(Object... components) {
     if (components != null) {
index 06d856790de86752ce9ef94dd21d1c8d6c78a1e1..93b68d49878c1ddb046405f3850bb30184598134 100644 (file)
@@ -27,10 +27,9 @@ import org.sonar.api.PropertyType;
 
 import javax.annotation.Nullable;
 
+import java.util.ArrayList;
 import java.util.List;
 
-import static com.google.common.collect.Lists.newArrayList;
-
 /**
  * @since 3.3
  */
@@ -52,16 +51,16 @@ public final class PropertyFieldDefinition {
   }
 
   static List<PropertyFieldDefinition> create(PropertyField[] fields) {
-    List<PropertyFieldDefinition> definitions = newArrayList();
+    List<PropertyFieldDefinition> definitions = new ArrayList<>();
     for (PropertyField field : fields) {
       definitions.add(PropertyFieldDefinition.build(field.key())
-          .name(field.name())
-          .description(field.description())
-          .indicativeSize(field.indicativeSize())
-          .type(field.type())
-          .options(field.options())
-          .build()
-      );
+        .name(field.name())
+        .description(field.description())
+        .indicativeSize(field.indicativeSize())
+        .type(field.type())
+        .options(field.options())
+        .build()
+        );
     }
     return definitions;
   }
@@ -112,7 +111,7 @@ public final class PropertyFieldDefinition {
       this.description = "";
       this.indicativeSize = 20;
       this.type = PropertyType.STRING;
-      this.options = newArrayList();
+      this.options = new ArrayList<>();
     }
 
     public Builder name(String name) {
index fa422fa815f5f2b6b6c20446005a3cdfc97d0a6c..662c661d1952609b7cd69595b994b6abcc0547eb 100644 (file)
@@ -23,7 +23,6 @@ import com.google.common.base.Joiner;
 import com.google.common.base.Splitter;
 import com.google.common.base.Strings;
 import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Lists;
 import com.google.common.collect.Maps;
 import org.apache.commons.lang.ArrayUtils;
 import org.apache.commons.lang.StringUtils;
@@ -33,6 +32,7 @@ import org.sonar.api.utils.DateUtils;
 
 import javax.annotation.Nullable;
 
+import java.util.ArrayList;
 import java.util.Date;
 import java.util.List;
 import java.util.Map;
@@ -235,7 +235,7 @@ public class Settings implements BatchComponent, ServerComponent {
         return ArrayUtils.EMPTY_STRING_ARRAY;
       }
 
-      List<String> values = Lists.newArrayList();
+      List<String> values = new ArrayList<>();
       for (String v : Splitter.on(",").trimResults().split(value)) {
         values.add(v.replace("%2C", ","));
       }
@@ -276,7 +276,7 @@ public class Settings implements BatchComponent, ServerComponent {
   }
 
   public List<String> getKeysStartingWith(String prefix) {
-    List<String> result = Lists.newArrayList();
+    List<String> result = new ArrayList<>();
     for (String key : properties.keySet()) {
       if (StringUtils.startsWith(key, prefix)) {
         result.add(key);
@@ -303,7 +303,7 @@ public class Settings implements BatchComponent, ServerComponent {
 
     String text = null;
     if (values != null) {
-      List<String> escaped = Lists.newArrayList();
+      List<String> escaped = new ArrayList<>();
       for (String value : values) {
         if (null != value) {
           escaped.add(value.replace(",", "%2C"));
index b13b2a4806ac9000e833a093f5e74f3b9f039784..149a7450994f29bc3c8b930acdf0d2a031dc40cb 100644 (file)
@@ -22,21 +22,16 @@ package org.sonar.api.issue.action;
 import com.google.common.annotations.Beta;
 import org.sonar.api.ServerExtension;
 
+import java.util.ArrayList;
 import java.util.List;
 
-import static com.google.common.collect.Lists.newArrayList;
-
 /**
  * @since 3.6
  */
 @Beta
 public class Actions implements ServerExtension {
 
-  private final List<Action> actions;
-
-  public Actions() {
-    actions = newArrayList();
-  }
+  private final List<Action> actions = new ArrayList<>();
 
   public Action add(String actionKey) {
     Action action = new Action(actionKey);
index d2827256243074bdcf374810f2fbb67272b1e575..db09f62cef27ce913be3456692b810e80f83f5d6 100644 (file)
@@ -42,8 +42,6 @@ import javax.annotation.Nullable;
 import java.io.Serializable;
 import java.util.*;
 
-import static com.google.common.collect.Lists.newArrayList;
-
 /**
  * PLUGINS MUST NOT BE USED THIS CLASS, EXCEPT FOR UNIT TESTING.
  *
@@ -506,7 +504,7 @@ public class DefaultIssue implements Issue {
 
   public DefaultIssue addChange(FieldDiffs change) {
     if (changes == null) {
-      changes = newArrayList();
+      changes = new ArrayList<>();
     }
     changes.add(change);
     return this;
@@ -526,7 +524,7 @@ public class DefaultIssue implements Issue {
 
   public DefaultIssue addComment(DefaultIssueComment comment) {
     if (comments == null) {
-      comments = newArrayList();
+      comments = new ArrayList<>();
     }
     comments.add(comment);
     return this;
index 3427c5a8461165a464f898d0e335744994fda320..7b3dddee46d0bc7be1274049a608b0b3f41df867 100644 (file)
@@ -22,7 +22,6 @@ package org.sonar.api.measures;
 import com.google.common.annotations.Beta;
 import com.google.common.base.Predicate;
 import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
 import org.sonar.api.resources.Scopes;
 import org.sonar.api.test.MutableTestPlan;
 import org.sonar.api.utils.SonarException;
@@ -31,6 +30,7 @@ import javax.annotation.Nullable;
 
 import java.lang.reflect.Field;
 import java.lang.reflect.Modifier;
+import java.util.LinkedList;
 import java.util.List;
 
 /**
@@ -2226,7 +2226,7 @@ public final class CoreMetrics {
   private static final List<Metric> METRICS;
 
   static {
-    METRICS = Lists.newLinkedList();
+    METRICS = new LinkedList<>();
     for (Field field : CoreMetrics.class.getFields()) {
       if (!Modifier.isTransient(field.getModifiers()) && Metric.class.isAssignableFrom(field.getType())) {
         try {
index 823155b2d0a6c4d81f3a7f99cc461d6aa257e80c..d4ddac918538f42ac1a2e1ab37204b9201790fa3 100644 (file)
  */
 package org.sonar.api.measures;
 
-import com.google.common.collect.Lists;
 import com.google.common.collect.Maps;
 import org.sonar.api.utils.KeyValueFormat;
 
+import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collection;
 import java.util.Collections;
@@ -110,7 +110,7 @@ public final class CoverageMeasuresBuilder {
   }
 
   public Collection<Measure> createMeasures() {
-    Collection<Measure> measures = Lists.newArrayList();
+    Collection<Measure> measures = new ArrayList<>();
     if (getLinesToCover() > 0) {
       measures.add(new Measure(CoreMetrics.LINES_TO_COVER, (double) getLinesToCover()));
       measures.add(new Measure(CoreMetrics.UNCOVERED_LINES, (double) (getLinesToCover() - getCoveredLines())));
index 15f8bd4b4cfc7f3feeb868d315795fe5c2217dba..a541337ca97d0cacb10203cbcea760c07ed28c3e 100644 (file)
@@ -21,7 +21,6 @@ package org.sonar.api.profiles;
 
 import com.google.common.base.Predicate;
 import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
 import org.apache.commons.collections.CollectionUtils;
 import org.apache.commons.collections.Transformer;
 import org.apache.commons.lang.StringUtils;
@@ -34,7 +33,6 @@ import org.sonar.api.utils.MessageException;
 
 import javax.annotation.CheckForNull;
 import javax.annotation.Nullable;
-
 import java.util.ArrayList;
 import java.util.List;
 
@@ -68,7 +66,7 @@ public class RulesProfile implements Cloneable {
   private Boolean defaultProfile = Boolean.FALSE;
   private String language;
   private String parentName;
-  private List<ActiveRule> activeRules = Lists.newArrayList();
+  private List<ActiveRule> activeRules = new ArrayList<>();
 
   /**
    * @deprecated use the factory method create()
@@ -84,7 +82,7 @@ public class RulesProfile implements Cloneable {
   public RulesProfile(String name, String language) {
     this.name = name;
     this.language = language;
-    this.activeRules = Lists.newArrayList();
+    this.activeRules = new ArrayList<>();
   }
 
   /**
@@ -163,7 +161,7 @@ public class RulesProfile implements Cloneable {
     if (acceptDisabledRules) {
       return activeRules;
     }
-    List<ActiveRule> result = Lists.newArrayList();
+    List<ActiveRule> result = new ArrayList<>();
     for (ActiveRule activeRule : activeRules) {
       if (activeRule.isEnabled()) {
         result.add(activeRule);
@@ -244,7 +242,7 @@ public class RulesProfile implements Cloneable {
    * @return the list of active rules for a given severity
    */
   public List<ActiveRule> getActiveRules(RulePriority severity) {
-    List<ActiveRule> result = Lists.newArrayList();
+    List<ActiveRule> result = new ArrayList<>();
     for (ActiveRule activeRule : activeRules) {
       if (activeRule.getSeverity().equals(severity) && activeRule.isEnabled()) {
         result.add(activeRule);
@@ -258,7 +256,7 @@ public class RulesProfile implements Cloneable {
    * Only enabled rules are selected. Disabled rules are excluded.
    */
   public List<ActiveRule> getActiveRulesByRepository(String repositoryKey) {
-    List<ActiveRule> result = Lists.newArrayList();
+    List<ActiveRule> result = new ArrayList<>();
     for (ActiveRule activeRule : activeRules) {
       if (repositoryKey.equals(activeRule.getRepositoryKey()) && activeRule.isEnabled()) {
         result.add(activeRule);
index 51a6cde057ed898f194bbe23ee2998cf8a7cceec..07457c9272960b8a41129e323dc7c7da12119b9c 100644 (file)
@@ -28,6 +28,7 @@ import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileNotFoundException;
 import java.io.InputStream;
+import java.util.ArrayList;
 import java.util.Collection;
 import java.util.List;
 
@@ -47,7 +48,7 @@ public final class InputFileUtils {
    * @return not null list
    */
   public static List<java.io.File> toFiles(Collection<InputFile> inputFiles) {
-    List<java.io.File> files = Lists.newArrayList();
+    List<java.io.File> files = new ArrayList<>();
     for (InputFile inputFile : inputFiles) {
       files.add(inputFile.getFile());
     }
@@ -89,7 +90,7 @@ public final class InputFileUtils {
    * For internal and for testing purposes. Please use the FileSystem component to access files.
    */
   public static List<InputFile> create(java.io.File basedir, Collection<java.io.File> files) {
-    List<InputFile> inputFiles = Lists.newArrayList();
+    List<InputFile> inputFiles = new ArrayList<>();
     for (File file : files) {
       InputFile inputFile = create(basedir, file);
       if (inputFile != null) {
index c6e4031f9e22fcbfc439e7ec080b97caebc2ad13..f6fa337b482461e6ef5101c51ca1fdf11e5c1e3c 100644 (file)
@@ -26,10 +26,10 @@ import com.google.common.collect.Collections2;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableListMultimap;
 import com.google.common.collect.ListMultimap;
-import com.google.common.collect.Lists;
 import org.sonar.api.ServerExtension;
 import org.sonar.api.task.TaskExtension;
 
+import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collection;
 import java.util.List;
@@ -80,7 +80,7 @@ public class ResourceTypeTree implements TaskExtension, ServerExtension {
   }
 
   public static final class Builder {
-    private List<ResourceType> types = Lists.newArrayList();
+    private List<ResourceType> types = new ArrayList<>();
     private ListMultimap<String, String> relations = ArrayListMultimap.create();
     private ResourceType root;
 
index a49829e9c209b37e3a22d65ff8fe0ffc353007c6..b5032895f83c35e9cc860009a1ed1fe80e23a63e 100644 (file)
  */
 package org.sonar.api.scan.filesystem;
 
-import com.google.common.collect.Lists;
 import com.google.common.collect.ObjectArrays;
 import org.apache.commons.lang.StringUtils;
 import org.sonar.api.BatchComponent;
 import org.sonar.api.CoreProperties;
 import org.sonar.api.config.Settings;
 
+import java.util.ArrayList;
 import java.util.List;
 
 /**
@@ -52,7 +52,7 @@ public class FileExclusions implements BatchComponent {
 
   private String[] inclusions(String propertyKey) {
     String[] patterns = sanitize(settings.getStringArray(propertyKey));
-    List<String> list = Lists.newArrayList();
+    List<String> list = new ArrayList<>();
     for (String pattern : patterns) {
       if (!"**/*".equals(pattern) && !"file:**/*".equals(pattern)) {
         list.add(pattern);
index 6da18e4a04902fc84bac8e569ae085354ca0b082..9bd4ac7be0c01696229e138eaafae709696d8864 100644 (file)
@@ -21,13 +21,13 @@ package org.sonar.api.scan.filesystem;
 
 import com.google.common.base.Joiner;
 import com.google.common.base.Preconditions;
-import com.google.common.collect.Lists;
 import org.sonar.api.BatchComponent;
 import org.sonar.api.utils.PathUtils;
 
 import javax.annotation.CheckForNull;
 
 import java.io.File;
+import java.util.ArrayList;
 import java.util.Collection;
 import java.util.List;
 
@@ -50,7 +50,7 @@ public class PathResolver implements BatchComponent {
   }
 
   public List<File> relativeFiles(File dir, List<String> paths) {
-    List<File> result = Lists.newArrayList();
+    List<File> result = new ArrayList<>();
     for (String path : paths) {
       result.add(relativeFile(dir, path));
     }
@@ -59,7 +59,7 @@ public class PathResolver implements BatchComponent {
 
   @CheckForNull
   public RelativePath relativePath(Collection<File> dirs, File file) {
-    List<String> stack = Lists.newArrayList();
+    List<String> stack = new ArrayList<>();
     File cursor = file;
     while (cursor != null) {
       File parentDir = parentDir(dirs, cursor);
@@ -74,7 +74,7 @@ public class PathResolver implements BatchComponent {
 
   @CheckForNull
   public String relativePath(File dir, File file) {
-    List<String> stack = Lists.newArrayList();
+    List<String> stack = new ArrayList<>();
     String dirPath = PathUtils.canonicalPath(dir);
     File cursor = file;
     while (cursor != null) {
index 2cbd0ef0b4dee829bcce4f4dc48404660d38fc42..427350b2ea61a0c2efa2ea0faa0209ec099c2d1b 100644 (file)
@@ -28,6 +28,7 @@ import org.sonar.api.utils.SonarException;
 import javax.annotation.CheckForNull;
 
 import java.io.InputStream;
+import java.util.ArrayList;
 import java.util.Date;
 import java.util.List;
 
@@ -187,7 +188,7 @@ public abstract class Request {
       return null;
     }
     Iterable<String> values = Splitter.on(',').omitEmptyStrings().trimResults().split(value);
-    List<E> result = Lists.newArrayList();
+    List<E> result = new ArrayList<>();
     for (String s : values) {
       result.add(Enum.valueOf(enumClass, s));
     }
index 054ba7731965ae813cba3fd4df19f1833b487be9..af6d5cb7a2e5271b52fdcacb520cc67435dc4a0a 100644 (file)
@@ -30,6 +30,7 @@ import javax.annotation.CheckForNull;
 import javax.annotation.Nullable;
 
 import java.io.InputStream;
+import java.util.ArrayList;
 import java.util.List;
 import java.util.Set;
 
@@ -94,7 +95,7 @@ public abstract class ValidatingRequest extends Request {
       return null;
     }
     Iterable<String> values = Splitter.on(',').omitEmptyStrings().trimResults().split(value);
-    List<E> result = Lists.newArrayList();
+    List<E> result = new ArrayList<>();
     for (String s : values) {
       validate(s, definition);
       result.add(Enum.valueOf(enumClass, s));
index 85f466672aaac4654c4dd7579f1df50c8a92b9c6..2acdbe275379fc9643536b549bfe54056b4ffb86 100644 (file)
  */
 package org.sonar.api.utils;
 
-import com.google.common.collect.Lists;
 import org.apache.commons.lang.ClassUtils;
 
 import java.lang.reflect.Field;
 import java.lang.reflect.Modifier;
+import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
 
@@ -44,13 +44,13 @@ public final class FieldUtils2 {
    *                    <code>False</code> only matches public fields.
    */
   public static List<Field> getFields(Class clazz, boolean forceAccess) {
-    List<Field> result = Lists.newArrayList();
+    List<Field> result = new ArrayList<>();
     Class c = clazz;
     while (c != null) {
       for (Field declaredField : c.getDeclaredFields()) {
         if (!Modifier.isPublic(declaredField.getModifiers())) {
           if (forceAccess) {
-            declaredField.setAccessible(true);//NOSONAR only works from sufficiently privileged code
+            declaredField.setAccessible(true);// NOSONAR only works from sufficiently privileged code
           } else {
             continue;
           }
index ee0ba26214c147a9685769fbc30509f1aadfc357..2c0ae79479c3a87a54c02d3f885944ea26681df4 100644 (file)
  */
 package org.sonar.api.utils;
 
-import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Joiner;
-import com.google.common.base.Strings;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
-import com.google.common.io.ByteStreams;
-import com.google.common.io.CharStreams;
-import com.google.common.io.Files;
-import com.google.common.io.InputSupplier;
-import org.apache.commons.codec.binary.Base64;
-import org.apache.commons.io.Charsets;
-import org.apache.commons.io.FileUtils;
-import org.apache.commons.io.IOUtils;
 import org.sonar.api.BatchComponent;
 import org.sonar.api.ServerComponent;
-import org.sonar.api.config.Settings;
-import org.sonar.api.platform.Server;
-import org.sonar.api.utils.log.Loggers;
-
-import javax.annotation.Nullable;
 
 import java.io.File;
-import java.io.IOException;
 import java.io.InputStream;
-import java.net.Authenticator;
-import java.net.HttpURLConnection;
-import java.net.PasswordAuthentication;
-import java.net.Proxy;
-import java.net.ProxySelector;
 import java.net.URI;
-import java.nio.charset.Charset;
-import java.util.List;
-import java.util.Map;
-import java.util.zip.GZIPInputStream;
 
 /**
- * This component downloads HTTP files
- *
- * @since 2.2
+ * This component is available in IoC container, so it should be injected through
+ * a constructor parameter. It is available in both batch and server.
  */
-public class HttpDownloader extends UriReader.SchemeProcessor implements BatchComponent, ServerComponent {
-  public static final int TIMEOUT_MILLISECONDS = 20 * 1000;
-
-  private final BaseHttpDownloader downloader;
-  private final Integer readTimeout;
-
-  public HttpDownloader(Server server, Settings settings) {
-    this(server, settings, null);
-  }
-
-  public HttpDownloader(Server server, Settings settings, @Nullable Integer readTimeout) {
-    this.readTimeout = readTimeout;
-    downloader = new BaseHttpDownloader(settings.getProperties(), server.getVersion());
-  }
-
-  public HttpDownloader(Settings settings) {
-    this(settings, null);
-  }
-
-  public HttpDownloader(Settings settings, @Nullable Integer readTimeout) {
-    this.readTimeout = readTimeout;
-    downloader = new BaseHttpDownloader(settings.getProperties(), null);
-  }
-
-  @Override
-  String description(URI uri) {
-    return String.format("%s (%s)", uri.toString(), getProxySynthesis(uri));
-  }
-
-  @Override
-  String[] getSupportedSchemes() {
-    return new String[] {"http", "https"};
-  }
-
-  @Override
-  byte[] readBytes(URI uri) {
-    return download(uri);
-  }
-
-  @Override
-  String readString(URI uri, Charset charset) {
-    try {
-      return CharStreams.toString(CharStreams.newReaderSupplier(downloader.newInputSupplier(uri, this.readTimeout), charset));
-    } catch (IOException e) {
-      throw failToDownload(uri, e);
-    }
-  }
-
-  public String downloadPlainText(URI uri, String encoding) {
-    return readString(uri, Charset.forName(encoding));
-  }
-
-  public byte[] download(URI uri) {
-    try {
-      return ByteStreams.toByteArray(downloader.newInputSupplier(uri, this.readTimeout));
-    } catch (IOException e) {
-      throw failToDownload(uri, e);
-    }
-  }
-
-  public String getProxySynthesis(URI uri) {
-    return downloader.getProxySynthesis(uri);
-  }
-
-  public InputStream openStream(URI uri) {
-    try {
-      return downloader.newInputSupplier(uri, this.readTimeout).getInput();
-    } catch (IOException e) {
-      throw failToDownload(uri, e);
-    }
-  }
-
-  public void download(URI uri, File toFile) {
-    try {
-      Files.copy(downloader.newInputSupplier(uri, this.readTimeout), toFile);
-    } catch (IOException e) {
-      FileUtils.deleteQuietly(toFile);
-      throw failToDownload(uri, e);
-    }
-  }
-
-  private SonarException failToDownload(URI uri, IOException e) {
-    throw new SonarException(String.format("Fail to download: %s (%s)", uri, getProxySynthesis(uri)), e);
-  }
-
-  public static class BaseHttpDownloader {
-
-    private static final String GET = "GET";
-    private static final String HTTP_PROXY_USER = "http.proxyUser";
-    private static final String HTTP_PROXY_PASSWORD = "http.proxyPassword";
-
-    private static final List<String> PROXY_SETTINGS = ImmutableList.of(
-      "http.proxyHost", "http.proxyPort", "http.nonProxyHosts",
-      "http.auth.ntlm.domain", "socksProxyHost", "socksProxyPort");
-
-    private String userAgent;
-
-    public BaseHttpDownloader(Map<String, String> settings, @Nullable String userAgent) {
-      initProxy(settings);
-      initUserAgent(userAgent);
-    }
-
-    private void initProxy(Map<String, String> settings) {
-      propagateProxySystemProperties(settings);
-      if (requiresProxyAuthentication(settings)) {
-        registerProxyCredentials(settings);
-      }
-    }
-
-    private void initUserAgent(@Nullable String sonarVersion) {
-      userAgent = (sonarVersion == null ? "SonarQube" : String.format("SonarQube %s", sonarVersion));
-      System.setProperty("http.agent", userAgent);
-    }
-
-    private String getProxySynthesis(URI uri) {
-      return getProxySynthesis(uri, ProxySelector.getDefault());
-    }
-
-    @VisibleForTesting
-    static String getProxySynthesis(URI uri, ProxySelector proxySelector) {
-      List<Proxy> proxies = proxySelector.select(uri);
-      if (proxies.size() == 1 && proxies.get(0).type().equals(Proxy.Type.DIRECT)) {
-        return "no proxy";
-      }
-
-      List<String> descriptions = Lists.newArrayList();
-      for (Proxy proxy : proxies) {
-        if (proxy.type() != Proxy.Type.DIRECT) {
-          descriptions.add(proxy.type() + " proxy: " + proxy.address());
-        }
-      }
-
-      return Joiner.on(", ").join(descriptions);
-    }
-
-    private void registerProxyCredentials(Map<String, String> settings) {
-      Authenticator.setDefault(new ProxyAuthenticator(
-        settings.get(HTTP_PROXY_USER),
-        settings.get(HTTP_PROXY_PASSWORD)));
-    }
-
-    private boolean requiresProxyAuthentication(Map<String, String> settings) {
-      return settings.containsKey(HTTP_PROXY_USER);
-    }
-
-    private void propagateProxySystemProperties(Map<String, String> settings) {
-      for (String key : PROXY_SETTINGS) {
-        if (settings.containsKey(key)) {
-          System.setProperty(key, settings.get(key));
-        }
-      }
-    }
-
-    public InputSupplier<InputStream> newInputSupplier(URI uri) {
-      return new HttpInputSupplier(uri, GET, userAgent, null, null, TIMEOUT_MILLISECONDS);
-    }
-
-    public InputSupplier<InputStream> newInputSupplier(URI uri, @Nullable Integer readTimeoutMillis) {
-      return newInputSupplier(uri, GET, readTimeoutMillis);
-    }
-
-    public InputSupplier<InputStream> newInputSupplier(URI uri, String requestMethod, @Nullable Integer readTimeoutMillis) {
-      if (readTimeoutMillis != null) {
-        return new HttpInputSupplier(uri, requestMethod, userAgent, null, null, readTimeoutMillis);
-      }
-      return new HttpInputSupplier(uri, requestMethod, userAgent, null, null, TIMEOUT_MILLISECONDS);
-    }
+public abstract class HttpDownloader extends UriReader.SchemeProcessor implements BatchComponent, ServerComponent {
+  public abstract String downloadPlainText(URI uri, String encoding);
 
-    public InputSupplier<InputStream> newInputSupplier(URI uri, String login, String password) {
-      return newInputSupplier(uri, GET, login, password);
-    }
-
-    /**
-     * @since 5.0
-     */
-    public InputSupplier<InputStream> newInputSupplier(URI uri, String requestMethod, String login, String password) {
-      return new HttpInputSupplier(uri, requestMethod, userAgent, login, password, TIMEOUT_MILLISECONDS);
-    }
-
-    public InputSupplier<InputStream> newInputSupplier(URI uri, String login, String password, @Nullable Integer readTimeoutMillis) {
-      return newInputSupplier(uri, GET, login, password, readTimeoutMillis);
-    }
-
-    /**
-     * @since 5.0
-     */
-    public InputSupplier<InputStream> newInputSupplier(URI uri, String requestMethod, String login, String password, @Nullable Integer readTimeoutMillis) {
-      if (readTimeoutMillis != null) {
-        return new HttpInputSupplier(uri, requestMethod, userAgent, login, password, readTimeoutMillis);
-      }
-      return new HttpInputSupplier(uri, requestMethod, userAgent, login, password, TIMEOUT_MILLISECONDS);
-    }
-
-    private static class HttpInputSupplier implements InputSupplier<InputStream> {
-      private final String login;
-      private final String password;
-      private final URI uri;
-      private final String userAgent;
-      private final int readTimeoutMillis;
-      private final String requestMethod;
-
-      HttpInputSupplier(URI uri, String requestMethod, String userAgent, String login, String password, int readTimeoutMillis) {
-        this.uri = uri;
-        this.requestMethod = requestMethod;
-        this.userAgent = userAgent;
-        this.login = login;
-        this.password = password;
-        this.readTimeoutMillis = readTimeoutMillis;
-      }
-
-      @Override
-      public InputStream getInput() throws IOException {
-        Loggers.get(getClass()).debug("Download: " + uri + " (" + getProxySynthesis(uri, ProxySelector.getDefault()) + ")");
-
-        HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection();
-        connection.setRequestMethod(requestMethod);
-        HttpsTrust.INSTANCE.trust(connection);
+  public abstract byte[] download(URI uri);
 
-        // allow both GZip and Deflate (ZLib) encodings
-        connection.setRequestProperty("Accept-Encoding", "gzip");
-        if (!Strings.isNullOrEmpty(login)) {
-          String encoded = Base64.encodeBase64String((login + ":" + password).getBytes(Charsets.UTF_8));
-          connection.setRequestProperty("Authorization", "Basic " + encoded);
-        }
-        connection.setConnectTimeout(TIMEOUT_MILLISECONDS);
-        connection.setReadTimeout(readTimeoutMillis);
-        connection.setUseCaches(true);
-        connection.setInstanceFollowRedirects(true);
-        connection.setRequestProperty("User-Agent", userAgent);
+  public abstract InputStream openStream(URI uri);
 
-        // establish connection, get response headers
-        connection.connect();
-
-        // obtain the encoding returned by the server
-        String encoding = connection.getContentEncoding();
-
-        int responseCode = connection.getResponseCode();
-        if (responseCode >= 400) {
-          InputStream errorResponse = null;
-          try {
-            errorResponse = connection.getErrorStream();
-            if (errorResponse != null) {
-              String errorResponseContent = IOUtils.toString(errorResponse);
-              throw new HttpException(uri, responseCode, errorResponseContent);
-            }
-            throw new HttpException(uri, responseCode);
-
-          } finally {
-            IOUtils.closeQuietly(errorResponse);
-          }
-        }
-
-        InputStream resultingInputStream;
-        // create the appropriate stream wrapper based on the encoding type
-        if (encoding != null && "gzip".equalsIgnoreCase(encoding)) {
-          resultingInputStream = new GZIPInputStream(connection.getInputStream());
-        } else {
-          resultingInputStream = connection.getInputStream();
-        }
-        return resultingInputStream;
-      }
-    }
-
-    private static class ProxyAuthenticator extends Authenticator {
-      private final PasswordAuthentication auth;
-
-      ProxyAuthenticator(String user, String password) {
-        auth = new PasswordAuthentication(user, password == null ? new char[0] : password.toCharArray());
-      }
-
-      @Override
-      protected PasswordAuthentication getPasswordAuthentication() {
-        return auth;
-      }
-    }
-  }
+  public abstract void download(URI uri, File toFile);
 
   public static class HttpException extends RuntimeException {
     private final URI uri;
diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/utils/HttpsTrust.java b/sonar-plugin-api/src/main/java/org/sonar/api/utils/HttpsTrust.java
deleted file mode 100644 (file)
index 3ca7471..0000000
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
- */
-package org.sonar.api.utils;
-
-import javax.net.ssl.*;
-import java.net.HttpURLConnection;
-import java.security.KeyManagementException;
-import java.security.NoSuchAlgorithmException;
-import java.security.SecureRandom;
-import java.security.cert.X509Certificate;
-
-/**
- * @since 4.0
- */
-class HttpsTrust {
-
-  static HttpsTrust INSTANCE = new HttpsTrust(new Ssl());
-
-  static class Ssl {
-    SSLSocketFactory newFactory(TrustManager... managers) throws NoSuchAlgorithmException, KeyManagementException {
-      SSLContext context = SSLContext.getInstance("TLS");
-      context.init(null, managers, new SecureRandom());
-      return context.getSocketFactory();
-    }
-  }
-
-  private final SSLSocketFactory socketFactory;
-  private final HostnameVerifier hostnameVerifier;
-
-  HttpsTrust(Ssl context) {
-    this.socketFactory = createSocketFactory(context);
-    this.hostnameVerifier = createHostnameVerifier();
-  }
-
-  void trust(HttpURLConnection connection) {
-    if (connection instanceof HttpsURLConnection) {
-      HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
-      httpsConnection.setSSLSocketFactory(socketFactory);
-      httpsConnection.setHostnameVerifier(hostnameVerifier);
-    }
-  }
-
-  /**
-   * Trust all certificates
-   */
-  private SSLSocketFactory createSocketFactory(Ssl context) {
-    try {
-      return context.newFactory(new AlwaysTrustManager());
-    } catch (Exception e) {
-      throw new IllegalStateException("Fail to build SSL factory", e);
-    }
-  }
-
-  /**
-   * Trust all hosts
-   */
-  private HostnameVerifier createHostnameVerifier() {
-    return new HostnameVerifier() {
-      @Override
-      public boolean verify(String hostname, SSLSession session) {
-        return true;
-      }
-    };
-  }
-
-  static class AlwaysTrustManager implements X509TrustManager {
-    @Override
-    public X509Certificate[] getAcceptedIssuers() {
-      return new X509Certificate[0];
-    }
-
-    @Override
-    public void checkClientTrusted(X509Certificate[] chain, String authType) {
-      // Do not check
-    }
-
-    @Override
-    public void checkServerTrusted(X509Certificate[] chain, String authType) {
-      // Do not check
-    }
-  }
-}
index a5d001731aab52b6d999b5dfed088976ee3df009..ad435de7b23ca7112038dc496f048b1bd50c463c 100644 (file)
@@ -86,14 +86,14 @@ public class UriReader implements BatchComponent, ServerComponent {
     return processor;
   }
 
-  abstract static class SchemeProcessor {
-    abstract String[] getSupportedSchemes();
+  public abstract static class SchemeProcessor {
+    protected abstract String[] getSupportedSchemes();
 
-    abstract byte[] readBytes(URI uri);
+    protected abstract byte[] readBytes(URI uri);
 
-    abstract String readString(URI uri, Charset charset);
+    protected abstract String readString(URI uri, Charset charset);
 
-    abstract String description(URI uri);
+    protected abstract String description(URI uri);
   }
 
 
@@ -108,7 +108,7 @@ public class UriReader implements BatchComponent, ServerComponent {
     }
 
     @Override
-    byte[] readBytes(URI uri) {
+    protected byte[] readBytes(URI uri) {
       try {
         return Files.toByteArray(new File(uri));
       } catch (IOException e) {
@@ -117,7 +117,7 @@ public class UriReader implements BatchComponent, ServerComponent {
     }
 
     @Override
-    String readString(URI uri, Charset charset) {
+    protected String readString(URI uri, Charset charset) {
       try {
         return Files.toString(new File(uri), charset);
       } catch (IOException e) {
@@ -126,7 +126,7 @@ public class UriReader implements BatchComponent, ServerComponent {
     }
 
     @Override
-    String description(URI uri) {
+    protected String description(URI uri) {
       return new File(uri).getAbsolutePath();
     }
   }
index c100a48cb54a9668669e1bb0bb5716677711c88f..7a14ba52e9e3d93a68e08f4d6d5e61f4cfb184ce 100644 (file)
@@ -23,12 +23,12 @@ import com.google.common.base.Joiner;
 import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Lists;
 import com.google.common.collect.Maps;
 import org.apache.commons.lang.StringUtils;
 import org.sonar.api.utils.System2;
 
 import java.io.File;
+import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
 import java.util.Map;
@@ -38,8 +38,8 @@ import java.util.Map;
  */
 public class Command {
   private final String executable;
-  private final List<String> arguments = Lists.newArrayList();
-  private final List<String> argumentsForLogs = Lists.newArrayList();
+  private final List<String> arguments = new ArrayList<>();
+  private final List<String> argumentsForLogs = new ArrayList<>();
   private final Map<String, String> env;
   private File directory;
   private boolean newShell = false;
index 113991951a424643a6c2c30c21c913715cbda474..6cd3b683af9c2f53cff6f09f5922cbca64439de7 100644 (file)
@@ -63,7 +63,7 @@ public class DirectAcyclicGraph {
   public List sort() {
     sortNodes();
 
-    List<Object> result = Lists.newArrayList();
+    List<Object> result = new ArrayList<>();
     for (Node node : nodes) {
       result.add(node.getObject());
     }
index 784ed579ef7a6f3ebf70499549e92d879ea31bca..0325360050c30f8624ea4bcbac4d5d6bdfea6532 100644 (file)
  */
 package org.sonar.api.web;
 
-import com.google.common.collect.Lists;
+import com.google.common.base.Preconditions;
 
+import java.util.ArrayList;
 import java.util.List;
 
-import com.google.common.base.Preconditions;
-
 /**
  * Definition of a filter.
  *
@@ -44,8 +43,8 @@ public final class Filter {
 
   private Filter() {
     displayAs = LIST;
-    criteria = Lists.newArrayList();
-    columns = Lists.newArrayList();
+    criteria = new ArrayList<>();
+    columns = new ArrayList<>();
   }
 
   /**
index b32de7f475d9628631f217f221be882729ce37b4..71a398979406b3792434f62264def5a694847861 100644 (file)
  */
 package org.sonar.api.utils;
 
-import com.google.common.collect.Lists;
 import org.assertj.core.api.Assertions;
 import org.junit.Rule;
 import org.junit.Test;
 import org.junit.rules.ExpectedException;
 
+import java.util.ArrayList;
 import java.util.Date;
 import java.util.List;
 
@@ -128,7 +128,7 @@ public class DateUtilsTest {
   public void shouldBeThreadSafe() throws Exception {
     final DateUtils.ThreadSafeDateFormat format = new DateUtils.ThreadSafeDateFormat("yyyy-MM-dd'T'HH:mm:ss,S z");
     final Date now = new Date();
-    final List<Throwable> throwables = Lists.newArrayList();
+    final List<Throwable> throwables = new ArrayList<>();
 
     final ThreadGroup tg = new ThreadGroup("shouldBeThreadSafe") {
       @Override
diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/HttpDownloaderTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/HttpDownloaderTest.java
deleted file mode 100644 (file)
index 091b157..0000000
+++ /dev/null
@@ -1,237 +0,0 @@
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
- */
-package org.sonar.api.utils;
-
-import com.google.common.base.Charsets;
-import org.hamcrest.BaseMatcher;
-import org.hamcrest.Description;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.DisableOnDebug;
-import org.junit.rules.ExpectedException;
-import org.junit.rules.TemporaryFolder;
-import org.junit.rules.TestRule;
-import org.junit.rules.Timeout;
-import org.simpleframework.http.Request;
-import org.simpleframework.http.Response;
-import org.simpleframework.http.core.Container;
-import org.simpleframework.transport.connect.SocketConnection;
-import org.sonar.api.config.Settings;
-import org.sonar.api.platform.Server;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.InetSocketAddress;
-import java.net.Proxy;
-import java.net.ProxySelector;
-import java.net.SocketAddress;
-import java.net.SocketTimeoutException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.util.Arrays;
-import java.util.Properties;
-import java.util.zip.GZIPOutputStream;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.mockito.Matchers.any;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-public class HttpDownloaderTest {
-
-  @Rule
-  public TemporaryFolder temporaryFolder = new TemporaryFolder();
-
-  @Rule
-  public ExpectedException thrown = ExpectedException.none();
-
-  @Rule
-  public TestRule timeout = new DisableOnDebug(Timeout.seconds(5));
-
-  private static SocketConnection socketConnection;
-  private static String baseUrl;
-
-  @BeforeClass
-  public static void startServer() throws IOException {
-    socketConnection = new SocketConnection(new Container() {
-      public void handle(Request req, Response resp) {
-        try {
-          if (req.getPath().getPath().contains("/redirect/")) {
-            resp.setCode(303);
-            resp.add("Location", "/");
-          }
-          else {
-            if (req.getPath().getPath().contains("/timeout/")) {
-              try {
-                Thread.sleep(500);
-              } catch (InterruptedException e) {
-                throw new IllegalStateException(e);
-              }
-            }
-            if (req.getPath().getPath().contains("/gzip/")) {
-              if (!"gzip".equals(req.getValue("Accept-Encoding"))) {
-                throw new IllegalStateException("Should accept gzip");
-              }
-              resp.set("Content-Encoding", "gzip");
-              GZIPOutputStream gzipOutputStream = new GZIPOutputStream(resp.getOutputStream());
-              gzipOutputStream.write("GZIP response".getBytes());
-              gzipOutputStream.close();
-            }
-            else {
-              resp.getPrintStream().append("agent=" + req.getValues("User-Agent").get(0));
-            }
-          }
-        } catch (IOException e) {
-          throw new IllegalStateException(e);
-        } finally {
-          try {
-            resp.close();
-          } catch (IOException ignored) {
-          }
-        }
-      }
-    });
-    SocketAddress address = socketConnection.connect(new InetSocketAddress(0));
-
-    baseUrl = "http://0.0.0.0:" + ((InetSocketAddress) address).getPort();
-  }
-
-  @AfterClass
-  public static void stopServer() throws IOException {
-    if (null != socketConnection) {
-      socketConnection.close();
-    }
-  }
-
-  @Test
-  public void downloadBytes() throws URISyntaxException {
-    byte[] bytes = new HttpDownloader(new Settings()).readBytes(new URI(baseUrl));
-    assertThat(bytes.length).isGreaterThan(10);
-  }
-
-  @Test
-  public void readString() throws URISyntaxException {
-    String text = new HttpDownloader(new Settings()).readString(new URI(baseUrl), Charsets.UTF_8);
-    assertThat(text.length()).isGreaterThan(10);
-  }
-
-  @Test
-  public void readGzipString() throws URISyntaxException {
-    String text = new HttpDownloader(new Settings()).readString(new URI(baseUrl + "/gzip/"), Charsets.UTF_8);
-    assertThat(text).isEqualTo("GZIP response");
-  }
-
-  @Test
-  public void readStringWithDefaultTimeout() throws URISyntaxException {
-    String text = new HttpDownloader(new Settings()).readString(new URI(baseUrl + "/timeout/"), Charsets.UTF_8);
-    assertThat(text.length()).isGreaterThan(10);
-  }
-
-  @Test
-  public void readStringWithTimeout() throws URISyntaxException {
-    thrown.expect(new BaseMatcher<Exception>() {
-      @Override
-      public boolean matches(Object ex) {
-        return ex instanceof SonarException && ((SonarException) ex).getCause() instanceof SocketTimeoutException;
-      }
-
-      @Override
-      public void describeTo(Description arg0) {
-      }
-    });
-    new HttpDownloader(new Settings(), 50).readString(new URI(baseUrl + "/timeout/"), Charsets.UTF_8);
-  }
-
-  @Test
-  public void downloadToFile() throws URISyntaxException, IOException {
-    File toDir = temporaryFolder.newFolder();
-    File toFile = new File(toDir, "downloadToFile.txt");
-
-    new HttpDownloader(new Settings()).download(new URI(baseUrl), toFile);
-    assertThat(toFile).exists();
-    assertThat(toFile.length()).isGreaterThan(10l);
-  }
-
-  @Test
-  public void shouldNotCreateFileIfFailToDownload() throws Exception {
-    File toDir = temporaryFolder.newFolder();
-    File toFile = new File(toDir, "downloadToFile.txt");
-
-    try {
-      int port = new InetSocketAddress(0).getPort();
-      new HttpDownloader(new Settings()).download(new URI("http://localhost:" + port), toFile);
-    } catch (SonarException e) {
-      assertThat(toFile).doesNotExist();
-    }
-  }
-
-  @Test
-  public void userAgentIsSonarVersion() throws URISyntaxException, IOException {
-    Server server = mock(Server.class);
-    when(server.getVersion()).thenReturn("2.2");
-
-    InputStream stream = new HttpDownloader(server, new Settings()).openStream(new URI(baseUrl));
-    Properties props = new Properties();
-    props.load(stream);
-    stream.close();
-
-    assertThat(props.getProperty("agent")).isEqualTo("SonarQube 2.2");
-  }
-
-  @Test
-  public void followRedirect() throws URISyntaxException {
-    String content = new HttpDownloader(new Settings()).readString(new URI(baseUrl + "/redirect/"), Charsets.UTF_8);
-    assertThat(content).contains("agent");
-  }
-
-  @Test
-  public void shouldGetDirectProxySynthesis() throws URISyntaxException {
-    ProxySelector proxySelector = mock(ProxySelector.class);
-    when(proxySelector.select(any(URI.class))).thenReturn(Arrays.asList(Proxy.NO_PROXY));
-    assertThat(HttpDownloader.BaseHttpDownloader.getProxySynthesis(new URI("http://an_url"), proxySelector)).isEqualTo("no proxy");
-  }
-
-  @Test
-  public void shouldGetProxySynthesis() throws URISyntaxException {
-    ProxySelector proxySelector = mock(ProxySelector.class);
-    when(proxySelector.select(any(URI.class))).thenReturn(Arrays.<Proxy>asList(new FakeProxy()));
-    assertThat(HttpDownloader.BaseHttpDownloader.getProxySynthesis(new URI("http://an_url"), proxySelector)).isEqualTo("HTTP proxy: /123.45.67.89:4040");
-  }
-
-  @Test
-  public void supported_schemes() {
-    assertThat(new HttpDownloader(new Settings()).getSupportedSchemes()).contains("http");
-  }
-
-  @Test
-  public void uri_description() throws URISyntaxException {
-    String description = new HttpDownloader(new Settings()).description(new URI("http://sonarsource.org"));
-    assertThat(description).matches("http://sonarsource.org \\(.*\\)");
-  }
-}
-
-class FakeProxy extends Proxy {
-  public FakeProxy() {
-    super(Type.HTTP, new InetSocketAddress("123.45.67.89", 4040));
-  }
-}
diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/HttpsTrustTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/HttpsTrustTest.java
deleted file mode 100644 (file)
index 40fdffb..0000000
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
- */
-package org.sonar.api.utils;
-
-import org.junit.Test;
-
-import javax.net.ssl.HttpsURLConnection;
-import javax.net.ssl.TrustManager;
-import java.io.IOException;
-import java.net.URL;
-import java.security.KeyManagementException;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.Assert.fail;
-import static org.mockito.Matchers.any;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-public class HttpsTrustTest {
-  @Test
-  public void trustAllHosts() throws Exception {
-    HttpsURLConnection connection = newHttpsConnection();
-    HttpsTrust.INSTANCE.trust(connection);
-
-    assertThat(connection.getHostnameVerifier()).isNotNull();
-    assertThat(connection.getHostnameVerifier().verify("foo", null)).isTrue();
-  }
-
-  @Test
-  public void singleHostnameVerifier() throws Exception {
-    HttpsURLConnection connection1 = newHttpsConnection();
-    HttpsTrust.INSTANCE.trust(connection1);
-    HttpsURLConnection connection2 = newHttpsConnection();
-    HttpsTrust.INSTANCE.trust(connection2);
-
-    assertThat(connection1.getHostnameVerifier()).isSameAs(connection2.getHostnameVerifier());
-  }
-
-  @Test
-  public void trustAllCerts() throws Exception {
-    HttpsURLConnection connection1 = newHttpsConnection();
-    HttpsTrust.INSTANCE.trust(connection1);
-
-    assertThat(connection1.getSSLSocketFactory()).isNotNull();
-    assertThat(connection1.getSSLSocketFactory().getDefaultCipherSuites()).isNotEmpty();
-  }
-
-  @Test
-  public void singleSslFactory() throws Exception {
-    HttpsURLConnection connection1 = newHttpsConnection();
-    HttpsTrust.INSTANCE.trust(connection1);
-    HttpsURLConnection connection2 = newHttpsConnection();
-    HttpsTrust.INSTANCE.trust(connection2);
-
-    assertThat(connection1.getSSLSocketFactory()).isSameAs(connection2.getSSLSocketFactory());
-  }
-
-  @Test
-  public void testAlwaysTrustManager() throws Exception {
-    HttpsTrust.AlwaysTrustManager manager = new HttpsTrust.AlwaysTrustManager();
-    assertThat(manager.getAcceptedIssuers()).isEmpty();
-    // does nothing
-    manager.checkClientTrusted(null, null);
-    manager.checkServerTrusted(null, null);
-  }
-
-  @Test
-  public void failOnError() throws Exception {
-    HttpsTrust.Ssl context = mock(HttpsTrust.Ssl.class);
-    KeyManagementException cause = new KeyManagementException("foo");
-    when(context.newFactory(any(TrustManager.class))).thenThrow(cause);
-
-    try {
-      new HttpsTrust(context);
-      fail();
-    } catch (IllegalStateException e) {
-      assertThat(e.getMessage()).isEqualTo("Fail to build SSL factory");
-      assertThat(e.getCause()).isSameAs(cause);
-    }
-  }
-
-  private HttpsURLConnection newHttpsConnection() throws IOException {
-    return (HttpsURLConnection) new URL("https://localhost").openConnection();
-  }
-}