Example usage for org.apache.http.auth AuthScope AuthScope

List of usage examples for org.apache.http.auth AuthScope AuthScope

Introduction

In this page you can find the example usage for org.apache.http.auth AuthScope AuthScope.

Prototype

public AuthScope(final String host, final int port) 

Source Link

Document

Creates a new credentials scope for the given host, port, any realm name, and any authentication scheme.

Usage

From source file:eu.esdihumboldt.util.http.ProxyUtil.java

/**
 * Set-up the given HTTP client to use the given proxy
 * /*from   w w w .  ja v  a2s.  co m*/
 * @param builder the HTTP client builder
 * @param proxy the proxy
 * @return the client builder adapted with the proxy settings
 */
public static HttpClientBuilder applyProxy(HttpClientBuilder builder, Proxy proxy) {
    init();

    // check if proxy shall be used
    if (proxy != null && proxy.type() == Type.HTTP) {
        InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address();

        // set the proxy
        HttpHost proxyHost = new HttpHost(proxyAddress.getHostName(), proxyAddress.getPort());
        builder = builder.setProxy(proxyHost);

        String user = System.getProperty("http.proxyUser"); //$NON-NLS-1$
        String password = System.getProperty("http.proxyPassword"); //$NON-NLS-1$
        boolean useProxyAuth = user != null && !user.isEmpty();

        if (useProxyAuth) {
            // set the proxy credentials
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(proxyAddress.getHostName(), proxyAddress.getPort()),
                    new UsernamePasswordCredentials(user, password));
            builder = builder.setDefaultCredentialsProvider(credsProvider)
                    .setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
        }

        _log.trace("Set proxy to " + proxyAddress.getHostName() + ":" + //$NON-NLS-1$ //$NON-NLS-2$
                proxyAddress.getPort() + ((useProxyAuth) ? (" as user " + user) : (""))); //$NON-NLS-1$ //$NON-NLS-2$
    }

    return builder;
}

From source file:com.ibm.watson.developer_cloud.retrieve_and_rank.RetrieveAndRankSolrJExample.java

private static HttpClient createHttpClient(String uri, String username, String password) {
    final URI scopeUri = URI.create(uri);

    final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(scopeUri.getHost(), scopeUri.getPort()),
            new UsernamePasswordCredentials(username, password));

    final HttpClientBuilder builder = HttpClientBuilder.create().setMaxConnTotal(128).setMaxConnPerRoute(32)
            .setDefaultRequestConfig(/*from   w  w w  .j a va 2  s  .c  o  m*/
                    RequestConfig.copy(RequestConfig.DEFAULT).setRedirectsEnabled(true).build())
            .setDefaultCredentialsProvider(credentialsProvider)
            .addInterceptorFirst(new PreemptiveAuthInterceptor());
    return builder.build();
}

From source file:ca.sqlpower.enterprise.ServerInfoProvider.java

private static void init(URL url, String username, String password, CookieStore cookieStore)
        throws IOException {

    if (version.containsKey(generateServerKey(url, username, password)))
        return;// w  ww  .  j a v a2  s  .co m

    try {
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(params, 2000);
        DefaultHttpClient httpClient = new DefaultHttpClient(params);
        httpClient.setCookieStore(cookieStore);
        httpClient.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(username, password));

        HttpUriRequest request = new HttpOptions(url.toURI());
        String responseBody = httpClient.execute(request, new BasicResponseHandler());

        // Decode the message
        String serverVersion;
        Boolean licensedServer;
        final String watermarkMessage;
        try {
            JSONObject jsonObject = new JSONObject(responseBody);
            serverVersion = jsonObject.getString(ServerProperties.SERVER_VERSION.toString());
            licensedServer = jsonObject.getBoolean(ServerProperties.SERVER_LICENSED.toString());
            watermarkMessage = jsonObject.getString(ServerProperties.SERVER_WATERMARK_MESSAGE.toString());
        } catch (JSONException e) {
            throw new IOException(e.getMessage());
        }

        // Save found values
        version.put(generateServerKey(url, username, password), new Version(serverVersion));
        licenses.put(generateServerKey(url, username, password), licensedServer);
        watermarkMessages.put(generateServerKey(url, username, password), watermarkMessage);

        // Notify the user if the server is not licensed.
        if (!licensedServer || (watermarkMessage != null && watermarkMessage.trim().length() > 0)) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    HyperlinkListener hyperlinkListener = new HyperlinkListener() {
                        @Override
                        public void hyperlinkUpdate(HyperlinkEvent e) {
                            try {
                                if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                                    if (e.getURL() != null) {
                                        BrowserUtil.launch(e.getURL().toString());
                                    }
                                }
                            } catch (IOException ex) {
                                throw new RuntimeException(ex);
                            }
                        }
                    };
                    HTMLUserPrompter htmlPrompter = new HTMLUserPrompter(UserPromptOptions.OK,
                            UserPromptResponse.OK, null, watermarkMessage, hyperlinkListener, "OK");
                    htmlPrompter.promptUser("");
                }
            });
        }

    } catch (URISyntaxException e) {
        throw new IOException(e.getLocalizedMessage());
    }
}

From source file:ru.neverdark.yotta.parser.YottaParser.java

private void parse(Array array) {
    final String URL = String.format("http://%s/hierarch.htm", array.getIp());
    final StringBuffer result = new StringBuffer();

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(array.getIp(), 80),
            new UsernamePasswordCredentials(array.getUser(), array.getPassword()));
    CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    try {/*from   w  w  w  . j a  va 2 s  .  c  o  m*/
        HttpGet httpget = new HttpGet(URL);
        CloseableHttpResponse response = httpClient.execute(httpget);
        System.err.printf("%s\t%s\n", array.getIp(), response.getStatusLine());
        try {
            BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            String line = "";
            while ((line = rd.readLine()) != null) {
                result.append(line);
            }

            Document doc = Jsoup.parse(result.toString());
            Elements tables = doc.getElementsByAttribute("vspace");
            // skip first
            for (int i = 1; i < tables.size(); i++) {
                parseTable(tables.get(i), array.getType());
            }

        } finally {
            response.close();
        }

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        try {
            httpClient.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

From source file:org.jboss.as.test.integration.web.security.jaspi.WebSecurityJaspiTestCase.java

protected void makeCall(String user, String pass, int expectedStatusCode) throws Exception {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(url.getHost(), url.getPort()),
            new UsernamePasswordCredentials(user, pass));
    try (CloseableHttpClient httpclient = HttpClients.custom()
            .setDefaultCredentialsProvider(credentialsProvider).build()) {

        HttpGet httpget = new HttpGet(url.toExternalForm() + "secured/");

        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();

        StatusLine statusLine = response.getStatusLine();
        if (entity != null) {
            log.trace("Response content length: " + entity.getContentLength());
        }/*from   www .j ava  2  s  .c  o m*/
        assertEquals(expectedStatusCode, statusLine.getStatusCode());
        EntityUtils.consume(entity);
    }
}

From source file:org.jfrog.build.client.PreemptiveHttpClient.java

private DefaultHttpClient createHttpClient(String userName, String password, int timeout) {
    BasicHttpParams params = new BasicHttpParams();
    int timeoutMilliSeconds = timeout * 1000;
    HttpConnectionParams.setConnectionTimeout(params, timeoutMilliSeconds);
    HttpConnectionParams.setSoTimeout(params, timeoutMilliSeconds);
    DefaultHttpClient client = new DefaultHttpClient(params);

    if (userName != null && !"".equals(userName)) {
        client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(userName, password));
        localContext = new BasicHttpContext();

        // Generate BASIC scheme object and stick it to the local execution context
        BasicScheme basicAuth = new BasicScheme();
        localContext.setAttribute("preemptive-auth", basicAuth);

        // Add as the first request interceptor
        client.addRequestInterceptor(new PreemptiveAuth(), 0);
    }/*ww  w .j  ava2 s.co  m*/
    boolean requestSentRetryEnabled = Boolean.parseBoolean(System.getProperty("requestSentRetryEnabled"));
    if (requestSentRetryEnabled) {
        client.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, requestSentRetryEnabled));
    }
    // set the following user agent with each request
    String userAgent = "ArtifactoryBuildClient/" + CLIENT_VERSION;
    HttpProtocolParams.setUserAgent(client.getParams(), userAgent);
    return client;
}

From source file:org.picketlink.test.trust.tests.JBWSTokenIssuingLoginModuleUnitTestCase.java

private void assertApp(String appUri, String userName, String password, String httpHeader,
        String httpHeaderValue) throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {/*from  www.  j av  a 2  s  .  c  o  m*/
        httpclient.getCredentialsProvider().setCredentials(new AuthScope(getServerAddress(), 8080), // localhost
                new UsernamePasswordCredentials(userName, password));

        HttpGet httpget = new HttpGet(getTargetURL(appUri)); // http://localhost:8080/test-app-1/test
        if (httpHeader != null)
            httpget.addHeader(httpHeader, httpHeaderValue);

        log.debug("executing request" + httpget.getRequestLine());
        HttpResponse response = httpclient.execute(httpget);
        assertEquals("Http response has to finish with 'HTTP/1.1 200 OK'", 200,
                response.getStatusLine().getStatusCode());

        HttpEntity entity = response.getEntity();
        log.debug("Status line: " + response.getStatusLine());

        ByteArrayOutputStream baos = new ByteArrayOutputStream((int) entity.getContentLength());
        entity.writeTo(baos);
        String content = baos.toString();
        baos.close();

        if (log.isTraceEnabled()) {
            log.trace(content);
        }

        Pattern p = Pattern.compile("[.|\\s]*Credential\\[\\d\\]\\=SamlCredential\\[.*\\]", Pattern.DOTALL);
        Matcher m = p.matcher(content);
        boolean samlCredPresentOnSubject = m.find();
        assertTrue("SamlCredential on subject is missing for (" + appUri + ")", samlCredPresentOnSubject);

        EntityUtils.consume(entity);

    } finally {
        httpclient.getConnectionManager().shutdown();
    }

}

From source file:com.testafy.Test.java

private HttpPost generateRequest(String command, String json) throws APIException {
    // Set up basic auth
    httpclient.getCredentialsProvider().setCredentials(new AuthScope(authScopeLoc, authScopePort),
            new UsernamePasswordCredentials(loginName, password));

    //compose the URI from the base and the given command
    String fullURI = baseURI + command;

    //set up the POST request
    HttpPost req = new HttpPost(fullURI);

    //add parameters to the request
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("json", json));
    UrlEncodedFormEntity paramEntity = new UrlEncodedFormEntity(nvps, Consts.UTF_8);

    req.setEntity(paramEntity);//from  w  w  w .  j  a  va 2s.c om

    return req;
}

From source file:osh.busdriver.mielegateway.MieleGatewayDispatcher.java

/**
 * CONSTRUCTOR/* ww  w  . j a va  2 s. c om*/
 * @param logger
 * @param address
 * @throws MalformedURLException
 */
public MieleGatewayDispatcher(String gatewayHostAndPort, String username, String password,
        OSHGlobalLogger logger) {
    super();

    this.homebusUrl = "http://" + gatewayHostAndPort + "/homebus/?language=en";

    this.httpCredsProvider = new BasicCredentialsProvider();
    this.httpCredsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(username, password));
    this.httpcontext = new BasicHttpContext();
    this.httpcontext.setAttribute(ClientContext.CREDS_PROVIDER, httpCredsProvider);

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

    ClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);

    this.httpclient = new DefaultHttpClient(cm);
    this.httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); // Default to HTTP 1.1 (connection persistence)
    this.httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");
    this.httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 1000);
    this.httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000);

    this.logger = logger;

    //this.parser = new MieleGatewayParser("http://" + device + "/homebus");
    this.deviceData = new HashMap<Integer, MieleDeviceHomeBusData>();

    new Thread(this, "MieleGatewayDispatcher for " + gatewayHostAndPort).start();
}

From source file:eu.seaclouds.platform.dashboard.http.HttpRequestBuilder.java

public HttpRequestBuilder setCredentials(String username, String password) {
    if (username != null && password != null) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(host.split(":")[0], Integer.parseInt(host.split(":")[1])),
                new UsernamePasswordCredentials(username, password));
        context.setCredentialsProvider(credsProvider);
    }//from w  ww. j  a v a 2s  .  c o  m

    return this;
}