Example usage for org.apache.http.impl.auth BasicScheme authenticate

List of usage examples for org.apache.http.impl.auth BasicScheme authenticate

Introduction

In this page you can find the example usage for org.apache.http.impl.auth BasicScheme authenticate.

Prototype

@Deprecated
public static Header authenticate(final Credentials credentials, final String charset, final boolean proxy) 

Source Link

Document

Returns a basic Authorization header value for the given Credentials and charset.

Usage

From source file:com.serena.rlc.provider.tfs.client.TFSClient.java

/**
 * Execute a patch request to TFS./*from  ww  w.j  a  v a 2  s  . c  om*/
 *
 * @param whichApi  the API to use
 * @param path  the path for the specific request
 * @param parameters  parameters to send with the query
 * @param body  the body to send with the request
 * @return String containing the response body
 * @throws TFSClientException
 */
public String processPatch(VisualStudioApi whichApi, String path, String parameters, String body)
        throws TFSClientException {
    String uri = createUrl(whichApi, path, parameters);

    logger.debug("Start executing TFS PATCH request to url=\"{}\" with data: {}", uri, body);

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPatch patchRequest = new HttpPatch(uri);
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(getTFSUsername(), getTFSPassword());
    patchRequest.addHeader(BasicScheme.authenticate(creds, "US-ASCII", false));
    patchRequest.addHeader(HttpHeaders.CONTENT_TYPE, DEFAULT_HTTP_CONTENT_TYPE);
    patchRequest.addHeader(HttpHeaders.ACCEPT, DEFAULT_HTTP_CONTENT_TYPE);

    try {
        patchRequest.setEntity(new StringEntity(body, "UTF-8"));
    } catch (UnsupportedEncodingException ex) {
        logger.error(ex.getMessage(), ex);
        throw new TFSClientException("Error creating body for PATCH request", ex);
    }
    String result = "";

    try {
        HttpResponse response = httpClient.execute(patchRequest);
        if (response.getStatusLine().getStatusCode() != org.apache.commons.httpclient.HttpStatus.SC_OK
                && response.getStatusLine()
                        .getStatusCode() != org.apache.commons.httpclient.HttpStatus.SC_CREATED
                && response.getStatusLine()
                        .getStatusCode() != org.apache.commons.httpclient.HttpStatus.SC_ACCEPTED) {
            throw createHttpError(response);
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
        StringBuilder sb = new StringBuilder(1024);
        String output;
        while ((output = br.readLine()) != null) {
            sb.append(output);
        }
        result = sb.toString();
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        throw new TFSClientException("Server not available", e);
    }

    logger.debug("End executing TFS PATCH request to url=\"{}\" and received this result={}", uri, result);

    return result;
}

From source file:org.jenkinsci.plugins.bitbucketNotifier.BitbucketNotifier.java

/**
 * Returns the HTTP POST request ready to be sent to the Bitbucket build API for
 * the given build and change set.//from   www.  jav  a2  s .c  om
 *
 * @param bitbucketBuildNotificationEntity   a entity containing the parameters
 *                               for Bitbucket
 * @param commitSha1   the SHA1 of the commit that was built
 * @return            the HTTP POST request to the Bitbucket build API
 */
private HttpPost createRequest(final HttpEntity bitbucketBuildNotificationEntity, final String commitSha1) {

    String url = bitbucketServerBaseUrl;
    DescriptorImpl descriptor = getDescriptor();

    if ("".equals(url) || url == null)
        url = descriptor.getBitbucketRootUrl();

    // https://api.bitbucket.org/2.0/repositories/{owner}/{repo_slug}/commit/{revision}/statuses/build
    HttpPost req = new HttpPost(url + "/commit/" + commitSha1 + "/statuses/build");

    // If we have a credential defined then we need to determine if it
    // is a basic auth

    credentialsId = getCredentialsId();
    if (StringUtils.isBlank(credentialsId)) {
        credentialsId = descriptor.getCredentialsId();
    }

    if (StringUtils.isNotBlank(credentialsId)) {

        Credentials credentials = CredentialsMatchers.firstOrNull(CredentialsProvider.lookupCredentials(
                com.cloudbees.plugins.credentials.common.UsernamePasswordCredentials.class,
                Jenkins.getInstance(), ACL.SYSTEM), CredentialsMatchers.withId(credentialsId));
        if (credentials instanceof com.cloudbees.plugins.credentials.common.UsernamePasswordCredentials) {
            req.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials(
                    ((com.cloudbees.plugins.credentials.common.UsernamePasswordCredentials) credentials)
                            .getUsername(),
                    ((com.cloudbees.plugins.credentials.common.UsernamePasswordCredentials) credentials)
                            .getPassword().getPlainText()),
                    "UTF-8", false));
        }
    }

    req.addHeader("Content-type", "application/json");
    req.setEntity(bitbucketBuildNotificationEntity);

    return req;
}

From source file:de.geomobile.joined.api.service.JOWebService.java

/**
 * @param userId//from  w w w  . ja va 2  s.  c  o  m
 * @param secureToken
 * @return
 */
private Header getAuthenticationHeader(String userId, String secureToken) {
    return BasicScheme.authenticate(new UsernamePasswordCredentials(userId, secureToken), JOConfig.UTF_8,
            false);
}

From source file:org.wso2.carbon.appfactory.jenkins.build.RestBasedJenkinsCIConnector.java

private HttpGet createGetByBaseUrl(String baseUrl, String relativePath, List<NameValuePair> queryParameters)
        throws AppFactoryException {
    String query = null;//from  ww w.  j a  v  a  2s . c om
    HttpGet get;

    if (queryParameters != null) {
        query = URLEncodedUtils.format(queryParameters, HTTP.UTF_8);
    }
    try {
        URL url = new URL(baseUrl);
        URI uri = URIUtils.createURI(url.getProtocol(), url.getHost(), url.getPort(), relativePath, query,
                null);

        get = new HttpGet(uri);
        if (authenticate) {
            get.addHeader(BasicScheme.authenticate(
                    new UsernamePasswordCredentials(this.username, this.apiKeyOrPassword), HTTP.UTF_8, false));
        }

    } catch (MalformedURLException e) {
        String msg = "Error while generating URL for the path : " + baseUrl
                + " during the creation of HttpGet method";
        log.error(msg, e);
        throw new AppFactoryException(msg, e);
    } catch (URISyntaxException e) {
        String msg = "Error while constructing the URI for url : " + baseUrl
                + " during the creation of HttpGet method";
        log.error(msg, e);
        throw new AppFactoryException(msg, e);
    }

    return get;
}

From source file:org.wso2.carbon.appfactory.jenkins.build.RestBasedJenkinsCIConnector.java

/**
 * Util method to create a http get method
 *
 * @param urlFragment     the url fragment
 * @param queryParameters query parameters
 * @param tenantDomain    tenant domain, to which the application is belongs
 * @return a {@link HttpGet}/*  w w w . j  a v a2s.co m*/
 */
private HttpGet createGet(String urlFragment, List<NameValuePair> queryParameters, String tenantDomain)
        throws AppFactoryException {

    String query = null;
    HttpGet get;

    if (queryParameters != null) {
        query = URLEncodedUtils.format(queryParameters, HTTP.UTF_8);
    }
    try {
        URL url = new URL(getJenkinsUrl(tenantDomain));
        URI uri = URIUtils.createURI(url.getProtocol(), url.getHost(), url.getPort(), urlFragment, query, null);
        get = new HttpGet(uri);
        if (authenticate) {
            get.addHeader(BasicScheme.authenticate(
                    new UsernamePasswordCredentials(this.username, this.apiKeyOrPassword), HTTP.UTF_8, false));
        }

    } catch (MalformedURLException e) {
        String msg = "Error while generating URL for the path : " + urlFragment + " in tenant : " + tenantDomain
                + " during the creation of HttpGet method";
        log.error(msg, e);
        throw new AppFactoryException(msg, e);
    } catch (URISyntaxException e) {
        String msg = "Error while constructing the URI for url fragment " + urlFragment + " in tenant : "
                + tenantDomain + " during the creation of HttpGet method";
        log.error(msg, e);
        throw new AppFactoryException(msg, e);
    }
    return get;
}

From source file:org.wso2.carbon.appfactory.jenkins.build.RestBasedJenkinsCIConnector.java

/**
 * Util method to create a POST method// w  w w  .  ja va 2s. c o m
 *
 * @param urlFragment     Url fragments.
 * @param queryParameters Query parameters.
 * @param httpEntity
 * @param tenantDomain    Tenant Domain of application
 * @return a {@link HttpPost}
 */
private HttpPost createPost(String urlFragment, List<NameValuePair> queryParameters, HttpEntity httpEntity,
        String tenantDomain) throws AppFactoryException {

    String query = "";
    HttpPost post;

    if (queryParameters != null) {
        query = URLEncodedUtils.format(queryParameters, HTTP.UTF_8);
    }
    try {
        URL url = new URL(getJenkinsUrl(tenantDomain));
        URI uri = URIUtils.createURI(url.getProtocol(), url.getHost(), url.getPort(), urlFragment, query, null);
        post = new HttpPost(uri);

        if (httpEntity != null) {
            post.setEntity(httpEntity);
        }

        if (authenticate) {
            post.addHeader(BasicScheme.authenticate(
                    new UsernamePasswordCredentials(this.username, this.apiKeyOrPassword), HTTP.UTF_8, false));
        }
    } catch (MalformedURLException e) {
        String msg = "Error while generating URL for the path : " + urlFragment + " in tenant : " + tenantDomain
                + " during the creation of HttpGet method";
        log.error(msg, e);
        throw new AppFactoryException(msg, e);
    } catch (URISyntaxException e) {
        String msg = "Error while constructing the URI for tenant : " + tenantDomain
                + " during the creation of " + "HttpPosts method";
        log.error(msg, e);
        throw new AppFactoryException(msg, e);
    }
    return post;
}

From source file:org.apache.http.impl.auth.TestBasicScheme.java

@Test
public void testBasicAuthenticationWith88591Chars() throws Exception {
    final int[] germanChars = { 0xE4, 0x2D, 0xF6, 0x2D, 0xFc };
    final StringBuilder buffer = new StringBuilder();
    for (final int germanChar : germanChars) {
        buffer.append((char) germanChar);
    }//from w w w.j a  v  a 2 s .c o m

    final UsernamePasswordCredentials creds = new UsernamePasswordCredentials("dh", buffer.toString());
    final BasicScheme authscheme = new BasicScheme(Consts.ISO_8859_1);

    final HttpRequest request = new BasicHttpRequest("GET", "/");
    final HttpContext context = new BasicHttpContext();
    final Header header = authscheme.authenticate(creds, request, context);
    Assert.assertEquals("Basic ZGg65C32Lfw=", header.getValue());
}

From source file:org.apache.http.impl.auth.TestBasicScheme.java

@Test
public void testBasicAuthentication() throws Exception {
    final UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass");

    final Header challenge = new BasicHeader(AUTH.WWW_AUTH, "Basic realm=\"test\"");

    final BasicScheme authscheme = new BasicScheme();
    authscheme.processChallenge(challenge);

    final HttpRequest request = new BasicHttpRequest("GET", "/");
    final HttpContext context = new BasicHttpContext();
    final Header authResponse = authscheme.authenticate(creds, request, context);

    final String expected = "Basic " + EncodingUtils
            .getAsciiString(Base64.encodeBase64(EncodingUtils.getAsciiBytes("testuser:testpass")));
    Assert.assertEquals(AUTH.WWW_AUTH_RESP, authResponse.getName());
    Assert.assertEquals(expected, authResponse.getValue());
    Assert.assertEquals("test", authscheme.getRealm());
    Assert.assertTrue(authscheme.isComplete());
    Assert.assertFalse(authscheme.isConnectionBased());
}

From source file:org.apache.http.impl.auth.TestBasicScheme.java

@Test
public void testBasicProxyAuthentication() throws Exception {
    final UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass");

    final Header challenge = new BasicHeader(AUTH.PROXY_AUTH, "Basic realm=\"test\"");

    final BasicScheme authscheme = new BasicScheme();
    authscheme.processChallenge(challenge);

    final HttpRequest request = new BasicHttpRequest("GET", "/");
    final HttpContext context = new BasicHttpContext();
    final Header authResponse = authscheme.authenticate(creds, request, context);

    final String expected = "Basic " + EncodingUtils
            .getAsciiString(Base64.encodeBase64(EncodingUtils.getAsciiBytes("testuser:testpass")));
    Assert.assertEquals(AUTH.PROXY_AUTH_RESP, authResponse.getName());
    Assert.assertEquals(expected, authResponse.getValue());
    Assert.assertEquals("test", authscheme.getRealm());
    Assert.assertTrue(authscheme.isComplete());
    Assert.assertFalse(authscheme.isConnectionBased());
}