* @throws NoSuchElementException, AuthorizationException
* @return
*/
public static ApiKeyPair loginToEndpointAsUsernameInDomainWithPasswordAndReturnApiKeyPair(
URI endpoint, String username, String password, String domain) {
CloudStackContext context = null;
try {
Properties overrides = new Properties();
overrides.put(Constants.PROPERTY_TRUST_ALL_CERTS, "true");
overrides.put(Constants.PROPERTY_RELAX_HOSTNAME, "true");
overrides.put("jclouds.cloudstack.credential-type", "passwordCredentials");
context = ContextBuilder.newBuilder(new CloudStackApiMetadata())
.endpoint(checkNotNull(endpoint, "endpoint").toASCIIString())
.credentials(String.format("%s/%s", checkNotNull(domain, "domain"), checkNotNull(username, "username")), password)
.overrides(overrides).build(CloudStackContext.class);
CloudStackClient client = context.unwrap(CloudStackApiMetadata.CONTEXT_TOKEN).getApi();
Set<Account> listOfAccounts = client.getAccountClient().listAccounts();
domain = (domain.equals("") || domain.equals("/")) ? "ROOT" : domain;
for (Account account : listOfAccounts) {
for (User user : account.getUsers()) {
if (user.getName().equals(username) && user.getDomain().equals(domain)) {
return ApiKeyPair.builder().apiKey(user.getApiKey())
.secretKey(user.getSecretKey()).build();
}
}
}
throw new NoSuchElementException("Unable to find API keypair for user " + username);
} finally {
if (context != null)
context.close();
}
}