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:com.marvelution.hudson.plugins.apiv2.client.connectors.HttpClient3Connector.java

/**
 * Get the first available {@link Proxy} using the {@link ProxySelector} implementation
 * //from ww  w  .  j a  va 2  s .  com
 * @return the first {@link Type#HTTP} proxy available, or {@link Proxy#NO_PROXY} if no
 *         proxy is available
 */
private Proxy chooseProxy() {
    try {
        for (Proxy proxy : ProxySelector.getDefault().select(new URI(server.getHost()))) {
            if (proxy.type() == Type.HTTP) {
                return proxy;
            }
        }
    } catch (URISyntaxException e) {
        // Failed to parse the server host URI
        // Fallback to the default NO_PROXY
        log.error("Failed to parse the host URI", e);
    }
    return Proxy.NO_PROXY;
}

From source file:org.xwiki.extension.repository.xwiki.internal.resources.ExtensionVersionFileRESTResource.java

private ResponseBuilder downloadLocalExtension(String extensionId, String extensionVersion)
        throws ResolveException, IOException, QueryException, XWikiException {
    XWikiDocument extensionDocument = getExistingExtensionDocumentById(extensionId);

    checkRights(extensionDocument);/*from   w  ww  .  j  av  a 2s  . c  o  m*/

    BaseObject extensionObject = getExtensionObject(extensionDocument);
    BaseObject extensionVersionObject = getExtensionVersionObject(extensionDocument, extensionVersion);

    ResponseBuilder response = null;

    ResourceReference resourceReference = this.repositoryManager.getDownloadReference(extensionDocument,
            extensionVersionObject);

    if (ResourceType.ATTACHMENT.equals(resourceReference.getType())) {
        // It's an attachment
        AttachmentReference attachmentReference = this.attachmentResolver
                .resolve(resourceReference.getReference(), extensionDocument.getDocumentReference());

        XWikiContext xcontext = getXWikiContext();

        XWikiDocument document = xcontext.getWiki().getDocument(attachmentReference.getDocumentReference(),
                xcontext);

        checkRights(document);

        XWikiAttachment xwikiAttachment = document.getAttachment(attachmentReference.getName());

        response = getAttachmentResponse(xwikiAttachment);
    } else if (ResourceType.URL.equals(resourceReference.getType())) {
        // It's an URL
        URL url = new URL(resourceReference.getReference());

        DefaultHttpClient httpClient = new DefaultHttpClient();

        httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "XWikiExtensionRepository");
        httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);
        httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);

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

        HttpGet getMethod = new HttpGet(url.toString());

        HttpResponse subResponse;
        try {
            subResponse = httpClient.execute(getMethod);
        } catch (Exception e) {
            throw new IOException("Failed to request [" + getMethod.getURI() + "]", e);
        }

        response = Response.status(subResponse.getStatusLine().getStatusCode());

        // TODO: find a proper way to do a perfect proxy of the URL without directly using Restlet classes.
        // Should probably use javax.ws.rs.ext.MessageBodyWriter
        HttpEntity entity = subResponse.getEntity();
        InputRepresentation content = new InputRepresentation(entity.getContent(),
                new MediaType(entity.getContentType().getValue()), entity.getContentLength());

        String type = getValue(extensionObject, XWikiRepositoryModel.PROP_EXTENSION_TYPE);

        Disposition disposition = new Disposition(Disposition.TYPE_ATTACHMENT);
        disposition.setFilename(extensionId + '-' + extensionVersion + '.' + type);
        content.setDisposition(disposition);

        response.entity(content);
    } else if (ExtensionResourceReference.TYPE.equals(resourceReference.getType())) {
        ExtensionResourceReference extensionResource;
        if (resourceReference instanceof ExtensionResourceReference) {
            extensionResource = (ExtensionResourceReference) resourceReference;
        } else {
            extensionResource = new ExtensionResourceReference(resourceReference.getReference());
        }

        response = downloadRemoteExtension(extensionResource);
    } else {
        throw new WebApplicationException(Status.NOT_FOUND);
    }

    return response;
}

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:org.sonar.plugins.github.GitHubPluginConfiguration.java

public Proxy getHttpProxy() {
    try {//  www  .  j a  v  a  2 s . co  m
        if (system2.property(HTTP_PROXY_HOSTNAME) != null && system2.property(HTTPS_PROXY_HOSTNAME) == null) {
            System.setProperty(HTTPS_PROXY_HOSTNAME, system2.property(HTTP_PROXY_HOSTNAME));
            System.setProperty(HTTPS_PROXY_PORT, system2.property(HTTP_PROXY_PORT));
        }

        String proxyUser = system2.property(HTTP_PROXY_USER);
        String proxyPass = system2.property(HTTP_PROXY_PASS);

        if (proxyUser != null && proxyPass != null) {
            Authenticator.setDefault(new Authenticator() {
                @Override
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(proxyUser, proxyPass.toCharArray());
                }
            });
        }

        Proxy selectedProxy = ProxySelector.getDefault().select(new URI(endpoint())).get(0);

        if (selectedProxy.type() == Proxy.Type.DIRECT) {
            LOG.debug("There was no suitable proxy found to connect to GitHub - direct connection is used ");
        }

        LOG.info("A proxy has been configured - {}", selectedProxy.toString());
        return selectedProxy;
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException(
                "Unable to perform GitHub WS operation - endpoint in wrong format: " + endpoint(), e);
    }
}

From source file:gov.nih.nci.nbia.StandaloneDMV2.java

private static List<String> connectAndReadFromURL(URL url, String fileName, String userId, String passWd) {
    List<String> data = null;
    DefaultHttpClient httpClient = null;
    TrustStrategy easyStrategy = new TrustStrategy() {
        @Override// www.  ja va2  s  . c  o m
        public boolean isTrusted(X509Certificate[] certificate, String authType) throws CertificateException {
            return true;
        }
    };
    try {
        // SSLContext sslContext = SSLContext.getInstance("SSL");
        // set up a TrustManager that trusts everything
        // sslContext.init(null, new TrustManager[] { new
        // EasyX509TrustManager(null)}, null);

        SSLSocketFactory sslsf = new SSLSocketFactory(easyStrategy,
                SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Scheme httpsScheme = new Scheme("https", 443, sslsf);
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(httpsScheme);
        schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
        ClientConnectionManager ccm = new ThreadSafeClientConnManager(schemeRegistry);

        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, 50000);
        HttpConnectionParams.setSoTimeout(httpParams, new Integer(12000));
        httpClient = new DefaultHttpClient(ccm, httpParams);
        httpClient.setRoutePlanner(new ProxySelectorRoutePlanner(schemeRegistry, ProxySelector.getDefault()));
        // // Additions by lrt for tcia -
        // // attempt to reduce errors going through a Coyote Point
        // Equalizer load balance switch
        httpClient.getParams().setParameter("http.socket.timeout", new Integer(12000));
        httpClient.getParams().setParameter("http.socket.receivebuffer", new Integer(16384));
        httpClient.getParams().setParameter("http.tcp.nodelay", true);
        httpClient.getParams().setParameter("http.connection.stalecheck", false);
        // // end lrt additions

        HttpPost httpPostMethod = new HttpPost(url.toString());

        List<BasicNameValuePair> postParams = new ArrayList<BasicNameValuePair>();
        postParams.add(new BasicNameValuePair("serverManifestLoc", fileName));
        if (userId != null && passWd != null) {
            postParams.add(new BasicNameValuePair("userId", userId));
            httpPostMethod.addHeader("password", passWd);
        }

        UrlEncodedFormEntity query = new UrlEncodedFormEntity(postParams);
        httpPostMethod.setEntity(query);
        HttpResponse response = httpClient.execute(httpPostMethod);
        int responseCode = response.getStatusLine().getStatusCode();
        // System.out.println("!!!!!Response code for requesting datda file:
        // " + responseCode);

        if (responseCode != HttpURLConnection.HTTP_OK) {
            return null;
        } else {
            InputStream inputStream = response.getEntity().getContent();
            data = IOUtils.readLines(inputStream);
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (httpClient != null) {
            httpClient.getConnectionManager().shutdown();
        }
    }
    return data;
}

From source file:org.apache.droids.protocol.http.DroidsHttpClient.java

/**
 * Added ProxySelectorRoutePlanner to support JVM Proxy Settings
 */// w w  w .j a  v  a  2  s.c  o m
@Override
protected HttpRoutePlanner createHttpRoutePlanner() {
    return new ProxySelectorRoutePlanner(this.getConnectionManager().getSchemeRegistry(),
            ProxySelector.getDefault());
}

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

public static int runApp(String[] args, Function<String, Integer> run) {
    try {/*  w  ww. j a v a2  s.co m*/

        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:com.kolich.http.HttpClient4ClosureBuilder.java

public HttpClientBuilder getHttpClientBuilder() {
    final HttpClientBuilder builder = HttpClients.custom().setDefaultRequestConfig(getRequestConfig())
            .setConnectionManager(getConnectionManager()).setUserAgent(userAgent_);
    // See http://stackoverflow.com/questions/21818242/with-httpclient-4-3-x-executing-a-httphead-for-a-specific-url-gives-nohttprespo
    // Also, see https://issues.apache.org/jira/browse/HTTPCLIENT-1464
    // This disables the addition of the `Accept-Encoding: gzip,deflate`
    // header on outgoing requests which seems to confuse some servers.
    // This is off by default, but can be turned off if desired.
    if (disableContentCompression_) {
        builder.disableContentCompression();
    }//from w ww  . j a va2  s  . co m
    if (disableAutomaticRetries_) {
        builder.disableAutomaticRetries();
    }
    if (disableAuthCaching_) {
        builder.disableAuthCaching();
    }
    if (useProxySelector_) {
        builder.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault()));
    }
    return builder;
}