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:net.sf.keystore_explorer.utilities.net.PacProxySelector.java

private String loadPacScript(String pacUrl) throws PacProxyException {
    URLConnection connection = null;

    // Save existing default proxy selector...
    ProxySelector defaultProxySelector = ProxySelector.getDefault();

    try {//w  w w  .  j av a 2s  .  co  m
        // ...and set use of no proxy selector. We don't want to try and use any proxy to get the the pac script
        ProxySelector.setDefault(new NoProxySelector());

        URL latestVersionUrl = new URL(pacUrl);
        connection = latestVersionUrl.openConnection();

        InputStreamReader isr = null;
        StringWriter sw = null;

        try {
            isr = new InputStreamReader(connection.getInputStream());
            sw = new StringWriter();

            CopyUtil.copy(isr, sw);

            return sw.toString();
        } finally {
            IOUtils.closeQuietly(isr);
            IOUtils.closeQuietly(sw);
        }
    } catch (IOException ex) {
        throw new PacProxyException(
                MessageFormat.format(res.getString("NoLoadPacScript.exception.message"), pacUrl), ex);
    } finally {
        // Restore saved default proxy selector
        ProxySelector.setDefault(defaultProxySelector);

        if ((connection != null) && (connection instanceof HttpURLConnection)) {
            ((HttpURLConnection) connection).disconnect();
        }
    }
}

From source file:es.eucm.eadventure.editor.plugin.vignette.ProxySetup.java

private static Proxy getProxy() {
    List<Proxy> l = null;
    try {/*from  w  w  w  .  j a va2s .  c om*/
        ProxySelector def = ProxySelector.getDefault();

        l = def.select(new URI("http://foo/bar"));
        ProxySelector.setDefault(null);
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (l != null) {
        for (Iterator<Proxy> iter = l.iterator(); iter.hasNext();) {
            java.net.Proxy proxy = iter.next();
            return proxy;
        }
    }
    return null;
}

From source file:com.clustercontrol.plugin.impl.ProxyManagerPlugin.java

@Override
public void activate() {
    ProxySelector.setDefault(new HinemosProxySelector(ProxySelector.getDefault()));
    Authenticator.setDefault(new HinemosAuthenticator());
}

From source file:com.microsoft.azure.servicebus.samples.queueswithproxy.QueuesWithProxy.java

public static int runApp(String[] args, Function<String, Integer> run) {
    try {/*from  w  w  w.j a  v  a  2  s .c om*/

        String connectionString;
        String proxyHostName;
        String proxyPortString;
        int proxyPort;

        // Add command line options and create parser
        Options options = new Options();
        options.addOption(new Option("c", true, "Connection string"));
        options.addOption(new Option("n", true, "Proxy hostname"));
        options.addOption(new Option("p", true, "Proxy port"));

        CommandLineParser clp = new DefaultParser();
        CommandLine cl = clp.parse(options, args);

        // Pull variables from command line options or environment variables
        connectionString = getOptionOrEnv(cl, "c", SB_SAMPLES_CONNECTIONSTRING);
        proxyHostName = getOptionOrEnv(cl, "n", SB_SAMPLES_PROXY_HOSTNAME);
        proxyPortString = getOptionOrEnv(cl, "p", SB_SAMPLES_PROXY_PORT);

        // Check for bad input
        if (StringUtil.isNullOrEmpty(connectionString) || StringUtil.isNullOrEmpty(proxyHostName)
                || StringUtil.isNullOrEmpty(proxyPortString)) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("run jar with", "", options, "", true);
            return 2;
        }

        if (!NumberUtils.isCreatable(proxyPortString)) {
            System.err.println("Please provide a numerical value for the port");
        }
        proxyPort = Integer.parseInt(proxyPortString);

        // ProxySelector set up for an HTTP proxy
        final ProxySelector systemDefaultSelector = ProxySelector.getDefault();
        ProxySelector.setDefault(new ProxySelector() {
            @Override
            public List<Proxy> select(URI uri) {
                if (uri != null && uri.getHost() != null && uri.getHost().equalsIgnoreCase(proxyHostName)) {
                    List<Proxy> proxies = new LinkedList<>();
                    proxies.add(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHostName, proxyPort)));
                    return proxies;
                }
                return systemDefaultSelector.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.");
                }
                systemDefaultSelector.connectFailed(uri, sa, ioe);
            }
        });

        return run.apply(connectionString);
    } catch (Exception e) {
        System.out.printf("%s", e.toString());
        return 3;
    }
}

From source file:org.springframework.cloud.config.server.environment.ConfigurableHttpConnectionFactoryIntegrationTests.java

@Test
public void httpProxy_fromSystemProperty() throws Exception {
    ProxySelector defaultProxySelector = ProxySelector.getDefault();
    try {/*from   w  ww.  java 2 s  .  c o m*/
        ProxySelector.setDefault(new ProxySelector() {
            @Override
            public List<Proxy> select(URI uri) {
                InetSocketAddress address = new InetSocketAddress(HTTP_PROXY.getHost(), HTTP_PROXY.getPort());
                Proxy proxy = new Proxy(Proxy.Type.HTTP, address);
                return Collections.singletonList(proxy);
            }

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

            }
        });
        String repoUrl = "https://myrepo/repo.git";
        new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE)
                .properties(new String[] { "spring.cloud.config.server.git.uri=" + repoUrl }).run();
        HttpClient httpClient = getHttpClientForUrl(repoUrl);
        this.expectedException.expectCause(allOf(instanceOf(UnknownHostException.class),
                hasProperty("message", containsString(HTTP_PROXY.getHost()))));

        makeRequest(httpClient, "http://somehost");
    } finally {
        ProxySelector.setDefault(defaultProxySelector);
    }
}

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

@Override
protected void activateInternal() {
    initialPull = false;//from w w  w.ja  va  2 s  .com

    try {
        super.activateInternal();

        if (gitProxyService.getOptional() != null) {
            // authenticator disabled, until properly tested it does not affect others, as Authenticator is static in the JVM
            // Authenticator.setDefault(new FabricGitLocalHostAuthenticator(gitProxyService.getOptional()));
            defaultProxySelector = ProxySelector.getDefault();
            ProxySelector fabricProxySelector = new FabricGitLocalHostProxySelector(defaultProxySelector,
                    gitProxyService.getOptional());
            ProxySelector.setDefault(fabricProxySelector);
            LOG.info("Setting up FabricProxySelector: {}", fabricProxySelector);
        }

        // [FIXME] Why can we not rely on the injected GitService
        GitService optionalService = gitService.getOptional();

        if (configuredUrl != null) {
            gitListener.onRemoteUrlChanged(configuredUrl);
            remoteUrl = configuredUrl;
        } else if (optionalService != null) {
            optionalService.addGitListener(gitListener);
            remoteUrl = optionalService.getRemoteUrl();
            gitListener.onRemoteUrlChanged(remoteUrl);
        }

        forceGetVersions();

        // import additional profiles
        Path homePath = getRuntimeProperties().getHomePath();
        Path dir = homePath.resolve(importDir);
        importFromFilesystem(dir);

        LOG.info("Starting to push to remote git repository every {} millis", gitPushInterval);
        threadPool.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                try {
                    // must do an initial pull to get data
                    if (!initialPull) {
                        LOG.trace("Performing initial pull");
                        pull();
                        initialPull = true;
                        LOG.debug("Performing initial pull done");
                    }

                    if (gitPullOnPush) {
                        LOG.trace("Performing timed pull");
                        pull();
                        LOG.debug("Performed timed pull done");
                    }
                    //a commit that failed to push for any reason, will not get pushed until the next commit.
                    //periodically pushing can address this issue.
                    LOG.trace("Performing timed push");
                    push();
                    LOG.debug("Performed timed push done");
                } catch (Throwable e) {
                    LOG.debug("Error during performed timed pull/push due " + e.getMessage(), e);
                    // we dont want stacktrace in WARNs
                    LOG.warn("Error during performed timed pull/push due " + e.getMessage()
                            + ". This exception is ignored.");
                }
            }

            @Override
            public String toString() {
                return "TimedPushTask";
            }
        }, 1000, gitPushInterval, TimeUnit.MILLISECONDS);
        // do the initial pull at first so just wait 1 sec

        if (!gitPullOnPush) {
            LOG.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(getCurator(), ZkPath.GIT_TRIGGER.getPath(), 0);
            counter.addListener(new SharedCountListener() {
                @Override
                public void countHasChanged(SharedCountReader sharedCountReader, int value) throws Exception {
                    LOG.debug("Watch counter updated to " + value + ", doing a pull");
                    try {
                        // must sleep a bit as otherwise we are too fast
                        Thread.sleep(1000);
                        pull();
                    } catch (Throwable e) {
                        LOG.debug("Error during pull due " + e.getMessage(), e);
                        // we dont want stacktrace in WARNs
                        LOG.warn("Error during pull due " + e.getMessage() + ". This exception is ignored.");
                    }
                }

                @Override
                public void stateChanged(CuratorFramework curatorFramework, ConnectionState connectionState) {
                    // ignore
                }
            });
            counter.start();
        }

    } catch (Exception ex) {
        throw new FabricException("Failed to start GitDataStore:", ex);
    }
}

From source file:de.ipk_gatersleben.ag_nw.graffiti.plugins.gui.webstart.MainM.java

public static void startVantedExt(String[] args, String[] developerAddon, String addPluginFile) {
    System.out.println("Welcome! About to start the application...");

    if (SystemInfo.isMac()) {
        try {/*  www .  j  av  a  2 s . com*/
            OSXAdapter.setFileHandler(new GravistoService(),
                    GravistoService.class.getDeclaredMethod("loadFile", new Class[] { String.class }));
        } catch (Exception err) {
            ErrorMsg.addErrorMessage(err);
        }
    }

    System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.NoOpLog");
    // System.setProperty("java.net.useSystemProxies","true");
    LoggingProxy ps = new LoggingProxy(ProxySelector.getDefault());
    ProxySelector.setDefault(ps);
    ReleaseInfo.setRunningReleaseStatus(Release.RELEASE_PUBLIC);

    GravistoMainHelper.setLookAndFeel();

    String stS = "<font color=\"#9500C0\"><b>";
    String stE = "</b></font>";
    String name = stS + "VANTED" + stE + " - " + stS + "V" + stE + "isualization and " + stS + "A" + stE
            + "nalysis of " + stS + "N" + stE + "e" + stS + "t" + stE + "works <br>containing " + stS + "E"
            + stE + "xperimental " + stS + "D" + stE + "ata";
    JComponent result = new JPanel();
    result.setLayout(TableLayout.getLayout(TableLayoutConstants.FILL, TableLayoutConstants.FILL));

    String s = "" + "<html><small><br>&nbsp;&nbsp;&nbsp;</small>Welcome to " + name.replaceAll("<br>", "")
            + "!<br>" + "<small>"
            + "&nbsp;&nbsp;&nbsp;In the <b>Help menu</b> you find a <b>tutorial section</b> which "
            + "quickly gives an overview on the various features of this application.<br>"
            + "&nbsp;&nbsp;&nbsp;Furthermore you will find <b>[?] buttons</b> throughout the "
            + "system which point directly to topics of interest.<br>"
            + "&nbsp;&nbsp;&nbsp;If you experience problems or would like to suggest enhancements, "
            + "feel free to use the <b>Send feedback command</b> in the Help menu!<br>&nbsp;";

    if (!ReleaseInfo.getIsAllowedFeature(FeatureSet.GravistoJavaHelp))
        s = "" + "<html><small>&nbsp;&nbsp;&nbsp;</small>Welcome to " + name.replaceAll("<br>", "") + "!"
                + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<font color='gray'>"
                + DBEgravistoHelper.DBE_GRAVISTO_VERSION_CODE_SUBVERSION + "</small>";// <br>"
    // +
    // "<small>" +
    // "&nbsp;&nbsp;&nbsp;The help functions may be enabled from the side panel <b>Help/Settings</b>.<br>" +
    // "&nbsp;&nbsp;&nbsp;If you experience problems or would like to suggest enhancements, " +
    // "feel free to use the <b>Send feedback command</b> in the Help menu!";

    ReleaseInfo.setHelpIntroductionText(s);

    DBEgravistoHelper.DBE_GRAVISTO_VERSION = "VANTED V" + DBEgravistoHelper.DBE_GRAVISTO_VERSION_CODE;
    DBEgravistoHelper.DBE_GRAVISTO_NAME = stS + "VANTED" + stE + "&nbsp;-&nbsp;" + stS + "V" + stE
            + "isualization&nbsp;and&nbsp;" + stS + "A" + stE + "nalysis&nbsp;of&nbsp;" + stS + "N" + stE + "e"
            + stS + "t" + stE + "works&nbsp;<br>containing&nbsp;" + stS + "E" + stE + "xperimental&nbsp;" + stS
            + "D" + stE + "ata<br>";
    DBEgravistoHelper.DBE_GRAVISTO_NAME_SHORT = "VANTED";
    DBEgravistoHelper.DBE_INFORMATIONSYSTEM_NAME = "";

    AttributeHelper.setMacOSsettings(DBEgravistoHelper.DBE_GRAVISTO_NAME_SHORT);

    new MainM(true, DBEgravistoHelper.DBE_GRAVISTO_VERSION, args, developerAddon, addPluginFile);
}

From source file:org.whitesource.agent.client.WssServiceClientImpl.java

private void findDefaultProxy() {
    ProxySearch proxySearch = new ProxySearch();
    proxySearch.addStrategy(ProxySearch.Strategy.JAVA);
    proxySearch.addStrategy(ProxySearch.Strategy.ENV_VAR);
    proxySearch.addStrategy(ProxySearch.Strategy.OS_DEFAULT);
    proxySearch.addStrategy(ProxySearch.Strategy.BROWSER);
    ProxySelector proxySelector = proxySearch.getProxySelector();

    if (proxySelector != null) {
        ProxySelector.setDefault(proxySelector);
        try {//from   w w  w  . j a v  a2  s. c  o m
            List<Proxy> proxyList = proxySelector.select(new URI(serviceUrl));
            if (proxyList != null && !proxyList.isEmpty()) {
                for (Proxy proxy : proxyList) {
                    InetSocketAddress address = (InetSocketAddress) proxy.address();
                    if (address != null) {
                        String host = address.getHostName();
                        int port = address.getPort();
                        String username = System.getProperty(HTTP_PROXY_USER);
                        String password = System.getProperty(HTTP_PROXY_PASSWORD);
                        setProxy(host, port, username, password);
                    }
                }
            }
        } catch (URISyntaxException e) {
            logger.error("Bad service url: " + serviceUrl, e);
        }
    }
}