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.eclipse.egit.github.core.service.DownloadService.java

/**
 * Create client to use to upload a resource to
 *
 * @return non-null http client/*from   w  w w .ja va 2s  .c o m*/
 */
protected HttpClient createDownloadClient() {
    DefaultHttpClient client = new DefaultHttpClient();
    client.setRoutePlanner(new ProxySelectorRoutePlanner(client.getConnectionManager().getSchemeRegistry(),
            ProxySelector.getDefault()));
    return client;
}

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

@Test
public void httpProxy_fromSystemProperty() throws Exception {
    ProxySelector defaultProxySelector = ProxySelector.getDefault();
    try {//from   ww w . ja v a2  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:com.xmlcalabash.library.ApacheHttpRequest.java

public void run() throws SaxonApiException {
    super.run();//from   w  w w  . j a  v a2  s . c  o  m

    XdmNode requestDoc = source.read();
    XdmNode start = S9apiUtils.getDocumentElement(requestDoc);

    if (!c_request.equals(start.getNodeName())) {
        throw new UnsupportedOperationException("Not a c:http-request!");
    }

    // Check for valid attributes
    XdmSequenceIterator iter = start.axisIterator(Axis.ATTRIBUTE);
    boolean ok = true;
    while (iter.hasNext()) {
        XdmNode attr = (XdmNode) iter.next();
        QName name = attr.getNodeName();
        if (_method.equals(name) || _href.equals(name) || _detailed.equals(name) || _status_only.equals(name)
                || _username.equals(name) || _password.equals(name) || _auth_method.equals(name)
                || _send_authorization.equals(name) || _override_content_type.equals(name)) {
            // nop
        } else {
            if (XMLConstants.DEFAULT_NS_PREFIX.equals(name.getNamespaceURI())) {
                throw new XProcException("Unsupported attribute on c:http-request: " + name);
            }
        }
    }

    method = start.getAttributeValue(_method);
    statusOnly = "true".equals(start.getAttributeValue(_status_only));
    detailed = "true".equals(start.getAttributeValue(_detailed));
    overrideContentType = start.getAttributeValue(_override_content_type);

    if (start.getAttributeValue(_href) == null) {
        throw new XProcException("The 'href' attribute must be specified on p:http-request");
    }

    requestURI = start.getBaseURI().resolve(start.getAttributeValue(_href));

    if ("file".equals(requestURI.getScheme())) {
        doFile();
        return;
    }

    client = new HttpClient();

    String timeOutStr = step.getExtensionAttribute(cx_timeout);
    if (timeOutStr != null) {
        HttpMethodParams params = client.getParams();
        params.setSoTimeout(Integer.parseInt(timeOutStr));
    }

    ProxySelector proxySelector = ProxySelector.getDefault();
    List<Proxy> plist = proxySelector.select(requestURI);
    // I have no idea what I'm expected to do if I get more than one...
    if (plist.size() > 0) {
        Proxy proxy = plist.get(0);
        switch (proxy.type()) {
        case DIRECT:
            // nop;
            break;
        case HTTP:
            // This can't cause a ClassCastException, right?
            InetSocketAddress addr = (InetSocketAddress) proxy.address();
            String host = addr.getHostName();
            int port = addr.getPort();
            client.getHostConfiguration().setProxy(host, port);
            break;
        default:
            // FIXME: send out a log message
            break;
        }
    }

    if (start.getAttributeValue(_username) != null) {
        String user = start.getAttributeValue(_username);
        String pass = start.getAttributeValue(_password);
        String meth = start.getAttributeValue(_auth_method);

        if (meth == null || !("basic".equals(meth.toLowerCase()) || "digest".equals(meth.toLowerCase()))) {
            throw XProcException.stepError(3, "Unsupported auth-method: " + meth);
        }

        String host = requestURI.getHost();
        int port = requestURI.getPort();
        AuthScope scope = new AuthScope(host, port);

        UsernamePasswordCredentials cred = new UsernamePasswordCredentials(user, pass);

        client.getState().setCredentials(scope, cred);
    }

    iter = start.axisIterator(Axis.CHILD);
    XdmNode body = null;
    while (iter.hasNext()) {
        XdmNode event = (XdmNode) iter.next();
        // FIXME: What about non-whitespace text nodes?
        if (event.getNodeKind() == XdmNodeKind.ELEMENT) {
            if (body != null) {
                throw new UnsupportedOperationException("Elements follow c:multipart or c:body");
            }

            if (XProcConstants.c_header.equals(event.getNodeName())) {
                headers.add(new Header(event.getAttributeValue(_name), event.getAttributeValue(_value)));
            } else if (XProcConstants.c_multipart.equals(event.getNodeName())
                    || XProcConstants.c_body.equals(event.getNodeName())) {
                body = event;
            } else {
                throw new UnsupportedOperationException("Unexpected request element: " + event.getNodeName());
            }
        }
    }

    HttpMethodBase httpResult;

    if (method == null) {
        throw new XProcException("Method must be specified.");
    }

    if ("get".equals(method.toLowerCase())) {
        httpResult = doGet();
    } else if ("post".equals(method.toLowerCase())) {
        httpResult = doPost(body);
    } else if ("put".equals(method.toLowerCase())) {
        httpResult = doPut(body);
    } else if ("head".equals(method.toLowerCase())) {
        httpResult = doHead();
    } else {
        throw new UnsupportedOperationException("Unrecognized http method: " + method);
    }

    TreeWriter tree = new TreeWriter(runtime);
    tree.startDocument(requestURI);

    try {
        // Execute the method.
        int statusCode = client.executeMethod(httpResult);

        String contentType = getContentType(httpResult);
        if (overrideContentType != null) {
            if ((xmlContentType(contentType) && overrideContentType.startsWith("image/"))
                    || (contentType.startsWith("text/") && overrideContentType.startsWith("image/"))
                    || (contentType.startsWith("image/") && xmlContentType(overrideContentType))
                    || (contentType.startsWith("image/") && overrideContentType.startsWith("text/"))
                    || (contentType.startsWith("multipart/") && !overrideContentType.startsWith("multipart/"))
                    || (!contentType.startsWith("multipart/")
                            && overrideContentType.startsWith("multipart/"))) {
                throw XProcException.stepError(30);
            }

            //System.err.println(overrideContentType + " overrides " + contentType);
            contentType = overrideContentType;
        }

        if (detailed) {
            tree.addStartElement(XProcConstants.c_response);
            tree.addAttribute(_status, "" + statusCode);
            tree.startContent();

            for (Header header : httpResult.getResponseHeaders()) {
                // I don't understand why/how HeaderElement parsing works. I get very weird results.
                // So I'm just going to go the long way around...
                String h = header.toString();
                int cp = h.indexOf(":");
                String name = header.getName();
                String value = h.substring(cp + 1).trim();

                tree.addStartElement(XProcConstants.c_header);
                tree.addAttribute(_name, name);
                tree.addAttribute(_value, value);
                tree.startContent();
                tree.addEndElement();
            }

            if (statusOnly) {
                // Skip reading the result
            } else {
                // Read the response body.
                InputStream bodyStream = httpResult.getResponseBodyAsStream();
                readBodyContent(tree, bodyStream, httpResult);
            }

            tree.addEndElement();
        } else {
            if (statusOnly) {
                // Skip reading the result
            } else {
                // Read the response body.
                InputStream bodyStream = httpResult.getResponseBodyAsStream();
                readBodyContent(tree, bodyStream, httpResult);
            }
        }
    } catch (Exception e) {
        throw new XProcException(e);
    } finally {
        // Release the connection.
        httpResult.releaseConnection();
    }

    tree.endDocument();

    XdmNode resultNode = tree.getResult();

    result.write(resultNode);
}

From source file:com.servoy.extensions.plugins.http.HttpProvider.java

public static void setHttpClientProxy(DefaultHttpClient client, String url, String proxyUser,
        String proxyPassword) {//from   ww  w  . j  a v a  2  s . c  om
    String proxyHost = null;
    int proxyPort = 8080;
    try {
        System.setProperty("java.net.useSystemProxies", "true");
        URI uri = new URI(url);
        List<Proxy> proxies = ProxySelector.getDefault().select(uri);
        if (proxies != null && client != null) {
            for (Proxy proxy : proxies) {
                if (proxy.address() != null && proxy.address() instanceof InetSocketAddress) {
                    InetSocketAddress address = (InetSocketAddress) proxy.address();
                    proxyHost = address.getHostName();
                    HttpHost host = new HttpHost(address.getHostName(), address.getPort());
                    client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, host);
                    break;
                }
            }
        }
    } catch (Exception ex) {
        Debug.log(ex);
    }

    if (proxyHost == null && System.getProperty("http.proxyHost") != null
            && !"".equals(System.getProperty("http.proxyHost"))) {
        proxyHost = System.getProperty("http.proxyHost");
        try {
            proxyPort = Integer.parseInt(System.getProperty("http.proxyPort"));
        } catch (Exception ex) {
            //ignore
        }
        HttpHost host = new HttpHost(proxyHost, proxyPort);
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, host);
    }

    if (proxyUser != null) {
        BasicCredentialsProvider bcp = new BasicCredentialsProvider();
        bcp.setCredentials(new AuthScope(proxyHost, proxyPort),
                new UsernamePasswordCredentials(proxyUser, proxyPassword));
        client.setCredentialsProvider(bcp);
    }
}

From source file:davmail.http.DavGatewayHttpClientFacade.java

/**
 * Retrieve Proxy Selector//from   w w  w .j av  a2 s .c  om
 *
 * @param uri target uri
 * @return proxy selector
 */
private static List<Proxy> getProxyForURI(java.net.URI uri) {
    LOGGER.debug("get Default proxy selector");
    ProxySelector proxySelector = ProxySelector.getDefault();
    LOGGER.debug("getProxyForURI(" + uri + ')');
    List<Proxy> proxies = proxySelector.select(uri);
    LOGGER.debug("got system proxies:" + proxies);
    return proxies;
}

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

@Override
protected void activateInternal() {
    initialPull = false;//from w  w  w  .  j a v a2 s .c  o m

    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:org.codegist.crest.HttpClientRestService.java

public static RestService newRestService(int maxConcurrentConnection, int maxConnectionPerRoute) {
    DefaultHttpClient httpClient;/* ww  w . j  a va2s. co  m*/
    if (maxConcurrentConnection > 1 || maxConnectionPerRoute > 1) {
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        if (maxConnectionPerRoute > 1) {
            ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(maxConnectionPerRoute));
        }
        if (maxConcurrentConnection > 1) {
            ConnManagerParams.setMaxTotalConnections(params, maxConcurrentConnection);
        } else {
            ConnManagerParams.setMaxTotalConnections(params, 1);
        }

        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

        ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
        httpClient = new DefaultHttpClient(cm, params);
    } else {
        httpClient = new DefaultHttpClient();
    }
    httpClient.setRoutePlanner(new ProxySelectorRoutePlanner(
            httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()));
    return new HttpClientRestService(httpClient);
}

From source file:org.expath.httpclient.impl.ApacheHttpConnection.java

/**
 * Make a new Apache HTTP client, in order to serve this request.
 *///from w w  w .j  a  v a2 s.c  o  m
private AbstractHttpClient makeClient() {
    AbstractHttpClient client = new DefaultHttpClient();
    HttpParams params = client.getParams();
    // use the default JVM proxy settings (http.proxyHost, etc.)
    HttpRoutePlanner route = new ProxySelectorRoutePlanner(client.getConnectionManager().getSchemeRegistry(),
            ProxySelector.getDefault());
    client.setRoutePlanner(route);
    // do follow redirections?
    params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, myFollowRedirect);
    // set the timeout if any
    if (myTimeout != null) {
        // See http://blog.jayway.com/2009/03/17/configuring-timeout-with-apache-httpclient-40/
        HttpConnectionParams.setConnectionTimeout(params, myTimeout * 1000);
        HttpConnectionParams.setSoTimeout(params, myTimeout * 1000);
    }
    // the shared cookie store
    client.setCookieStore(COOKIES);
    // the HTTP version (1.0 or 1.1)
    params.setParameter("http.protocol.version", myVersion);
    // return the just built client
    return client;
}

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 {/*from  w  w  w .  j ava  2  s. c  o  m*/
            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.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// w ww .jav  a 2 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) {
        }
    });
}