1 38 package com.gargoylesoftware.htmlunit; 39 40 import java.util.HashMap ; 41 import java.util.Iterator ; 42 import java.util.Map ; 43 44 import org.org.apache.commons.httpclient.Credentials; 45 import org.org.apache.commons.httpclient.UsernamePasswordCredentials; 46 import org.org.apache.commons.httpclient.auth.AuthScheme; 47 import org.org.apache.commons.httpclient.auth.AuthScope; 48 import org.org.apache.commons.httpclient.auth.CredentialsNotAvailableException; 49 import org.org.apache.commons.httpclient.auth.CredentialsProvider; 50 51 59 public class DefaultCredentialsProvider implements CredentialsProvider { 60 61 private final Map credentials_; 62 private final Map proxyCredentials_; 63 64 67 public DefaultCredentialsProvider() { 68 credentials_ = new HashMap (); 69 proxyCredentials_ = new HashMap (); 70 } 71 72 81 public void addCredentials( final String username, final String password ) { 82 addCredentials( username, password, AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM ); 83 } 84 85 95 public void addCredentials( final String username, final String password, final String host, 96 final int port, final String realm ) { 97 final AuthScope scope = new AuthScope( host, port, realm, AuthScope.ANY_SCHEME ); 98 final Credentials c = new UsernamePasswordCredentials( username, password ); 99 credentials_.put( scope, c ); 100 } 101 102 107 public void addProxyCredentials( final String username, final String password ) { 108 addProxyCredentials( username, password, AuthScope.ANY_HOST, AuthScope.ANY_PORT ); 109 } 110 111 118 public void addProxyCredentials( final String username, final String password, final String host, final int port ) { 119 final AuthScope scope = new AuthScope( host, port, AuthScope.ANY_REALM, AuthScope.ANY_SCHEME ); 120 final Credentials c = new UsernamePasswordCredentials( username, password ); 121 proxyCredentials_.put( scope, c ); 122 } 123 124 134 public Credentials getCredentials( final AuthScheme scheme, final String host, final int port, final boolean proxy ) 135 throws CredentialsNotAvailableException { 136 final Map credentials; 137 if( proxy ) { 138 credentials = proxyCredentials_; 139 } 140 else { 141 credentials = credentials_; 142 } 143 for( final Iterator i = credentials.entrySet().iterator(); i.hasNext(); ) { 144 final Map.Entry entry = (Map.Entry ) i.next(); 145 final AuthScope scope = (AuthScope) entry.getKey(); 146 final Credentials c = (Credentials) entry.getValue(); 147 if( scope.getScheme() == AuthScope.ANY_SCHEME || scope.getScheme().equals(scheme.getSchemeName()) ) { 148 if( scope.getHost() == AuthScope.ANY_HOST || scope.getHost().equals(host) ) { 149 if( scope.getPort() == AuthScope.ANY_PORT || scope.getPort() == port ) { 150 if( scope.getRealm() == AuthScope.ANY_REALM || scope.getRealm().equals(scheme.getRealm()) ) { 151 return c; 152 } 153 } 154 } 155 } 156 } 157 return null; 158 } 159 160 } 161 | Popular Tags |