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 AuthScope authscope) 

Source Link

Document

Creates a copy of the given credentials scope.

Usage

From source file:org.bimserver.build.CreateGitHubRelease.java

public static void main(String[] args) {
    String username = args[0];// w ww .j  a  va2 s.c om
    String password = args[1];
    String repo = args[2];
    String project = args[3];
    String tagname = args[4];
    String name = args[5];
    String body = args[6];
    String draft = args[7];
    String prerelease = args[8];
    String filesString = args[9];
    String[] filenames = filesString.split(";");

    GitHubClient gitHubClient = new GitHubClient("api.github.com");
    gitHubClient.setCredentials(username, password);

    Map<String, String> map = new HashMap<String, String>();
    map.put("tag_name", tagname);
    // map.put("target_commitish", "test");
    map.put("name", name);
    map.put("body", body);
    //      map.put("draft", draft);
    //      map.put("prerelease", prerelease);
    try {
        String string = "/repos/" + repo + "/" + project + "/releases";
        System.out.println(string);
        JsonObject gitHubResponse = gitHubClient.post(string, map, JsonObject.class);
        System.out.println(gitHubResponse);
        String id = gitHubResponse.get("id").getAsString();

        HttpHost httpHost = new HttpHost("uploads.github.com", 443, "https");

        BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider();
        basicCredentialsProvider.setCredentials(new AuthScope(httpHost),
                new UsernamePasswordCredentials(username, password));

        HostnameVerifier hostnameVerifier = new AllowAllHostnameVerifier();

        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
        CloseableHttpClient client = HttpClients.custom()
                .setDefaultCredentialsProvider(basicCredentialsProvider)
                .setHostnameVerifier((X509HostnameVerifier) hostnameVerifier).setSSLSocketFactory(sslsf)
                .build();

        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(httpHost, basicAuth);

        HttpClientContext context = HttpClientContext.create();
        context.setCredentialsProvider(basicCredentialsProvider);
        context.setAuthCache(authCache);

        for (String filename : filenames) {
            File file = new File(filename);
            String url = "https://uploads.github.com/repos/" + repo + "/" + project + "/releases/" + id
                    + "/assets?name=" + file.getName();
            HttpPost post = new HttpPost(url);
            post.setHeader("Accept", "application/vnd.github.manifold-preview");
            post.setHeader("Content-Type", "application/zip");
            post.setEntity(new InputStreamEntity(new FileInputStream(file), file.length()));
            HttpResponse execute = client.execute(httpHost, post, context);
            execute.getEntity().getContent().close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
}

From source file:com.dlmu.heipacker.crawler.client.ClientInteractiveAuthentication.java

public static void main(String[] args) throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {//  w ww  .  ja v  a2s  .co m
        // Create local execution context
        HttpContext localContext = new BasicHttpContext();

        HttpGet httpget = new HttpGet("http://localhost/test");

        boolean trying = true;
        while (trying) {
            System.out.println("executing request " + httpget.getRequestLine());
            HttpResponse response = httpclient.execute(httpget, localContext);

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());

            // Consume response content
            HttpEntity entity = response.getEntity();
            EntityUtils.consume(entity);

            int sc = response.getStatusLine().getStatusCode();

            AuthState authState = null;
            HttpHost authhost = null;
            if (sc == HttpStatus.SC_UNAUTHORIZED) {
                // Target host authentication required
                authState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE);
                authhost = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
            }
            if (sc == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
                // Proxy authentication required
                authState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE);
                authhost = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_PROXY_HOST);
            }

            if (authState != null) {
                System.out.println("----------------------------------------");
                AuthScheme authscheme = authState.getAuthScheme();
                System.out.println("Please provide credentials for " + authscheme.getRealm() + "@"
                        + authhost.toHostString());

                BufferedReader console = new BufferedReader(new InputStreamReader(System.in));

                System.out.print("Enter username: ");
                String user = console.readLine();
                System.out.print("Enter password: ");
                String password = console.readLine();

                if (user != null && user.length() > 0) {
                    Credentials creds = new UsernamePasswordCredentials(user, password);
                    httpclient.getCredentialsProvider().setCredentials(new AuthScope(authhost), creds);
                    trying = true;
                } else {
                    trying = false;
                }
            } else {
                trying = false;
            }
        }

    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:com.jaspersoft.studio.server.utils.HttpUtils.java

public static void setupProxy(ClientConfig clientConfig, URI uri) {
    CredentialsProvider cp = (CredentialsProvider) clientConfig
            .getProperty(ApacheClientProperties.CREDENTIALS_PROVIDER);
    for (IProxyData d : net.sf.jasperreports.eclipse.util.HttpUtils.proxyService.select(uri)) {
        Credentials c = net.sf.jasperreports.eclipse.util.HttpUtils.getCredentials(d);
        if (c != null)
            cp.setCredentials(new AuthScope(new HttpHost(d.getHost(), d.getPort())), c);
        clientConfig.property(ClientProperties.PROXY_URI,
                d.getType().toLowerCase() + "://" + d.getHost() + ":" + d.getPort());
        break;/* w w  w. j  av a 2  s .co  m*/
    }
    clientConfigs.put(clientConfig, uri);
}

From source file:org.apache.jena.atlas.web.auth.AbstractCredentialsAuthenticator.java

@Override
public void apply(AbstractHttpClient client, HttpContext context, URI target) {
    // At least a user name is required or no authentication will be done
    if (!this.hasUserName(target))
        return;// w ww  . j av a 2  s .  c o  m

    // Be careful to scope credentials to the specific URI so that
    // HttpClient won't try and send them to other servers
    HttpHost host = new HttpHost(target.getHost(), target.getPort());
    CredentialsProvider provider = new BasicCredentialsProvider();

    provider.setCredentials(new AuthScope(host), this.createCredentials(target));

    client.setCredentialsProvider(provider);
}

From source file:fr.gael.dhus.util.http.BasicAuthHttpClientProducer.java

@Override
public CloseableHttpAsyncClient generateClient() {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(AuthScope.ANY),
            new UsernamePasswordCredentials(username, password));

    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
    if (timeout == 0) {
        requestConfigBuilder.setSocketTimeout(Timeouts.SOCKET_TIMEOUT)
                .setConnectTimeout(Timeouts.CONNECTION_TIMEOUT)
                .setConnectionRequestTimeout(Timeouts.CONNECTION_REQUEST_TIMEOUT);
    } else {//from w w  w.jav a2s  .com
        requestConfigBuilder.setSocketTimeout(timeout).setConnectTimeout(timeout)
                .setConnectionRequestTimeout(timeout);
    }

    requestConfigBuilder.setCookieSpec(CookieSpecs.DEFAULT);

    CloseableHttpAsyncClient res = HttpAsyncClients.custom().setDefaultCredentialsProvider(credsProvider)
            .setDefaultRequestConfig(requestConfigBuilder.build()).build();
    res.start();

    return res;
}

From source file:org.fcrepo.camel.FcrepoHttpClientBuilder.java

/**
 *  Build an HttpClient/*from  ww w.ja va2 s  . c  o  m*/
 *
 *  @return an HttpClient
 */
public CloseableHttpClient build() {

    if (isBlank(username) || isBlank(password)) {
        return HttpClients.createDefault();
    } else {
        LOGGER.debug("Accessing fcrepo with user credentials");

        final CredentialsProvider credsProvider = new BasicCredentialsProvider();
        AuthScope scope = null;

        if (isBlank(host)) {
            scope = new AuthScope(AuthScope.ANY);
        } else {
            scope = new AuthScope(new HttpHost(host));
        }
        credsProvider.setCredentials(scope, new UsernamePasswordCredentials(username, password));
        return HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    }
}

From source file:org.fcrepo.client.FcrepoHttpClientBuilder.java

/**
 *  Build an HttpClient//from   w  w w.j  a v a  2s .  c om
 *
 *  @return an HttpClient
 */
public CloseableHttpClient build() {

    if (isBlank(username) || isBlank(password)) {
        return HttpClients.createSystem();
    } else {
        LOGGER.debug("Accessing fcrepo with user credentials");

        final CredentialsProvider credsProvider = new BasicCredentialsProvider();
        AuthScope scope = null;

        if (isBlank(host)) {
            scope = new AuthScope(AuthScope.ANY);
        } else {
            scope = new AuthScope(new HttpHost(host));
        }
        credsProvider.setCredentials(scope, new UsernamePasswordCredentials(username, password));
        return HttpClients.custom().setDefaultCredentialsProvider(credsProvider).useSystemProperties().build();
    }
}

From source file:com.ccreanga.bitbucket.rest.client.http.BitBucketHttpExecutor.java

public BitBucketHttpExecutor(String baseUrl, BitBucketCredentials credentials) {
    this.baseUrl = baseUrl;

    HttpHost targetHost = HttpHost.create(baseUrl);
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setMaxTotal(5);//from  ww w  . j  a va 2s  . co  m
    connectionManager.setDefaultMaxPerRoute(4);

    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(targetHost),
            new UsernamePasswordCredentials(credentials.getUsername(), credentials.getPassword()));

    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);

    context = HttpClientContext.create();
    context.setCredentialsProvider(credentialsProvider);
    context.setAuthCache(authCache);

    httpClient = HttpClients.custom().setConnectionManager(connectionManager)
            .setDefaultCredentialsProvider(credentialsProvider).build();

}

From source file:org.springframework.cloud.dataflow.rest.util.HttpClientConfigurer.java

public HttpClientConfigurer basicAuthCredentials(String username, String password) {
    final CredentialsProvider credentialsProvider = this.getOrInitializeCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(this.targetHost),
            new UsernamePasswordCredentials(username, password));
    httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    useBasicAuth = true;//from  w ww  .  j  a v  a  2  s. co  m
    return this;
}

From source file:org.fcrepo.camel.FedoraClient.java

/**
 * Create a FedoraClient with a set of authentication values.
 *///from w w  w .  j  av  a  2 s  . com
public FedoraClient(final String username, final String password, final String host,
        final Boolean throwExceptionOnFailure) {

    final CredentialsProvider credsProvider = new BasicCredentialsProvider();
    AuthScope scope = null;

    this.throwExceptionOnFailure = throwExceptionOnFailure;

    if ((username == null || username.isEmpty()) || (password == null || password.isEmpty())) {
        this.httpclient = HttpClients.createDefault();
    } else {
        if (host != null) {
            scope = new AuthScope(new HttpHost(host));
        }
        credsProvider.setCredentials(scope, new UsernamePasswordCredentials(username, password));
        this.httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    }
}