org.apache.maven.settings.Proxy Java Examples

The following examples show how to use org.apache.maven.settings.Proxy. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MojoUtils.java    From wisdom with Apache License 2.0 6 votes vote down vote up
public static ProxyConfig getProxyConfig(MavenSession mavenSession, SettingsDecrypter decrypter) {
    if (mavenSession == null ||
            mavenSession.getSettings() == null ||
            mavenSession.getSettings().getProxies() == null ||
            mavenSession.getSettings().getProxies().isEmpty()) {
        return new ProxyConfig(Collections.<ProxyConfig.Proxy>emptyList());
    } else {
        final List<Proxy> mavenProxies = mavenSession.getSettings().getProxies();

        final List<ProxyConfig.Proxy> proxies = new ArrayList<>(mavenProxies.size());

        for (Proxy mavenProxy : mavenProxies) {
            if (mavenProxy.isActive()) {
                mavenProxy = decryptProxy(mavenProxy, decrypter);
                proxies.add(new ProxyConfig.Proxy(mavenProxy.getId(), mavenProxy.getProtocol(), mavenProxy.getHost(),
                        mavenProxy.getPort(), mavenProxy.getUsername(), mavenProxy.getPassword(), mavenProxy.getNonProxyHosts()));
            }
        }

        return new ProxyConfig(proxies);
    }
}
 
Example #2
Source File: PGPKeysServerClient.java    From pgpverify-maven-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Create a PGP key server for a given URL.
 *
 * @param keyServer
 *         The key server address / URL.
 * @param proxy proxy server config
 * @param connectTimeout
 *         The timeout (in milliseconds) that the client should wait to establish a connection to
 *         the PGP server.
 * @param readTimeout
 *         The timeout (in milliseconds) that the client should wait for data from the PGP server.
 * @param maxAttempts
 *         The maximum number of automatically retry request by client
 *
 * @return The right PGP client for the given address.
 *
 * @throws IOException
 *         If some problem during client create.
 */
static PGPKeysServerClient getClient(String keyServer, Proxy proxy,
        int connectTimeout, int readTimeout, int maxAttempts) throws IOException {
    final URI uri = Try.of(() -> new URI(keyServer))
            .getOrElseThrow((Function<Throwable, IOException>) IOException::new);

    final String protocol = uri.getScheme().toLowerCase(Locale.ROOT);

    switch (protocol) {
        case "hkp":
        case "http":
            return new PGPKeysServerClientHttp(uri, connectTimeout, readTimeout, maxAttempts, proxy);

        case "hkps":
        case "https":
            return new PGPKeysServerClientHttps(uri, connectTimeout, readTimeout, maxAttempts, proxy);

        default:
            throw new IOException("Unsupported protocol: " + protocol);
    }
}
 
Example #3
Source File: PGPVerifyMojo.java    From pgpverify-maven-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the maven proxy with a matching id or the first active one
 *
 * @return the maven proxy
 */
Proxy getMavenProxy() {
    if (settings == null) {
        return null;
    }
    List<Proxy> proxies = settings.getProxies();
    if (proxies == null || proxies.isEmpty()) {
        return null;
    }
    if (proxyName == null) {
        return proxies.stream()
                .filter(Proxy::isActive)
                .findFirst()
                .orElse(null);
    } else {
        return proxies.stream()
                .filter(proxy -> proxyName.equalsIgnoreCase(proxy.getId()))
                .findFirst()
                .orElse(null);
    }
}
 
Example #4
Source File: PGPVerifyMojoTest.java    From pgpverify-maven-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * test that if we set a proxy, we want to ensure that it is the right one from our config
 * @throws Exception unexcpected reflection issues etc.
 */
@Test
public void testIfProxyDeterminationWorksUsingIDs() throws Exception {

    List<Proxy> proxies = Arrays.asList(
        makeMavenProxy(null, null, "p1", true),
        makeMavenProxy(null, null, "p2", false));

    PGPVerifyMojo mojo = new PGPVerifyMojo();
    Field settings = PGPVerifyMojo.class.getDeclaredField("settings");
    settings.setAccessible(true);
    Settings mavenSettings = mock(Settings.class);
    settings.set(mojo, mavenSettings);
    Field proxyName = PGPVerifyMojo.class.getDeclaredField("proxyName");
    proxyName.setAccessible(true);

    when(mavenSettings.getProxies()).thenReturn(proxies);

    proxyName.set(mojo, "p2");
    Assert.assertEquals(mojo.getMavenProxy().getId(), "p2");
    proxyName.set(mojo, "p1");
    Assert.assertEquals(mojo.getMavenProxy().getId(), "p1");
    proxyName.set(mojo, "p3");
    Assert.assertNull(mojo.getMavenProxy());
}
 
Example #5
Source File: PGPVerifyMojoTest.java    From pgpverify-maven-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * If the proxy is not set, it should take the first active one
 * @throws Exception unexpected reflection issue
 */
@Test
public void testIfProxyDeterminationWorksUsinFirstActive() throws Exception {
    List<Proxy> proxies = Arrays.asList(
        makeMavenProxy(null, null, "p1", false),
        makeMavenProxy(null, null, "p2", true));
    PGPVerifyMojo mojo = new PGPVerifyMojo();
    Field settings = PGPVerifyMojo.class.getDeclaredField("settings");
    settings.setAccessible(true);
    Settings mavenSettings = mock(Settings.class);
    settings.set(mojo, mavenSettings);
    Field proxyName = PGPVerifyMojo.class.getDeclaredField("proxyName");
    proxyName.setAccessible(true);

    when(mavenSettings.getProxies()).thenReturn(proxies);

    proxyName.set(mojo, null);
    Assert.assertEquals(mojo.getMavenProxy().getId(), "p2");
}
 
Example #6
Source File: Repository.java    From webdriverextensions-maven-plugin with Apache License 2.0 6 votes vote down vote up
private static String downloadAsString(URL url, Proxy proxySettings) throws IOException {
    URLConnection connection;
    if (proxySettings != null) {
        java.net.Proxy proxy = new java.net.Proxy(java.net.Proxy.Type.HTTP,
                                                  new InetSocketAddress(proxySettings.getHost(),
                                                                        proxySettings.getPort()));
        if (proxySettings.getUsername() != null) {
            ProxyUtils.setProxyAuthenticator(proxySettings);
        }
        connection = url.openConnection(proxy);
    } else {
        connection = url.openConnection();
    }

    try (InputStream inputStream = connection.getInputStream()) {
        return IOUtils.toString(inputStream, UTF_8);
    }
}
 
Example #7
Source File: DriverDownloader.java    From webdriverextensions-maven-plugin with Apache License 2.0 6 votes vote down vote up
private HttpClientBuilder prepareHttpClientBuilderWithTimeoutsAndProxySettings(Proxy proxySettings) throws MojoExecutionException {
    SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(FILE_DOWNLOAD_READ_TIMEOUT).build();
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(FILE_DOWNLOAD_CONNECT_TIMEOUT)
            .setCookieSpec(CookieSpecs.IGNORE_COOKIES).build();
    HttpClientBuilder httpClientBuilder = HttpClients.custom();
    httpClientBuilder
            .setDefaultSocketConfig(socketConfig)
            .setDefaultRequestConfig(requestConfig)
            .disableContentCompression();
    HttpHost proxy = ProxyUtils.createProxyFromSettings(proxySettings);
    if (proxy != null) {
        httpClientBuilder.setProxy(proxy);
        CredentialsProvider proxyCredentials = ProxyUtils.createProxyCredentialsFromSettings(proxySettings);
        if (proxyCredentials != null) {
            httpClientBuilder.setDefaultCredentialsProvider(proxyCredentials);
        }
    }
    return httpClientBuilder;
}
 
Example #8
Source File: JDOMSettingsConverter.java    From pom-manipulation-ext with Apache License 2.0 6 votes vote down vote up
/**
 * Method updateProxy.
 *
 * @param proxy
 * @param element
 * @param counter
 */
protected void updateProxy( final Proxy proxy, final IndentationCounter counter, final Element element )
{
    final IndentationCounter innerCount = new IndentationCounter( counter.getDepth() + 1 );
    findAndReplaceSimpleElement( innerCount, element, "active", String.valueOf( proxy.isActive() ),
                                 "true" );
    findAndReplaceSimpleElement( innerCount, element, "protocol", proxy.getProtocol(),
                                 "http" );
    findAndReplaceSimpleElement( innerCount, element, "username", proxy.getUsername(),
                                 null );
    findAndReplaceSimpleElement( innerCount, element, "password", proxy.getPassword(),
                                 null );
    findAndReplaceSimpleElement( innerCount, element, "port", String.valueOf( proxy.getPort() ),
                                 "8080" );
    findAndReplaceSimpleElement( innerCount, element, "host", proxy.getHost(), null );
    findAndReplaceSimpleElement( innerCount, element, "nonProxyHosts", proxy.getNonProxyHosts(),
                                 null );
    findAndReplaceSimpleElement( innerCount, element, "id", proxy.getId(), "default" );
}
 
Example #9
Source File: MojoUtils.java    From frontend-maven-plugin with Apache License 2.0 6 votes vote down vote up
static ProxyConfig getProxyConfig(MavenSession mavenSession, SettingsDecrypter decrypter) {
    if (mavenSession == null ||
            mavenSession.getSettings() == null ||
            mavenSession.getSettings().getProxies() == null ||
            mavenSession.getSettings().getProxies().isEmpty()) {
        return new ProxyConfig(Collections.<ProxyConfig.Proxy>emptyList());
    } else {
        final List<Proxy> mavenProxies = mavenSession.getSettings().getProxies();

        final List<ProxyConfig.Proxy> proxies = new ArrayList<ProxyConfig.Proxy>(mavenProxies.size());

        for (Proxy mavenProxy : mavenProxies) {
            if (mavenProxy.isActive()) {
                mavenProxy = decryptProxy(mavenProxy, decrypter);
                proxies.add(new ProxyConfig.Proxy(mavenProxy.getId(), mavenProxy.getProtocol(), mavenProxy.getHost(),
                        mavenProxy.getPort(), mavenProxy.getUsername(), mavenProxy.getPassword(), mavenProxy.getNonProxyHosts()));
            }
        }

        LOGGER.info("Found proxies: {}", proxies);
        return new ProxyConfig(proxies);
    }
}
 
Example #10
Source File: CreateProjectMojo.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private void setProxySystemPropertiesFromSession() {
    List<Proxy> proxiesFromSession = session.getRequest().getProxies();
    // - takari maven uses https to download the maven wrapper
    // - don't do anything if proxy system property is already set
    if (!proxiesFromSession.isEmpty() && System.getProperty("https.proxyHost") == null) {

        // use the first active proxy for setting the system properties
        proxiesFromSession.stream()
                .filter(Proxy::isActive)
                .findFirst()
                .ifPresent(proxy -> {
                    // note: a http proxy _is_ usable as https.proxyHost
                    System.setProperty("https.proxyHost", proxy.getHost());
                    System.setProperty("https.proxyPort", String.valueOf(proxy.getPort()));
                    if (proxy.getNonProxyHosts() != null) {
                        System.setProperty("http.nonProxyHosts", proxy.getNonProxyHosts());
                    }
                });
    }
}
 
Example #11
Source File: AbstractCodegenMojo.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected void configureProxyServerSettings() throws MojoExecutionException {

        Proxy proxy = mavenSession.getSettings().getActiveProxy();

        if (proxy != null) {

            getLog().info("Using proxy server configured in maven.");

            if (proxy.getHost() == null) {
                throw new MojoExecutionException("Proxy in settings.xml has no host");
            }
            if (proxy.getHost() != null) {
                System.setProperty(HTTP_PROXY_HOST, proxy.getHost());
            }
            if (String.valueOf(proxy.getPort()) != null) {
                System.setProperty(HTTP_PROXY_PORT, String.valueOf(proxy.getPort()));
            }
            if (proxy.getNonProxyHosts() != null) {
                System.setProperty(HTTP_NON_PROXY_HOSTS, proxy.getNonProxyHosts());
            }
            if (!StringUtils.isEmpty(proxy.getUsername())
                && !StringUtils.isEmpty(proxy.getPassword())) {
                final String authUser = proxy.getUsername();
                final String authPassword = proxy.getPassword();
                Authenticator.setDefault(new Authenticator() {
                    public PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(authUser, authPassword.toCharArray());
                    }
                });

                System.setProperty(HTTP_PROXY_USER, authUser);
                System.setProperty(HTTP_PROXY_PASSWORD, authPassword);
            }

        }
    }
 
Example #12
Source File: AbstractCodegenMojo.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void restoreProxySetting(String originalProxyHost, String originalProxyPort,
                                 String originalNonProxyHosts,
                                 String originalProxyUser,
                                 String originalProxyPassword) {
    if (originalProxyHost != null) {
        System.setProperty(HTTP_PROXY_HOST, originalProxyHost);
    } else {
        System.getProperties().remove(HTTP_PROXY_HOST);
    }
    if (originalProxyPort != null) {
        System.setProperty(HTTP_PROXY_PORT, originalProxyPort);
    } else {
        System.getProperties().remove(HTTP_PROXY_PORT);
    }
    if (originalNonProxyHosts != null) {
        System.setProperty(HTTP_NON_PROXY_HOSTS, originalNonProxyHosts);
    } else {
        System.getProperties().remove(HTTP_NON_PROXY_HOSTS);
    }
    if (originalProxyUser != null) {
        System.setProperty(HTTP_PROXY_USER, originalProxyUser);
    } else {
        System.getProperties().remove(HTTP_PROXY_USER);
    }
    if (originalProxyPassword != null) {
        System.setProperty(HTTP_PROXY_PASSWORD, originalProxyPassword);
    } else {
        System.getProperties().remove(HTTP_PROXY_PASSWORD);
    }
    Proxy proxy = mavenSession.getSettings().getActiveProxy();
    if (proxy != null && !StringUtils.isEmpty(proxy.getUsername())
        && !StringUtils.isEmpty(proxy.getPassword())) {
        Authenticator.setDefault(null);
    }
}
 
Example #13
Source File: ProxyUtils.java    From webdriverextensions-maven-plugin with Apache License 2.0 5 votes vote down vote up
public static void setProxyAuthenticator(final Proxy proxy) {
    Authenticator authenticator = new Authenticator() {
        @Override
        public PasswordAuthentication getPasswordAuthentication() {
            return (new PasswordAuthentication(proxy.getUsername(),
                    proxy.getPassword().toCharArray()));
        }
    };
    Authenticator.setDefault(authenticator);
}
 
Example #14
Source File: ProxyUtils.java    From webdriverextensions-maven-plugin with Apache License 2.0 5 votes vote down vote up
static CredentialsProvider createProxyCredentialsFromSettings(Proxy proxySettings) throws MojoExecutionException {
    if (proxySettings.getUsername() == null) {
        return null;
    }
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials(proxySettings.getUsername(), proxySettings.getPassword()));

    return credentialsProvider;
}
 
Example #15
Source File: ProxyUtil.java    From pgpverify-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * create a new proxy for tests
 * @param proxyUser the username
 * @param proxyPassword the password
 * @param id the proxy id
 * @return a proxy
 */
public static Proxy makeMavenProxy(String proxyUser, String proxyPassword, String id, boolean active) {
    Proxy proxy = new Proxy();
    proxy.setHost("localhost");
    proxy.setActive(active);
    proxy.setNonProxyHosts("*");
    proxy.setUsername(proxyUser);
    proxy.setPassword(proxyPassword);
    proxy.setId(id);
    proxy.setProtocol("http");
    return proxy;
}
 
Example #16
Source File: MavenContainer.java    From furnace with Eclipse Public License 1.0 5 votes vote down vote up
public static org.eclipse.aether.repository.Proxy convertFromMavenProxy(org.apache.maven.settings.Proxy proxy)
{
   org.eclipse.aether.repository.Proxy result = null;
   if (proxy != null)
   {
      Authentication auth = new AuthenticationBuilder().addUsername(proxy.getUsername())
               .addPassword(proxy.getPassword()).build();
      result = new org.eclipse.aether.repository.Proxy(proxy.getProtocol(), proxy.getHost(), proxy.getPort(), auth);
   }
   return result;
}
 
Example #17
Source File: MavenContainer.java    From furnace with Eclipse Public License 1.0 5 votes vote down vote up
public DefaultRepositorySystemSession setupRepoSession(final RepositorySystem repoSystem, final Settings settings)
{
   DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession();
   session.setOffline(false);

   Proxy activeProxy = settings.getActiveProxy();
   if (activeProxy != null)
   {
      DefaultProxySelector dps = new DefaultProxySelector();
      dps.add(convertFromMavenProxy(activeProxy), activeProxy.getNonProxyHosts());
      session.setProxySelector(dps);
   }

   final DefaultMirrorSelector mirrorSelector = createMirrorSelector(settings);
   final LazyAuthenticationSelector authSelector = createAuthSelector(settings, mirrorSelector);

   session.setMirrorSelector(mirrorSelector);
   session.setAuthenticationSelector(authSelector);

   LocalRepository localRepo = new LocalRepository(new File(settings.getLocalRepository()));
   session.setLocalRepositoryManager(repoSystem.newLocalRepositoryManager(session, localRepo));
   session.setChecksumPolicy(RepositoryPolicy.CHECKSUM_POLICY_IGNORE);
   session.setCache(new DefaultRepositoryCache());
   boolean cacheNotFoundArtifacts = true;
   boolean cacheTransferErrors = true;
   session.setResolutionErrorPolicy(new SimpleResolutionErrorPolicy(cacheNotFoundArtifacts, cacheTransferErrors));
   session.setWorkspaceReader(new ClasspathWorkspaceReader());
   if (Boolean.getBoolean("org.apache.maven.log_transfer"))
   {
      session.setTransferListener(new JULMavenTransferListener());
   }
   return session;
}
 
Example #18
Source File: PGPKeysServerClientTest.java    From pgpverify-maven-plugin with Apache License 2.0 5 votes vote down vote up
private void runProxyConfig(URI uri, Proxy proxy) throws IOException {
    PGPKeysServerClient pgpKeysServerClient = new PGPKeysServerClient(uri, 10_000, 10_000, 10_000, proxy) {
        @Override
        protected HttpClientBuilder createClientBuilder() {
            return null;
        }
    };
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    pgpKeysServerClient.setupProxy(httpClientBuilder);
    try (CloseableHttpClient closeableHttpClient = httpClientBuilder.build()) {
        // client can be created - cannot look inside if it actually worked because all setters are final.
        Assert.assertNotNull(closeableHttpClient);
    }
}
 
Example #19
Source File: PGPKeysServerClientTest.java    From pgpverify-maven-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testIfClientWithOutProxyIsIgnored2() throws URISyntaxException, IOException {
    URI uri = new URI("https://localhost/");
    Proxy proxy = makeMavenProxy(null, null);

    runProxyConfig(uri, proxy);
}
 
Example #20
Source File: PGPKeysServerClientTest.java    From pgpverify-maven-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testIfClientWithOutProxyIsIgnored() throws URISyntaxException, IOException {
    URI uri = new URI("https://localhost/");
    Proxy proxy = makeMavenProxy("", "");

    runProxyConfig(uri, proxy);
}
 
Example #21
Source File: PGPKeysServerClientTest.java    From pgpverify-maven-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testIfClientWithProxySetsProperties() throws URISyntaxException, IOException {
    URI uri = new URI("https://localhost/");
    Proxy proxy = makeMavenProxy("user", "password");

    runProxyConfig(uri, proxy);
}
 
Example #22
Source File: MavenRepositories.java    From furnace with Eclipse Public License 1.0 5 votes vote down vote up
static RemoteRepository convertToMavenRepo(final String id, String url, final Settings settings)
{
   RemoteRepository.Builder remoteRepositoryBuilder = new RemoteRepository.Builder(id, "default", url);
   Proxy activeProxy = settings.getActiveProxy();
   if (activeProxy != null)
   {
      Authentication auth = new AuthenticationBuilder().addUsername(activeProxy.getUsername())
               .addPassword(activeProxy.getPassword()).build();
      remoteRepositoryBuilder.setProxy(new org.eclipse.aether.repository.Proxy(activeProxy.getProtocol(),
               activeProxy
                        .getHost(),
               activeProxy.getPort(), auth));
   }
   return remoteRepositoryBuilder.build();
}
 
Example #23
Source File: MavenSettings.java    From spring-init with Apache License 2.0 5 votes vote down vote up
private ProxySelector createProxySelector(
		SettingsDecryptionResult decryptedSettings) {
	DefaultProxySelector selector = new DefaultProxySelector();
	for (Proxy proxy : decryptedSettings.getProxies()) {
		Authentication authentication = new AuthenticationBuilder()
				.addUsername(proxy.getUsername()).addPassword(proxy.getPassword())
				.build();
		selector.add(
				new org.eclipse.aether.repository.Proxy(proxy.getProtocol(),
						proxy.getHost(), proxy.getPort(), authentication),
				proxy.getNonProxyHosts());
	}
	return selector;
}
 
Example #24
Source File: ProxySettings.java    From mvn-golang with Apache License 2.0 5 votes vote down vote up
public ProxySettings(@Nonnull final Proxy mavenProxy) {
    this.protocol = mavenProxy.getProtocol();
    this.host = mavenProxy.getHost();
    this.port = mavenProxy.getPort();
    this.username = mavenProxy.getUsername();
    this.password = mavenProxy.getPassword();
    this.nonProxyHosts = mavenProxy.getNonProxyHosts();
}
 
Example #25
Source File: MavenMvnSettings.java    From galleon with Apache License 2.0 5 votes vote down vote up
MavenMvnSettings(MavenConfig config, RepositorySystem repoSystem, RepositoryListener listener) throws ArtifactException {
    this.config = config;
    Settings settings = buildMavenSettings(config.getSettings());
    Proxy proxy = settings.getActiveProxy();
    if (proxy != null) {
        MavenProxySelector.Builder builder = new MavenProxySelector.Builder(proxy.getHost(), proxy.getPort(), proxy.getProtocol());
        builder.setPassword(proxy.getPassword());
        builder.setUserName(proxy.getUsername());
        if (proxy.getNonProxyHosts() != null) {
            String[] hosts = proxy.getNonProxyHosts().split("\\|");
            builder.addNonProxyHosts(Arrays.asList(hosts));
        }
        proxySelector = builder.build();
        Authentication auth = null;
        if (proxy.getPassword() != null && proxy.getUsername() != null) {
            auth = new AuthenticationBuilder().addUsername(proxy.getUsername()).addPassword(proxy.getPassword()).build();
        }
        this.proxy = new org.eclipse.aether.repository.Proxy(proxy.getProtocol(), proxy.getHost(), proxy.getPort(), auth);
    } else {
        this.proxy = null;
        proxySelector = null;
    }
    try {
        repositories = Collections.unmodifiableList(buildRemoteRepositories(settings));
    } catch (MalformedURLException ex) {
        throw new ArtifactException(ex.getMessage(), ex);
    }
    session = Util.newRepositorySession(repoSystem,
            settings.getLocalRepository() == null ? config.getLocalRepository() : Paths.get(settings.getLocalRepository()),
            listener, proxySelector, settings.isOffline());
}
 
Example #26
Source File: PGPKeysServerClientHttps.java    From pgpverify-maven-plugin with Apache License 2.0 5 votes vote down vote up
protected PGPKeysServerClientHttps(URI uri, int connectTimeout, int readTimeout, int maxAttempts, Proxy proxy)
        throws IOException {

    super(prepareKeyServerURI(uri), connectTimeout, readTimeout, maxAttempts, proxy);

    try {
        if (uri.getHost().toLowerCase(Locale.ROOT).endsWith("sks-keyservers.net")) {
            final CertificateFactory cf = CertificateFactory.getInstance("X.509");
            final Certificate ca = cf.generateCertificate(
                    getClass().getClassLoader().getResourceAsStream("sks-keyservers.netCA.pem"));

            final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

            keyStore.load(null, null);
            keyStore.setCertificateEntry("ca", ca);

            final TrustManagerFactory tmf
                    = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            tmf.init(keyStore);

            final SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, tmf.getTrustManagers(), null);

            this.sslSocketFactory
                    = new SSLConnectionSocketFactory(
                    context, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
        } else {
            this.sslSocketFactory = SSLConnectionSocketFactory.getSystemSocketFactory();
        }
    } catch (CertificateException | KeyStoreException | NoSuchAlgorithmException | KeyManagementException e) {
        throw new IOException(e);
    }
}
 
Example #27
Source File: AbstractSwarmMojo.java    From wildfly-swarm with Apache License 2.0 5 votes vote down vote up
public static org.eclipse.aether.repository.Proxy convertFromMavenProxy(Proxy proxy) {
    if (proxy != null) {
        return  new org.eclipse.aether.repository.Proxy(proxy.getProtocol(),
                                                        proxy.getHost(),
                                                        proxy.getPort(),
                                                        new AuthenticationBuilder()
                                                                .addUsername(proxy.getUsername())
                                                                .addPassword(proxy.getPassword())
                                                                .build());
    }

    return null;
}
 
Example #28
Source File: RemoteExistsMojo.java    From exists-maven-plugin with Apache License 2.0 5 votes vote down vote up
ProxyInfo getProxyInfo() {
  Proxy proxy = settings.getActiveProxy();
  if (proxy == null) {
    return null;
  }

  ProxyInfo proxyInfo = new ProxyInfo();
  proxyInfo.setHost(proxy.getHost());
  proxyInfo.setType(proxy.getProtocol());
  proxyInfo.setPort(proxy.getPort());
  proxyInfo.setNonProxyHosts(proxy.getNonProxyHosts());
  proxyInfo.setUserName(proxy.getUsername());
  proxyInfo.setPassword(proxy.getPassword());
  return proxyInfo;
}
 
Example #29
Source File: GatewayAbstractMojo.java    From apigee-deploy-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Check hostname that matched nonProxy setting
 *
 * @param proxy    Maven Proxy. Must not null
 * @param hostname
 *
 * @return matching result. true: match nonProxy
 */
protected boolean matchNonProxy(final Proxy proxy, final String hostname) {

	// code from org.apache.maven.plugins.site.AbstractDeployMojo#getProxyInfo
	final String nonProxyHosts = proxy.getNonProxyHosts();
	if (null != nonProxyHosts) {
		final String[] nonProxies = nonProxyHosts.split("(,)|(;)|(\\|)");
		if (null != nonProxies) {
			for (final String nonProxyHost : nonProxies) {
				//if ( StringUtils.contains( nonProxyHost, "*" ) )
				if (null != nonProxyHost && nonProxyHost.contains("*")) {
					// Handle wildcard at the end, beginning or middle of the nonProxyHost
					final int pos = nonProxyHost.indexOf('*');
					String nonProxyHostPrefix = nonProxyHost.substring(0, pos);
					String nonProxyHostSuffix = nonProxyHost.substring(pos + 1);
					// prefix*
					if (!isBlank(nonProxyHostPrefix) && hostname.startsWith(nonProxyHostPrefix) && isBlank(nonProxyHostSuffix)) {
						return true;
					}
					// *suffix
					if (isBlank(nonProxyHostPrefix) && !isBlank(nonProxyHostSuffix) && hostname.endsWith(nonProxyHostSuffix)) {
						return true;
					}
					// prefix*suffix
					if (!isBlank(nonProxyHostPrefix) && hostname.startsWith(nonProxyHostPrefix)
							&& !isBlank(nonProxyHostSuffix) && hostname.endsWith(nonProxyHostSuffix)) {
						return true;
					}
				} else if (hostname.equals(nonProxyHost)) {
					return true;
				}
			}
		}
	}

	return false;
}
 
Example #30
Source File: GatewayAbstractMojo.java    From apigee-deploy-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Get the proxy configuration from the maven settings
 *
 * @param settings the maven settings
 * @param host     the host name of the apigee edge endpoint
 *
 * @return proxy or null if none was configured or the host was non-proxied
 */
protected Proxy getProxy(final Settings settings, final String host) {

	if (settings == null) {
		return null;
	}

	List<Proxy> proxies = settings.getProxies();

	if (proxies == null || proxies.isEmpty()) {
		return null;
	}

	String protocol = "https";
	String hostname = host;

	// check if protocol is present, if not assume https
	Matcher matcher = URL_PARSE_REGEX.matcher(host);
	if (matcher.matches()) {
		protocol = matcher.group(1);
		hostname = matcher.group(2);
	}

	// search active proxy
	for (Proxy proxy : proxies) {
		if (proxy.isActive() && protocol.equalsIgnoreCase(proxy.getProtocol()) && !matchNonProxy(proxy, hostname)) {
			if (settingsDecrypter != null) {
				return settingsDecrypter.decrypt(new DefaultSettingsDecryptionRequest(proxy)).getProxy();
			} else {
				getLog().warn("Maven did not inject SettingsDecrypter, " +
						"proxy may contain an encrypted password, which cannot be " +
						"used to setup the REST client.");
				return proxy;
			}
		}
	}
	return null;
}