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

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

Introduction

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

Prototype

String ANY_HOST

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

Click Source Link

Document

The null value represents any host.

Usage

From source file:org.ttrssreader.net.deprecated.ApacheJSONConnector.java

@Override
public void init() {
    super.init();
    if (!httpAuth) {
        credProvider = null;/*from  w w  w.  j a va  2  s  . c o m*/
        return;
    }

    // Refresh Credentials-Provider
    if (httpUsername.equals(Constants.EMPTY) || httpPassword.equals(Constants.EMPTY)) {
        credProvider = null;
    } else {
        credProvider = new BasicCredentialsProvider();
        credProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(httpUsername, httpPassword));
    }
}

From source file:org.ocsinventoryng.android.actions.OCSProtocol.java

public String sendmethod(File pFile, String server, boolean gziped) throws OCSProtocolException {
    OCSLog ocslog = OCSLog.getInstance();
    OCSSettings ocssettings = OCSSettings.getInstance();
    ocslog.debug("Start send method");
    String retour;/*from   www .  ja  va  2s . c o  m*/

    HttpPost httppost;

    try {
        httppost = new HttpPost(server);
    } catch (IllegalArgumentException e) {
        ocslog.error(e.getMessage());
        throw new OCSProtocolException("Incorect serveur URL");
    }

    File fileToPost;
    if (gziped) {
        ocslog.debug("Start compression");
        fileToPost = ocsfile.getGzipedFile(pFile);
        if (fileToPost == null) {
            throw new OCSProtocolException("Error during temp file creation");
        }
        ocslog.debug("Compression done");
    } else {
        fileToPost = pFile;
    }

    FileEntity fileEntity = new FileEntity(fileToPost, "text/plain; charset=\"UTF-8\"");
    httppost.setEntity(fileEntity);
    httppost.setHeader("User-Agent", http_agent);
    if (gziped) {
        httppost.setHeader("Content-Encoding", "gzip");
    }

    DefaultHttpClient httpClient = getNewHttpClient(OCSSettings.getInstance().isSSLStrict());

    if (ocssettings.isProxy()) {
        ocslog.debug("Use proxy : " + ocssettings.getProxyAdr());
        HttpHost proxy = new HttpHost(ocssettings.getProxyAdr(), ocssettings.getProxyPort());
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }
    if (ocssettings.isAuth()) {
        ocslog.debug("Use AUTH : " + ocssettings.getLogin() + "/*****");
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(ocssettings.getLogin(),
                ocssettings.getPasswd());
        ocslog.debug(creds.toString());
        httpClient.getCredentialsProvider()
                .setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), creds);
    }

    ocslog.debug("Call : " + server);
    HttpResponse localHttpResponse;
    try {
        localHttpResponse = httpClient.execute(httppost);
        ocslog.debug("Message sent");
    } catch (ClientProtocolException e) {
        ocslog.error("ClientProtocolException" + e.getMessage());
        throw new OCSProtocolException(e.getMessage());
    } catch (IOException e) {
        String msg = appCtx.getString(R.string.err_cant_connect) + " " + e.getMessage();
        ocslog.error(msg);
        throw new OCSProtocolException(msg);
    }

    try {
        int httpCode = localHttpResponse.getStatusLine().getStatusCode();
        ocslog.debug("Response status code : " + String.valueOf(httpCode));
        if (httpCode == 200) {
            if (gziped) {
                InputStream is = localHttpResponse.getEntity().getContent();
                GZIPInputStream gzis = new GZIPInputStream(is);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] buff = new byte[128];
                int n;
                while ((n = gzis.read(buff, 0, buff.length)) > 0) {
                    baos.write(buff, 0, n);
                }
                retour = baos.toString();
            } else {
                retour = EntityUtils.toString(localHttpResponse.getEntity());
            }
        } else if (httpCode == 400) {
            throw new OCSProtocolException("Error http 400 may be wrong agent version");
        } else {
            ocslog.error("***Server communication error: ");
            throw new OCSProtocolException("Http communication error code " + String.valueOf(httpCode));
        }
        ocslog.debug("Finnish send method");
    } catch (IOException localIOException) {
        String msg = localIOException.getMessage();
        ocslog.error(msg);
        throw new OCSProtocolException(msg);
    }
    return retour;
}

From source file:com.seyren.core.util.graphite.GraphiteHttpClient.java

private HttpClient createHttpClient() {
    HttpClientBuilder clientBuilder = HttpClientBuilder.create().useSystemProperties()
            .setConnectionManager(createConnectionManager())
            .setDefaultRequestConfig(RequestConfig.custom()
                    .setConnectionRequestTimeout(graphiteConnectionRequestTimeout)
                    .setConnectTimeout(graphiteConnectTimeout).setSocketTimeout(graphiteSocketTimeout).build());

    // Set auth header for graphite if username and password are provided
    if (!StringUtils.isEmpty(graphiteUsername) && !StringUtils.isEmpty(graphitePassword)) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(graphiteUsername, graphitePassword));
        clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        context.setAttribute("preemptive-auth", new BasicScheme());
        clientBuilder.addInterceptorFirst(new PreemptiveAuth());
    }/*  w  w  w  .  jav  a 2  s.c  o  m*/

    return clientBuilder.build();
}

From source file:uk.org.openeyes.oink.itest.adapters.ITProxyAdapter.java

@Test
public void testOrganizationCreateUpdateAndDelete() throws Exception {

    // CREATE// www.j a  v a  2s . c  o  m
    // http://192.168.1.100:80/api/Organization?_profile=http://openeyes.org.uk/fhir/1.7.0/profile/Organization/Practice
    OINKRequestMessage req = new OINKRequestMessage();
    req.setResourcePath("/Organization");
    req.setMethod(HttpMethod.POST);
    req.addProfile("http://openeyes.org.uk/fhir/1.7.0/profile/Organization/Practice");
    InputStream is = ITProxyAdapter.class.getResourceAsStream("/example-messages/fhir/organization.json");
    Parser parser = new JsonParser();
    Organization p = (Organization) parser.parse(is);
    FhirBody body = new FhirBody(p);
    req.setBody(body);

    RabbitClient client = new RabbitClient(props.getProperty("rabbit.host"),
            Integer.parseInt(props.getProperty("rabbit.port")), props.getProperty("rabbit.vhost"),
            props.getProperty("rabbit.username"), props.getProperty("rabbit.password"));

    OINKResponseMessage resp = client.sendAndRecieve(req, props.getProperty("rabbit.routingKey"),
            props.getProperty("rabbit.defaultExchange"));

    assertEquals(201, resp.getStatus());
    String locationHeader = resp.getLocationHeader();
    assertNotNull(locationHeader);
    assertFalse(locationHeader.isEmpty());
    log.info("Posted to " + locationHeader);

    // See if Patient exists
    DefaultHttpClient httpClient = new DefaultHttpClient();

    httpClient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials("admin", "admin"));

    HttpGet httpGet = new HttpGet(locationHeader);
    httpGet.setHeader("Accept", "application/fhir+json");
    HttpResponse response1 = httpClient.execute(httpGet);
    assertEquals(200, response1.getStatusLine().getStatusCode());

    // UPDATE
    String id = getIdFromLocationHeader("Organization", locationHeader);
    OINKRequestMessage updateRequest = new OINKRequestMessage();
    updateRequest.setResourcePath("/Organization/" + id);
    updateRequest.setMethod(HttpMethod.PUT);
    updateRequest.addProfile("http://openeyes.org.uk/fhir/1.7.0/profile/Organization/Practice");
    p.getTelecom().get(0).setValueSimple("0222 222 2222");
    updateRequest.setBody(new FhirBody(p));

    OINKResponseMessage updateResponse = client.sendAndRecieve(updateRequest,
            props.getProperty("rabbit.routingKey"), props.getProperty("rabbit.defaultExchange"));
    assertEquals(200, updateResponse.getStatus());

    // DELETE
    OINKRequestMessage deleteRequest = new OINKRequestMessage();
    deleteRequest.setResourcePath("/Organization/" + id);
    deleteRequest.setMethod(HttpMethod.DELETE);
    deleteRequest.addProfile("http://openeyes.org.uk/fhir/1.7.0/profile/Organization/Practice");

    OINKResponseMessage deleteResponse = client.sendAndRecieve(deleteRequest,
            props.getProperty("rabbit.routingKey"), props.getProperty("rabbit.defaultExchange"));
    assertEquals(204, deleteResponse.getStatus());

}

From source file:fr.ippon.wip.http.hc.HttpClientExecutor.java

/**
 * This method updates the CredentialsProvider associated to the current
 * PortletSession and the windowID with the provided login and password.
 * Basic and NTLM authentication schemes are supported. This method uses the
 * current fr.ippon.wip.state.PortletWindow to retrieve the authentication
 * schemes requested by remote server./*from ww w  . j a v a 2s  .  co m*/
 * 
 * @param login
 * @param password
 * @param portletRequest
 *            Used to get current javax.portlet.PortletSession and windowID
 */
public void login(String login, String password, PortletRequest portletRequest) {
    HttpClientResourceManager resourceManager = HttpClientResourceManager.getInstance();
    CredentialsProvider credentialsProvider = resourceManager.getCredentialsProvider(portletRequest);
    PortletWindow portletWindow = PortletWindow.getInstance(portletRequest);
    List<String> schemes = portletWindow.getRequestedAuthSchemes();

    if (schemes.contains("Basic")) {
        // Creating basic credentials
        AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, "Basic");
        Credentials credentials = new UsernamePasswordCredentials(login, password);
        credentialsProvider.setCredentials(scope, credentials);
    }
    if (schemes.contains("NTLM")) {
        // Creating ntlm credentials
        AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, "NTLM");
        Credentials credentials = new NTCredentials(login, password, "", "");
        credentialsProvider.setCredentials(scope, credentials);
    }
}

From source file:com.github.sardine.impl.SardineImpl.java

private CredentialsProvider getCredentialsProvider(String username, String password, String domain,
        String workstation) {/*from   ww  w.ja v a 2 s.  com*/
    CredentialsProvider provider = new BasicCredentialsProvider();
    if (username != null) {
        provider.setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthPolicy.NTLM),
                new NTCredentials(username, password, workstation, domain));
        provider.setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthPolicy.BASIC),
                new UsernamePasswordCredentials(username, password));
        provider.setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthPolicy.DIGEST),
                new UsernamePasswordCredentials(username, password));
        provider.setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthPolicy.SPNEGO),
                new UsernamePasswordCredentials(username, password));
        provider.setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthPolicy.KERBEROS),
                new UsernamePasswordCredentials(username, password));
    }
    return provider;
}

From source file:com.domuslink.communication.ApiHandler.java

/**
 * Pull the raw text content of the given URL. This call blocks until the
 * operation has completed, and is synchronized because it uses a shared
 * buffer {@link #sBuffer}./*from  w  w  w . j  a  v a 2 s .  c  om*/
 *
 * @param type The type of either a GET or POST for the request
 * @param commandURI The constructed URI for the path
 * @return The raw content returned by the server.
 * @throws ApiException If any connection or server error occurs.
 */
protected static synchronized String urlContent(int type, URI commandURI, ApiCookieHandler cookieHandler)
        throws ApiException {
    HttpResponse response;
    HttpRequestBase request;

    if (sUserAgent == null) {
        throw new ApiException("User-Agent string must be prepared");
    }

    // Create client and set our specific user-agent string
    DefaultHttpClient client = new DefaultHttpClient();
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials("", sPassword);
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), creds);
    client.setCredentialsProvider(credsProvider);
    CookieStore cookieStore = cookieHandler.getCookieStore();
    if (cookieStore != null) {
        boolean expiredCookies = false;
        Date nowTime = new Date();
        for (Cookie theCookie : cookieStore.getCookies()) {
            if (theCookie.isExpired(nowTime))
                expiredCookies = true;
        }
        if (!expiredCookies)
            client.setCookieStore(cookieStore);
        else {
            cookieHandler.setCookieStore(null);
            cookieStore = null;
        }
    }

    try {
        if (type == POST_TYPE)
            request = new HttpPost(commandURI);
        else
            request = new HttpGet(commandURI);

        request.setHeader("User-Agent", sUserAgent);
        response = client.execute(request);

        // Check if server response is valid
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() != HTTP_STATUS_OK) {
            Log.e(TAG,
                    "urlContent: Url issue: " + commandURI.toString() + " with status: " + status.toString());
            throw new ApiException("Invalid response from server: " + status.toString());
        }

        // Pull content stream from response
        HttpEntity entity = response.getEntity();
        InputStream inputStream = entity.getContent();

        ByteArrayOutputStream content = new ByteArrayOutputStream();

        // Read response into a buffered stream
        int readBytes = 0;
        while ((readBytes = inputStream.read(sBuffer)) != -1) {
            content.write(sBuffer, 0, readBytes);
        }

        if (cookieStore == null) {
            List<Cookie> realCookies = client.getCookieStore().getCookies();
            if (!realCookies.isEmpty()) {
                BasicCookieStore newCookies = new BasicCookieStore();
                for (int i = 0; i < realCookies.size(); i++) {
                    newCookies.addCookie(realCookies.get(i));
                    //                      Log.d(TAG, "aCookie - " + realCookies.get(i).toString());
                }
                cookieHandler.setCookieStore(newCookies);
            }
        }

        // Return result from buffered stream
        return content.toString();
    } catch (IOException e) {
        Log.e(TAG, "urlContent: client execute: " + commandURI.toString());
        throw new ApiException("Problem communicating with API", e);
    } catch (IllegalArgumentException e) {
        Log.e(TAG, "urlContent: client execute: " + commandURI.toString());
        throw new ApiException("Problem communicating with API", e);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        client.getConnectionManager().shutdown();
    }
}

From source file:org.springframework.xd.dirt.integration.bus.rabbit.RabbitBusCleaner.java

@VisibleForTesting
static RestTemplate buildRestTemplate(String adminUri, String user, String password) {
    BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(user, password));
    HttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    // Set up pre-emptive basic Auth because the rabbit plugin doesn't currently support challenge/response for PUT
    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local; from the apache docs...
    // auth cache
    BasicScheme basicAuth = new BasicScheme();
    URI uri;/*from   w  w  w .j  a  v  a 2 s  . c  o  m*/
    try {
        uri = new URI(adminUri);
    } catch (URISyntaxException e) {
        throw new RabbitAdminException("Invalid URI", e);
    }
    authCache.put(new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()), basicAuth);
    // Add AuthCache to the execution context
    final HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);
    RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient) {

        @Override
        protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
            return localContext;
        }

    });
    restTemplate.setMessageConverters(
            Collections.<HttpMessageConverter<?>>singletonList(new MappingJackson2HttpMessageConverter()));
    return restTemplate;
}

From source file:org.opensaml.soap.client.http.AbstractPipelineHttpSOAPClient.java

/**
 * A convenience method to set a (single) username and password used for BASIC authentication.
 * To disable BASIC authentication pass null for the credentials instance.
 * //from w w w  . j  a  v a 2  s.c o m
 * <p>
 * If the <code>authScope</code> is null, an {@link AuthScope} will be generated which specifies
 * any host, port, scheme and realm.
 * </p>
 * 
 * <p>To specify multiple usernames and passwords for multiple host, port, scheme, and realm combinations, instead 
 * provide an instance of {@link CredentialsProvider} via {@link #setCredentialsProvider(CredentialsProvider)}.</p>
 * 
 * @param credentials the username and password credentials
 * @param scope the HTTP client auth scope with which to scope the credentials, may be null
 */
public void setBasicCredentialsWithScope(@Nullable final UsernamePasswordCredentials credentials,
        @Nullable final AuthScope scope) {
    ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this);
    ComponentSupport.ifDestroyedThrowDestroyedComponentException(this);

    if (credentials != null) {
        AuthScope authScope = scope;
        if (authScope == null) {
            authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT);
        }
        BasicCredentialsProvider provider = new BasicCredentialsProvider();
        provider.setCredentials(authScope, credentials);
        setCredentialsProvider(provider);
    } else {
        log.debug("Either username or password were null, disabling basic auth");
        setCredentialsProvider(null);
    }

}

From source file:com.googlecode.sardine.impl.SardineImpl.java

/**
 * @param username//from  w w w .j  av a  2s.  c o m
 *            Use in authentication header credentials
 * @param password
 *            Use in authentication header credentials
 * @param domain
 *            NTLM authentication
 * @param workstation
 *            NTLM authentication
 */
public void setCredentials(String username, String password, String domain, String workstation) {
    if (username != null) {
        this.client.getCredentialsProvider().setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthPolicy.NTLM),
                new NTCredentials(username, password, workstation, domain));
        this.client.getCredentialsProvider().setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthPolicy.BASIC),
                new UsernamePasswordCredentials(username, password));
        this.client.getCredentialsProvider().setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthPolicy.DIGEST),
                new UsernamePasswordCredentials(username, password));
    }
}