Java Code Examples for org.apache.http.auth.AuthScope

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project Core_2, under directory /shell/src/main/java/org/jboss/forge/shell/util/.

Source file: PluginUtil.java

  22 
vote

private static void configureProxy(final ProxySettings proxySettings,final DefaultHttpClient client){
  if (proxySettings != null) {
    HttpHost proxy=new HttpHost(proxySettings.getProxyHost(),proxySettings.getProxyPort());
    client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);
    if (proxySettings.isAuthenticationSupported()) {
      AuthScope authScope=new AuthScope(proxySettings.getProxyHost(),proxySettings.getProxyPort());
      UsernamePasswordCredentials credentials=new UsernamePasswordCredentials(proxySettings.getProxyUserName(),proxySettings.getProxyPassword());
      client.getCredentialsProvider().setCredentials(authScope,credentials);
    }
  }
}
 

Example 2

From project couchdb-lucene, under directory /src/main/java/com/github/rnewson/couchdb/lucene/.

Source file: HttpClientFactory.java

  22 
vote

public void process(final HttpRequest request,final HttpContext context) throws HttpException, IOException {
  final AuthState authState=(AuthState)context.getAttribute(ClientContext.TARGET_AUTH_STATE);
  final CredentialsProvider credsProvider=(CredentialsProvider)context.getAttribute(ClientContext.CREDS_PROVIDER);
  final HttpHost targetHost=(HttpHost)context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
  if (authState.getAuthScheme() == null) {
    AuthScope authScope=new AuthScope(targetHost.getHostName(),targetHost.getPort());
    Credentials creds=credsProvider.getCredentials(authScope);
    if (creds != null) {
      authState.setAuthScheme(new BasicScheme());
      authState.setCredentials(creds);
    }
  }
}
 

Example 3

From project DeliciousDroid, under directory /src/com/deliciousdroid/client/.

Source file: PreemptiveAuthInterceptor.java

  22 
vote

public void process(final HttpRequest request,final HttpContext context) throws HttpException, IOException {
  AuthState authState=(AuthState)context.getAttribute(ClientContext.TARGET_AUTH_STATE);
  CredentialsProvider credsProvider=(CredentialsProvider)context.getAttribute(ClientContext.CREDS_PROVIDER);
  HttpHost targetHost=(HttpHost)context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
  if (authState.getAuthScheme() == null) {
    AuthScope authScope=new AuthScope(targetHost.getHostName(),targetHost.getPort());
    Credentials creds=credsProvider.getCredentials(authScope);
    if (creds != null) {
      authState.setAuthScheme(new BasicScheme());
      authState.setCredentials(creds);
    }
  }
}
 

Example 4

From project droidparts, under directory /extra/src/org/droidparts/http/wrapper/.

Source file: DefaultHttpClientWrapper.java

  22 
vote

@Override protected void setProxy(String protocol,String host,int port,String user,String password){
  HttpHost proxyHost=new HttpHost(host,port,protocol);
  httpClient.getParams().setParameter(DEFAULT_PROXY,proxyHost);
  if (!isEmpty(user) && !isEmpty(password)) {
    AuthScope authScope=new AuthScope(host,port);
    UsernamePasswordCredentials credentials=new UsernamePasswordCredentials(user,password);
    httpClient.getCredentialsProvider().setCredentials(authScope,credentials);
  }
}
 

Example 5

From project exo.social.client, under directory /src/main/java/org/exoplatform/social/client/core/net/.

Source file: SocialHttpClientImpl.java

  22 
vote

@Override public void process(HttpRequest request,HttpContext context) throws HttpException, IOException {
  AuthState authState=(AuthState)context.getAttribute(ClientContext.TARGET_AUTH_STATE);
  CredentialsProvider credsProvider=(CredentialsProvider)context.getAttribute(ClientContext.CREDS_PROVIDER);
  HttpHost targetHost=(HttpHost)context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
  if (authState.getAuthScheme() == null) {
    AuthScope authScope=new AuthScope(targetHost.getHostName(),targetHost.getPort());
    Credentials creds=credsProvider.getCredentials(authScope);
    if (creds != null) {
      authState.setAuthScheme(new BasicScheme());
      authState.setCredentials(creds);
    }
  }
}
 

Example 6

From project fanfoudroid, under directory /src/com/ch_linghu/fanfoudroid/http/.

Source file: HttpClient.java

  22 
vote

@Override public void process(final HttpRequest request,final HttpContext context){
  AuthState authState=(AuthState)context.getAttribute(ClientContext.TARGET_AUTH_STATE);
  CredentialsProvider credsProvider=(CredentialsProvider)context.getAttribute(ClientContext.CREDS_PROVIDER);
  HttpHost targetHost=(HttpHost)context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
  if (authState.getAuthScheme() == null) {
    AuthScope authScope=new AuthScope(targetHost.getHostName(),targetHost.getPort());
    Credentials creds=credsProvider.getCredentials(authScope);
    if (creds != null) {
      authState.setAuthScheme(new BasicScheme());
      authState.setCredentials(creds);
    }
  }
}
 

Example 7

From project httpClient, under directory /httpclient/src/test/java/org/apache/http/impl/client/integration/.

Source file: TestClientAuthentication.java

  22 
vote

@Test public void testBasicAuthenticationNoCreds() throws Exception {
  this.localServer.register("*",new AuthHandler());
  TestCredentialsProvider credsProvider=new TestCredentialsProvider(null);
  this.httpclient=new HttpClientBuilder().setCredentialsProvider(credsProvider).build();
  HttpGet httpget=new HttpGet("/");
  HttpResponse response=this.httpclient.execute(getServerHttp(),httpget);
  HttpEntity entity=response.getEntity();
  Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED,response.getStatusLine().getStatusCode());
  Assert.assertNotNull(entity);
  EntityUtils.consume(entity);
  AuthScope authscope=credsProvider.getAuthScope();
  Assert.assertNotNull(authscope);
  Assert.assertEquals("test realm",authscope.getRealm());
}
 

Example 8

From project Shopify4J, under directory /ShopifyAPI/src/com/shopify/api/.

Source file: APIAuthorization.java

  22 
vote

public HttpClient getAuthorizedClient(String hostName,int port){
  if (client == null) {
    DefaultHttpClient client=new DefaultHttpClient();
    client.addRequestInterceptor(new ShopifyRequestInterceptor());
    client.addResponseInterceptor(new ShopifyResponseInterceptor());
    AuthScope scope=new AuthScope(hostName,port);
    UsernamePasswordCredentials creds=new UsernamePasswordCredentials(credential.getApiKey(),credential.getPassword());
    client.getCredentialsProvider().setCredentials(scope,creds);
    this.client=client;
  }
  return client;
}
 

Example 9

From project zirco-browser, under directory /src/org/emergent/android/weave/client/.

Source file: WeaveTransport.java

  22 
vote

public void process(final HttpRequest request,final HttpContext context) throws HttpException, IOException {
  AuthState authState=(AuthState)context.getAttribute(ClientContext.TARGET_AUTH_STATE);
  CredentialsProvider credsProvider=(CredentialsProvider)context.getAttribute(ClientContext.CREDS_PROVIDER);
  HttpHost targetHost=(HttpHost)context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
  if (authState.getAuthScheme() == null) {
    AuthScope authScope=new AuthScope(targetHost.getHostName(),targetHost.getPort());
    Credentials creds=credsProvider.getCredentials(authScope);
    if (creds != null) {
      authState.setAuthScheme(new BasicScheme());
      authState.setCredentials(creds);
    }
  }
}
 

Example 10

From project android-client, under directory /xwiki-android-rest/src/org/xwiki/android/rest/.

Source file: HttpConnector.java

  21 
vote

/** 
 * set user credentials with manually developed preemtive Auth
 */
private void setCredentials(){
  if (isSecured) {
    preemptiveAuth=new HttpRequestInterceptor(){
      public void process(      HttpRequest request,      HttpContext context) throws HttpException, IOException {
        AuthState authState=(AuthState)context.getAttribute(ClientContext.TARGET_AUTH_STATE);
        CredentialsProvider credsProvider=(CredentialsProvider)context.getAttribute(ClientContext.CREDS_PROVIDER);
        HttpHost targetHost=(HttpHost)context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        if (authState.getAuthScheme() == null) {
          AuthScope authScope=new AuthScope(targetHost.getHostName(),targetHost.getPort());
          Credentials creds=credsProvider.getCredentials(authScope);
          if (creds != null) {
            authState.setAuthScheme(new BasicScheme());
            authState.setCredentials(creds);
          }
        }
      }
    }
;
    client.addRequestInterceptor(preemptiveAuth,0);
    Credentials defaultcreds=new UsernamePasswordCredentials(username,password);
    client.getCredentialsProvider().setCredentials(new AuthScope(null,-1,AuthScope.ANY_REALM),defaultcreds);
  }
}
 

Example 11

From project build-info, under directory /build-info-client/src/main/java/org/jfrog/build/client/.

Source file: PreemptiveHttpClient.java

  21 
vote

public void setProxyConfiguration(String host,int port,String username,String password){
  HttpHost proxy=new HttpHost(host,port);
  httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);
  if (username != null) {
    httpClient.getCredentialsProvider().setCredentials(new AuthScope(host,port),new UsernamePasswordCredentials(username,password));
  }
}
 

Example 12

From project chargifyService, under directory /src/main/java/com/mondora/chargify/controller/.

Source file: Chargify.java

  21 
vote

protected void setup(String key,String domain){
  this.domain=domain;
  this.key=key;
  host=new HttpHost(domain + ".chargify.com",443,"https");
  UsernamePasswordCredentials creds=new UsernamePasswordCredentials(key,"x");
  credsProvider=new BasicCredentialsProvider();
  credsProvider.setCredentials(new AuthScope(domain + ".chargify.com",443,"ChargifyService API"),creds);
  if (logger.isDebugEnabled())   logger.debug("ChargifyService client created for domain " + domain);
}
 

Example 13

From project Fotolia-API, under directory /java/org/webservice/fotolia/.

Source file: FotoliaApi.java

  21 
vote

/** 
 * Construct and returns a usuable http client
 * @param auto_refresh_token
 * @return DefaultHttpClient
 */
private DefaultHttpClient _getHttpClient(final boolean auto_refresh_token){
  DefaultHttpClient client;
  client=new DefaultHttpClient();
  client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST,AuthScope.ANY_PORT,AuthScope.ANY_REALM),new UsernamePasswordCredentials(this._api_key,this._getSessionId(auto_refresh_token)));
  HttpConnectionParams.setConnectionTimeout(client.getParams(),FotoliaApi.API_CONNECT_TIMEOUT * 1000);
  HttpConnectionParams.setSoTimeout(client.getParams(),FotoliaApi.API_PROCESS_TIMEOUT * 1000);
  return client;
}
 

Example 14

From project friendica-for-android, under directory /mw-android-friendica-01/src/de/wikilab/android/friendica01/.

Source file: TwAjax.java

  21 
vote

private void setHttpClientProxy(DefaultHttpClient httpclient){
  if (myProxyIp == null)   return;
  httpclient.getCredentialsProvider().setCredentials(new AuthScope(myProxyIp,myProxyPort),new UsernamePasswordCredentials(myProxyUsername,myProxyPassword));
  HttpHost proxy=new HttpHost(myProxyIp,myProxyPort);
  httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);
}
 

Example 15

From project isohealth, under directory /Oauth/java/core/httpclient4/src/main/java/net/oauth/client/httpclient4/.

Source file: PreemptiveAuthorizer.java

  21 
vote

/** 
 * If no auth scheme has been selected for the given context, consider each of the preferred auth schemes and select the first one for which an AuthScheme and matching Credentials are available.
 */
public void process(HttpRequest request,HttpContext context) throws HttpException, IOException {
  AuthState authState=(AuthState)context.getAttribute(ClientContext.TARGET_AUTH_STATE);
  if (authState != null && authState.getAuthScheme() != null) {
    return;
  }
  HttpHost target=(HttpHost)context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
  CredentialsProvider creds=(CredentialsProvider)context.getAttribute(ClientContext.CREDS_PROVIDER);
  AuthSchemeRegistry schemes=(AuthSchemeRegistry)context.getAttribute(ClientContext.AUTHSCHEME_REGISTRY);
  for (  Object schemeName : (Iterable)context.getAttribute(ClientContext.AUTH_SCHEME_PREF)) {
    AuthScheme scheme=schemes.getAuthScheme(schemeName.toString(),request.getParams());
    if (scheme != null) {
      AuthScope targetScope=new AuthScope(target.getHostName(),target.getPort(),scheme.getRealm(),scheme.getSchemeName());
      Credentials cred=creds.getCredentials(targetScope);
      if (cred != null) {
        authState.setAuthScheme(scheme);
        authState.setCredentials(cred);
        return;
      }
    }
  }
}
 

Example 16

From project lightbox-android-webservices, under directory /LightboxAndroidWebServices/src/com/lightbox/android/network/.

Source file: HttpHelper.java

  21 
vote

/** 
 * Set Http Basic Authentication. 
 * @param hostname
 * @param username
 * @param password
 */
public void setBasicAuth(String hostname,String username,String password){
  if (hostname != null && username != null && password != null) {
    mHttpClient.getCredentialsProvider().setCredentials(new AuthScope(hostname,443,AuthScope.ANY_REALM),new UsernamePasswordCredentials(username,password));
    mHttpClient.getCredentialsProvider().setCredentials(new AuthScope(hostname,80,AuthScope.ANY_REALM),new UsernamePasswordCredentials(username,password));
  }
}
 

Example 17

From project Locast-Android, under directory /src/edu/mit/mobile/android/locast/net/.

Source file: NetworkClient.java

  21 
vote

private void setBaseUrl(String baseUrlString) throws MalformedURLException {
  final URL baseUrl=new URL(baseUrlString);
  try {
    mBaseUrl=baseUrl.toURI();
    mAuthScope=new AuthScope(mBaseUrl.getHost(),mBaseUrl.getPort());
  }
 catch (  final URISyntaxException e) {
    final MalformedURLException me=new MalformedURLException(e.getLocalizedMessage());
    me.initCause(e);
    throw me;
  }
}
 

Example 18

From project maven-wagon, under directory /wagon-providers/wagon-http-shared4/src/main/java/org/apache/maven/wagon/shared/http4/.

Source file: AbstractHttpClientWagon.java

  21 
vote

public void openConnectionInternal(){
  repository.setUrl(getURL(repository));
  client=new DefaultHttpClient(getConnectionManager());
  client.getParams().setParameter(ClientPNames.COOKIE_POLICY,CookiePolicy.BROWSER_COMPATIBILITY);
  if (authenticationInfo != null) {
    String username=authenticationInfo.getUserName();
    String password=authenticationInfo.getPassword();
    if (StringUtils.isNotEmpty(username) && StringUtils.isNotEmpty(password)) {
      Credentials creds=new UsernamePasswordCredentials(username,password);
      String host=getRepository().getHost();
      int port=getRepository().getPort() > -1 ? getRepository().getPort() : AuthScope.ANY_PORT;
      client.getCredentialsProvider().setCredentials(new AuthScope(host,port),creds);
    }
  }
  ProxyInfo proxyInfo=getProxyInfo(getRepository().getProtocol(),getRepository().getHost());
  if (proxyInfo != null) {
    String proxyUsername=proxyInfo.getUserName();
    String proxyPassword=proxyInfo.getPassword();
    String proxyHost=proxyInfo.getHost();
    int proxyPort=proxyInfo.getPort();
    String proxyNtlmHost=proxyInfo.getNtlmHost();
    String proxyNtlmDomain=proxyInfo.getNtlmDomain();
    if (proxyHost != null) {
      HttpHost proxy=new HttpHost(proxyHost,proxyPort);
      if (proxyUsername != null && proxyPassword != null) {
        Credentials creds;
        if (proxyNtlmHost != null || proxyNtlmDomain != null) {
          creds=new NTCredentials(proxyUsername,proxyPassword,proxyNtlmHost,proxyNtlmDomain);
        }
 else {
          creds=new UsernamePasswordCredentials(proxyUsername,proxyPassword);
        }
        int port=proxyInfo.getPort() > -1 ? proxyInfo.getPort() : AuthScope.ANY_PORT;
        AuthScope authScope=new AuthScope(proxyHost,port);
        client.getCredentialsProvider().setCredentials(authScope,creds);
      }
      client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);
    }
  }
}
 

Example 19

From project nuxeo-android, under directory /nuxeo-android-connector/src/main/java/org/nuxeo/ecm/automation/client/jaxrs/impl/.

Source file: HttpPreemptiveAuthInterceptor.java

  21 
vote

@Override public void process(HttpRequest request,HttpContext context) throws HttpException, IOException {
  AuthState authState=(AuthState)context.getAttribute(ClientContext.TARGET_AUTH_STATE);
  if (authState.getAuthScheme() != null) {
    return;
  }
  CredentialsProvider credsProvider=(CredentialsProvider)context.getAttribute(ClientContext.CREDS_PROVIDER);
  HttpHost targetHost=(HttpHost)context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
  AuthScope authScope=new AuthScope(targetHost.getHostName(),targetHost.getPort());
  Credentials creds=credsProvider.getCredentials(authScope);
  if (creds == null) {
    System.out.println("no credentials provided for " + authScope);
    return;
  }
  authState.setAuthScheme(authScheme);
  authState.setCredentials(creds);
}
 

Example 20

From project OpenMEAP, under directory /java-shared/openmeap-shared-jdk5/src/com/openmeap/http/.

Source file: HttpRequestExecuterImpl.java

  21 
vote

protected void setProxy(DefaultHttpClient httpclient,String proxyHost,Integer proxyPort,String proxyUser,String proxyPassword){
  if (proxyUser != null) {
    httpclient.getCredentialsProvider().setCredentials(new AuthScope(proxyHost,proxyPort),new UsernamePasswordCredentials(proxyUser,proxyPassword));
  }
  HttpHost proxy=new HttpHost(proxyHost,proxyPort);
  httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);
}
 

Example 21

From project overthere, under directory /src/main/java/com/xebialabs/overthere/cifs/winrm/connector/.

Source file: ApacheHttpComponentsHttpClientHttpConnector.java

  21 
vote

/** 
 * Configure auth schemes to use for the HttpClient.
 */
protected void configureAuthentication(final DefaultHttpClient httpclient,final String scheme,final Principal principal){
  httpclient.getCredentialsProvider().setCredentials(new AuthScope(ANY_HOST,ANY_PORT,ANY_REALM,scheme),new Credentials(){
    public Principal getUserPrincipal(){
      return principal;
    }
    public String getPassword(){
      return password;
    }
  }
);
}
 

Example 22

From project platform_external_apache-http, under directory /src/org/apache/http/impl/client/.

Source file: BasicCredentialsProvider.java

  21 
vote

/** 
 * Find matching  {@link Credentials credentials} for the given authentication scope.
 * @param map the credentials hash map
 * @param authscope the {@link AuthScope authentication scope}
 * @return the credentials 
 */
private static Credentials matchCredentials(final HashMap<AuthScope,Credentials> map,final AuthScope authscope){
  Credentials creds=map.get(authscope);
  if (creds == null) {
    int bestMatchFactor=-1;
    AuthScope bestMatch=null;
    for (    AuthScope current : map.keySet()) {
      int factor=authscope.match(current);
      if (factor > bestMatchFactor) {
        bestMatchFactor=factor;
        bestMatch=current;
      }
    }
    if (bestMatch != null) {
      creds=map.get(bestMatch);
    }
  }
  return creds;
}
 

Example 23

From project Primum-Android, under directory /src/main/java/com/primum/mobile/rest/.

Source file: AbstractRESTClient.java

  21 
vote

public AbstractRESTClient(PrimumPrefs_ primumPrefs){
  this.primumPrefs=primumPrefs;
  httpClient=new DefaultHttpClient();
  String serviceUrl=primumPrefs.serviceUrl().getOr(Constants.DEFAULT_SERVICE_URL);
  httpClient.getCredentialsProvider().setCredentials(new AuthScope(serviceUrl,80),new UsernamePasswordCredentials(primumPrefs.serviceUser().get(),primumPrefs.servicepass().get()));
  baseUrl="http://" + serviceUrl + "/"+ getServiceContext()+ "/api/secure/jsonws/"+ getModelName();
  requestFactory=new HttpComponentsClientHttpRequestFactory(httpClient);
  rt=new RestTemplate(requestFactory);
  rt.getMessageConverters().add(new GsonHttpMessageConverter());
}
 

Example 24

From project processFlowProvision, under directory /osProvision/src/main/java/org/jboss/processFlow/openshift/.

Source file: ShifterProvisioner.java

  21 
vote

private void prepConnection() throws Exception {
  httpClient=new DefaultHttpClient();
  SSLContext sslContext=SSLContext.getInstance("SSL");
  sslContext.init(null,new TrustManager[]{new X509TrustManager(){
    public X509Certificate[] getAcceptedIssuers(){
      System.out.println("getAcceptedIssuers =============");
      return null;
    }
    public void checkClientTrusted(    X509Certificate[] certs,    String authType){
      System.out.println("checkClientTrusted =============");
    }
    public void checkServerTrusted(    X509Certificate[] certs,    String authType){
      System.out.println("checkServerTrusted =============");
    }
  }
},new SecureRandom());
  SSLSocketFactory ssf=new SSLSocketFactory(sslContext,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  ClientConnectionManager ccm=httpClient.getConnectionManager();
  SchemeRegistry sr=ccm.getSchemeRegistry();
  sr.register(new Scheme("https",443,ssf));
  UsernamePasswordCredentials credentials=new UsernamePasswordCredentials(accountId,password);
  URL urlObj=new URL(openshiftRestURI);
  AuthScope aScope=new AuthScope(urlObj.getHost(),urlObj.getPort());
  httpClient.getCredentialsProvider().setCredentials(aScope,credentials);
  httpClient.addRequestInterceptor(new PreemptiveAuthInterceptor(),0);
}
 

Example 25

From project qi4j-libraries, under directory /shiro-core/src/test/java/org/qi4j/library/shiro/.

Source file: UsernamePasswordHttpBasicTest.java

  21 
vote

@Test public void test() throws IOException {
  HttpGet get=new HttpGet(SECURED_SERVLET_PATH);
  ResponseHandler<String> responseHandler=new BasicResponseHandler();
  DefaultHttpClient client=new DefaultHttpClient();
  client.getCredentialsProvider().setCredentials(new AuthScope(httpHost.getHostName(),httpHost.getPort()),new UsernamePasswordCredentials(UsernameFixtures.USERNAME,new String(UsernameFixtures.PASSWORD)));
  String response=client.execute(httpHost,get,responseHandler);
  assertEquals(ServletUsingSecuredService.OK,response);
  soutCookies(client.getCookieStore().getCookies());
  client.getCredentialsProvider().clear();
  response=client.execute(httpHost,get,responseHandler);
  assertEquals(ServletUsingSecuredService.OK,response);
}
 

Example 26

From project tshirtslayer_android, under directory /src/org/xmlrpc/android/.

Source file: XMLRPCClient.java

  21 
vote

/** 
 * Sets basic authentication on web request using plain credentials
 * @param username The plain text username
 * @param password The plain text password
 * @param doPreemptiveAuth Select here whether to authenticate without it being requested first by the server.  
 */
public void setBasicAuthentication(String username,String password,boolean doPreemptiveAuth){
  if (doPreemptiveAuth=true) {
    this.httpPreAuth=doPreemptiveAuth;
    this.username=username;
    this.password=password;
  }
 else {
    ((DefaultHttpClient)client).getCredentialsProvider().setCredentials(new AuthScope(postMethod.getURI().getHost(),postMethod.getURI().getPort(),AuthScope.ANY_REALM),new UsernamePasswordCredentials(username,password));
  }
}
 

Example 27

From project api-sdk-java, under directory /api-sdk/src/main/java/com/smartling/api/sdk/file/.

Source file: FileApiClientAdapterImpl.java

  20 
vote

private void setupProxy(HttpClient httpClient){
  HttpHost proxy;
  String protocol=null;
  if (StringUtils.isNotBlank(System.getProperty(SCHEME_HTTPS + PROPERTY_SUFFIX_PROXY_HOST)) && StringUtils.isNotBlank(System.getProperty(SCHEME_HTTPS + PROPERTY_SUFFIX_PROXY_PORT)))   protocol=SCHEME_HTTPS;
 else   if (StringUtils.isNotBlank(System.getProperty(SCHEME_HTTP + PROPERTY_SUFFIX_PROXY_HOST)) && StringUtils.isNotBlank(System.getProperty(SCHEME_HTTP + PROPERTY_SUFFIX_PROXY_PORT)))   protocol=SCHEME_HTTP;
  if (null != protocol) {
    String proxyHost=System.getProperty(protocol + PROPERTY_SUFFIX_PROXY_HOST);
    Integer proxyPort=Integer.valueOf(System.getProperty(protocol + PROPERTY_SUFFIX_PROXY_PORT));
    String proxyUsername=System.getProperty(protocol + PROPERTY_SUFFIX_PROXY_USERNAME);
    String proxyPassword=System.getProperty(protocol + PROPERTY_SUFFIX_PROXY_PASSWORD);
    if (StringUtils.isNotBlank(proxyUsername) && StringUtils.isNotBlank(proxyPassword) && httpClient instanceof DefaultHttpClient) {
      ((DefaultHttpClient)httpClient).getCredentialsProvider().setCredentials(new AuthScope(proxyHost,proxyPort,protocol),new UsernamePasswordCredentials(proxyUsername,proxyPassword));
    }
    proxy=new HttpHost(proxyHost,proxyPort,protocol);
    httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);
  }
}
 

Example 28

From project capedwarf-green, under directory /connect/src/main/java/org/jboss/capedwarf/connect/server/.

Source file: ServerProxyHandler.java

  20 
vote

/** 
 * Get client.
 * @return the client
 */
private synchronized HttpClient getClient(){
  if (client == null) {
    HttpParams params=createHttpParams();
    HttpProtocolParams.setVersion(params,config.getHttpVersion());
    HttpProtocolParams.setContentCharset(params,config.getContentCharset());
    HttpProtocolParams.setUseExpectContinue(params,config.isExpectContinue());
    HttpConnectionParams.setStaleCheckingEnabled(params,config.isStaleCheckingEnabled());
    HttpConnectionParams.setConnectionTimeout(params,config.getConnectionTimeout());
    HttpConnectionParams.setSoTimeout(params,config.getSoTimeout());
    HttpConnectionParams.setSocketBufferSize(params,config.getSocketBufferSize());
    SchemeRegistry schemeRegistry=createSchemeRegistry();
    ClientConnectionManager ccm=createClientConnectionManager(params,schemeRegistry);
    HttpClient tmp=createClient(ccm,params);
    String username=config.getUsername();
    String password=config.getPassword();
    if (username != null && password != null) {
      if (tmp instanceof AbstractHttpClient) {
        CredentialsProvider credsProvider=AbstractHttpClient.class.cast(tmp).getCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(config.getHostName(),config.getSslPort()),new UsernamePasswordCredentials(username,password));
      }
 else {
        Logger.getLogger(getClass().getName()).warning("Cannot set CredentialsProvider on HttpClient: " + tmp);
      }
    }
    client=tmp;
  }
  return client;
}
 

Example 29

From project CityBikes, under directory /src/net/homelinux/penecoptero/android/citybikes/app/.

Source file: RESTHelper.java

  20 
vote

private static DefaultHttpClient setCredentials(DefaultHttpClient httpclient,String url,String username,String password) throws HttpException, IOException {
  HttpHost targetHost=new HttpHost(url);
  final UsernamePasswordCredentials access=new UsernamePasswordCredentials(username,password);
  httpclient.getCredentialsProvider().setCredentials(new AuthScope(targetHost.getHostName(),targetHost.getPort()),access);
  httpclient.addRequestInterceptor(new HttpRequestInterceptor(){
    @Override public void process(    HttpRequest request,    HttpContext context) throws HttpException, IOException {
      AuthState authState=(AuthState)context.getAttribute(ClientContext.TARGET_AUTH_STATE);
      if (authState.getAuthScheme() == null) {
        authState.setAuthScheme(new BasicScheme());
        authState.setCredentials(access);
      }
    }
  }
,0);
  return httpclient;
}
 

Example 30

From project cloudify, under directory /rest-client/src/main/java/org/cloudifysource/restclient/.

Source file: GSRestClient.java

  20 
vote

/** 
 * Ctor.
 * @param username Username for the HTTP client, optional.
 * @param password Password for the HTTP client, optional.
 * @param url      URL to the rest service.
 * @param version  cloudify api version of the client 
 * @throws RestException Reporting failure to create a SSL HTTP client.
 */
public GSRestClient(final String username,final String password,final URL url,final String version) throws RestException {
  this.url=url;
  this.urlStr=createUrlStr();
  if (isSSL()) {
    httpClient=getSSLHttpClient();
  }
 else {
    httpClient=new DefaultHttpClient();
  }
  httpClient.addRequestInterceptor(new HttpRequestInterceptor(){
    @Override public void process(    HttpRequest request,    HttpContext context) throws HttpException, IOException {
      request.addHeader(CloudifyConstants.REST_API_VERSION_HEADER,version);
    }
  }
);
  if (StringUtils.notEmpty(username) && StringUtils.notEmpty(password)) {
    httpClient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY),new UsernamePasswordCredentials(username,password));
  }
}
 

Example 31

From project ihatovgram, under directory /src/client/android/ihatovgram/lib/httpcomponents-client-4.1.3/examples/org/apache/http/examples/client/.

Source file: ClientAuthentication.java

  20 
vote

public static void main(String[] args) throws Exception {
  DefaultHttpClient httpclient=new DefaultHttpClient();
  try {
    httpclient.getCredentialsProvider().setCredentials(new AuthScope("localhost",443),new UsernamePasswordCredentials("username","password"));
    HttpGet httpget=new HttpGet("https://localhost/protected");
    System.out.println("executing request" + httpget.getRequestLine());
    HttpResponse response=httpclient.execute(httpget);
    HttpEntity entity=response.getEntity();
    System.out.println("----------------------------------------");
    System.out.println(response.getStatusLine());
    if (entity != null) {
      System.out.println("Response content length: " + entity.getContentLength());
    }
    EntityUtils.consume(entity);
  }
  finally {
    httpclient.getConnectionManager().shutdown();
  }
}
 

Example 32

From project iSpace, under directory /base/httpcrawler/src/main/java/com/villemos/ispace/httpcrawler/.

Source file: HttpClientConfigurer.java

  20 
vote

public static HttpClient setupClient(boolean ignoreAuthenticationFailure,String domain,Integer port,String proxyHost,Integer proxyPort,String authUser,String authPassword,CookieStore cookieStore) throws NoSuchAlgorithmException, KeyManagementException {
  DefaultHttpClient client=null;
  if (ignoreAuthenticationFailure) {
    SSLContext sslContext=SSLContext.getInstance("SSL");
    sslContext.init(null,new TrustManager[]{new EasyX509TrustManager()},new SecureRandom());
    SchemeRegistry schemeRegistry=new SchemeRegistry();
    SSLSocketFactory sf=new SSLSocketFactory(sslContext);
    Scheme httpsScheme=new Scheme("https",sf,443);
    schemeRegistry.register(httpsScheme);
    SocketFactory sfa=new PlainSocketFactory();
    Scheme httpScheme=new Scheme("http",sfa,80);
    schemeRegistry.register(httpScheme);
    HttpParams params=new BasicHttpParams();
    ClientConnectionManager cm=new SingleClientConnManager(params,schemeRegistry);
    client=new DefaultHttpClient(cm,params);
  }
 else {
    client=new DefaultHttpClient();
  }
  if (proxyHost != null && proxyPort != null) {
    HttpHost proxy=new HttpHost(proxyHost,proxyPort);
    client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);
  }
 else {
    ProxySelectorRoutePlanner routePlanner=new ProxySelectorRoutePlanner(client.getConnectionManager().getSchemeRegistry(),ProxySelector.getDefault());
    client.setRoutePlanner(routePlanner);
  }
  if (authUser != null && authPassword != null) {
    client.getCredentialsProvider().setCredentials(new AuthScope(domain,port),new UsernamePasswordCredentials(authUser,authPassword));
  }
  client.setCookieStore(cookieStore);
  client.getParams().setParameter(ClientPNames.COOKIE_POLICY,CookiePolicy.BEST_MATCH);
  return client;
}
 

Example 33

From project jira-hudson-integration, under directory /hudson-apiv2-wsclient/src/main/java/com/marvelution/hudson/plugins/apiv2/client/connectors/.

Source file: HttpClient4Connector.java

  20 
vote

/** 
 * Get the  {@link AuthScope} for the {@link #server}
 * @return the {@link AuthScope}
 */
private AuthScope getAuthScope(){
  String host=AuthScope.ANY_HOST;
  int port=AuthScope.ANY_PORT;
  try {
    final URI hostUri=new URI(server.getHost());
    host=hostUri.getHost();
    if (hostUri.getPort() > -1) {
      port=hostUri.getPort();
    }
 else     if ("http".equalsIgnoreCase(hostUri.getScheme())) {
      port=80;
    }
 else     if ("https".equalsIgnoreCase(hostUri.getScheme())) {
      port=443;
    }
  }
 catch (  URISyntaxException e) {
    log.error("Failed to parse the Server host url to an URI",e);
  }
  return new AuthScope(host,port,"realm");
}
 

Example 34

From project milton, under directory /milton/apps/milton-android-photouploader/src/com/ettrema/android/photouploader/.

Source file: MiltonPostUploader.java

  20 
vote

public void process(final HttpRequest request,final HttpContext context) throws HttpException, IOException {
  AuthState authState=(AuthState)context.getAttribute(ClientContext.TARGET_AUTH_STATE);
  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");
      }
      authState.setAuthScheme(authScheme);
      authState.setCredentials(creds);
    }
  }
}
 

Example 35

From project milton2, under directory /apps/milton-android-photouploader/src/com/ettrema/android/photouploader/.

Source file: MiltonPostUploader.java

  20 
vote

public void process(final HttpRequest request,final HttpContext context) throws HttpException, IOException {
  AuthState authState=(AuthState)context.getAttribute(ClientContext.TARGET_AUTH_STATE);
  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");
      }
      authState.setAuthScheme(authScheme);
      authState.setCredentials(creds);
    }
  }
}
 

Example 36

From project nuxeo-distribution, under directory /nuxeo-startup-wizard/src/main/java/org/nuxeo/wizard/download/.

Source file: PackageDownloader.java

  20 
vote

public void setProxy(String proxy,int port,String login,String password,String NTLMHost,String NTLMDomain){
  if (proxy != null) {
    HttpHost proxyHost=new HttpHost(proxy,port);
    httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxyHost);
    if (login != null) {
      if (NTLMHost != null && !NTLMHost.trim().isEmpty()) {
        NTCredentials ntlmCredentials=new NTCredentials(login,password,NTLMHost,NTLMDomain);
        httpClient.getCredentialsProvider().setCredentials(new AuthScope(proxy,port),ntlmCredentials);
      }
 else {
        httpClient.getCredentialsProvider().setCredentials(new AuthScope(proxy,port),new UsernamePasswordCredentials(login,password));
      }
    }
 else {
      httpClient.getCredentialsProvider().clear();
    }
  }
 else {
    httpClient.getParams().removeParameter(ConnRoutePNames.DEFAULT_PROXY);
    httpClient.getCredentialsProvider().clear();
  }
}
 

Example 37

From project openbicing, under directory /src/net/homelinux/penecoptero/android/openbicing/app/.

Source file: RESTHelper.java

  20 
vote

private static DefaultHttpClient setCredentials(DefaultHttpClient httpclient,String url,String username,String password) throws HttpException, IOException {
  HttpHost targetHost=new HttpHost(url);
  final UsernamePasswordCredentials access=new UsernamePasswordCredentials(username,password);
  httpclient.getCredentialsProvider().setCredentials(new AuthScope(targetHost.getHostName(),targetHost.getPort()),access);
  httpclient.addRequestInterceptor(new HttpRequestInterceptor(){
    @Override public void process(    HttpRequest request,    HttpContext context) throws HttpException, IOException {
      AuthState authState=(AuthState)context.getAttribute(ClientContext.TARGET_AUTH_STATE);
      if (authState.getAuthScheme() == null) {
        authState.setAuthScheme(new BasicScheme());
        authState.setCredentials(access);
      }
    }
  }
,0);
  return httpclient;
}
 

Example 38

From project org.ops4j.pax.web, under directory /itest/src/test/java/org/ops4j/pax/web/itest/.

Source file: ITestBase.java

  20 
vote

/** 
 * @param path
 * @param authenticate
 * @param basicHttpContext
 * @return
 * @throws IOException
 * @throws ClientProtocolException
 */
protected HttpResponse getHttpResponse(String path,boolean authenticate,BasicHttpContext basicHttpContext) throws IOException, ClientProtocolException {
  HttpGet httpget=null;
  HttpHost targetHost=new HttpHost("localhost",8181,"http");
  BasicHttpContext localcontext=basicHttpContext == null ? new BasicHttpContext() : basicHttpContext;
  if (authenticate) {
    ((DefaultHttpClient)httpclient).getCredentialsProvider().setCredentials(new AuthScope(targetHost.getHostName(),targetHost.getPort()),new UsernamePasswordCredentials("admin","admin"));
    AuthCache authCache=new BasicAuthCache();
    BasicScheme basicAuth=new BasicScheme();
    authCache.put(targetHost,basicAuth);
    localcontext.setAttribute(ClientContext.AUTH_CACHE,authCache);
  }
  httpget=new HttpGet(path);
  HttpResponse response=null;
  if (!authenticate && basicHttpContext == null)   response=httpclient.execute(httpget);
 else   response=httpclient.execute(targetHost,httpget,localcontext);
  return response;
}
 

Example 39

From project osgi-tests, under directory /test/glassfish-derby/src/test/java/org/ancoron/osgi/test/glassfish/.

Source file: GlassfishDerbyTest.java

  20 
vote

@Test(dependsOnGroups={"glassfish-osgi-startup"}) public void testWebAvailability() throws NoSuchAlgorithmException, KeyManagementException, IOException {
  logTest();
  DefaultHttpClient http=getHTTPClient();
  try {
    HttpGet httpget=new HttpGet("http://[::1]/movie/dummy/");
    httpget.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION,HttpVersion.HTTP_1_1);
    httpget.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE,Boolean.FALSE);
    HttpResponse res=http.execute(httpget);
    if (res.getStatusLine().getStatusCode() == 200) {
      fail("Gained access to secured page at '" + httpget.getURI().toASCIIString() + "' [status="+ res.getStatusLine().getStatusCode()+ "]");
    }
    log.log(Level.INFO,"[HTTP] Got response for ''{0}'' [status={1}]",new Object[]{httpget.getURI().toASCIIString(),res.getStatusLine().getStatusCode()});
    HttpGet httpsget=new HttpGet("https://[::1]/movie/dummy/");
    httpsget.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION,HttpVersion.HTTP_1_1);
    httpsget.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE,Boolean.FALSE);
    res=http.execute(httpsget);
    if (res.getStatusLine().getStatusCode() == 200) {
      fail("Gained access to secured page at '" + httpsget.getURI().toASCIIString() + "' [status="+ res.getStatusLine().getStatusCode()+ "] "+ res.getStatusLine().getReasonPhrase());
    }
    log.log(Level.INFO,"[HTTP] Got response for ''{0}'' [status={1}]",new Object[]{httpget.getURI().toASCIIString(),res.getStatusLine().getStatusCode()});
    http.getCredentialsProvider().setCredentials(new AuthScope("[::1]",8181),new UsernamePasswordCredentials("fail","fail"));
    res=http.execute(httpsget);
    if (res.getStatusLine().getStatusCode() == 200) {
      fail("Gained access with invalid user role to secured page at '" + httpsget.getURI().toASCIIString() + "' [status="+ res.getStatusLine().getStatusCode()+ "] "+ res.getStatusLine().getReasonPhrase());
    }
    log.log(Level.INFO,"[HTTP] Got response for ''{0}'' [status={1}]",new Object[]{httpget.getURI().toASCIIString(),res.getStatusLine().getStatusCode()});
    http.getCredentialsProvider().setCredentials(new AuthScope("[::1]",8181),new UsernamePasswordCredentials("test","test"));
    res=http.execute(httpsget);
    if (res.getStatusLine().getStatusCode() != 200) {
      fail("Failed to access " + httpsget.getURI().toASCIIString() + ": [status="+ res.getStatusLine().getStatusCode()+ "] "+ res.getStatusLine().getReasonPhrase());
    }
    log.log(Level.INFO,"[HTTP] Got response for ''{0}'' [status={1}]",new Object[]{httpget.getURI().toASCIIString(),res.getStatusLine().getStatusCode()});
  }
  finally {
    http.getConnectionManager().shutdown();
  }
}
 

Example 40

From project PageTurner, under directory /src/main/java/net/nightwhistler/pageturner/activity/.

Source file: CatalogActivity.java

  20 
vote

private void loadImageLink(Map<String,byte[]> cache,Link imageLink,String baseUrl) throws IOException {
  HttpParams httpParams=new BasicHttpParams();
  DefaultHttpClient client=new DefaultHttpClient(httpParams);
  client.getCredentialsProvider().setCredentials(new AuthScope(null,-1),new UsernamePasswordCredentials(user,password));
  if (imageLink != null) {
    String href=imageLink.getHref();
    if (cache.containsKey(href)) {
      imageLink.setBinData(cache.get(href));
    }
 else {
      String target=new URL(new URL(baseUrl),href).toString();
      LOG.info("Downloading image: " + target);
      HttpResponse resp=client.execute(new HttpGet(target));
      imageLink.setBinData(EntityUtils.toByteArray(resp.getEntity()));
      cache.put(href,imageLink.getBinData());
    }
  }
}
 

Example 41

From project picketbox-http, under directory /src/test/java/org/picketbox/test/authentication/http/jetty/.

Source file: DelegatingSecurityFilterHTTPBasicUnitTestCase.java

  20 
vote

@Test public void testBasicAuth() throws Exception {
  URL url=new URL(urlStr);
  DefaultHttpClient httpclient=null;
  try {
    String user="Aladdin";
    String pass="Open Sesame";
    httpclient=new DefaultHttpClient();
    httpclient.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(),url.getPort()),new UsernamePasswordCredentials(user,pass));
    HttpGet httpget=new HttpGet(url.toExternalForm());
    System.out.println("executing request" + httpget.getRequestLine());
    HttpResponse response=httpclient.execute(httpget);
    HttpEntity entity=response.getEntity();
    System.out.println("----------------------------------------");
    StatusLine statusLine=response.getStatusLine();
    System.out.println(statusLine);
    if (entity != null) {
      System.out.println("Response content length: " + entity.getContentLength());
    }
    assertEquals(200,statusLine.getStatusCode());
    EntityUtils.consume(entity);
  }
  finally {
    httpclient.getConnectionManager().shutdown();
  }
}
 

Example 42

From project picketlink-integration-tests, under directory /unit-tests/trust/src/test/java/org/picketlink/test/trust/tests/.

Source file: Gateway2ServiceHttpUnitTestCase.java

  20 
vote

private String getContentFromApp(String appUri,String userName,String password) throws Exception {
  DefaultHttpClient httpclient=new DefaultHttpClient();
  String content=null;
  try {
    httpclient.getCredentialsProvider().setCredentials(new AuthScope(getServerAddress(),8080),new UsernamePasswordCredentials(userName,password));
    HttpGet httpget=new HttpGet(getTargetURL(appUri));
    log.debug("executing request:" + httpget.getRequestLine());
    HttpResponse response=httpclient.execute(httpget);
    assertEquals("Http response has to finish with 'HTTP/1.1 200 OK'",200,response.getStatusLine().getStatusCode());
    HttpEntity entity=response.getEntity();
    log.debug("Status line: " + response.getStatusLine());
    ByteArrayOutputStream baos=new ByteArrayOutputStream();
    entity.writeTo(baos);
    content=baos.toString();
    baos.close();
    if (log.isTraceEnabled()) {
      log.trace(content);
    }
    EntityUtils.consume(entity);
  }
  finally {
    httpclient.getConnectionManager().shutdown();
  }
  return content;
}
 

Example 43

From project rain-workload-toolkit, under directory /thirdparty/httpcomponents-client-4.0.1/examples/org/apache/http/examples/client/.

Source file: ClientAuthentication.java

  20 
vote

public static void main(String[] args) throws Exception {
  DefaultHttpClient httpclient=new DefaultHttpClient();
  httpclient.getCredentialsProvider().setCredentials(new AuthScope("localhost",443),new UsernamePasswordCredentials("username","password"));
  HttpGet httpget=new HttpGet("https://localhost/protected");
  System.out.println("executing request" + httpget.getRequestLine());
  HttpResponse response=httpclient.execute(httpget);
  HttpEntity entity=response.getEntity();
  System.out.println("----------------------------------------");
  System.out.println(response.getStatusLine());
  if (entity != null) {
    System.out.println("Response content length: " + entity.getContentLength());
  }
  if (entity != null) {
    entity.consumeContent();
  }
  httpclient.getConnectionManager().shutdown();
}
 

Example 44

From project rest-driver, under directory /rest-client-driver/src/test/java/com/github/restdriver/clientdriver/integration/.

Source file: BasicAuthTest.java

  20 
vote

@Test public void basicAuthWorks() throws Exception {
  clientDriver.addExpectation(onRequestTo("/").withBasicAuth("Aladdin","open sesame"),giveEmptyResponse().withStatus(418)).anyTimes();
  DefaultHttpClient client=new DefaultHttpClient();
  client.getCredentialsProvider().setCredentials(new AuthScope("localhost",AuthScope.ANY_PORT),new UsernamePasswordCredentials("Aladdin","open sesame"));
  HttpHost host=new HttpHost("localhost",12345);
  AuthCache authCache=new BasicAuthCache();
  BasicScheme basicAuth=new BasicScheme();
  authCache.put(host,basicAuth);
  BasicHttpContext context=new BasicHttpContext();
  context.setAttribute(ClientContext.AUTH_CACHE,authCache);
  List<String> authPrefs=new ArrayList<String>();
  authPrefs.add(AuthPolicy.BASIC);
  client.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF,authPrefs);
  HttpGet get=new HttpGet(clientDriver.getBaseUrl() + "/");
  HttpResponse response=client.execute(host,get,context);
  assertThat(response.getStatusLine().getStatusCode(),is(418));
}
 

Example 45

From project Rhybudd, under directory /src/net/networksaremadeofstring/rhybudd/.

Source file: ZenossAPIv2.java

  20 
vote

public ZenossAPIv2(String UserName,String Password,String URL,String BAUser,String BAPassword) throws Exception {
  if (URL.contains("https://")) {
    this.PrepareSSLHTTPClient();
  }
 else {
    this.PrepareHTTPClient();
  }
  if (!BAUser.equals("") || !BAPassword.equals("")) {
    CredentialsProvider credProvider=new BasicCredentialsProvider();
    credProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST,AuthScope.ANY_PORT),new UsernamePasswordCredentials(BAUser,BAPassword));
    httpclient.setCredentialsProvider(credProvider);
  }
  HttpParams httpParameters=new BasicHttpParams();
  int timeoutConnection=20000;
  HttpConnectionParams.setConnectionTimeout(httpParameters,timeoutConnection);
  int timeoutSocket=30000;
  HttpConnectionParams.setSoTimeout(httpParameters,timeoutSocket);
  httpclient.setParams(httpParameters);
  HttpPost httpost=new HttpPost(URL + "/zport/acl_users/cookieAuthHelper/login");
  List<NameValuePair> nvps=new ArrayList<NameValuePair>();
  nvps.add(new BasicNameValuePair("__ac_name",UserName));
  nvps.add(new BasicNameValuePair("__ac_password",Password));
  nvps.add(new BasicNameValuePair("submitted","true"));
  nvps.add(new BasicNameValuePair("came_from",URL + "/zport/dmd"));
  httpost.setEntity(new UrlEncodedFormEntity(nvps,HTTP.UTF_8));
  HttpResponse response=httpclient.execute(httpost);
  response.getEntity().consumeContent();
  this.ZENOSS_INSTANCE=URL;
  this.ZENOSS_USERNAME=UserName;
  this.ZENOSS_PASSWORD=Password;
}
 

Example 46

From project tomcat-maven-plugin, under directory /common-tomcat-maven-plugin/src/main/java/org/apache/tomcat/maven/common/deployer/.

Source file: TomcatManager.java

  20 
vote

/** 
 * Creates a Tomcat manager wrapper for the specified URL, username, password and URL encoding.
 * @param url      the full URL of the Tomcat manager instance to use
 * @param username the username to use when authenticating with Tomcat manager
 * @param password the password to use when authenticating with Tomcat manager
 * @param charset  the URL encoding charset to use when communicating with Tomcat manager
 */
public TomcatManager(URL url,String username,String password,String charset){
  this.url=url;
  this.username=username;
  this.password=password;
  this.charset=charset;
  PoolingClientConnectionManager poolingClientConnectionManager=new PoolingClientConnectionManager();
  poolingClientConnectionManager.setMaxTotal(5);
  this.httpClient=new DefaultHttpClient(poolingClientConnectionManager);
  if (StringUtils.isNotEmpty(username)) {
    Credentials creds=new UsernamePasswordCredentials(username,password);
    String host=url.getHost();
    int port=url.getPort() > -1 ? url.getPort() : AuthScope.ANY_PORT;
    httpClient.getCredentialsProvider().setCredentials(new AuthScope(host,port),creds);
    AuthCache authCache=new BasicAuthCache();
    BasicScheme basicAuth=new BasicScheme();
    HttpHost targetHost=new HttpHost(url.getHost(),url.getPort(),url.getProtocol());
    authCache.put(targetHost,basicAuth);
    localContext=new BasicHttpContext();
    localContext.setAttribute(ClientContext.AUTH_CACHE,authCache);
  }
}
 

Example 47

From project twitter4j_1, under directory /twitter4j-httpclient-support/src/main/java/twitter4j/internal/http/alternative/.

Source file: HttpClientImpl.java

  20 
vote

public HttpClientImpl(HttpClientConfiguration conf){
  this.conf=conf;
  SchemeRegistry schemeRegistry=new SchemeRegistry();
  schemeRegistry.register(new Scheme("http",80,PlainSocketFactory.getSocketFactory()));
  schemeRegistry.register(new Scheme("https",443,SSLSocketFactory.getSocketFactory()));
  ThreadSafeClientConnManager cm=new ThreadSafeClientConnManager(schemeRegistry);
  cm.setMaxTotal(conf.getHttpMaxTotalConnections());
  cm.setDefaultMaxPerRoute(conf.getHttpDefaultMaxPerRoute());
  DefaultHttpClient client=new DefaultHttpClient(cm);
  HttpParams params=client.getParams();
  HttpConnectionParams.setConnectionTimeout(params,conf.getHttpConnectionTimeout());
  HttpConnectionParams.setSoTimeout(params,conf.getHttpReadTimeout());
  if (conf.getHttpProxyHost() != null && !conf.getHttpProxyHost().equals("")) {
    HttpHost proxy=new HttpHost(conf.getHttpProxyHost(),conf.getHttpProxyPort());
    client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);
    if (conf.getHttpProxyUser() != null && !conf.getHttpProxyUser().equals("")) {
      if (logger.isDebugEnabled()) {
        logger.debug("Proxy AuthUser: " + conf.getHttpProxyUser());
        logger.debug("Proxy AuthPassword: " + z_T4JInternalStringUtil.maskString(conf.getHttpProxyPassword()));
      }
      client.getCredentialsProvider().setCredentials(new AuthScope(conf.getHttpProxyHost(),conf.getHttpProxyPort()),new UsernamePasswordCredentials(conf.getHttpProxyUser(),conf.getHttpProxyPassword()));
    }
  }
  this.client=client;
}
 

Example 48

From project zeitgeist-api, under directory /deps/httpcomponents-client/examples/org/apache/http/examples/client/.

Source file: ClientAuthentication.java

  20 
vote

public static void main(String[] args) throws Exception {
  DefaultHttpClient httpclient=new DefaultHttpClient();
  try {
    httpclient.getCredentialsProvider().setCredentials(new AuthScope("localhost",443),new UsernamePasswordCredentials("username","password"));
    HttpGet httpget=new HttpGet("https://localhost/protected");
    System.out.println("executing request" + httpget.getRequestLine());
    HttpResponse response=httpclient.execute(httpget);
    HttpEntity entity=response.getEntity();
    System.out.println("----------------------------------------");
    System.out.println(response.getStatusLine());
    if (entity != null) {
      System.out.println("Response content length: " + entity.getContentLength());
    }
    EntityUtils.consume(entity);
  }
  finally {
    httpclient.getConnectionManager().shutdown();
  }
}
 

Example 49

From project AirCastingAndroidClient, under directory /src/main/java/pl/llp/aircasting/util/http/.

Source file: HttpBuilder.java

  19 
vote

private HttpRequestInterceptor preemptiveAuth(){
  return new HttpRequestInterceptor(){
    @Override public void process(    HttpRequest httpRequest,    HttpContext httpContext) throws HttpException, IOException {
      AuthState authState=(AuthState)httpContext.getAttribute(ClientContext.TARGET_AUTH_STATE);
      Credentials credentials;
      if (useLogin) {
        credentials=new UsernamePasswordCredentials(login,password);
      }
 else {
        credentials=new UsernamePasswordCredentials(settingsHelper.getAuthToken(),"X");
      }
      authState.setAuthScope(AuthScope.ANY);
      authState.setAuthScheme(new BasicScheme());
      authState.setCredentials(credentials);
    }
  }
;
}
 

Example 50

From project components-ness-httpclient, under directory /client/src/main/java/com/nesscomputing/httpclient/factory/httpclient4/.

Source file: InternalCredentialsProvider.java

  19 
vote

@Override public Credentials getCredentials(final AuthScope authScope){
  for (  final HttpClientAuthProvider authProvider : authProviders) {
    if (authProvider.acceptRequest(authScope.getScheme(),authScope.getHost(),authScope.getPort(),authScope.getRealm())) {
      return new Credentials(){
        @Override public Principal getUserPrincipal(){
          return new BasicUserPrincipal(authProvider.getUser());
        }
        @Override public String getPassword(){
          return authProvider.getPassword();
        }
      }
;
    }
  }
  return null;
}
 

Example 51

From project couchdb4j, under directory /src/java/com/fourspaces/couchdb/.

Source file: Session.java

  19 
vote

/** 
 * Constructor for obtaining a Session with an HTTP-AUTH username/password and (optionally) a secure connection This isn't supported by CouchDB - you need a proxy in front to use this
 * @param host - hostname
 * @param port - port to use
 * @param user - username
 * @param pass - password
 * @param secure  - use an SSL connection?
 */
public Session(String host,int port,String user,String pass,boolean usesAuth,boolean secure){
  this.host=host;
  this.port=port;
  this.user=user;
  this.pass=pass;
  this.usesAuth=usesAuth;
  this.secure=secure;
  httpParams=new BasicHttpParams();
  SchemeRegistry schemeRegistry=new SchemeRegistry();
  schemeRegistry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  schemeRegistry.register(new Scheme("https",SSLSocketFactory.getSocketFactory(),443));
  ThreadSafeClientConnManager connManager=new ThreadSafeClientConnManager(httpParams,schemeRegistry);
  DefaultHttpClient defaultClient=new DefaultHttpClient(connManager,httpParams);
  if (user != null) {
    defaultClient.getCredentialsProvider().setCredentials(AuthScope.ANY,new UsernamePasswordCredentials(user,pass));
  }
  this.httpClient=defaultClient;
  setUserAgent("couchdb4j");
  setSocketTimeout((30 * 1000));
  setConnectionTimeout((15 * 1000));
}
 

Example 52

From project jolokia, under directory /client/java/src/main/java/org/jolokia/client/.

Source file: J4pClientBuilder.java

  19 
vote

/** 
 * Build the agent with the information given before
 * @return a new J4pClient
 */
public J4pClient build(){
  ClientConnectionManager cm=createClientConnectionManager();
  DefaultHttpClient httpClient=new DefaultHttpClient(cm,getHttpParams());
  if (user != null) {
    httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY,new UsernamePasswordCredentials(user,password));
  }
  return new J4pClient(url,httpClient,targetUrl != null ? new J4pTargetConfig(targetUrl,targetUser,targetPassword) : null);
}
 

Example 53

From project lyo.testsuite, under directory /org.eclipse.lyo.testsuite.server/src/main/java/org/eclipse/lyo/testsuite/server/util/.

Source file: OSLCUtils.java

  19 
vote

private static HttpClient getHttpClient(Credentials creds){
  if (httpclient == null) {
    httpclient=new DefaultHttpClient();
    setupLazySSLSupport(httpclient);
    if (creds != null) {
      httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY,creds);
    }
    httpclient.setRedirectStrategy(new DefaultRedirectStrategy(){
      @Override public boolean isRedirected(      HttpRequest request,      HttpResponse response,      org.apache.http.protocol.HttpContext context){
        boolean isRedirect=false;
        try {
          isRedirect=super.isRedirected(request,response,context);
        }
 catch (        ProtocolException e) {
          e.printStackTrace();
        }
        if (!isRedirect) {
          int responseCode=response.getStatusLine().getStatusCode();
          if (responseCode == 301 || responseCode == 302) {
            return true;
          }
        }
        return isRedirect;
      }
    }
);
  }
  return httpclient;
}
 

Example 54

From project memcached-session-manager, under directory /core/src/test/java/de/javakaffee/web/msm/integration/.

Source file: TestUtils.java

  19 
vote

private static HttpResponse executeRequestWithAuth(final DefaultHttpClient client,final HttpUriRequest method,final Credentials credentials) throws IOException, ClientProtocolException {
  client.getCredentialsProvider().setCredentials(AuthScope.ANY,credentials);
  final BasicHttpContext localcontext=new BasicHttpContext();
  final BasicScheme basicAuth=new BasicScheme();
  localcontext.setAttribute("preemptive-auth",basicAuth);
  return client.execute(method,localcontext);
}
 

Example 55

From project sandbox, under directory /authenticators/xwiki-authentication-http/src/main/java/org/xwiki/contrib/authentication/http/.

Source file: XWikiHTTPAuthenticator.java

  19 
vote

private boolean checkAuth(String username,String password,URI uri) throws ClientProtocolException, IOException {
  DefaultHttpClient httpClient=new DefaultHttpClient();
  httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT,"XWik");
  httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT,60000);
  httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,10000);
  httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY,new UsernamePasswordCredentials(username,password));
  HttpGet httpget=new HttpGet(uri);
  HttpResponse response=httpClient.execute(httpget);
  return response.getStatusLine().getStatusCode() == HttpStatus.SC_OK;
}
 

Example 56

From project sched-assist, under directory /sched-assist-spi-caldav/src/main/java/org/jasig/schedassist/impl/caldav/.

Source file: DefaultCredentialsProviderImpl.java

  19 
vote

@Override public Credentials getCredentials(AuthScope authscope){
  if (!targetAuthScope.equals(authscope)) {
    return null;
  }
  return adminCredentials;
}
 

Example 57

From project skalli, under directory /org.eclipse.skalli.core/src/main/java/org/eclipse/skalli/core/internal/destination/.

Source file: DestinationServiceImpl.java

  19 
vote

private void setCredentials(DefaultHttpClient client,URL url){
  if (configService == null) {
    return;
  }
  DestinationsConfig config=configService.readCustomization(DestinationsResource.KEY,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)) {
          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;
    }
  }
}
 

Example 58

From project SqueezeControl, under directory /src/com/squeezecontrol/download/.

Source file: MusicDownloadService.java

  19 
vote

public MusicDownloadService(MusicBrowser musicBrowser,String baseUrl,String username,String password){
  this.mMusicBrowser=musicBrowser;
  this.mBaseUrl=baseUrl;
  this.mSongFolder=Environment.getExternalStorageDirectory() + "/Music/";
  mClient=new DefaultHttpClient();
  if (username != null && !"".equals(username)) {
    Credentials defaultcreds=new UsernamePasswordCredentials("dag","test");
    mClient.getCredentialsProvider().setCredentials(AuthScope.ANY,defaultcreds);
  }
}
 

Example 59

From project WebproxyPortlet, under directory /src/main/java/edu/wisc/my/webproxy/beans/http/.

Source file: HttpManagerImpl.java

  19 
vote

@Override public void setCredentials(Credentials credentials){
  if (credentials.getUserPrincipal() == null && credentials.getPassword() == null) {
    throw new IllegalArgumentException("Both username and password are null for BASIC authentication");
  }
  client.getCredentialsProvider().setCredentials(AuthScope.ANY,credentials);
}