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

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 chargifyService, under directory /src/main/java/com/mondora/chargify/controller/.

Source file: Chargify.java

  22 
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 2

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 3

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 4

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

Source file: TestBasicScheme.java

  22 
vote

@Test public void testBasicAuthenticationWith88591Chars() throws Exception {
  int[] germanChars={0xE4,0x2D,0xF6,0x2D,0xFc};
  StringBuilder buffer=new StringBuilder();
  for (int i=0; i < germanChars.length; i++) {
    buffer.append((char)germanChars[i]);
  }
  UsernamePasswordCredentials credentials=new UsernamePasswordCredentials("dh",buffer.toString());
  Header header=BasicScheme.authenticate(credentials,"ISO-8859-1",false);
  Assert.assertEquals("Basic ZGg65C32Lfw=",header.getValue());
}
 

Example 5

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

Source file: J4pClientBuilderTest.java

  22 
vote

@Test public void simple(){
  J4pClient client=J4pClient.url("http://localhost:8080/jolokia").user("roland").password("s!c!r!t").connectionTimeout(100).expectContinue(false).tcpNoDelay(true).contentCharset("utf-8").maxConnectionPoolTimeout(3000).maxTotalConnections(500).pooledConnections().socketBufferSize(8192).socketTimeout(5000).build();
  DefaultHttpClient hc=(DefaultHttpClient)client.getHttpClient();
  assertNotNull(hc.getCredentialsProvider());
  UsernamePasswordCredentials credentials=(UsernamePasswordCredentials)hc.getCredentialsProvider().getCredentials(AuthScope.ANY);
  assertEquals(credentials.getUserName(),"roland");
  assertEquals(credentials.getPassword(),"s!c!r!t");
}
 

Example 6

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

Source file: OracleCommsCredentialsProviderImpl.java

  22 
vote

@Override public Credentials getCredentials(AuthScope authscope){
  if (!getTargetAuthScope().equals(authscope)) {
    return null;
  }
  StringBuilder username=new StringBuilder(getAdminCredentials().getUserPrincipal().getName());
  username.append(SEMICOLON);
  username.append(accountToProxy.getEmailAddress());
  UsernamePasswordCredentials proxyCredentials=new UsernamePasswordCredentials(username.toString(),getAdminCredentials().getPassword());
  return proxyCredentials;
}
 

Example 7

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 8

From project xwiki-eclipse, under directory /plugins/org.xwiki.eclipse.storage/src/main/java/org/xwiki/eclipse/storage/rest/.

Source file: XWikiRestClient.java

  22 
vote

protected HttpResponse executeGet(URI uri) throws Exception {
  DefaultHttpClient httpClient=new DefaultHttpClient();
  UsernamePasswordCredentials creds=new UsernamePasswordCredentials(username,password);
  HttpGet request=new HttpGet(uri);
  request.addHeader(new BasicScheme().authenticate(creds,request));
  HttpResponse response=httpClient.execute(request);
  return response;
}
 

Example 9

From project AudioBox.fm-JavaLib, under directory /audiobox.fm-core/src/main/java/fm/audiobox/.

Source file: AudioBox.java

  21 
vote

/** 
 * This method should be called before any other call to AudioBox.fm.<br/> It tries to perform a login. If succeeds a  {@link User} object is returned otherwise a {@link LoginException} is thrown.<br/>This method also checks whether the user is active or not. If not a LoginException is thrown. <p>
 * @param username the username to login to AudioBox.fm in form of an e-mail
 * @param password the password to use for authentication
 * @return {@link User} object
 * @throws ModelException if any of the custom model class does not exists or is not instantiable.
 * @throws LoginException if user doesn't exists or is inactive.
 * @throws ServiceException if any connection problem occurs.
 */
public User login(String username,String password) throws LoginException, ServiceException {
  log.info("Executing login for user: " + username);
  this.logout();
  User user=(User)this.configuration.getFactory().getEntity(User.TAGNAME,this.getConfiguration());
  user.setUsername(username);
  mCredentials=new UsernamePasswordCredentials(username,password);
  this.configuration.getFactory().getConnector().get(user,null,null).send(false);
  this.user=user;
  Event event=new Event(this.user,Event.States.CONNECTED);
  this.setChanged();
  this.notifyObservers(event);
  return this.user;
}
 

Example 10

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 11

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

Source file: RESTHelper.java

  21 
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 12

From project EasySOA, under directory /easysoa-proxy/easysoa-proxy-core/easysoa-proxy-core-api/src/main/java/org/easysoa/proxy/core/api/nuxeo/registration/.

Source file: NuxeoRegistrationService.java

  21 
vote

/** 
 * Queries nuxeo docs
 * @param query Query to send
 * @return The response send back by Nuxeo
 * @throws Exception 
 */
public String sendQuery(String query) throws Exception {
  StringBuffer urlBuf=new StringBuffer(PropertyManager.getPropertyManager().getProperty("nuxeo.automation.service"));
  urlBuf.append("Document.Query");
  try {
    JSONObject bodyBuf=new JSONObject();
    JSONObject bodyBufQuery=new JSONObject();
    bodyBufQuery.put("query",query);
    bodyBuf.put("params",bodyBufQuery);
    logger.debug("[sendQuery()] --- Request URL = " + urlBuf.toString());
    DefaultHttpClient httpClient=new DefaultHttpClient();
    UsernamePasswordCredentials creds=new UsernamePasswordCredentials(PropertyManager.getPropertyManager().getProperty("nuxeo.auth.login","Administrator"),PropertyManager.getPropertyManager().getProperty("nuxeo.auth.password","Administrator"));
    HttpPost postRequest=new HttpPost(urlBuf.toString());
    postRequest.addHeader(new BasicScheme().authenticate(creds,postRequest));
    HttpEntity entity=new StringEntity(bodyBuf.toString());
    postRequest.setEntity(entity);
    postRequest.addHeader(new BasicHeader("X-NXDocumentProperties","*"));
    postRequest.setHeader(new BasicHeader(HTTP.CONTENT_TYPE,"application/json+nxrequest; charset=UTF-8"));
    HttpResponse response=httpClient.execute(postRequest);
    int status=response.getStatusLine().getStatusCode();
    logger.debug("[sendQuery()] --- sendQuery response status = " + status);
    String textEntity=ContentReader.read(response.getEntity().getContent());
    logger.debug("[sendQuery()] --- sendQuery response = " + textEntity);
    return textEntity;
  }
 catch (  JSONException e) {
    logger.error("Failed to create request body",e);
    return null;
  }
}
 

Example 13

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

Source file: SocialHttpClientImpl.java

  21 
vote

@Override public void setBasicAuthenticateToRequest() throws SocialClientLibException {
  if (delegate == null)   return;
  if (SocialClientContext.getUsername() == null || SocialClientContext.getPassword() == null) {
    throw new SocialClientLibException("401 Unauthorized",new UnAuthenticatedException());
  }
  delegate.getCredentialsProvider().setCredentials(new AuthScope(SocialClientContext.getHost(),SocialClientContext.getPort()),new UsernamePasswordCredentials(SocialClientContext.getUsername(),SocialClientContext.getPassword()));
  delegate.addRequestInterceptor(preemptiveAuthInterceptor,0);
}
 

Example 14

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 15

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 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 lyo.testsuite, under directory /org.eclipse.lyo.testsuite.server/src/main/java/org/eclipse/lyo/testsuite/server/oslcv1tests/.

Source file: CreationAndUpdateTests.java

  21 
vote

@Before public void setup() throws IOException, ParserConfigurationException, SAXException, XPathException {
  Properties setupProps=SetupProperties.setup(null);
  if (setupProps.getProperty("testBackwardsCompatability") != null && Boolean.parseBoolean(setupProps.getProperty("testBackwardsCompatability"))) {
    setupProps=SetupProperties.setup(setupProps.getProperty("version1Properties"));
  }
  String userId=setupProps.getProperty("userId");
  String pw=setupProps.getProperty("pw");
  basicCreds=new UsernamePasswordCredentials(userId,pw);
  templatedDocument=OSLCUtils.readFileAsString(new File(setupProps.getProperty("createTemplateXmlFile")));
  updateDocument=OSLCUtils.readFileAsString(new File(setupProps.getProperty("updateTemplateXmlFile")));
  jsonDocument=OSLCUtils.readFileAsString(new File(setupProps.getProperty("createTemplateJsonFile")));
  jsonUpdate=OSLCUtils.readFileAsString(new File(setupProps.getProperty("updateTemplateJsonFile")));
}
 

Example 18

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

Source file: NonStickySessionsIntegrationTest.java

  21 
vote

@Test(enabled=true) public void testBasicAuth() throws Exception {
  _tomcat1.stop();
  _tomcat2.stop();
  _tomcat1=startTomcatWithAuth(TC_PORT_1,LockingMode.AUTO);
  _tomcat2=startTomcatWithAuth(TC_PORT_2,LockingMode.AUTO);
  setChangeSessionIdOnAuth(_tomcat1,false);
  setChangeSessionIdOnAuth(_tomcat2,false);
  final Response tc1Response1=post(_httpClient,TC_PORT_1,"/",null,asMap("foo","bar"),new UsernamePasswordCredentials(TestUtils.USER_NAME,TestUtils.PASSWORD),true);
  final String sessionId=tc1Response1.getSessionId();
  assertNotNull(sessionId);
  final Response tc2Response1=get(_httpClient,TC_PORT_2,sessionId);
  assertEquals(sessionId,tc2Response1.get(TestServlet.ID));
  assertEquals(tc2Response1.get("foo"),"bar");
}
 

Example 19

From project Mockey, under directory /src/java/com/mockey/model/.

Source file: ProxyServerModel.java

  21 
vote

public Credentials getCredentials(){
  String username=getProxyUsername();
  String pass=getProxyPassword();
  if (username == null) {
    username="";
  }
  if (pass == null) {
    username="";
  }
  return new UsernamePasswordCredentials(username,pass);
}
 

Example 20

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

Source file: RESTHelper.java

  21 
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 21

From project OpenConext-teams, under directory /coin-teams-scim/src/main/java/nl/surfnet/coin/teams/service/.

Source file: ASyncProvisioningManager.java

  21 
vote

private void execute(HttpUriRequest request,ScimEvent event) throws IOException, JsonGenerationException, JsonMappingException, ClientProtocolException {
  request.addHeader(HttpHeaders.CONTENT_TYPE,ContentType.APPLICATION_JSON.getMimeType());
  UsernamePasswordCredentials credentials=new UsernamePasswordCredentials(username,password);
  request.addHeader(BasicScheme.authenticate(credentials,UTF_8,false));
  if (request instanceof HttpEntityEnclosingRequest) {
    HttpEntityEnclosingRequest enclosingRequest=(HttpEntityEnclosingRequest)request;
    HttpEntity entity=new StringEntity(mapper.writeValueAsString(event),ContentType.APPLICATION_JSON);
    enclosingRequest.setEntity(entity);
  }
  HttpResponse response=client.execute(request);
  IOUtils.toString(response.getEntity().getContent());
  int status=response.getStatusLine().getStatusCode();
  if (status < 200 || status > 299) {
    throw new RuntimeException("Status = " + status);
  }
}
 

Example 22

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 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 sandbox, under directory /authenticators/xwiki-authentication-http/src/main/java/org/xwiki/contrib/authentication/http/.

Source file: XWikiHTTPAuthenticator.java

  21 
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 27

From project sparsemapcontent, under directory /extensions/resource/src/test/java/uk/co/tfd/sm/integration/resource/.

Source file: DataTypesTest.java

  21 
vote

private JsonObject testType(String type,Object testsingle,Object[] testproperty,Object testarray) throws AuthenticationException, ClientProtocolException, IOException {
  String resource="/" + this.getClass().getName() + "/test"+ type+ "Type"+ System.currentTimeMillis();
  String resourceUrl=IntegrationServer.BASEURL + resource;
  HttpPost post=new HttpPost(resourceUrl);
  UsernamePasswordCredentials creds=new UsernamePasswordCredentials(ADMIN_USER,ADMIN_PASSWORD);
  post.addHeader(new BasicScheme().authenticate(creds,post));
  List<BasicNameValuePair> v=Lists.newArrayList();
  v.add(new BasicNameValuePair("[email protected]" + type,String.valueOf(testsingle)));
  for (  Object o : testproperty) {
    v.add(new BasicNameValuePair("[email protected]" + type,String.valueOf(o)));
  }
  v.add(new BasicNameValuePair("testarray[]@" + type,String.valueOf(testarray)));
  UrlEncodedFormEntity form=new UrlEncodedFormEntity(v);
  post.setEntity(form);
  post.setHeader("Referer","/integratriontest/" + this.getClass().getName());
  httpTestUtils.execute(post,200,APPLICATION_JSON);
  JsonObject json=JsonTestUtils.toJsonObject(httpTestUtils.get(resourceUrl + ".pp.json",200,APPLICATION_JSON));
  JsonTestUtils.checkProperty(json,"_path",resource);
  return json;
}
 

Example 28

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

Source file: MusicDownloadService.java

  21 
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 29

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 30

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

Source file: WeaveTransport.java

  21 
vote

private HttpClient createHttpClient(String userId,String password){
  DefaultHttpClient retval=createDefaultHttpClient();
  Credentials defaultcreds=new UsernamePasswordCredentials(userId,password);
  retval.getCredentialsProvider().setCredentials(AuthScope.ANY,defaultcreds);
  retval.addRequestInterceptor(sm_preemptiveAuth,0);
  return retval;
}
 

Example 31

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

Source file: HttpConnector.java

  20 
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 32

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 33

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 34

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 35

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

Source file: HttpClientFactory.java

  20 
vote

public static synchronized HttpClient getInstance() throws MalformedURLException {
  if (instance == null) {
    final HttpParams params=new BasicHttpParams();
    HttpProtocolParams.setVersion(params,HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUseExpectContinue(params,false);
    HttpConnectionParams.setTcpNoDelay(params,true);
    HttpConnectionParams.setStaleCheckingEnabled(params,false);
    ConnManagerParams.setMaxTotalConnections(params,1000);
    ConnManagerParams.setMaxConnectionsPerRoute(params,new ConnPerRouteBean(1000));
    final SchemeRegistry schemeRegistry=new SchemeRegistry();
    schemeRegistry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),5984));
    schemeRegistry.register(new Scheme("https",SSLSocketFactory.getSocketFactory(),443));
    final ClientConnectionManager cm=new ShieldedClientConnManager(new ThreadSafeClientConnManager(params,schemeRegistry));
    instance=new DefaultHttpClient(cm,params);
    if (INI != null) {
      final CredentialsProvider credsProvider=new BasicCredentialsProvider();
      final Iterator<?> it=INI.getKeys();
      while (it.hasNext()) {
        final String key=(String)it.next();
        if (!key.startsWith("lucene.") && key.endsWith(".url")) {
          final URL url=new URL(INI.getString(key));
          if (url.getUserInfo() != null) {
            credsProvider.setCredentials(new AuthScope(url.getHost(),url.getPort()),new UsernamePasswordCredentials(url.getUserInfo()));
          }
        }
      }
      instance.setCredentialsProvider(credsProvider);
      instance.addRequestInterceptor(new PreemptiveAuthenticationRequestInterceptor(),0);
    }
  }
  return instance;
}
 

Example 36

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

Source file: Session.java

  20 
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 37

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 38

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 39

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

Source file: AbstractHttpClientWagon.java

  20 
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 40

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 41

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 42

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 43

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 44

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 45

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 46

From project PinDroid, under directory /src/com/pindroid/client/.

Source file: NetworkUtilities.java

  20 
vote

/** 
 * Attempts to authenticate to Pinboard using a legacy Pinboard account.
 * @param username The user's username.
 * @param password The user's password.
 * @param handler The hander instance from the calling UI thread.
 * @param context The context of the calling Activity.
 * @return The boolean result indicating whether the user wassuccessfully authenticated.
 */
public static boolean pinboardAuthenticate(String username,String password){
  final HttpResponse resp;
  Uri.Builder builder=new Uri.Builder();
  builder.scheme(SCHEME);
  builder.authority(PINBOARD_AUTHORITY);
  builder.appendEncodedPath("v1/posts/update");
  Uri uri=builder.build();
  HttpGet request=new HttpGet(String.valueOf(uri));
  DefaultHttpClient client=(DefaultHttpClient)HttpClientFactory.getThreadSafeClient();
  CredentialsProvider provider=client.getCredentialsProvider();
  Credentials credentials=new UsernamePasswordCredentials(username,password);
  provider.setCredentials(SCOPE,credentials);
  try {
    resp=client.execute(request);
    if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
      if (Log.isLoggable(TAG,Log.VERBOSE)) {
        Log.v(TAG,"Successful authentication");
      }
      return true;
    }
 else {
      if (Log.isLoggable(TAG,Log.VERBOSE)) {
        Log.v(TAG,"Error authenticating" + resp.getStatusLine());
      }
      return false;
    }
  }
 catch (  final IOException e) {
    if (Log.isLoggable(TAG,Log.VERBOSE)) {
      Log.v(TAG,"IOException when getting authtoken",e);
    }
    return false;
  }
 finally {
    if (Log.isLoggable(TAG,Log.VERBOSE)) {
      Log.v(TAG,"getAuthtoken completing");
    }
  }
}
 

Example 47

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 48

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 49

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 50

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

Source file: DestinationServiceImpl.java

  20 
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 51

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 52

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 53

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

Source file: WebProxyPortlet.java

  20 
vote

/** 
 * @param portletRequest
 * @param httpRequest
 */
private void doHttpAuth(final PortletRequest portletRequest,HttpManager manager){
  final PortletPreferences myPreferences=new PortletPreferencesWrapper(portletRequest.getPreferences(),(Map)portletRequest.getAttribute(PortletRequest.USER_INFO));
  final boolean authEnabled=new Boolean(myPreferences.getValue(HttpClientConfigImpl.AUTH_ENABLE,null)).booleanValue();
  final String authType=ConfigUtils.checkEmptyNullString(myPreferences.getValue(HttpClientConfigImpl.AUTH_TYPE,""),"");
  if (authEnabled && HttpClientConfigImpl.AUTH_TYPE_BASIC.equals(authType) || HttpClientConfigImpl.AUTH_TYPE_NTLM.equals(authType)) {
    final PortletSession session=portletRequest.getPortletSession();
    String userName=(String)session.getAttribute(HttpClientConfigImpl.USER_NAME);
    if (userName == null)     userName=myPreferences.getValue(HttpClientConfigImpl.USER_NAME,"");
    String password=(String)session.getAttribute(HttpClientConfigImpl.PASSWORD);
    if (password == null)     password=myPreferences.getValue(HttpClientConfigImpl.PASSWORD,"");
    final Credentials creds;
    if (HttpClientConfigImpl.AUTH_TYPE_BASIC.equals(authType)) {
      creds=new UsernamePasswordCredentials(userName,password);
    }
 else {
      String domain=(String)session.getAttribute(HttpClientConfigImpl.DOMAIN);
      if (domain == null)       domain=myPreferences.getValue(HttpClientConfigImpl.DOMAIN,"");
      final String host=portletRequest.getProperty("REMOTE_HOST");
      creds=new NTCredentials(userName,password,domain,host);
    }
    manager.setCredentials(creds);
  }
}
 

Example 54

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 55

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);
    }
  }
;
}