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:at.orz.arangodb.http.HttpManager.java

/**
 * /* w w w. j a v a 2  s .  c om*/
 * @param requestEntity
 * @return
 * @throws ArangoException
 */
public HttpResponseEntity execute(HttpRequestEntity requestEntity) throws ArangoException {

    String url = buildUrl(requestEntity);

    if (logger.isDebugEnabled()) {
        if (requestEntity.type == RequestType.POST || requestEntity.type == RequestType.PUT
                || requestEntity.type == RequestType.PATCH) {
            logger.debug("[REQ]http-{}: url={}, headers={}, body={}",
                    new Object[] { requestEntity.type, url, requestEntity.headers, requestEntity.bodyText });
        } else {
            logger.debug("[REQ]http-{}: url={}, headers={}",
                    new Object[] { requestEntity.type, url, requestEntity.headers });
        }
    }

    HttpRequestBase request = null;
    switch (requestEntity.type) {
    case GET:
        request = new HttpGet(url);
        break;
    case POST:
        HttpPost post = new HttpPost(url);
        configureBodyParams(requestEntity, post);
        request = post;
        break;
    case PUT:
        HttpPut put = new HttpPut(url);
        configureBodyParams(requestEntity, put);
        request = put;
        break;
    case PATCH:
        HttpPatch patch = new HttpPatch(url);
        configureBodyParams(requestEntity, patch);
        request = patch;
        break;
    case HEAD:
        request = new HttpHead(url);
        break;
    case DELETE:
        request = new HttpDelete(url);
        break;
    }

    // common-header
    String userAgent = "Mozilla/5.0 (compatible; ArangoDB-JavaDriver/1.0; +http://mt.orz.at/)"; // TODO: 
    request.setHeader("User-Agent", userAgent);
    //request.setHeader("Content-Type", "binary/octet-stream");

    // optinal-headers
    if (requestEntity.headers != null) {
        for (Entry<String, Object> keyValue : requestEntity.headers.entrySet()) {
            request.setHeader(keyValue.getKey(), keyValue.getValue().toString());
        }
    }

    // Basic Auth
    Credentials credentials = null;
    if (requestEntity.username != null && requestEntity.password != null) {
        credentials = new UsernamePasswordCredentials(requestEntity.username, requestEntity.password);
    } else if (configure.getUser() != null && configure.getPassword() != null) {
        credentials = new UsernamePasswordCredentials(configure.getUser(), configure.getPassword());
    }
    if (credentials != null) {
        request.addHeader(BasicScheme.authenticate(credentials, "US-ASCII", false));
    }

    // CURL/httpie Logger
    if (configure.isEnableCURLLogger()) {
        CURLLogger.log(url, requestEntity, userAgent, credentials);
    }

    HttpResponse response = null;
    try {

        response = client.execute(request);
        if (response == null) {
            return null;
        }

        HttpResponseEntity responseEntity = new HttpResponseEntity();

        // http status
        StatusLine status = response.getStatusLine();
        responseEntity.statusCode = status.getStatusCode();
        responseEntity.statusPhrase = status.getReasonPhrase();

        logger.debug("[RES]http-{}: statusCode={}", requestEntity.type, responseEntity.statusCode);

        // ??
        //// TODO etag???
        Header etagHeader = response.getLastHeader("etag");
        if (etagHeader != null) {
            responseEntity.etag = Long.parseLong(etagHeader.getValue().replace("\"", ""));
        }
        // Map???
        responseEntity.headers = new TreeMap<String, String>();
        for (Header header : response.getAllHeaders()) {
            responseEntity.headers.put(header.getName(), header.getValue());
        }

        // ???
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            Header contentType = entity.getContentType();
            if (contentType != null) {
                responseEntity.contentType = contentType.getValue();
                if (responseEntity.isDumpResponse()) {
                    responseEntity.stream = entity.getContent();
                    logger.debug("[RES]http-{}: stream, {}", requestEntity.type, contentType.getValue());
                }
            }
            // Close stream in this method.
            if (responseEntity.stream == null) {
                responseEntity.text = IOUtils.toString(entity.getContent());
                logger.debug("[RES]http-{}: text={}", requestEntity.type, responseEntity.text);
            }
        }

        return responseEntity;

    } catch (ClientProtocolException e) {
        throw new ArangoException(e);
    } catch (IOException e) {
        throw new ArangoException(e);
    }

}

From source file:org.hyperic.hq.plugin.netservices.HTTPCollector.java

private void addCredentials(HttpMessage request, DefaultHttpClient client) {
    if (hasCredentials()) {
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(getUsername(), getPassword());
        String realm = getProperties().getProperty("realm", "");
        if (realm.length() == 0) {
            // send header w/o challenge
            boolean isProxied = (StringUtils.hasText(proxyHost.get()) && proxyPort.get() != -1);
            Header authenticationHeader = BasicScheme.authenticate(credentials, "UTF-8", isProxied);
            request.addHeader(authenticationHeader);
        } else {/*w  w  w.  j a  va2s  .c  o  m*/
            String authenticationHost = (hosthdr.get() == null) ? getHostname() : hosthdr.get();
            AuthScope authScope = new AuthScope(authenticationHost, -1, realm);
            ((DefaultHttpClient) client).getCredentialsProvider().setCredentials(authScope, credentials);
            request.getParams().setParameter(ClientPNames.HANDLE_AUTHENTICATION, true);
        }
    }
}

From source file:com.serena.rlc.provider.servicenow.client.ServiceNowClient.java

/**
 * Execute a get request to ServiceNow.//from   w w w . ja v  a  2s .  c  o  m
 *
 * @param path  the path for the specific request
 * @param parameters  parameters to send with the query
 * @return String containing the response body
 * @throws ServiceNowClientException
 */
protected String processGet(String path, String parameters) throws ServiceNowClientException {
    String uri = createUrl(path, parameters);

    logger.debug("Start executing ServiceNow GET request to url=\"{}\"", uri);

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpGet getRequest = new HttpGet(uri);
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(getSnowUsername(), getSnowPassword());
    getRequest.addHeader(BasicScheme.authenticate(creds, "US-ASCII", false));
    getRequest.addHeader(HttpHeaders.CONTENT_TYPE, DEFAULT_HTTP_CONTENT_TYPE);
    getRequest.addHeader(HttpHeaders.ACCEPT, DEFAULT_HTTP_CONTENT_TYPE);
    String result = "";

    try {
        HttpResponse response = httpClient.execute(getRequest);
        if (response.getStatusLine().getStatusCode() != org.apache.http.HttpStatus.SC_OK) {
            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 ex) {
        logger.error(ex.getMessage(), ex);
        throw new ServiceNowClientException("Server not available", ex);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

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

    return result;
}

From source file:org.jenkinsci.plugins.stashNotifier.StashNotifier.java

/**
 * Returns the HTTP POST request ready to be sent to the Stash build API for
 * the given build and change set. /*  w ww .  j av  a  2s  .co m*/
 * 
 * @param stashBuildNotificationEntity   a entity containing the parameters 
 *                               for Stash
 * @param commitSha1   the SHA1 of the commit that was built
 * @return            the HTTP POST request to the Stash build API
 */
private HttpPost createRequest(final HttpEntity stashBuildNotificationEntity, final String commitSha1) {

    String url = stashServerBaseUrl;
    String username = stashUserName;
    String pwd = stashUserPassword;
    DescriptorImpl descriptor = getDescriptor();

    if ("".equals(url) || url == null)
        url = descriptor.getStashRootUrl();
    if ("".equals(username) || username == null)
        username = descriptor.getStashUser();
    if ("".equals(pwd) || pwd == null)
        pwd = descriptor.getStashPassword().getPlainText();

    HttpPost req = new HttpPost(url + "/rest/build-status/1.0/commits/" + commitSha1);

    req.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials(username, pwd), "UTF-8", false));

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

    return req;
}

From source file:com.serena.rlc.provider.jenkins.JenkinsExecutionProvider.java

@Getter(name = EXTENDED_FIELDS, displayName = "Extended Fields", description = "Get Jenkins job field property values.")
@Params(params = {//from   w  w w  . j  a v a  2  s .  com
        @Param(fieldName = BUILD_JOB_PARAM, displayName = "Job", description = "Jenkins build job", required = true, dataType = DataType.SELECT) })
public FieldInfo getExtendedFieldValues(String fieldName, List<Field> properties) throws ProviderException {
    if (properties == null || properties.size() < 1) {
        throw new ProviderException("Missing required field properties!");
    }

    Field field = Field.getFieldByName(properties, BUILD_JOB_PARAM);
    if (field == null || StringUtils.isEmpty(field.getValue())) {
        throw new ProviderException("Missing required field: " + BUILD_JOB_PARAM);
    }

    String buildJob = field.getValue();

    FieldInfo fieldInfo = new FieldInfo(fieldName);
    String result = "";

    //http://10.31.25.44:8080/jenkins/job/QLARIUS/api/json?tree=name,displayName,actions[parameterDefinitions[*]]
    String uri = jenkinsUrl;

    if (!uri.endsWith("/")) {
        uri += "/";
    }
    try {

        uri += "job/" + URLEncoder.encode(buildJob, "UTF-8").replace("+", "%20")
                + "/api/json?tree=name,displayName,actions[parameterDefinitions[*,defaultParameterValue[*]]]";

        logger.debug("Start executing Jenkins GET request to url=\"{}\"", uri);

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet getRequest = new HttpGet(uri);
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(getServiceUser(),
                getServicePassword());
        getRequest.addHeader(BasicScheme.authenticate(creds, "US-ASCII", false));
        getRequest.addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
        getRequest.addHeader(HttpHeaders.ACCEPT, "application/json");

        HttpResponse response = httpClient.execute(getRequest);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            throw new ProviderException("HTTP Status Code: " + response.getStatusLine().getStatusCode());
        }

        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 ProviderException(e);
    }

    List<JobParameter> jobParams = JobParameter.parse(result);

    /* if (jobParams == null || jobParams.size() < 1) {
     return null;
     }*/
    //FieldInfo fieldInfo = new FieldInfo(fieldName);
    List<FieldValueInfo> values = new ArrayList<>();
    FieldValueInfo value = new FieldValueInfo(EXTENDED_FIELDS, "Job Parameters");
    List<Field> fields = new ArrayList<>();
    Field paramField;

    if (jobParams != null && jobParams.size() > 0) {

        for (JobParameter param : jobParams) {
            if (param.getName().equals("RLC_EXECUTION_ID"))
                continue;
            if ("StringParameterDefinition".equalsIgnoreCase(param.getType())) {
                paramField = new Field(param.getName(), param.getName());
                paramField.setType(DataType.TEXT);
                paramField.setEditable(true);
                paramField.setEnvironmentProperty(true);
                paramField.setValue(param.getDefaultValue());
                fields.add(paramField);
            }
            if ("TextParameterDefinition".equalsIgnoreCase(param.getType())) {
                paramField = new Field(param.getName(), param.getName());
                paramField.setType(DataType.TEXTAREA);
                paramField.setEditable(true);
                paramField.setEnvironmentProperty(true);
                paramField.setValue(param.getDefaultValue());
                fields.add(paramField);
            }
            if ("BooleanParameterDefinition".equalsIgnoreCase(param.getType())) {
                paramField = new Field(param.getName(), param.getName());
                paramField.setType(DataType.BOOLEAN);
                paramField.setEditable(true);
                paramField.setEnvironmentProperty(true);
                paramField.setValue(param.getDefaultValue());
                fields.add(paramField);
            }
            if ("PasswordParameterDefinition".equalsIgnoreCase(param.getType())) {
                paramField = new Field(param.getName(), param.getName());
                paramField.setType(DataType.PASSWORD);
                paramField.setEditable(true);
                paramField.setEnvironmentProperty(true);
                paramField.setValue(param.getDefaultValue());
                fields.add(paramField);
            }
        }

        value.setProperties(fields);
    }

    values.add(value);
    fieldInfo.setValues(values);

    return fieldInfo;
}

From source file:com.serena.rlc.provider.servicenow.client.ServiceNowClient.java

/**
 * Execute a put request to ServiceNow.//from  w  ww  . j  a  va2s  .  c  om
 *
 * @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 ServiceNowClientException
 */
protected String processPut(String path, String parameters, String body) throws ServiceNowClientException {
    String uri = createUrl(path, parameters);

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

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPut putRequest = new HttpPut(uri);
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(getSnowUsername(), getSnowPassword());
    putRequest.addHeader(BasicScheme.authenticate(creds, "US-ASCII", false));
    putRequest.addHeader(HttpHeaders.CONTENT_TYPE, DEFAULT_HTTP_CONTENT_TYPE);
    putRequest.addHeader(HttpHeaders.ACCEPT, DEFAULT_HTTP_CONTENT_TYPE);

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

    try {
        HttpResponse response = httpClient.execute(putRequest);
        if (response.getStatusLine().getStatusCode() != org.apache.commons.httpclient.HttpStatus.SC_OK
                && 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 ServiceNowClientException("Server not available", e);
    }

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

    return result;
}

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

/**
 * Execute a get request to TFS./*  w w w .  jav a  2 s  .c  o m*/
 *
 * @param whichApi  the API to use
 * @param path  the path for the specific request
 * @param parameters  parameters to send with the query
 * @return String containing the response body
 * @throws TFSClientException
 */
protected String processGet(VisualStudioApi whichApi, String path, String parameters)
        throws TFSClientException {
    String uri = createUrl(whichApi, path, parameters);

    logger.debug("Start executing TFS GET request to url=\"{}\"", uri);

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

    try {
        HttpResponse response = httpClient.execute(getRequest);
        if (response.getStatusLine().getStatusCode() != org.apache.http.HttpStatus.SC_OK) {
            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 ex) {
        logger.error(ex.getMessage(), ex);
        throw new TFSClientException("Server not available", ex);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

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

    return result;
}

From source file:com.serena.rlc.provider.servicenow.client.ServiceNowClient.java

/**
 * Execute a post request to ServiceNow.
 *
 * @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 ServiceNowClientException// ww  w .  j  a  va  2 s  .c  o m
 */
protected String processPost(String path, String parameters, String body) throws ServiceNowClientException {
    String uri = createUrl(path, parameters);

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

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost postRequest = new HttpPost(uri);
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(getSnowUsername(), getSnowPassword());
    postRequest.addHeader(BasicScheme.authenticate(creds, "US-ASCII", false));
    postRequest.addHeader(HttpHeaders.CONTENT_TYPE, DEFAULT_HTTP_CONTENT_TYPE);
    postRequest.addHeader(HttpHeaders.ACCEPT, DEFAULT_HTTP_CONTENT_TYPE);

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

    try {
        HttpResponse response = httpClient.execute(postRequest);
        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 ServiceNowClientException("Server not available", e);
    }

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

    return result;
}

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

/**
 * Execute a post request to TFS.//from   www.j  a  v  a 2  s  . c  o  m
 *
 * @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 processPost(VisualStudioApi whichApi, String path, String parameters, String body)
        throws TFSClientException {
    String uri = createUrl(whichApi, path, parameters);

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

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

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

    try {
        HttpResponse response = httpClient.execute(postRequest);
        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 POST request to url=\"{}\" and received this result={}", uri, result);

    return result;
}

From source file:fm.audiobox.core.models.User.java

/**
 * Use this method for manually logging in the User to AudioBox.fm
 * <br />/*w  w  w  . ja  v a 2  s  .  com*/
 * Before invoking this method, you should set {@code username} and {@code password}
 * <br />
 * <b><i>Use {@link AudioBox#login(String, String)} method instead</i></b>
 */
@Deprecated
public IConnectionMethod load(boolean async, IResponseHandler responseHandler)
        throws ServiceException, LoginException, ForbiddenException {
    IConnectionMethod req = this.getConfiguration().getFactory().getConnector().get(this, null, null);

    if (this.getUsername() != null && this.getPassword() != null) {
        req.setAuthenticationHandle(new IAuthenticationHandle() {
            public void handle(IConnectionMethod request) {
                UsernamePasswordCredentials mCredentials = new UsernamePasswordCredentials(username, password);
                request.addHeader(BasicScheme.authenticate(mCredentials, HTTP.UTF_8, false));
            }
        });
    }

    req.send(async);

    return req;
}