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

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

Introduction

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

Prototype

AuthScope ANY

To view the source code for org.apache.http.auth AuthScope ANY.

Click Source Link

Document

Default scope matching any host, port, realm and authentication scheme.

Usage

From source file:org.obiba.opal.rest.client.magma.OpalJavaClient.java

private void createClient() {
    log.info("Connecting to Opal: {}", opalURI);
    DefaultHttpClient httpClient = new DefaultHttpClient();
    if (keyStore == null)
        httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials);
    httpClient.getParams().setParameter(ClientPNames.HANDLE_AUTHENTICATION, Boolean.TRUE);
    httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF,
            Collections.singletonList(OpalAuth.CREDENTIALS_HEADER));
    httpClient.getParams().setParameter(ClientPNames.CONNECTION_MANAGER_FACTORY_CLASS_NAME,
            OpalClientConnectionManagerFactory.class.getName());
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout);
    httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout);
    httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(DEFAULT_MAX_ATTEMPT, false));
    httpClient.getAuthSchemes().register(OpalAuth.CREDENTIALS_HEADER, new OpalAuthScheme.Factory());

    try {/* w w  w. j av  a  2  s  .  c  o m*/
        httpClient.getConnectionManager().getSchemeRegistry()
                .register(new Scheme("https", HTTPS_PORT, getSocketFactory()));
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        throw new RuntimeException(e);
    }
    client = enableCaching(httpClient);

    ctx = new BasicHttpContext();
    ctx.setAttribute(ClientContext.COOKIE_STORE, new BasicCookieStore());
}

From source file:org.alfresco.http.SharedHttpClientProvider.java

@Override
public HttpClient getHttpClient(String username, String password) {
    DefaultHttpClient client = (DefaultHttpClient) getHttpClient();

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY),
            new UsernamePasswordCredentials(username, password));
    client.setCredentialsProvider(credentialsProvider);

    return client;
}

From source file:com.socrata.ApiBase.java

/**
 * Sets up http authentication (BASIC) for default requests
 *///from   w w  w. java  2  s  .co  m
private void setupBasicAuthentication() {
    Credentials defaultcreds = new UsernamePasswordCredentials(username, password);
    CredentialsProvider credProvider = new BasicCredentialsProvider();

    credProvider.setCredentials(AuthScope.ANY, defaultcreds);

    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();

    httpContext = new BasicHttpContext();
    httpContext.setAttribute(ClientContext.AUTH_CACHE, basicAuth);

    httpClient.setCredentialsProvider(credProvider);
}

From source file:org.squale.squalerest.client.SqualeRestHttpClient.java

/**
 * This method executes the search/* w w  w. java2s  . co m*/
 * 
 * @param path The query
 * @param xstream The xstream processor
 * @return The object result of the query
 * @throws SqualeRestException Exception occurs during the serach
 */
private Object execute(String path, XStream xstream) throws SqualeRestException {
    Object objectToReturn = null;
    DefaultHttpClient httpclient = null;
    try {
        httpclient = new DefaultHttpClient();

        // Create credentials
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, password);
        httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);

        // Define the host
        HttpHost targetHost = new HttpHost(host, port);

        // Define the get method
        HttpGet httpget = new HttpGet(path);

        // Execute the request
        HttpResponse response = httpclient.execute(targetHost, httpget);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream is = null;
                try {
                    // Transform the xml stream into java object
                    is = entity.getContent();
                    objectToReturn = xstream.fromXML(is);
                } finally {
                    // In all case close the input stream
                    if (is != null) {
                        is.close();
                    }
                }
            }
        } else {
            throw new SqualeRestException(response.getStatusLine().getStatusCode() + " : "
                    + response.getStatusLine().getReasonPhrase());
        }
    } catch (ClientProtocolException e) {
        throw new SqualeRestException(e);
    } catch (IOException e) {
        throw new SqualeRestException(e);
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
    return objectToReturn;
}

From source file:com.ibm.watson.developer_cloud.professor_languo.pipeline.RnrMergerAndRanker.java

/**
 * If {@code correctAnswers != null}, this method will create the training data csv file from the
 * list of CandidateAnswers and return {@code answers} unchanged. Else, it will apply the ranker
 * created in the current invocation of this class.
 * /*from   w ww  . ja va 2  s  . c o m*/
 * @param question {@link Question} from which {@code answers} are generated
 * @param answers List of {@link CandidateAnswer}s
 * @param correctAnswers List of {@link CorrectAnswer}s to the {@code question}. There should only
 *        be one correct answer for each question.
 * 
 */
@Override
public Observable<CandidateAnswer> mergeAndRankAnswers(Question question, Observable<CandidateAnswer> answers,
        Collection<CorrectAnswer> correctAnswers) {

    client = RankerCreationUtil.createHttpClient(AuthScope.ANY, creds);

    if (correctAnswers != null) { // TRAINING PHASE
        train(question, answers, correctAnswers);
        return answers;
    } else { // TESTING PHASE
        return apply(question, answers);
    }
}

From source file:org.everit.osgi.webconsole.tests.GetConfigurationTest.java

@Before
public void setUp() {
    BasicCredentialsProvider credProv = new BasicCredentialsProvider();
    credProv.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("admin", "admin"));
    client = HttpClientBuilder.create().setDefaultCredentialsProvider(credProv).build();
}

From source file:aajavafx.DevicesController.java

@FXML
private void handleSaveButton(ActionEvent event) {
    //labelError.setText(null);
    try {/*from   w ww. j a  v a 2s  .c  om*/

        String devName = DevName.getText();
        DevName.clear();
        String devID = deviceID.getText();
        deviceID.clear();
        System.out.println(customerBox.getValue());
        String string = (String) customerBox.getValue();
        System.out.println("STRING VALUE: " + string);
        int customerId = Integer.parseInt("" + string.charAt(0));
        System.out.println("CUSTOMER ID VALUE:" + customerId);
        Customers customer = getCustomerByID(customerId);

        Gson gson = new Gson();

        //......for ssl handshake....
        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("EMPLOYEE", "password");
        provider.setCredentials(AuthScope.ANY, credentials);
        //........
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpEntityEnclosingRequestBase HttpEntity = null; //this is the superclass for post, put, get, etc
        if (deviceID.isEditable()) { //then we are posting a new record
            HttpEntity = new HttpPost(DevicesCustomerRootURL); //so make a http post object
        } else { //we are editing a record 
            HttpEntity = new HttpPut(DevicesCustomerRootURL + devID); //so make a http put object
        }
        DevicesCustomers devCust = new DevicesCustomers(devID, devName, customer);

        String jsonString = new String(gson.toJson(devCust));
        System.out.println("json string: " + jsonString);
        StringEntity postString = new StringEntity(jsonString);

        HttpEntity.setEntity(postString);
        HttpEntity.setHeader("Content-type", "application/json");
        HttpResponse response = httpClient.execute(HttpEntity);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == 204) {
            System.out.println("Device posted successfully");
        } else {
            System.out.println("Server error: " + response.getStatusLine());
        }
        DevName.setEditable(false);
        deviceID.setEditable(false);
        customerBox.setDisable(true);

    } catch (Exception ex) {
        System.out.println("Error: " + ex);
    }
    try {
        //refresh table
        tableCustomer.setItems(getDevicesCustomer());
    } catch (IOException ex) {
        Logger.getLogger(DevicesController.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(DevicesController.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:net.wm161.microblog.lib.backends.statusnet.HTTPAPIRequest.java

protected String getData(URI location) throws APIException {
    Log.d("HTTPAPIRequest", "Downloading " + location);
    DefaultHttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(location);
    client.addRequestInterceptor(preemptiveAuth, 0);

    client.getParams().setBooleanParameter("http.protocol.expect-continue", false);

    if (!m_params.isEmpty()) {
        MultipartEntity params = new MultipartEntity();
        for (Entry<String, Object> item : m_params.entrySet()) {
            Object value = item.getValue();
            ContentBody data;// w ww  .  ja v  a2s.c o  m
            if (value instanceof Attachment) {
                Attachment attachment = (Attachment) value;
                try {
                    data = new InputStreamBody(attachment.getStream(), attachment.contentType(),
                            attachment.name());
                    Log.d("HTTPAPIRequest",
                            "Found a " + attachment.contentType() + " attachment named " + attachment.name());
                } catch (FileNotFoundException e) {
                    getRequest().setError(ErrorType.ERROR_ATTACHMENT_NOT_FOUND);
                    throw new APIException();
                } catch (IOException e) {
                    getRequest().setError(ErrorType.ERROR_ATTACHMENT_NOT_FOUND);
                    throw new APIException();
                }
            } else {
                try {
                    data = new StringBody(value.toString());
                } catch (UnsupportedEncodingException e) {
                    getRequest().setError(ErrorType.ERROR_INTERNAL);
                    throw new APIException();
                }
            }
            params.addPart(item.getKey(), data);
        }
        post.setEntity(params);
    }

    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(m_api.getAccount().getUser(),
            m_api.getAccount().getPassword());
    client.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);

    HttpResponse req;
    try {
        req = client.execute(post);
    } catch (ClientProtocolException e3) {
        getRequest().setError(ErrorType.ERROR_CONNECTION_BROKEN);
        throw new APIException();
    } catch (IOException e3) {
        getRequest().setError(ErrorType.ERROR_CONNECTION_FAILED);
        throw new APIException();
    }

    InputStream result;
    try {
        result = req.getEntity().getContent();
    } catch (IllegalStateException e1) {
        getRequest().setError(ErrorType.ERROR_INTERNAL);
        throw new APIException();
    } catch (IOException e1) {
        getRequest().setError(ErrorType.ERROR_CONNECTION_BROKEN);
        throw new APIException();
    }

    InputStreamReader in = null;
    int status;
    in = new InputStreamReader(result);
    status = req.getStatusLine().getStatusCode();
    Log.d("HTTPAPIRequest", "Got status code of " + status);
    setStatusCode(status);
    if (status >= 300 || status < 200) {
        getRequest().setError(ErrorType.ERROR_SERVER);
        Log.w("HTTPAPIRequest", "Server code wasn't 2xx, got " + m_status);
        throw new APIException();
    }

    int totalSize = -1;
    if (req.containsHeader("Content-length"))
        totalSize = Integer.parseInt(req.getFirstHeader("Content-length").getValue());

    char[] buffer = new char[1024];
    //2^17 = 131072.
    StringBuilder contents = new StringBuilder(131072);
    try {
        int size = 0;
        while ((totalSize > 0 && size < totalSize) || totalSize == -1) {
            int readSize = in.read(buffer);
            size += readSize;
            if (readSize == -1)
                break;
            if (totalSize >= 0)
                getRequest().publishProgress(new APIProgress((size / totalSize) * 5000));
            contents.append(buffer, 0, readSize);
        }
    } catch (IOException e) {
        getRequest().setError(ErrorType.ERROR_CONNECTION_BROKEN);
        throw new APIException();
    }
    return contents.toString();
}

From source file:org.eclipse.skalli.core.destination.DestinationComponent.java

private void setCredentials(DefaultHttpClient client, URL url) {
    if (configService == null) {
        return;/* w  ww.jav a  2s . c  o m*/
    }

    DestinationsConfig config = configService.readConfiguration(DestinationsConfig.class);
    if (config == null) {
        return;
    }

    for (DestinationConfig destination : config.getDestinations()) {
        Pattern regex = Pattern.compile(destination.getPattern());
        Matcher matcher = regex.matcher(url.toExternalForm());
        if (matcher.matches()) {
            if (LOG.isDebugEnabled()) {
                LOG.debug(MessageFormat.format("matched URL {0} with destination ''{1}''", url.toExternalForm(),
                        destination.getId()));
            }

            if (StringUtils.isNotBlank(destination.getUser())
                    && StringUtils.isNotBlank(destination.getPattern())) {
                String authenticationMethod = destination.getAuthenticationMethod();
                if ("basic".equalsIgnoreCase(authenticationMethod)) { //$NON-NLS-1$
                    CredentialsProvider credsProvider = new BasicCredentialsProvider();
                    credsProvider.setCredentials(AuthScope.ANY,
                            new UsernamePasswordCredentials(destination.getUser(), destination.getPassword()));
                    client.setCredentialsProvider(credsProvider);
                } else if (StringUtils.isNotBlank(authenticationMethod)) {
                    LOG.warn(MessageFormat.format("Authentication method ''{1}'' is not supported",
                            authenticationMethod));
                }
            }
            break;
        }
    }
}