Example usage for java.net ProxySelector setDefault

List of usage examples for java.net ProxySelector setDefault

Introduction

In this page you can find the example usage for java.net ProxySelector setDefault.

Prototype

public static void setDefault(ProxySelector ps) 

Source Link

Document

Sets (or unsets) the system-wide proxy selector.

Usage

From source file:io.fabric8.git.internal.GitDataStoreImpl.java

private void activateInternal() throws Exception {

    LOGGER.info("Starting up GitDataStore " + this);

    // Call the bootstrap {@link DataStoreTemplate}
    DataStoreTemplate template = runtimeProperties.get().removeRuntimeAttribute(DataStoreTemplate.class);
    if (template != null) {

        // Do the initial commit and set the root tag
        Ref rootTag = getGit().getRepository().getRef(GitHelpers.ROOT_TAG);
        if (rootTag == null) {
            getGit().commit().setMessage("First Commit").setCommitter("fabric", "user@fabric").call();
            getGit().tag().setName(GitHelpers.ROOT_TAG).setMessage("Tag the root commit").call();
        }// w w w.  j  a v a2 s. c om

        LOGGER.debug("Running datastore bootstrap template: " + template);
        template.doWith(this, dataStore.get());
    }

    // Setup proxy service
    GitProxyService proxyService = gitProxyService.get();
    defaultProxySelector = ProxySelector.getDefault();

    // authenticator disabled, until properly tested it does not affect others, as Authenticator is static in the JVM
    // Authenticator.setDefault(new FabricGitLocalHostAuthenticator(proxyService));
    ProxySelector fabricProxySelector = new FabricGitLocalHostProxySelector(defaultProxySelector, proxyService);
    ProxySelector.setDefault(fabricProxySelector);
    LOGGER.debug("Setting up FabricProxySelector: {}", fabricProxySelector);

    if (configuredUrl != null) {
        gitListener.runRemoteUrlChanged(configuredUrl);
        remoteUrl = configuredUrl;
    } else {
        gitService.get().addGitListener(gitListener);
        remoteUrl = gitService.get().getRemoteUrl();
        if (remoteUrl != null) {
            gitListener.runRemoteUrlChanged(remoteUrl);
        }
    }

    // Get initial versions
    getInitialVersions();

    LOGGER.info(
            "Using ZooKeeper SharedCount to react when master git repo is changed, so we can do a git pull to the local git repo.");
    counter = new SharedCount(curator.get(), ZkPath.GIT_TRIGGER.getPath(), 0);
    counter.addListener(new SharedCountListener() {
        @Override
        public void countHasChanged(final SharedCountReader sharedCountReader, final int value)
                throws Exception {
            threadPool.submit(new Runnable() {
                @Override
                public void run() {
                    LOGGER.info("Watch counter updated to " + value + ", doing a pull");
                    doPullInternal();
                }
            });
        }

        @Override
        public void stateChanged(CuratorFramework curatorFramework, ConnectionState connectionState) {
            switch (connectionState) {
            case CONNECTED:
            case RECONNECTED:
                LOGGER.info("Shared Counter (Re)connected, doing a pull");
                doPullInternal();
            }
        }
    });
    counter.start();

    //It is not safe to assume that we will get notified by the ShareCounter, if the component is not activated
    // when the SharedCounter gets updated.
    //Also we cannot rely on the remote url change event, as it will only trigger when there is an actual change.
    //So we should be awesome and always attempt a pull when we are activating if we don't want to loose stuff.
    doPullInternal();
}

From source file:io.fabric8.git.internal.GitDataStoreImpl.java

private void deactivateInternal() {

    // Remove the GitListener
    gitService.get().removeGitListener(gitListener);

    // Shutdown the thread pool
    threadPool.shutdown();//from  www .  ja va 2  s. c  o  m
    try {
        // Give some time to the running task to complete.
        if (!threadPool.awaitTermination(5, TimeUnit.SECONDS)) {
            threadPool.shutdownNow();
        }
    } catch (InterruptedException ex) {
        threadPool.shutdownNow();
        // Preserve interrupt status.
        Thread.currentThread().interrupt();
    } catch (Exception ex) {
        throw FabricException.launderThrowable(ex);
    }

    LOGGER.debug("Restoring ProxySelector to original: {}", defaultProxySelector);
    ProxySelector.setDefault(defaultProxySelector);
    // authenticator disabled, until properly tested it does not affect others, as Authenticator is static in the JVM
    // reset authenticator by setting it to null
    // Authenticator.setDefault(null);

    // Closing the shared counter
    try {
        counter.close();
    } catch (IOException ex) {
        LOGGER.warn("Error closing SharedCount due " + ex.getMessage() + ". This exception is ignored.");
    }
}

From source file:io.fabric8.git.internal.GitDataStore.java

@Override
protected void deactivateInternal() {
    try {//  w ww . java 2s. co  m
        GitService optsrv = gitService.getOptional();
        if (optsrv != null) {
            optsrv.removeGitListener(gitListener);
        }
        if (threadPool != null) {
            threadPool.shutdown();
            try {
                //Give some time to the running task to complete.
                if (!threadPool.awaitTermination(5, TimeUnit.SECONDS)) {
                    threadPool.shutdownNow();
                }
            } catch (InterruptedException ex) {
                threadPool.shutdownNow();
                // Preserve interrupt status.
                Thread.currentThread().interrupt();
            } catch (Exception ex) {
                throw FabricException.launderThrowable(ex);
            }
        }

        if (defaultProxySelector != null) {
            LOG.info("Restoring ProxySelector to original: {}", defaultProxySelector);
            ProxySelector.setDefault(defaultProxySelector);
            // authenticator disabled, until properly tested it does not affect others, as Authenticator is static in the JVM
            // reset authenticator by setting it to null
            // Authenticator.setDefault(null);
        }

        try {
            if (counter != null) {
                counter.close();
                counter = null;
            }
        } catch (IOException e) {
            LOG.warn("Error closing SharedCount due " + e.getMessage() + ". This exception is ignored.", e);
        }

    } finally {
        super.deactivateInternal();
    }
}

From source file:com.syncleus.maven.plugins.mongodb.StartMongoMojo.java

private void addProxySelector() {

    // Add authenticator with proxyUser and proxyPassword
    if (proxyUser != null && proxyPassword != null) {
        Authenticator.setDefault(new Authenticator() {
            @Override/*from w w  w . jav a2  s.  c om*/
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(proxyUser, proxyPassword.toCharArray());
            }
        });
    }

    final ProxySelector defaultProxySelector = ProxySelector.getDefault();
    ProxySelector.setDefault(new ProxySelector() {
        @Override
        public List<Proxy> select(final URI uri) {
            if (uri.getHost().equals("fastdl.mongodb.org")) {
                return singletonList(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)));
            } else {
                return defaultProxySelector.select(uri);
            }
        }

        @Override
        public void connectFailed(final URI uri, final SocketAddress sa, final IOException ioe) {
        }
    });
}

From source file:com.photon.phresco.framework.impl.SCMManagerImpl.java

void additionalAuthentication(String passPhrase) {
    final String passwordPhrase = passPhrase;
    JschConfigSessionFactory sessionFactory = new JschConfigSessionFactory() {
        @Override/*from   ww  w  .  jav  a  2s  .  c o  m*/
        protected void configure(OpenSshConfig.Host hc, Session session) {
            CredentialsProvider provider = new CredentialsProvider() {
                @Override
                public boolean isInteractive() {
                    return false;
                }

                @Override
                public boolean supports(CredentialItem... items) {
                    return true;
                }

                @Override
                public boolean get(URIish uri, CredentialItem... items) throws UnsupportedCredentialItem {
                    for (CredentialItem item : items) {
                        if (item instanceof CredentialItem.StringType) {
                            ((CredentialItem.StringType) item).setValue(passwordPhrase);
                        }
                    }
                    return true;
                }
            };
            UserInfo userInfo = new CredentialsProviderUserInfo(session, provider);
            // Unknown host key for ssh
            java.util.Properties config = new java.util.Properties();
            config.put(STRICT_HOST_KEY_CHECKING, NO);
            session.setConfig(config);

            session.setUserInfo(userInfo);
        }
    };

    SshSessionFactory.setInstance(sessionFactory);

    /*
     * Enable clone of https url by trusting those urls
     */
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    } };

    final String https_proxy = System.getenv(HTTPS_PROXY);
    final String http_proxy = System.getenv(HTTP_PROXY);

    ProxySelector.setDefault(new ProxySelector() {
        final ProxySelector delegate = ProxySelector.getDefault();

        @Override
        public List<Proxy> select(URI uri) {
            // Filter the URIs to be proxied

            if (uri.toString().contains(HTTPS) && StringUtils.isNotEmpty(http_proxy) && http_proxy != null) {
                try {
                    URI httpsUri = new URI(https_proxy);
                    String host = httpsUri.getHost();
                    int port = httpsUri.getPort();
                    return Arrays.asList(new Proxy(Type.HTTP, InetSocketAddress.createUnresolved(host, port)));
                } catch (URISyntaxException e) {
                    if (debugEnabled) {
                        S_LOGGER.debug("Url exception caught in https block of additionalAuthentication()");
                    }
                }
            }

            if (uri.toString().contains(HTTP) && StringUtils.isNotEmpty(http_proxy) && http_proxy != null) {
                try {
                    URI httpUri = new URI(http_proxy);
                    String host = httpUri.getHost();
                    int port = httpUri.getPort();
                    return Arrays.asList(new Proxy(Type.HTTP, InetSocketAddress.createUnresolved(host, port)));
                } catch (URISyntaxException e) {
                    if (debugEnabled) {
                        S_LOGGER.debug("Url exception caught in http block of additionalAuthentication()");
                    }
                }
            }

            // revert to the default behaviour
            return delegate == null ? Arrays.asList(Proxy.NO_PROXY) : delegate.select(uri);
        }

        @Override
        public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
            if (uri == null || sa == null || ioe == null) {
                throw new IllegalArgumentException("Arguments can't be null.");
            }
        }
    });

    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance(SSL);
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (GeneralSecurityException e) {
        e.getLocalizedMessage();
    }
}

From source file:org.dbflute.intro.app.logic.dfprop.TestConnectionLogic.java

public void testConnection(String dbfluteVersion, OptionalThing<String> jdbcDriverJarPath,
        DatabaseInfoMap databaseInfoMap) {
    final ProxySelector proxySelector = ProxySelector.getDefault();
    ProxySelector.setDefault(null);
    Connection connection = null;
    try {//ww w .  j a  v a2  s  .  c  om
        final Driver driver = prepareJdbcDriver(dbfluteVersion, jdbcDriverJarPath, databaseInfoMap);
        final Properties info = new Properties();
        final DbConnectionBox dbConnectionBox = databaseInfoMap.getDbConnectionBox();
        final String user = dbConnectionBox.getUser();
        if (DfStringUtil.is_NotNull_and_NotEmpty(user)) {
            info.put("user", user);
        }
        final String password = dbConnectionBox.getPassword();
        if (DfStringUtil.is_NotNull_and_NotEmpty(password)) {
            info.put("password", password);
        }
        logger.debug("...Connecting the database: " + databaseInfoMap);
        connection = driver.connect(dbConnectionBox.getUrl(), info);
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | MalformedURLException
            | SQLException e) {
        final String failureHint = e.getClass().getName() + " :: " + e.getMessage();
        throw new DatabaseConnectionException("Failed to test the connection: " + databaseInfoMap, failureHint,
                e);
    } finally {
        ProxySelector.setDefault(proxySelector);
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException ignored) {
            }
        }
    }
}

From source file:org.fuin.esmp.AbstractEventStoreMojo.java

private void addProxySelector(final String proxyHost, final int proxyPort, final String proxyUser,
        final String proxyPassword, final URL downloadUrl) throws URISyntaxException {

    // Add authenticator with proxyUser and proxyPassword
    if (proxyUser != null && proxyPassword != null) {
        Authenticator.setDefault(new Authenticator() {
            @Override/*from  ww  w. j  av  a2 s  .  c o m*/
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(proxyUser, proxyPassword.toCharArray());
            }
        });
    }
    final ProxySelector defaultProxySelector = ProxySelector.getDefault();

    final URI downloadUri = downloadUrl.toURI();

    ProxySelector.setDefault(new ProxySelector() {
        @Override
        public List<Proxy> select(final URI uri) {
            if (uri.getHost().equals(downloadUri.getHost()) && proxyHost != null && proxyHost.length() != 0) {
                return singletonList(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)));
            } else {
                return defaultProxySelector.select(uri);
            }
        }

        @Override
        public void connectFailed(final URI uri, final SocketAddress sa, final IOException ioe) {
        }
    });
}

From source file:org.seedstack.hub.infra.vcs.ProxySelectorService.java

@Override
public void started() {
    defaultProxySelector = ProxySelector.getDefault();
    initializeProxiesFromConfiguration();
    ProxySelector.setDefault(this);
}

From source file:org.seedstack.hub.infra.vcs.ProxySelectorService.java

@Override
public void stopping() {
    ProxySelector.setDefault(null);
}