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

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

Introduction

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

Prototype

public AuthScope(final String host, final int port) 

Source Link

Document

Creates a new credentials scope for the given host, port, any realm name, and any authentication scheme.

Usage

From source file:de.fraunhofer.iosb.ilt.tests.Constants.java

public static SensorThingsService createService(URL serviceUrl)
        throws MalformedURLException, URISyntaxException {
    SensorThingsService service = new SensorThingsService(serviceUrl);
    if (USE_OPENID_CONNECT) {
        service.setTokenManager(new TokenManagerOpenIDConnect().setTokenServerUrl(TOKEN_SERVER_URL)
                .setClientId(CLIENT_ID).setUserName(USERNAME).setPassword(PASSWORD));
    }/* w  w w  . j  a v a 2s . co  m*/
    if (USE_BASIC_AUTH) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        URL url = new URL(BASE_URL);
        credsProvider.setCredentials(new AuthScope(url.getHost(), url.getPort()),
                new UsernamePasswordCredentials(USERNAME, PASSWORD));
        CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider)
                .build();
        service.setClient(httpclient);
    }
    return service;
}

From source file:com.mycompany.projecta.PreemptiveAuth.java

@Override
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
    // Get the AuthState
    AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);

    // If no auth scheme available yet, try to initialize it preemptively
    if (authState.getAuthScheme() == null) {
        AuthScheme authScheme = (AuthScheme) context.getAttribute("preemptive-auth");
        CredentialsProvider credsProvider = (CredentialsProvider) context
                .getAttribute(ClientContext.CREDS_PROVIDER);
        HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        if (authScheme != null) {
            Credentials creds = credsProvider
                    .getCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()));
            if (creds == null) {
                throw new HttpException("No credentials for preemptive authentication");
            }//  ww  w .  j  ava 2s.  c om
            authState.setAuthScheme(authScheme);
            authState.setCredentials(creds);
        }
    }

}

From source file:com.natixis.appdynamics.traitements.GetInfoLicense.java

public Map<String, Object> RetrieveInfoLicense() throws ClientProtocolException, IOException {
    Map<String, Object> myMapInfoLicense = new HashMap<String, Object>();

    HttpClient client = new DefaultHttpClient();

    String[] chaineUrl = GetParamApplication.urlApm.split("/" + "/");
    String hostApm = chaineUrl[1];

    URI uri = null;/* w  ww  . j ava2  s .  c  o m*/
    try {
        uri = new URIBuilder().setScheme("http").setHost(hostApm).setPath(GetParamApplication.uriInfoLicense)
                .setParameter("startdate", GetDateInfoLicence()).setParameter("enddate", GetDateInfoLicence())
                .build();
    } catch (URISyntaxException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    ((DefaultHttpClient) client).getCredentialsProvider().setCredentials(new AuthScope(hostApm, 80),
            new UsernamePasswordCredentials(GetParamApplication.userApm, GetParamApplication.passwordApm));
    HttpGet request = new HttpGet(uri);
    HttpResponse response = client.execute(request);
    HttpEntity entity = response.getEntity();
    String jsonContent = EntityUtils.toString(entity);
    Reader stringReader = new StringReader(jsonContent);
    JsonReader rdr = Json.createReader(stringReader);
    JsonObject obj = rdr.readObject();
    JsonArray results = obj.getJsonArray("usages");

    for (JsonObject result : results.getValuesAs(JsonObject.class)) {
        BeanInfoLicense myBeanInfoLicense = new BeanInfoLicense(result.getString("agentType"),
                result.getInt("avgUnitsAllowed"), result.getInt("avgUnitsUsed"));
        myMapInfoLicense.put(result.getString("agentType"), myBeanInfoLicense);
        //System.out.println(result.getString("agentType")+","+result.getInt("avgUnitsAllowed")+","+result.getInt("avgUnitsUsed"));
    }

    return myMapInfoLicense;
}

From source file:eu.diacron.crawlservice.app.Util.java

public static String getCrawlid(URL urltoCrawl) {
    String crawlid = "";
    System.out.println("start crawling page");

    CredentialsProvider credsProvider = new BasicCredentialsProvider();

    credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(Configuration.REMOTE_CRAWLER_USERNAME,
                    Configuration.REMOTE_CRAWLER_PASS));
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    try {// ww w .  ja v a  2s . co  m
        //HttpPost httppost = new HttpPost("http://diachron.hanzoarchives.com/crawl");
        HttpPost httppost = new HttpPost(Configuration.REMOTE_CRAWLER_URL_CRAWL_INIT);

        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
        urlParameters.add(new BasicNameValuePair("name", UUID.randomUUID().toString()));
        urlParameters.add(new BasicNameValuePair("scope", "page"));
        urlParameters.add(new BasicNameValuePair("seed", urltoCrawl.toString()));

        httppost.setEntity(new UrlEncodedFormEntity(urlParameters));

        System.out.println("Executing request " + httppost.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            System.out.println("----------------------------------------");

            BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                crawlid = inputLine;
            }
            in.close();
            EntityUtils.consume(response.getEntity());
        } finally {
            response.close();
        }
    } catch (IOException ex) {
        Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            httpclient.close();
        } catch (IOException ex) {
            Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    return crawlid;
}

From source file:com.fredhopper.core.connector.index.upload.impl.RestTemplateProvider.java

public RestTemplate createTemplate(final String host, final Integer port, final String username,
        final String password) {
    Preconditions.checkArgument(StringUtils.isNotBlank(host));
    Preconditions.checkArgument(port != null);
    Preconditions.checkArgument(StringUtils.isNotBlank(username));
    Preconditions.checkArgument(StringUtils.isNotBlank(password));

    final AuthScope authscope = new AuthScope(host, port.intValue());
    final Credentials credentials = new UsernamePasswordCredentials(username, password);
    final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(authscope, credentials);

    final HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    final CloseableHttpClient httpClient = clientBuilder.build();

    final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
    requestFactory.setHttpClient(httpClient);

    return new RestTemplate(requestFactory);
}

From source file:main.java.com.surevine.rssimporter.connection.BuddycloudClient.java

public BuddycloudClient(String host, String username, String password) throws MalformedURLException {
    this.host = host;
    httpClient = new DefaultHttpClient();
    httpClient.getCredentialsProvider().setCredentials(new AuthScope(new URL(host).getHost(), 443),
            new UsernamePasswordCredentials(username, password));
}

From source file:jobhunter.api.infojobs.Client.java

public Client() {
    provider = new BasicCredentialsProvider();
    provider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(clientId, privateKey));
}

From source file:uk.ac.ox.oucs.vle.TestPopulatorInput.java

public InputStream getInput(PopulatorContext context) {

    InputStream input;// w  w w  . j a  va  2s  .  co m
    DefaultHttpClient httpclient = new DefaultHttpClient();

    try {
        URL xcri = new URL(context.getURI());
        if ("file".equals(xcri.getProtocol())) {
            input = xcri.openStream();

        } else {
            HttpHost targetHost = new HttpHost(xcri.getHost(), xcri.getPort(), xcri.getProtocol());

            httpclient.getCredentialsProvider().setCredentials(
                    new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                    new UsernamePasswordCredentials(context.getUser(), context.getPassword()));

            HttpGet httpget = new HttpGet(xcri.toURI());
            HttpResponse response = httpclient.execute(targetHost, httpget);
            HttpEntity entity = response.getEntity();

            if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode()) {
                throw new IllegalStateException(
                        "Invalid response [" + response.getStatusLine().getStatusCode() + "]");
            }

            input = entity.getContent();
        }
    } catch (MalformedURLException e) {
        throw new PopulatorException(e.getLocalizedMessage());

    } catch (IllegalStateException e) {
        throw new PopulatorException(e.getLocalizedMessage());

    } catch (IOException e) {
        throw new PopulatorException(e.getLocalizedMessage());

    } catch (URISyntaxException e) {
        throw new PopulatorException(e.getLocalizedMessage());

    }

    return input;
}

From source file:com.sonyericsson.hudson.plugins.gerrit.trigger.utils.HttpUtils.java

/**
 * @param config Gerrit Server Configuration.
 * @param url URL to get.//from  w  w w.  j  av  a2 s  . c o m
 * @return httpresponse.
 * @throws IOException if found.
 */
public static HttpResponse performHTTPGet(IGerritHudsonTriggerConfig config, String url) throws IOException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(url);
    if (config.getGerritProxy() != null && !config.getGerritProxy().isEmpty()) {
        try {
            URL proxyUrl = new URL(config.getGerritProxy());
            HttpHost proxy = new HttpHost(proxyUrl.getHost(), proxyUrl.getPort(), proxyUrl.getProtocol());
            httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        } catch (MalformedURLException e) {
            logger.error("Could not parse proxy URL, attempting without proxy.", e);
        }
    }

    httpclient.getCredentialsProvider().setCredentials(new AuthScope(null, -1), config.getHttpCredentials());
    HttpResponse execute;
    return httpclient.execute(httpGet);
}

From source file:org.wso2.developerstudio.appfactory.core.client.RssClient.java

public static String getDBinfo(String operation, String dsBaseUrl) {
    String url = dsBaseUrl + "NDataSourceAdmin";
    DefaultHttpClient client = new DefaultHttpClient();
    client = (DefaultHttpClient) HttpsJaggeryClient.wrapClient(client, url);
    client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(Authenticator.getInstance().getCredentials().getUser(),
                    Authenticator.getInstance().getCredentials().getPassword()));

    // Generate BASIC scheme object and stick it to the execution context
    BasicScheme basicAuth = new BasicScheme();
    BasicHttpContext context = new BasicHttpContext();
    context.setAttribute("preemptive-auth", basicAuth);
    client.addRequestInterceptor(new PreemptiveAuth(), 0);

    HttpPost post = new HttpPost(url);
    String sopactionValue = "urn:" + operation;
    post.addHeader("SOAPAction", sopactionValue);
    String body = createPayLoad(operation);
    try {//from w ww  .  j  a va  2s  . c  om
        StringEntity entity = new StringEntity(body.toString(), "text/xml", HTTP.DEFAULT_CONTENT_CHARSET);
        post.setEntity(entity);
        HttpResponse response = client.execute(post);
        if (200 == response.getStatusLine().getStatusCode()) {
            HttpEntity entityGetAppsOfUser = response.getEntity();
            BufferedReader rd = new BufferedReader(new InputStreamReader(entityGetAppsOfUser.getContent()));
            StringBuilder sb = new StringBuilder();
            String line = "";
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
            String respond = sb.toString();
            EntityUtils.consume(entityGetAppsOfUser);
            return respond;
        }
    } catch (Exception e) {
        // log.error("Jenkins Client err", e);
    }
    return null;
}