private void addCredentials( HttpClientContext context ) {
    String userName;
    String password;
    String host;
    int port;
    String proxyHost;
    lock.readLock().lock();
    try {
      host = environmentSubstitute( hostname );
      port = Const.toInt( environmentSubstitute( this.port ), 80 );
      userName = environmentSubstitute( username );
      password = Encr.decryptPasswordOptionallyEncrypted( environmentSubstitute( this.password ) );
      proxyHost = environmentSubstitute( proxyHostname );
    } finally {
      lock.readLock().unlock();
    }
    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials( userName, password );
    if ( !Utils.isEmpty( proxyHost ) && host.equals( "localhost" ) ) {
      host = "127.0.0.1";
    }
    provider.setCredentials( new AuthScope( host, port ), credentials );
    context.setCredentialsProvider( provider );
    // Generate BASIC scheme object and add it to the local auth cache
    HttpHost target = new HttpHost( host, port, isSslMode() ? HTTPS : HTTP );
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put( target, basicAuth );
    context.setAuthCache( authCache );
  }
@Test
  public void testAddCredentials() throws IOException, ClassNotFoundException {
    String testUser = "test_username";
    slaveServer.setUsername( testUser );
    String testPassword = "test_password";
    slaveServer.setPassword( testPassword );
    String host = "somehost";
    slaveServer.setHostname( host );
    int port = 1000;
    slaveServer.setPort( "" + port );

    HttpClientContext auth = slaveServer.getAuthContext();
    Credentials cred = auth.getCredentialsProvider().getCredentials( new AuthScope( host, port ) );
    assertEquals( testUser, cred.getUserPrincipal().getName() );
    assertEquals( testPassword, cred.getPassword() );

    String user2 = "user2";
    slaveServer.setUsername( user2 );
    slaveServer.setPassword( "pass2" );
    auth = slaveServer.getAuthContext();
    cred = auth.getCredentialsProvider().getCredentials( new AuthScope( host, port ) );
    assertEquals( user2, cred.getUserPrincipal().getName() );
  }