Search in sources :

Example 66 with CredentialsProvider

use of org.apache.http.client.CredentialsProvider in project Activiti by Activiti.

the class BaseJPARestTestCase method executeBinaryHttpRequest.

public HttpResponse executeBinaryHttpRequest(HttpUriRequest request, int expectedStatusCode) {
    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("kermit", "kermit");
    provider.setCredentials(AuthScope.ANY, credentials);
    HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
    try {
        HttpResponse response = client.execute(request);
        Assert.assertNotNull(response.getStatusLine());
        Assert.assertEquals(expectedStatusCode, response.getStatusLine().getStatusCode());
        return response;
    } catch (ClientProtocolException e) {
        Assert.fail(e.getMessage());
    } catch (IOException e) {
        Assert.fail(e.getMessage());
    }
    return null;
}
Also used : BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpClient(org.apache.http.client.HttpClient) HttpResponse(org.apache.http.HttpResponse) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) IOException(java.io.IOException) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) ClientProtocolException(org.apache.http.client.ClientProtocolException)

Example 67 with CredentialsProvider

use of org.apache.http.client.CredentialsProvider in project azure-tools-for-java by Microsoft.

the class Executor method main.

public static void main(String[] args) throws Exception {
    CredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("admin", "Pa$$w0rd1234"));
    HttpClient client = HttpClients.custom().setDefaultCredentialsProvider(provider).build();
    String id = "application_1491222722583_0007";
    HttpResponse response = client.execute(new HttpGet("https://spark2withblob.azurehdinsight.net/sparkhistory/api/v1/applications/application_1491222722583_0008/1/jobs"));
    String res = EntityUtils.toString(response.getEntity());
    //List<Executor> response1 = ObjectConvertUtils.convertJsonToList(res, Executor.class).get();
    List<Job> stages = ObjectConvertUtils.convertJsonToList(res, Job.class).get();
    //Optional<Executor[]> v = ObjectConvertUtils.convertJsonToObject(res, Executor[].class);
    int a = 1;
}
Also used : BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpClient(org.apache.http.client.HttpClient) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) Job(com.microsoft.azure.hdinsight.sdk.rest.spark.job.Job) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 68 with CredentialsProvider

use of org.apache.http.client.CredentialsProvider in project azure-tools-for-java by Microsoft.

the class AddHDInsightAdditionalClusterImpl method getMessageByAmbari.

private static String getMessageByAmbari(String clusterName, String userName, String passwd) throws HDIException {
    String linuxClusterConfigureFileUrl = String.format(clusterConfigureFileUrl, clusterName, clusterName);
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName.trim(), passwd));
    CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build();
    CloseableHttpResponse response = null;
    int responseCode = -1;
    try {
        response = tryGetHttpResponse(httpClient, linuxClusterConfigureFileUrl);
    } catch (UnknownHostException e1) {
        throw new HDIException("Invalid Cluster Name");
    } catch (Exception e3) {
        throw new HDIException("Something wrong with the cluster! Please try again later");
    }
    responseCode = response.getStatusLine().getStatusCode();
    if (responseCode == 200) {
        try {
            return StreamUtil.getResultFromHttpResponse(response).getMessage();
        } catch (IOException e) {
            throw new HDIException("Not support cluster");
        }
    } else if (responseCode == 401 || responseCode == 403) {
        throw new HDIException("Invalid Cluster Name or Password");
    } else {
        throw new HDIException("Something wrong with the cluster! Please try again later");
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) UnknownHostException(java.net.UnknownHostException) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) HDIException(com.microsoft.azure.hdinsight.sdk.common.HDIException) IOException(java.io.IOException) HDIException(com.microsoft.azure.hdinsight.sdk.common.HDIException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) AzureCmdException(com.microsoft.azuretools.azurecommons.helpers.AzureCmdException) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 69 with CredentialsProvider

use of org.apache.http.client.CredentialsProvider in project robovm by robovm.

the class DefaultRequestDirector method createTunnelToTarget.

// establishConnection
/**
     * Creates a tunnel to the target server.
     * The connection must be established to the (last) proxy.
     * A CONNECT request for tunnelling through the proxy will
     * be created and sent, the response received and checked.
     * This method does <i>not</i> update the connection with
     * information about the tunnel, that is left to the caller.
     *
     * @param route     the route to establish
     * @param context   the context for request execution
     *
     * @return  <code>true</code> if the tunnelled route is secure,
     *          <code>false</code> otherwise.
     *          The implementation here always returns <code>false</code>,
     *          but derived classes may override.
     *
     * @throws HttpException    in case of a problem
     * @throws IOException      in case of an IO problem
     */
protected boolean createTunnelToTarget(HttpRoute route, HttpContext context) throws HttpException, IOException {
    HttpHost proxy = route.getProxyHost();
    HttpHost target = route.getTargetHost();
    HttpResponse response = null;
    boolean done = false;
    while (!done) {
        done = true;
        if (!this.managedConn.isOpen()) {
            this.managedConn.open(route, context, this.params);
        }
        HttpRequest connect = createConnectRequest(route, context);
        String agent = HttpProtocolParams.getUserAgent(params);
        if (agent != null) {
            connect.addHeader(HTTP.USER_AGENT, agent);
        }
        connect.addHeader(HTTP.TARGET_HOST, target.toHostString());
        AuthScheme authScheme = this.proxyAuthState.getAuthScheme();
        AuthScope authScope = this.proxyAuthState.getAuthScope();
        Credentials creds = this.proxyAuthState.getCredentials();
        if (creds != null) {
            if (authScope != null || !authScheme.isConnectionBased()) {
                try {
                    connect.addHeader(authScheme.authenticate(creds, connect));
                } catch (AuthenticationException ex) {
                    if (this.log.isErrorEnabled()) {
                        this.log.error("Proxy authentication error: " + ex.getMessage());
                    }
                }
            }
        }
        response = requestExec.execute(connect, this.managedConn, context);
        int status = response.getStatusLine().getStatusCode();
        if (status < 200) {
            throw new HttpException("Unexpected response to CONNECT request: " + response.getStatusLine());
        }
        CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
        if (credsProvider != null && HttpClientParams.isAuthenticating(params)) {
            if (this.proxyAuthHandler.isAuthenticationRequested(response, context)) {
                this.log.debug("Proxy requested authentication");
                Map<String, Header> challenges = this.proxyAuthHandler.getChallenges(response, context);
                try {
                    processChallenges(challenges, this.proxyAuthState, this.proxyAuthHandler, response, context);
                } catch (AuthenticationException ex) {
                    if (this.log.isWarnEnabled()) {
                        this.log.warn("Authentication error: " + ex.getMessage());
                        break;
                    }
                }
                updateAuthState(this.proxyAuthState, proxy, credsProvider);
                if (this.proxyAuthState.getCredentials() != null) {
                    done = false;
                    // Retry request
                    if (this.reuseStrategy.keepAlive(response, context)) {
                        this.log.debug("Connection kept alive");
                        // Consume response content
                        HttpEntity entity = response.getEntity();
                        if (entity != null) {
                            entity.consumeContent();
                        }
                    } else {
                        this.managedConn.close();
                    }
                }
            } else {
                // Reset proxy auth scope
                this.proxyAuthState.setAuthScope(null);
            }
        }
    }
    int status = response.getStatusLine().getStatusCode();
    if (status > 299) {
        // Buffer response content
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            response.setEntity(new BufferedHttpEntity(entity));
        }
        this.managedConn.close();
        throw new TunnelRefusedException("CONNECT refused by proxy: " + response.getStatusLine(), response);
    }
    this.managedConn.markReusable();
    // Leave it to derived classes, consider insecure by default here.
    return false;
}
Also used : HttpRequest(org.apache.http.HttpRequest) BasicHttpRequest(org.apache.http.message.BasicHttpRequest) AbortableHttpRequest(org.apache.http.client.methods.AbortableHttpRequest) HttpEntity(org.apache.http.HttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) AuthenticationException(org.apache.http.auth.AuthenticationException) HttpResponse(org.apache.http.HttpResponse) CredentialsProvider(org.apache.http.client.CredentialsProvider) AuthScheme(org.apache.http.auth.AuthScheme) Header(org.apache.http.Header) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) HttpHost(org.apache.http.HttpHost) AuthScope(org.apache.http.auth.AuthScope) HttpException(org.apache.http.HttpException) Credentials(org.apache.http.auth.Credentials)

Example 70 with CredentialsProvider

use of org.apache.http.client.CredentialsProvider in project robolectric by robolectric.

the class DefaultRequestDirector method handleResponse.

/**
   * Analyzes a response to check need for a followup.
   *
   * @param roureq    the request and route.
   * @param response  the response to analayze
   * @param context   the context used for the current request execution
   *
   * @return  the followup request and route if there is a followup, or
   *          <code>null</code> if the response should be returned as is
   *
   * @throws HttpException    in case of a problem
   * @throws IOException      in case of an IO problem
   */
protected RoutedRequest handleResponse(RoutedRequest roureq, HttpResponse response, HttpContext context) throws HttpException, IOException {
    HttpRoute route = roureq.getRoute();
    RequestWrapper request = roureq.getRequest();
    HttpParams params = request.getParams();
    if (HttpClientParams.isRedirecting(params) && this.redirectHandler.isRedirectRequested(response, context)) {
        if (redirectCount >= maxRedirects) {
            throw new RedirectException("Maximum redirects (" + maxRedirects + ") exceeded");
        }
        redirectCount++;
        // Virtual host cannot be used any longer
        virtualHost = null;
        URI uri = this.redirectHandler.getLocationURI(response, context);
        HttpHost newTarget = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
        // Unset auth scope
        targetAuthState.setAuthScope(null);
        proxyAuthState.setAuthScope(null);
        // Invalidate auth states if redirecting to another host
        if (!route.getTargetHost().equals(newTarget)) {
            targetAuthState.invalidate();
            AuthScheme authScheme = proxyAuthState.getAuthScheme();
            if (authScheme != null && authScheme.isConnectionBased()) {
                proxyAuthState.invalidate();
            }
        }
        HttpRedirect redirect = new HttpRedirect(request.getMethod(), uri);
        HttpRequest orig = request.getOriginal();
        redirect.setHeaders(orig.getAllHeaders());
        RequestWrapper wrapper = new RequestWrapper(redirect);
        wrapper.setParams(params);
        HttpRoute newRoute = determineRoute(newTarget, wrapper, context);
        RoutedRequest newRequest = new RoutedRequest(wrapper, newRoute);
        if (this.log.isDebugEnabled()) {
            this.log.debug("Redirecting to '" + uri + "' via " + newRoute);
        }
        return newRequest;
    }
    CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
    if (credsProvider != null && HttpClientParams.isAuthenticating(params)) {
        if (this.targetAuthHandler.isAuthenticationRequested(response, context)) {
            HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
            if (target == null) {
                target = route.getTargetHost();
            }
            this.log.debug("Target requested authentication");
            Map<String, Header> challenges = this.targetAuthHandler.getChallenges(response, context);
            try {
                processChallenges(challenges, this.targetAuthState, this.targetAuthHandler, response, context);
            } catch (AuthenticationException ex) {
                if (this.log.isWarnEnabled()) {
                    this.log.warn("Authentication error: " + ex.getMessage());
                    return null;
                }
            }
            updateAuthState(this.targetAuthState, target, credsProvider);
            if (this.targetAuthState.getCredentials() != null) {
                // Re-try the same request via the same route
                return roureq;
            } else {
                return null;
            }
        } else {
            // Reset target auth scope
            this.targetAuthState.setAuthScope(null);
        }
        if (this.proxyAuthHandler.isAuthenticationRequested(response, context)) {
            HttpHost proxy = route.getProxyHost();
            this.log.debug("Proxy requested authentication");
            Map<String, Header> challenges = this.proxyAuthHandler.getChallenges(response, context);
            try {
                processChallenges(challenges, this.proxyAuthState, this.proxyAuthHandler, response, context);
            } catch (AuthenticationException ex) {
                if (this.log.isWarnEnabled()) {
                    this.log.warn("Authentication error: " + ex.getMessage());
                    return null;
                }
            }
            updateAuthState(this.proxyAuthState, proxy, credsProvider);
            if (this.proxyAuthState.getCredentials() != null) {
                // Re-try the same request via the same route
                return roureq;
            } else {
                return null;
            }
        } else {
            // Reset proxy auth scope
            this.proxyAuthState.setAuthScope(null);
        }
    }
    return null;
}
Also used : HttpRequest(org.apache.http.HttpRequest) BasicHttpRequest(org.apache.http.message.BasicHttpRequest) AbortableHttpRequest(org.apache.http.client.methods.AbortableHttpRequest) AuthenticationException(org.apache.http.auth.AuthenticationException) CredentialsProvider(org.apache.http.client.CredentialsProvider) URI(java.net.URI) AuthScheme(org.apache.http.auth.AuthScheme) HttpRoute(org.apache.http.conn.routing.HttpRoute) HttpParams(org.apache.http.params.HttpParams) Header(org.apache.http.Header) HttpHost(org.apache.http.HttpHost) RequestWrapper(org.apache.http.impl.client.RequestWrapper) EntityEnclosingRequestWrapper(org.apache.http.impl.client.EntityEnclosingRequestWrapper) RoutedRequest(org.apache.http.impl.client.RoutedRequest) RedirectException(org.apache.http.client.RedirectException)

Aggregations

CredentialsProvider (org.apache.http.client.CredentialsProvider)92 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)65 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)57 AuthScope (org.apache.http.auth.AuthScope)51 HttpHost (org.apache.http.HttpHost)28 HttpGet (org.apache.http.client.methods.HttpGet)19 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)17 Test (org.junit.Test)17 HttpResponse (org.apache.http.HttpResponse)16 Credentials (org.apache.http.auth.Credentials)16 IOException (java.io.IOException)13 HttpClientContext (org.apache.http.client.protocol.HttpClientContext)12 BasicScheme (org.apache.http.impl.auth.BasicScheme)12 Header (org.apache.http.Header)11 HttpRequest (org.apache.http.HttpRequest)10 AuthCache (org.apache.http.client.AuthCache)10 BasicAuthCache (org.apache.http.impl.client.BasicAuthCache)10 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)10 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)9 HttpEntity (org.apache.http.HttpEntity)8