Java 类org.apache.commons.httpclient.UsernamePasswordCredentials 实例源码

项目:oscm    文件:BasicAuthLoader.java   
/**
 * Retrieves the content under the given URL with username and passwort
 * authentication.
 * 
 * @param url
 *            the URL to read
 * @param username
 * @param password
 * @return the read content.
 * @throws IOException
 *             if an I/O exception occurs.
 */
private static byte[] getUrlContent(URL url, String username,
        String password) throws IOException {
    final HttpClient client = new HttpClient();

    // Set credentials:
    client.getParams().setAuthenticationPreemptive(true);
    final Credentials credentials = new UsernamePasswordCredentials(
            username, password);
    client.getState()
            .setCredentials(
                    new AuthScope(url.getHost(), url.getPort(),
                            AuthScope.ANY_REALM), credentials);

    // Retrieve content:
    final GetMethod method = new GetMethod(url.toString());
    final int status = client.executeMethod(method);
    if (status != HttpStatus.SC_OK) {
        throw new IOException("Error " + status + " while retrieving "
                + url);
    }
    return method.getResponseBody();
}
项目:jrpip    文件:ThankYouWriterTest.java   
public void testAddRequest() throws Exception
{
    AuthenticatedUrl url = new AuthenticatedUrl(this.getJrpipUrl(), new UsernamePasswordCredentials("username"));
    Cookie cookie1 = new Cookie("domain", "cookie1", "val1", "/", 1000, false);
    Cookie cookie2 = new Cookie("domain", "cookie2", "val2", "/", 1000, false);
    Cookie cookie3 = new Cookie("domain", "cookie3", "val3", "/", 1000, false);
    ThankYouWriter thankYouWriter = ThankYouWriter.getINSTANCE();
    thankYouWriter.stopThankYouThread();
    thankYouWriter.addRequest(url, new Cookie[]{cookie1, cookie2, cookie3}, new RequestId(1));
    thankYouWriter.addRequest(url, new Cookie[]{cookie1, cookie2, cookie3}, new RequestId(2));  // same combination
    thankYouWriter.addRequest(url, new Cookie[]{cookie3, cookie2, cookie1}, new RequestId(3)); // cookie order changed
    thankYouWriter.addRequest(url, new Cookie[]{cookie3}, new RequestId(4)); // mismatch cookies
    thankYouWriter.addRequest(url, new Cookie[]{}, new RequestId(5)); // no cookies
    thankYouWriter.addRequest(url, null, new RequestId(6)); // null cookies

    assertEquals(3, thankYouWriter.getPendingRequests());
}
项目:sling-org-apache-sling-launchpad-integration-tests    文件:RemoveAcesTest.java   
public void testRemoveAce() throws IOException, JsonException {
    String folderUrl = createFolderWithAces(false);

    //remove the ace for the testUser principal
    String postUrl = folderUrl + ".deleteAce.html"; 
    List<NameValuePair> postParams = new ArrayList<NameValuePair>();
    postParams.add(new NameValuePair(":applyTo", testUserId));
       Credentials creds = new UsernamePasswordCredentials("admin", "admin");
    assertAuthenticatedPostStatus(creds, postUrl, HttpServletResponse.SC_OK, postParams, null);

    //fetch the JSON for the acl to verify the settings.
    String getUrl = folderUrl + ".acl.json";

    String json = getAuthenticatedContent(creds, getUrl, CONTENT_TYPE_JSON, null, HttpServletResponse.SC_OK);
    assertNotNull(json);

    JsonObject jsonObject = JsonUtil.parseObject(json);
    assertNotNull(jsonObject);
    assertEquals(0, jsonObject.size());
}
项目:sling-org-apache-sling-launchpad-integration-tests    文件:RemoveAcesTest.java   
public void testRemoveAces() throws IOException, JsonException {
    String folderUrl = createFolderWithAces(true);

    //remove the ace for the testUser principal
    String postUrl = folderUrl + ".deleteAce.html"; 
    List<NameValuePair> postParams = new ArrayList<NameValuePair>();
    postParams.add(new NameValuePair(":applyTo", testUserId));
    postParams.add(new NameValuePair(":applyTo", testGroupId));
       Credentials creds = new UsernamePasswordCredentials("admin", "admin");
    assertAuthenticatedPostStatus(creds, postUrl, HttpServletResponse.SC_OK, postParams, null);

    //fetch the JSON for the acl to verify the settings.
    String getUrl = folderUrl + ".acl.json";

    String json = getAuthenticatedContent(creds, getUrl, CONTENT_TYPE_JSON, null, HttpServletResponse.SC_OK);
    assertNotNull(json);

    JsonObject jsonObject = JsonUtil.parseObject(json);
    assertNotNull(jsonObject);
    assertEquals(0, jsonObject.size());
}
项目:sling-org-apache-sling-launchpad-integration-tests    文件:RemoveAcesTest.java   
/**
 * Test for SLING-1677
 */
public void testRemoveAcesResponseAsJSON() throws IOException, JsonException {
    String folderUrl = createFolderWithAces(true);

    //remove the ace for the testUser principal
    String postUrl = folderUrl + ".deleteAce.json"; 
    List<NameValuePair> postParams = new ArrayList<NameValuePair>();
    postParams.add(new NameValuePair(":applyTo", testUserId));
    postParams.add(new NameValuePair(":applyTo", testGroupId));
       Credentials creds = new UsernamePasswordCredentials("admin", "admin");
       String json = getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);

       //make sure the json response can be parsed as a JSON object
       JsonObject jsonObject = JsonUtil.parseObject(json);
    assertNotNull(jsonObject);
}
项目:sling-org-apache-sling-launchpad-integration-tests    文件:AnonymousAccessTest.java   
public void testAnonymousContent() throws Exception {
    // disable credentials -> anonymous session
    final URL url = new URL(HTTP_BASE_URL);
    final AuthScope scope = new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM);
    httpClient.getParams().setAuthenticationPreemptive(false);
    httpClient.getState().setCredentials(scope, null);

    try {
        assertContent();
    } finally {
        // re-enable credentials -> admin session
        httpClient.getParams().setAuthenticationPreemptive(true);
        Credentials defaultcreds = new UsernamePasswordCredentials("admin", "admin");
        httpClient.getState().setCredentials(scope, defaultcreds);
    }
}
项目:sling-org-apache-sling-launchpad-integration-tests    文件:AuthenticationResponseCodeTest.java   
@Test
public void testValidatingIncorrectHttpBasicCredentials() throws Exception {

    // assume http and webdav are on the same host + port
    URL url = new URL(HttpTest.HTTP_BASE_URL);
    Credentials defaultcreds = new UsernamePasswordCredentials("garbage", "garbage");
    H.getHttpClient().getState()
            .setCredentials(new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM), defaultcreds);

    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new NameValuePair("j_validate", "true"));
    HttpMethod post = H.assertPostStatus(HttpTest.HTTP_BASE_URL + "/j_security_check",
            HttpServletResponse.SC_FORBIDDEN, params, null);
    assertXReason(post);

    HttpMethod get = H.assertHttpStatus(HttpTest.HTTP_BASE_URL + "/?j_validate=true",
            HttpServletResponse.SC_FORBIDDEN);
    assertXReason(get);
}
项目:sling-org-apache-sling-launchpad-integration-tests    文件:AuthenticationResponseCodeTest.java   
@Test
public void testPreventLoopIncorrectHttpBasicCredentials() throws Exception {

    // assume http and webdav are on the same host + port
    URL url = new URL(HttpTest.HTTP_BASE_URL);
    Credentials defaultcreds = new UsernamePasswordCredentials("garbage", "garbage");
    H.getHttpClient().getState()
            .setCredentials(new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM), defaultcreds);

    final String requestUrl = HttpTest.HTTP_BASE_URL + "/junk?param1=1";
    HttpMethod get = new GetMethod(requestUrl);
    get.setRequestHeader("Referer", requestUrl);
    get.setRequestHeader("User-Agent", "Mozilla/5.0 Sling Integration Test");
    int status = H.getHttpClient().executeMethod(get);
    assertEquals(HttpServletResponse.SC_UNAUTHORIZED, status);
}
项目:lib-commons-httpclient    文件:TestDigestAuth.java   
/** 
 * Test digest authentication with invalud qop value
 */
public void testDigestAuthenticationMD5SessInvalidQop() throws Exception {
    // Example using Digest auth with MD5-sess

    String realm="realm";
    String username="username";
    String password="password";
    String nonce="e273f1776275974f1a120d8b92c5b3cb";

    String challenge="Digest realm=\"" + realm + "\", "
        + "nonce=\"" + nonce + "\", "
        + "opaque=\"SomeString\", "
        + "stale=false, "
        + "algorithm=MD5-sess, "
        + "qop=\"jakarta\""; // jakarta is an invalid qop value

    UsernamePasswordCredentials cred =
        new UsernamePasswordCredentials(username, password);
    try {
        AuthScheme authscheme = new DigestScheme();
        authscheme.processChallenge(challenge);
        fail("MalformedChallengeException exception expected due to invalid qop value");
    } catch(MalformedChallengeException e) {
    }
}
项目:sling-org-apache-sling-launchpad-integration-tests    文件:AuthenticatedTestUtil.java   
public String createTestUser() throws IOException {
      String postUrl = HTTP_BASE_URL + "/system/userManager/user.create.html";

      String testUserId = "testUser" + getNextInt();
      List<NameValuePair> postParams = new ArrayList<NameValuePair>();
      postParams.add(new NameValuePair(":name", testUserId));
      postParams.add(new NameValuePair("pwd", "testPwd"));
      postParams.add(new NameValuePair("pwdConfirm", "testPwd"));
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
final String msg = "Unexpected status while attempting to create test user at " + postUrl; 
      assertAuthenticatedPostStatus(creds, postUrl, HttpServletResponse.SC_OK, postParams, msg);

      final String sessionInfoUrl = HTTP_BASE_URL + "/system/sling/info.sessionInfo.json";
      assertAuthenticatedHttpStatus(creds, sessionInfoUrl, HttpServletResponse.SC_OK, 
              "session info failed for user " + testUserId);

      return testUserId;
  }
项目:sling-org-apache-sling-launchpad-integration-tests    文件:CreateUserTest.java   
/**
 * Test for SLING-1677
 */
@Test 
public void testCreateUserResponseAsJSON() throws IOException, JsonException {
       String postUrl = HttpTest.HTTP_BASE_URL + "/system/userManager/user.create.json";

    testUserId = "testUser" + random.nextInt();
    List<NameValuePair> postParams = new ArrayList<NameValuePair>();
    postParams.add(new NameValuePair(":name", testUserId));
    postParams.add(new NameValuePair("marker", testUserId));
    postParams.add(new NameValuePair("pwd", "testPwd"));
    postParams.add(new NameValuePair("pwdConfirm", "testPwd"));
    Credentials creds = new UsernamePasswordCredentials("admin", "admin");
    String json = H.getAuthenticatedPostContent(creds, postUrl, HttpTest.CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);

    //make sure the json response can be parsed as a JSON object
    JsonObject jsonObj = JsonUtil.parseObject(json);
    assertNotNull(jsonObj);
}
项目:sling-org-apache-sling-launchpad-integration-tests    文件:UpdateUserTest.java   
/**
 * Test for SLING-1677
 */
@Test 
public void testUpdateUserResponseAsJSON() throws IOException, JsonException {
    testUserId = H.createTestUser();

       String postUrl = HttpTest.HTTP_BASE_URL + "/system/userManager/user/" + testUserId + ".update.json";

    List<NameValuePair> postParams = new ArrayList<NameValuePair>();
    postParams.add(new NameValuePair("displayName", "My Updated Test User"));
    postParams.add(new NameValuePair("url", "http://www.apache.org/updated"));
    Credentials creds = new UsernamePasswordCredentials(testUserId, "testPwd");
    String json = H.getAuthenticatedPostContent(creds, postUrl, HttpTest.CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);

    //make sure the json response can be parsed as a JSON object
    JsonObject jsonObj = JsonUtil.parseObject(json);
    assertNotNull(jsonObj);
}
项目:sling-org-apache-sling-launchpad-integration-tests    文件:UserPrivilegesInfoTest.java   
/**
 * Checks whether the current user has been granted privileges
 * to add a new user.
 */
@Test 
public void testCanAddUser() throws JsonException, IOException {
    testUserId = H.createTestUser();

    String getUrl = HttpTest.HTTP_BASE_URL + "/system/userManager/user/" + testUserId + ".privileges-info.json";

    //fetch the JSON for the test page to verify the settings.
    Credentials testUserCreds = new UsernamePasswordCredentials(testUserId, "testPwd");

    String json = H.getAuthenticatedContent(testUserCreds, getUrl, HttpTest.CONTENT_TYPE_JSON, null, HttpServletResponse.SC_OK);
    assertNotNull(json);
    JsonObject jsonObj = JsonUtil.parseObject(json);

    assertEquals(false, jsonObj.getBoolean("canAddUser"));
}
项目:sling-org-apache-sling-launchpad-integration-tests    文件:UserPrivilegesInfoTest.java   
/**
 * Checks whether the current user has been granted privileges
 * to add a new group.
 */
@Test 
public void testCanAddGroup() throws IOException, JsonException {
    testUserId = H.createTestUser();

    String getUrl = HttpTest.HTTP_BASE_URL + "/system/userManager/user/" + testUserId + ".privileges-info.json";

    //fetch the JSON for the test page to verify the settings.
    Credentials testUserCreds = new UsernamePasswordCredentials(testUserId, "testPwd");

    String json = H.getAuthenticatedContent(testUserCreds, getUrl, HttpTest.CONTENT_TYPE_JSON, null, HttpServletResponse.SC_OK);
    assertNotNull(json);
    JsonObject jsonObj = JsonUtil.parseObject(json);

    assertEquals(false, jsonObj.getBoolean("canAddGroup"));
}
项目:sling-org-apache-sling-launchpad-integration-tests    文件:UserPrivilegesInfoTest.java   
/**
 * Checks whether the current user has been granted privileges
 * to update the properties of the specified group.
 */
@Test 
public void testCanUpdateGroupProperties() throws IOException, JsonException {
    testGroupId = H.createTestGroup();
    testUserId = H.createTestUser();

    //1. Verify non admin user can not update group properties
    String getUrl = HttpTest.HTTP_BASE_URL + "/system/userManager/group/" + testGroupId + ".privileges-info.json";

    //fetch the JSON for the test page to verify the settings.
    Credentials testUserCreds = new UsernamePasswordCredentials(testUserId, "testPwd");

    String json = H.getAuthenticatedContent(testUserCreds, getUrl, HttpTest.CONTENT_TYPE_JSON, null, HttpServletResponse.SC_OK);
    assertNotNull(json);
    JsonObject jsonObj = JsonUtil.parseObject(json);

    //normal user can not update group properties
    assertEquals(false, jsonObj.getBoolean("canUpdateProperties"));
}
项目:sling-org-apache-sling-launchpad-integration-tests    文件:UserPrivilegesInfoTest.java   
/**
 * Checks whether the current user has been granted privileges
 * to remove the specified group.
 */
@Test 
public void testCanRemoveGroup() throws IOException, JsonException {
    testGroupId = H.createTestGroup();
    testUserId = H.createTestUser();

    //1. Verify non admin user can not remove group
    String getUrl = HttpTest.HTTP_BASE_URL + "/system/userManager/group/" + testGroupId + ".privileges-info.json";

    //fetch the JSON for the test page to verify the settings.
    Credentials testUserCreds = new UsernamePasswordCredentials(testUserId, "testPwd");

    String json = H.getAuthenticatedContent(testUserCreds, getUrl, HttpTest.CONTENT_TYPE_JSON, null, HttpServletResponse.SC_OK);
    assertNotNull(json);
    JsonObject jsonObj = JsonUtil.parseObject(json);

    //normal user can not remove group
    assertEquals(false, jsonObj.getBoolean("canRemove"));
}
项目:sling-org-apache-sling-launchpad-integration-tests    文件:UserPrivilegesInfoTest.java   
/**
 * Checks whether the current user has been granted privileges
 * to update the membership of the specified group.
 */
@Test 
public void testCanUpdateGroupMembers() throws IOException, JsonException {
    testGroupId = H.createTestGroup();
    testUserId = H.createTestUser();

    //1. Verify non admin user can not update group membership
    String getUrl = HttpTest.HTTP_BASE_URL + "/system/userManager/group/" + testGroupId + ".privileges-info.json";

    //fetch the JSON for the test page to verify the settings.
    Credentials testUserCreds = new UsernamePasswordCredentials(testUserId, "testPwd");

    String json = H.getAuthenticatedContent(testUserCreds, getUrl, HttpTest.CONTENT_TYPE_JSON, null, HttpServletResponse.SC_OK);
    assertNotNull(json);
    JsonObject jsonObj = JsonUtil.parseObject(json);

    //normal user can not remove group
    assertEquals(false, jsonObj.getBoolean("canUpdateGroupMembers"));
}
项目:sling-org-apache-sling-launchpad-integration-tests    文件:CreateGroupTest.java   
public void testCreateGroup() throws IOException, JsonException {
       String postUrl = HTTP_BASE_URL + "/system/userManager/group.create.html";

    testGroupId = "testGroup" + random.nextInt();
    List<NameValuePair> postParams = new ArrayList<NameValuePair>();
    postParams.add(new NameValuePair(":name", testGroupId));
    postParams.add(new NameValuePair("marker", testGroupId));
    assertAuthenticatedAdminPostStatus(postUrl, HttpServletResponse.SC_OK, postParams, null);

    //fetch the group profile json to verify the settings
    String getUrl = HTTP_BASE_URL + "/system/userManager/group/" + testGroupId + ".json";
    Credentials creds = new UsernamePasswordCredentials("admin", "admin");
    String json = getAuthenticatedContent(creds, getUrl, CONTENT_TYPE_JSON, null, HttpServletResponse.SC_OK);
    assertNotNull(json);
    JsonObject jsonObj = JsonUtil.parseObject(json);
    assertEquals(testGroupId, jsonObj.getString("marker"));
}
项目:sling-org-apache-sling-launchpad-integration-tests    文件:UpdateGroupTest.java   
public void testUpdateGroup() throws IOException, JsonException {
    testGroupId = createTestGroup();

       String postUrl = HTTP_BASE_URL + "/system/userManager/group/" + testGroupId + ".update.html";

    List<NameValuePair> postParams = new ArrayList<NameValuePair>();
    postParams.add(new NameValuePair("displayName", "My Updated Test Group"));
    postParams.add(new NameValuePair("url", "http://www.apache.org/updated"));

    Credentials creds = new UsernamePasswordCredentials("admin", "admin");
    assertAuthenticatedPostStatus(creds, postUrl, HttpServletResponse.SC_OK, postParams, null);

    //fetch the user profile json to verify the settings
    String getUrl = HTTP_BASE_URL + "/system/userManager/group/" + testGroupId + ".json";
    assertAuthenticatedHttpStatus(creds, getUrl, HttpServletResponse.SC_OK, null); //make sure the profile request returns some data
    String json = getAuthenticatedContent(creds, getUrl, CONTENT_TYPE_JSON, null, HttpServletResponse.SC_OK);
    assertNotNull(json);
    JsonObject jsonObj = JsonUtil.parseObject(json);
    assertEquals("My Updated Test Group", jsonObj.getString("displayName"));
    assertEquals("http://www.apache.org/updated", jsonObj.getString("url"));
}
项目:sling-org-apache-sling-launchpad-integration-tests    文件:UpdateGroupTest.java   
/**
 * Test for SLING-1677
 */
public void testUpdateGroupResponseAsJSON() throws IOException, JsonException {
    testGroupId = createTestGroup();

       String postUrl = HTTP_BASE_URL + "/system/userManager/group/" + testGroupId + ".update.json";

    List<NameValuePair> postParams = new ArrayList<NameValuePair>();
    postParams.add(new NameValuePair("displayName", "My Updated Test Group"));
    postParams.add(new NameValuePair("url", "http://www.apache.org/updated"));

    Credentials creds = new UsernamePasswordCredentials("admin", "admin");
    String json = getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);

    //make sure the json response can be parsed as a JSON object
    JsonObject jsonObj = JsonUtil.parseObject(json);
    assertNotNull(jsonObj);
}
项目:sling-org-apache-sling-launchpad-integration-tests    文件:RemoveAuthorizablesTest.java   
public void testRemoveAuthorizables() throws IOException {
    String userId = createTestUser();
    String groupId = createTestGroup();

       Credentials creds = new UsernamePasswordCredentials("admin", "admin");

    String getUrl = HTTP_BASE_URL + "/system/userManager/user/" + userId + ".json";
    assertAuthenticatedHttpStatus(creds, getUrl, HttpServletResponse.SC_OK, null); //make sure the profile request returns some data

    getUrl = HTTP_BASE_URL + "/system/userManager/group/" + groupId + ".json";
    assertAuthenticatedHttpStatus(creds, getUrl, HttpServletResponse.SC_OK, null); //make sure the profile request returns some data

    String postUrl = HTTP_BASE_URL + "/system/userManager.delete.html";
    List<NameValuePair> postParams = new ArrayList<NameValuePair>();
    postParams.add(new NameValuePair(":applyTo", "group/" + groupId));
    postParams.add(new NameValuePair(":applyTo", "user/" + userId));
    assertAuthenticatedPostStatus(creds, postUrl, HttpServletResponse.SC_OK, postParams, null);

    getUrl = HTTP_BASE_URL + "/system/userManager/user/" + userId + ".json";
    assertAuthenticatedHttpStatus(creds, getUrl, HttpServletResponse.SC_NOT_FOUND, null); //make sure the profile request returns some data

    getUrl = HTTP_BASE_URL + "/system/userManager/group/" + groupId + ".json";
    assertAuthenticatedHttpStatus(creds, getUrl, HttpServletResponse.SC_NOT_FOUND, null); //make sure the profile request returns some data
}
项目:sling-org-apache-sling-launchpad-integration-tests    文件:RemoveAuthorizablesTest.java   
/**
 * Test the problem reported as SLING-1237
 */
public void testRemoveGroupWithMembers() throws IOException {
    String groupId = createTestGroup();
    String userId = createTestUser();

       Credentials creds = new UsernamePasswordCredentials("admin", "admin");
       String addMemberPostUrl = HTTP_BASE_URL + "/system/userManager/group/" + groupId + ".update.html";
    List<NameValuePair> addMemberPostParams = new ArrayList<NameValuePair>();
    addMemberPostParams.add(new NameValuePair(":member", userId));
    assertAuthenticatedPostStatus(creds, addMemberPostUrl, HttpServletResponse.SC_OK, addMemberPostParams, null);

    String getUrl = HTTP_BASE_URL + "/system/userManager/group/" + groupId + ".json";
    assertAuthenticatedHttpStatus(creds, getUrl, HttpServletResponse.SC_OK, null); //make sure the profile request returns some data

    String postUrl = HTTP_BASE_URL + "/system/userManager/group/" + groupId + ".delete.html";
    List<NameValuePair> postParams = new ArrayList<NameValuePair>();
    assertAuthenticatedPostStatus(creds, postUrl, HttpServletResponse.SC_OK, postParams, null);

    getUrl = HTTP_BASE_URL + "/system/userManager/group/" + groupId + ".json";
    assertAuthenticatedHttpStatus(creds, getUrl, HttpServletResponse.SC_NOT_FOUND, null); //make sure the profile request returns some data
}
项目:lib-commons-httpclient    文件:BasicScheme.java   
/**
 * Returns a basic <tt>Authorization</tt> header value for the given 
 * {@link UsernamePasswordCredentials} and charset.
 * 
 * @param credentials The credentials to encode.
 * @param charset The charset to use for encoding the credentials
 * 
 * @return a basic authorization string
 * 
 * @since 3.0
 */
public static String authenticate(UsernamePasswordCredentials credentials, String charset) {

    LOG.trace("enter BasicScheme.authenticate(UsernamePasswordCredentials, String)");

    if (credentials == null) {
        throw new IllegalArgumentException("Credentials may not be null"); 
    }
    if (charset == null || charset.length() == 0) {
        throw new IllegalArgumentException("charset may not be null or empty");
    }
    StringBuffer buffer = new StringBuffer();
    buffer.append(credentials.getUserName());
    buffer.append(":");
    buffer.append(credentials.getPassword());

    return "Basic " + EncodingUtil.getAsciiString(
            Base64.encodeBase64(EncodingUtil.getBytes(buffer.toString(), charset)));
}
项目:alfresco-repository    文件:SolrAdminHTTPClient.java   
public void init()
{
    ParameterCheck.mandatory("baseUrl", baseUrl);

    StringBuilder sb = new StringBuilder();
    sb.append(baseUrl + "/admin/cores");
    this.adminUrl = sb.toString();

    httpClient = httpClientFactory.getHttpClient();
    HttpClientParams params = httpClient.getParams();
    params.setBooleanParameter(HttpClientParams.PREEMPTIVE_AUTHENTICATION, true);
    httpClient.getState().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials("admin", "admin"));
}
项目:alfresco-repository    文件:SOLRAdminClient.java   
public void init()
{
    ParameterCheck.mandatory("solrHost", solrHost);
    ParameterCheck.mandatory("solrPort", solrPort);
    ParameterCheck.mandatory("solrUser", solrUser);
    ParameterCheck.mandatory("solrPassword", solrPassword);
    ParameterCheck.mandatory("solrPingCronExpression", solrPingCronExpression);
    ParameterCheck.mandatory("solrConnectTimeout", solrConnectTimeout);

    try
    {
        StringBuilder sb = new StringBuilder();
        sb.append(httpClientFactory.isSSL() ? "https://" : "http://");
        sb.append(solrHost);
        sb.append(":");
        sb.append(httpClientFactory.isSSL() ? solrSSLPort: solrPort);
        sb.append(baseUrl);
        this.solrUrl = sb.toString();
        HttpClient httpClient = httpClientFactory.getHttpClient();

        server = new CommonsHttpSolrServer(solrUrl, httpClient);
        server.setParser(new XMLResponseParser());
        // TODO remove credentials because we're using SSL?
        Credentials defaultcreds = new UsernamePasswordCredentials(solrUser, solrPassword); 
        server.getHttpClient().getState().setCredentials(new AuthScope(solrHost, solrPort, AuthScope.ANY_REALM), 
                defaultcreds);
        server.setConnectionTimeout(solrConnectTimeout);
        server.setSoTimeout(20000);

        this.solrTracker = new SolrTracker(scheduler);
    }
    catch(MalformedURLException e)
    {
        throw new AlfrescoRuntimeException("Cannot initialise Solr admin http client", e);
    }
}
项目:alfresco-repository    文件:AbstractRemoteAlfrescoTicketImpl.java   
/**
 * Returns the Ticket in the form used for HTTP Basic Authentication. 
 * This should be added as the value to a HTTP Request Header with 
 *  key Authorization
 */
public String getAsHTTPAuthorization()
{
    // Build from the Username and Password
    Pair<String,String> userPass = getAsUsernameAndPassword();
    Credentials credentials = new UsernamePasswordCredentials(userPass.getFirst(), userPass.getSecond());

    // Encode it into the required format
    String credentialsEncoded = Base64.encodeBytes(
            credentials.toString().getBytes(utf8), Base64.DONT_BREAK_LINES );

    // Mark it as Basic, and we're done
    return "Basic " + credentialsEncoded;
}
项目:alfresco-repository    文件:BaseWebScriptTest.java   
@Override
protected void setUp() throws Exception
{
    super.setUp();

    if (remoteServer != null)
    {
        httpClient = new HttpClient();
        httpClient.getParams().setBooleanParameter(HttpClientParams.PREEMPTIVE_AUTHENTICATION, true);
        if (remoteServer.username != null)
        {
            httpClient.getState().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(remoteServer.username, remoteServer.password));
        }
    }
}
项目:uDetective    文件:ServiceNowDataSource.java   
@Override
public Object connect() {
    HttpClient client = new HttpClient();
    client.getParams().setAuthenticationPreemptive(false);
    Credentials creds = new UsernamePasswordCredentials(AppProperties.getProperty("username"), AppProperties.getProperty("password"));
    client.getState().setCredentials(AuthScope.ANY, creds);

    return client;
}
项目:convertigo-engine    文件:ProxyManager.java   
public void setBasicAuth(HttpState httpState) {
    // Setting basic authentication for proxy
    if ((!this.proxyServer.equals("")) && (!this.proxyUser.equals(""))) {
            httpState.setProxyCredentials(
                    new AuthScope(this.proxyServer, -1, AuthScope.ANY_REALM),
                    new UsernamePasswordCredentials(this.proxyUser, this.proxyPassword));

            Engine.logProxyManager.debug("(ProxyManager) Using credentials: " + promptUser
                    + ", <password not logged, set engine logger log level to TRACE to see it>");
            Engine.logProxyManager.trace("(ProxyManager) Using password: " + proxyPassword);
    }
}
项目:convertigo-engine    文件:ProxyManager.java   
public void setCredentials() {
    //Setting credentials for XUL
    if (this.promptUser == null) {
        this.promptUser = this.proxyUser;
    }
    if (this.promptPassword == null) {
        this.promptPassword = this.proxyPassword;
    }
    if (this.promptUser != null && this.promptPassword.length() > 0 && proxyMethod.equals(ProxyMethod.basic.name())) {
        this.basicValue = BasicScheme.authenticate(new UsernamePasswordCredentials(this.promptUser, this.promptPassword), "UTF-8");
    } else {
        this.basicValue = null;
    }   
}
项目:convertigo-engine    文件:HttpStateEvent.java   
public String getUserName() {
    String userName = null;
    Credentials credentials = getCredentials();
    if (credentials != null) {
        if (credentials instanceof UsernamePasswordCredentials) {
            userName = ((UsernamePasswordCredentials)credentials).getUserName();
        }
    }

    return userName;
}
项目:convertigo-engine    文件:HttpStateEvent.java   
public String getUserPassword() {
    String userPassword = null;
    Credentials credentials = getCredentials();
    if (credentials != null) {
        if (credentials instanceof UsernamePasswordCredentials) {
            userPassword = ((UsernamePasswordCredentials)credentials).getPassword();
        }
    }

    return userPassword;
}
项目:lams    文件:HttpClientBuilder.java   
/**
 * Builds an HTTP client with the given settings. Settings are NOT reset to their default values after a client has
 * been created.
 * 
 * @return the created client.
 */
public HttpClient buildClient() {
    if (httpsProtocolSocketFactory != null) {
        Protocol.registerProtocol("https", new Protocol("https", httpsProtocolSocketFactory, 443));
    }

    HttpClientParams clientParams = new HttpClientParams();
    clientParams.setAuthenticationPreemptive(isPreemptiveAuthentication());
    clientParams.setContentCharset(getContentCharSet());
    clientParams.setParameter(HttpClientParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(
            connectionRetryAttempts, false));

    HttpConnectionManagerParams connMgrParams = new HttpConnectionManagerParams();
    connMgrParams.setConnectionTimeout(getConnectionTimeout());
    connMgrParams.setDefaultMaxConnectionsPerHost(getMaxConnectionsPerHost());
    connMgrParams.setMaxTotalConnections(getMaxTotalConnections());
    connMgrParams.setReceiveBufferSize(getReceiveBufferSize());
    connMgrParams.setSendBufferSize(getSendBufferSize());
    connMgrParams.setTcpNoDelay(isTcpNoDelay());

    MultiThreadedHttpConnectionManager connMgr = new MultiThreadedHttpConnectionManager();
    connMgr.setParams(connMgrParams);

    HttpClient httpClient = new HttpClient(clientParams, connMgr);

    if (proxyHost != null) {
        HostConfiguration hostConfig = new HostConfiguration();
        hostConfig.setProxy(proxyHost, proxyPort);
        httpClient.setHostConfiguration(hostConfig);

        if (proxyUsername != null) {
            AuthScope proxyAuthScope = new AuthScope(proxyHost, proxyPort);
            UsernamePasswordCredentials proxyCredentials = new UsernamePasswordCredentials(proxyUsername,
                    proxyPassword);
            httpClient.getState().setProxyCredentials(proxyAuthScope, proxyCredentials);
        }
    }

    return httpClient;
}
项目:lams    文件:HTTPMetadataProvider.java   
/**
 * Sets the username and password used to access the metadata URL. To disable BASIC authentication set the username
 * and password to null;
 * 
 * @param username the username
 * @param password the password
 */
public void setBasicCredentials(String username, String password) {
    if (username == null && password == null) {
        httpClient.getState().setCredentials(null, null);
    } else {
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
        httpClient.getState().setCredentials(authScope, credentials);
    }
}
项目:sling-org-apache-sling-launchpad-integration-tests    文件:ModifyAceTest.java   
/**
 * Test to verify adding an ACE in the first position of 
 * the ACL
 */
@Test 
public void testAddAceOrderByFirst() throws IOException, JsonException {
    createAceOrderTestFolderWithOneAce();

    testGroupId = H.createTestGroup();

    addOrUpdateAce(testFolderUrl, testGroupId, true, "first");

    //fetch the JSON for the acl to verify the settings.
    String getUrl = testFolderUrl + ".acl.json";

    Credentials creds = new UsernamePasswordCredentials("admin", "admin");
    String json = H.getAuthenticatedContent(creds, getUrl, HttpTest.CONTENT_TYPE_JSON, null, HttpServletResponse.SC_OK);
    assertNotNull(json);

    JsonObject jsonObject = JsonUtil.parseObject(json);
    assertEquals(2, jsonObject.size());

    JsonObject group = jsonObject.getJsonObject(testGroupId);
    assertNotNull(group);
    assertEquals(testGroupId, group.getString("principal"));
               assertEquals(0, group.getInt("order"));
    JsonObject user =  jsonObject.getJsonObject(testUserId);
               assertNotNull(user);
               assertEquals(testUserId, user.getString("principal"));
               assertEquals(1, user.getInt("order"));
}
项目:sling-org-apache-sling-launchpad-integration-tests    文件:ModifyAceTest.java   
/**
 * Test to verify adding an ACE at the end 
 * the ACL
 */
@Test 
public void testAddAceOrderByLast() throws IOException, JsonException {
    createAceOrderTestFolderWithOneAce();

    testGroupId = H.createTestGroup();

    addOrUpdateAce(testFolderUrl, testGroupId, true, "last");

    //fetch the JSON for the acl to verify the settings.
    String getUrl = testFolderUrl + ".acl.json";

    Credentials creds = new UsernamePasswordCredentials("admin", "admin");
    String json = H.getAuthenticatedContent(creds, getUrl, HttpTest.CONTENT_TYPE_JSON, null, HttpServletResponse.SC_OK);
    assertNotNull(json);

    JsonObject jsonObject = JsonUtil.parseObject(json);
    assertEquals(2, jsonObject.size());

               JsonObject user =  jsonObject.getJsonObject(testUserId);
               assertNotNull(user);
               assertEquals(testUserId, user.getString("principal"));
               assertEquals(0, user.getInt("order"));
               JsonObject group = jsonObject.getJsonObject(testGroupId);
               assertNotNull(group);
               assertEquals(testGroupId, group.getString("principal"));
               assertEquals(1, group.getInt("order"));

}