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

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

Introduction

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

Prototype

int ANY_PORT

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

Click Source Link

Document

The -1 value represents any port.

Usage

From source file:com.rightscale.provider.rest.DashboardSession.java

private void setupBasicAuth(StatefulClient client) {
    AuthScope authScope = new AuthScope(_baseURI.getHost(), AuthScope.ANY_PORT, AuthScope.ANY_REALM);
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(_username, _password);
    AbstractHttpClient realClient = (AbstractHttpClient) client.getRealClient();
    realClient.getCredentialsProvider().setCredentials(authScope, creds);
    realClient.addRequestInterceptor(createBasicAuthInterceptor(), 0);
}

From source file:com.intuit.tank.httpclient4.TankHttpClient4.java

@Override
public void addAuth(AuthCredentials creds) {
    String host = (StringUtils.isBlank(creds.getHost()) || "*".equals(creds.getHost())) ? AuthScope.ANY_HOST
            : creds.getHost();/*from  w ww.j a  v a2s. com*/
    String realm = (StringUtils.isBlank(creds.getRealm()) || "*".equals(creds.getRealm())) ? AuthScope.ANY_REALM
            : creds.getRealm();
    int port = NumberUtils.toInt(creds.getPortString(), AuthScope.ANY_PORT);
    String scheme = creds.getScheme() != null ? creds.getScheme().getRepresentation() : AuthScope.ANY_SCHEME;
    AuthScope scope = new AuthScope(host, port, realm, scheme);
    if (AuthScheme.NTLM == creds.getScheme()) {
        context.getCredentialsProvider().setCredentials(scope,
                new NTCredentials(creds.getUserName(), creds.getPassword(), "tank-test", creds.getRealm()));
    } else {
        context.getCredentialsProvider().setCredentials(scope,
                new UsernamePasswordCredentials(creds.getUserName(), creds.getPassword()));
    }

}

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 v  a 2s .  c om

    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());
    }//from  ww  w. j a  v  a  2  s. c om

    return clientBuilder.build();
}

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

@Test
public void testOrganizationCreateUpdateAndDelete() throws Exception {

    // CREATE//  w w  w . j a va2 s .  com
    // 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:net.bitquill.delicious.api.DeliciousClient.java

public final void setCredentials(String username, String password) {
    if (username != null && password != null) {
        mCredentials = new UsernamePasswordCredentials(username, password);
        mHttpClient.getCredentialsProvider().setCredentials(new AuthScope(getApiHostname(), AuthScope.ANY_PORT),
                mCredentials);//from w  w  w  . ja v  a2 s  .  c om
    }
}

From source file:com.jfrog.bintray.client.impl.HttpClientConfigurator.java

private void configureProxy(ProxyConfig proxy) {
    if (proxy != null) {
        config.setProxy(new HttpHost(proxy.getHost(), proxy.getPort()));
        if (proxy.getUserName() != null) {
            Credentials creds = null;/* ww w.j  av a2  s. com*/
            if (proxy.getNtDomain() == null) {
                creds = new UsernamePasswordCredentials(proxy.getUserName(), proxy.getPassword());
                List<String> authPrefs = Arrays.asList(AuthSchemes.DIGEST, AuthSchemes.BASIC, AuthSchemes.NTLM);
                config.setProxyPreferredAuthSchemes(authPrefs);

                // preemptive proxy authentication
                builder.addInterceptorFirst(new ProxyPreemptiveAuthInterceptor());
            } else {
                try {
                    String ntHost = StringUtils.isBlank(proxy.getNtHost())
                            ? InetAddress.getLocalHost().getHostName()
                            : proxy.getNtHost();
                    creds = new NTCredentials(proxy.getUserName(), proxy.getPassword(), ntHost,
                            proxy.getNtDomain());
                } catch (UnknownHostException e) {
                    log.error("Failed to determine required local hostname for NTLM credentials.", e);
                }
            }
            if (creds != null) {
                credsProvider.setCredentials(
                        new AuthScope(proxy.getHost(), proxy.getPort(), AuthScope.ANY_REALM), creds);
                if (proxy.getRedirectToHosts() != null) {
                    for (String hostName : proxy.getRedirectToHosts()) {
                        credsProvider.setCredentials(
                                new AuthScope(hostName, AuthScope.ANY_PORT, AuthScope.ANY_REALM), creds);
                    }
                }
            }
        }
    }
}

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./*  ww  w . j a va2  s .c  o  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) {// ww  w  .  j a v  a2 s  . c om
    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;
}