Example usage for java.net ProxySelector getDefault

List of usage examples for java.net ProxySelector getDefault

Introduction

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

Prototype

public static ProxySelector getDefault() 

Source Link

Document

Gets the system-wide proxy selector.

Usage

From source file:org.ulteo.utils.ProxyManager.java

public void detect(String remoteHost) {
    Logger.debug("Detect proxy");
    List<Proxy> proxyList = null;
    System.setProperty("java.net.useSystemProxies", "true");
    ProxySelector ps = ProxySelector.getDefault();

    if (ps == null) {
        Logger.warn("Unable to detect a proxy: no proxySelector available");
        return;/*from  www .j  a va  2 s.com*/
    }
    try {
        URI uri = new URI("https://" + remoteHost);
        proxyList = ps.select(uri);
    } catch (URISyntaxException e) {
        Logger.warn("Unable to detect a proxy: bad URL");
        return;
    }
    if (proxyList != null) {
        for (Proxy proxy : proxyList) {
            InetSocketAddress addr = (InetSocketAddress) proxy.address();
            if (addr != null) {
                this.host = addr.getHostName();
                this.port = addr.getPort();
                System.setProperty("https.proxyHost", this.host);
                System.setProperty("https.proxyPort", new Integer(this.port).toString());
                Logger.debug("using proxy[" + this.host + ":" + this.port + "]");
                break;
            }
        }
    }
}

From source file:org.xwiki.extension.repository.xwiki.internal.httpclient.DefaultHttpClientFactory.java

@Override
public HttpClient createClient(String user, String password) {
    DefaultHttpClient httpClient = new DefaultHttpClient();

    httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, this.configuration.getUserAgent());
    httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);
    httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);

    // Setup proxy
    ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
            httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
    httpClient.setRoutePlanner(routePlanner);

    // Setup authentication
    if (user != null) {
        httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(user, password));
    }/*from   www.  j  a va2  s. c  om*/

    return httpClient;
}

From source file:cc.arduino.net.CustomProxySelector.java

public Proxy getProxyFor(URI uri) throws IOException, ScriptException, NoSuchMethodException {
    String proxyType = preferences.get(Constants.PREF_PROXY_TYPE);
    if (proxyType == null || proxyType.isEmpty()) {
        proxyType = Constants.PROXY_TYPE_AUTO;
    }/*from w  w  w .j  a v a2  s.  c om*/

    if (Constants.PROXY_TYPE_NONE.equals(proxyType)) {
        return Proxy.NO_PROXY;
    }

    if (Constants.PROXY_TYPE_AUTO.equals(proxyType)) {
        String pac = preferences.get(Constants.PREF_PROXY_PAC_URL);
        if (pac == null || pac.isEmpty()) {
            return ProxySelector.getDefault().select(uri).get(0);
        }

        return pacProxy(pac, uri);
    }

    if (Constants.PROXY_TYPE_MANUAL.equals(proxyType)) {
        return manualProxy();
    }

    throw new IllegalStateException("Unable to understand proxy settings");
}

From source file:org.kawanfw.test.parms.ProxyLoader.java

public Proxy getProxy() throws IOException, URISyntaxException {
    if (FrameworkSystemUtil.isAndroid()) {
        return null;
    }/*from  w w w  .ja  v a2 s  .c  o  m*/

    System.setProperty("java.net.useSystemProxies", "true");
    List<Proxy> proxies = ProxySelector.getDefault().select(new URI("http://www.google.com/"));

    if (proxies != null && proxies.size() >= 1) {
        System.out.println("Loading proxy file info...");

        if (proxies.get(0).type().equals(Proxy.Type.DIRECT)) {
            return null;
        }

        File file = new File(NEOTUNNEL_TXT);
        if (file.exists()) {
            String proxyValues = FileUtils.readFileToString(file);
            String username = StringUtils.substringBefore(proxyValues, " ");
            String password = StringUtils.substringAfter(proxyValues, " ");

            username = username.trim();
            password = password.trim();

            proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("localhost", 8080));

            passwordAuthentication = new PasswordAuthentication(username, password.toCharArray());

            System.out.println("USING PROXY WITH AUTHENTICATION: " + proxy + " / " + username + " " + password);
        } else {
            throw new FileNotFoundException("proxy values not found. No file " + file);
        }
    }

    return proxy;
}

From source file:org.kawanfw.file.test.parms.ProxyLoader.java

public Proxy getProxy() throws IOException, URISyntaxException {
    if (FrameworkSystemUtil.isAndroid()) {
        return null;
    }/*  w  w w .j ava2s. c  o  m*/

    System.setProperty("java.net.useSystemProxies", "true");
    List<Proxy> proxies = ProxySelector.getDefault().select(new URI("http://www.google.com/"));

    if (proxies != null && proxies.size() >= 1) {

        System.out.println("Proxy in use: " + proxies.get(0));

        if (proxies.get(0).type().equals(Proxy.Type.DIRECT)) {
            return null;
        }

        System.out.println("Loading proxy file info...");
        // System.setProperty("java.net.useSystemProxies", "false");
        File file = new File(NEOTUNNEL_TXT);
        if (file.exists()) {
            String proxyValues = FileUtils.readFileToString(file);
            String username = StringUtils.substringBefore(proxyValues, " ");
            String password = StringUtils.substringAfter(proxyValues, " ");

            //      proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(
            //         "127.0.0.1", 8080));
            proxy = proxies.get(0);

            passwordAuthentication = new PasswordAuthentication(username, password.toCharArray());

            System.out.println("USING PROXY WITH AUTHENTICATION: " + proxy + " / " + username + "-" + password);
        } else {
            throw new FileNotFoundException("proxy values not found. No file " + file);
        }
    }

    return proxy;
}

From source file:org.n52.oxf.util.web.ProxyAwareHttpClient.java

private ProxySelectorRoutePlanner createProxyPlanner() {
    DefaultHttpClient decoratedHttpClient = getHttpClientToDecorate();
    ClientConnectionManager connectionManager = decoratedHttpClient.getConnectionManager();
    SchemeRegistry schemeRegistry = connectionManager.getSchemeRegistry();
    ProxySelector defaultProxySelector = ProxySelector.getDefault();
    return new ProxySelectorRoutePlanner(schemeRegistry, defaultProxySelector);
}

From source file:org.n52.sps.util.http.SimpleHttpClient.java

private void initProxyAwareClient() {
    ClientConnectionManager connectionManager = httpclient.getConnectionManager();
    SchemeRegistry schemeRegistry = connectionManager.getSchemeRegistry();
    ProxySelector defaultProxySelector = ProxySelector.getDefault();
    ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(schemeRegistry,
            defaultProxySelector);//from  w  w  w.ja v  a2 s .c o  m
    httpclient.setRoutePlanner(routePlanner);
    httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);
}

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  ava2 s . c o  m
        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:net.orpiske.ssps.common.resource.HttpResourceExchange.java

/**
 * Default constructor: setups a default http client object and uses system
 * proxy information if available//w  w w.  ja v  a  2 s.c o  m
 */
public HttpResourceExchange() {
    ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
            httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());

    httpClient.setRoutePlanner(routePlanner);
}

From source file:org.hbird.estcube.mibreader.Parser.java

public void parse() throws Exception {

    if (proxyHost != null) {
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    } else {/* w  ww  .  j av a  2 s  .co m*/
        ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
                client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
        client.setRoutePlanner(routePlanner);
    }

    HttpResponse response = client.execute(new HttpGet(
            "http://tudengisatelliit.ut.ee:8001/svn/MCS/trunk/eu.estcube.sdc/src/main/resources/commands.xml"));

    Pattern commandPattern = Pattern.compile("<command>(.*?)</command>");
    Pattern commandNamePattern = Pattern.compile("<name>(.*?)</name>");
    Pattern commandDecriptionPattern = Pattern.compile("<description>(.*?)</description>");
    Pattern commandSystemPattern = Pattern.compile("<subsys>(.*?)</subsys>");
    Pattern commandArgumentPattern = Pattern.compile(
            "<param><description>(.*?)</description><name>(.*?)</name><type little_endian=\"true\">(.*?)</type></param>");

    if (response.getStatusLine().getStatusCode() == 200) {
        String text = readFully(response.getEntity().getContent()).replaceAll("(\\n|\\t|\\r)", "");

        LOG.info("File length with comments=" + text.length());
        /** Remove all comments */
        text = text.replaceAll("<!--(.*?)-->", "");
        LOG.info("File length without comments=" + text.length());

        /** Turn the part list into something easier to use. */
        Map<String, CommandableEntity> partsMap = new HashMap<String, CommandableEntity>();
        for (CommandableEntity part : parts) {
            partsMap.put(part.getName(), part);
        }

        /** Parse the XML */
        Matcher commandMatcher = commandPattern.matcher(text);
        while (commandMatcher.find()) {
            String commandDefintion = commandMatcher.group(1);

            Matcher nameMatcher = commandNamePattern.matcher(commandDefintion);
            nameMatcher.find();
            String name = nameMatcher.group(1);

            Matcher descriptionMatcher = commandDecriptionPattern.matcher(commandDefintion);
            descriptionMatcher.find();
            String description = descriptionMatcher.group(1);

            /** Create the command */
            Command command = new Command(name, description);

            Matcher subsysMatcher = commandSystemPattern.matcher(commandDefintion);
            while (subsysMatcher.find()) {
                String subsys = subsysMatcher.group(1);

                if (partsMap.containsKey(subsys)) {
                    LOG.info("Adding command '" + name + "' to part '" + subsys + "'.");
                    partsMap.get(subsys).addCommand(command);
                } else {
                    LOG.error("Found command for part '" + subsys
                            + "'. Parts is unknown. Check the Spring XML assembly.");
                }
            }

            Matcher argumentMatcher = commandArgumentPattern.matcher(commandDefintion);
            while (argumentMatcher.find()) {
                String argumentDescription = argumentMatcher.group(1);
                String argumentName = argumentMatcher.group(2);
                String argumentType = argumentMatcher.group(3);

                Class<?> type = null;
                if (argumentType.contains("int")) {
                    type = Integer.class;
                } else if (argumentType.contains("string")) {
                    type = String.class;
                } else {
                    LOG.error("Unknown type '" + argumentType + "'.");
                }

                LOG.info("Adding argument '" + argumentName + "' to command '" + name + "'.");
                command.addArgument(new CommandArgument(argumentName, argumentDescription, type, true));
            }
        }
    }

    for (CommandableEntity part : parts) {
        LOG.info("Publishing satellite part (subsystem) '" + part.getName() + "'");
        publisher.publish(part);
    }
}