Fix vCloud test usage of new ContextBuilder

This commit is contained in:
Andrew Donald Kennedy 2012-04-13 12:23:45 +01:00
parent c56c2d2f72
commit c0d781a11d
4 changed files with 113 additions and 117 deletions

View File

@ -133,7 +133,6 @@ public class ContextBuilder<S, A, C extends Closeable, M extends ApiMetadata<S,
} }
} }
@SuppressWarnings("unchecked")
public static <S, A, C extends Closeable, M extends ApiMetadata<S, A, C, M>> ContextBuilder<S, A, C, M> newBuilder( public static <S, A, C extends Closeable, M extends ApiMetadata<S, A, C, M>> ContextBuilder<S, A, C, M> newBuilder(
ApiMetadata<S, A, C, M> apiMetadata) { ApiMetadata<S, A, C, M> apiMetadata) {
try { try {
@ -149,7 +148,6 @@ public class ContextBuilder<S, A, C extends Closeable, M extends ApiMetadata<S,
} }
} }
@SuppressWarnings("unchecked")
public static <S, A, C extends Closeable, M extends ApiMetadata<S, A, C, M>> ContextBuilder<S, A, C, M> newBuilder( public static <S, A, C extends Closeable, M extends ApiMetadata<S, A, C, M>> ContextBuilder<S, A, C, M> newBuilder(
ProviderMetadata<S, A, C, M> providerMetadata) { ProviderMetadata<S, A, C, M> providerMetadata) {
try { try {
@ -232,10 +230,8 @@ public class ContextBuilder<S, A, C extends Closeable, M extends ApiMetadata<S,
} }
/** /**
*
* @throws NoSuchElementException * @throws NoSuchElementException
*/ */
public static String searchPropertiesForProviderScopedProperty(Properties overrides, String prov, String key, public static String searchPropertiesForProviderScopedProperty(Properties overrides, String prov, String key,
String defaultVal) { String defaultVal) {
try { try {

View File

@ -49,13 +49,17 @@ public abstract class BaseContextLiveTest<C extends Closeable> {
protected volatile C context; protected volatile C context;
protected String identity;
protected String credential;
protected String endpoint;
protected Properties setupProperties() { protected Properties setupProperties() {
Properties overrides = new Properties(); Properties overrides = new Properties();
overrides.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "true"); overrides.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "true");
overrides.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, "true"); overrides.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, "true");
setIfTestSystemPropertyPresent(overrides, provider + ".identity"); identity = setIfTestSystemPropertyPresent(overrides, provider + ".identity");
setIfTestSystemPropertyPresent(overrides, provider + ".credential"); credential = setIfTestSystemPropertyPresent(overrides, provider + ".credential");
setIfTestSystemPropertyPresent(overrides, provider + ".endpoint"); endpoint = setIfTestSystemPropertyPresent(overrides, provider + ".endpoint");
setIfTestSystemPropertyPresent(overrides, provider + ".api-version"); setIfTestSystemPropertyPresent(overrides, provider + ".api-version");
setIfTestSystemPropertyPresent(overrides, provider + ".build-version"); setIfTestSystemPropertyPresent(overrides, provider + ".build-version");
return overrides; return overrides;
@ -65,6 +69,7 @@ public abstract class BaseContextLiveTest<C extends Closeable> {
if (System.getProperties().containsKey("test." + key)) { if (System.getProperties().containsKey("test." + key)) {
String val = System.getProperty("test." + key); String val = System.getProperty("test." + key);
overrides.setProperty(key, val); overrides.setProperty(key, val);
return val;
} }
return null; return null;
} }
@ -91,7 +96,6 @@ public abstract class BaseContextLiveTest<C extends Closeable> {
/** /**
* @see org.jclouds.providers.Providers#withId * @see org.jclouds.providers.Providers#withId
*/ */
@SuppressWarnings("unchecked")
protected ProviderMetadata<?, ?, C, ?> createProviderMetadata() { protected ProviderMetadata<?, ?, C, ?> createProviderMetadata() {
try { try {
return (ProviderMetadata<?, ?, C, ?>) Providers.withId(provider); return (ProviderMetadata<?, ?, C, ?>) Providers.withId(provider);
@ -103,7 +107,6 @@ public abstract class BaseContextLiveTest<C extends Closeable> {
/** /**
* @see org.jclouds.apis.Apis#withId * @see org.jclouds.apis.Apis#withId
*/ */
@SuppressWarnings("unchecked")
protected ApiMetadata<?, ?, C, ?> createApiMetadata() { protected ApiMetadata<?, ?, C, ?> createApiMetadata() {
try { try {
return (ApiMetadata<?, ?, C, ?>) Apis.withId(provider); return (ApiMetadata<?, ?, C, ?>) Apis.withId(provider);

View File

@ -51,6 +51,13 @@ import org.jclouds.vcloud.director.v1_5.domain.Link;
import org.jclouds.vcloud.director.v1_5.domain.Reference; import org.jclouds.vcloud.director.v1_5.domain.Reference;
import org.jclouds.vcloud.director.v1_5.domain.ResourceEntity.Status; import org.jclouds.vcloud.director.v1_5.domain.ResourceEntity.Status;
import org.jclouds.vcloud.director.v1_5.domain.Role.DefaultRoles; import org.jclouds.vcloud.director.v1_5.domain.Role.DefaultRoles;
import org.jclouds.vcloud.director.v1_5.domain.RoleReferences;
import org.jclouds.vcloud.director.v1_5.domain.Session;
import org.jclouds.vcloud.director.v1_5.domain.Task;
import org.jclouds.vcloud.director.v1_5.domain.User;
import org.jclouds.vcloud.director.v1_5.domain.VApp;
import org.jclouds.vcloud.director.v1_5.domain.VAppTemplate;
import org.jclouds.vcloud.director.v1_5.domain.Vdc;
import org.jclouds.vcloud.director.v1_5.domain.network.Network; import org.jclouds.vcloud.director.v1_5.domain.network.Network;
import org.jclouds.vcloud.director.v1_5.domain.network.NetworkConfiguration; import org.jclouds.vcloud.director.v1_5.domain.network.NetworkConfiguration;
import org.jclouds.vcloud.director.v1_5.domain.network.VAppNetworkConfiguration; import org.jclouds.vcloud.director.v1_5.domain.network.VAppNetworkConfiguration;
@ -59,13 +66,6 @@ import org.jclouds.vcloud.director.v1_5.domain.params.InstantiateVAppTemplatePar
import org.jclouds.vcloud.director.v1_5.domain.params.InstantiationParams; import org.jclouds.vcloud.director.v1_5.domain.params.InstantiationParams;
import org.jclouds.vcloud.director.v1_5.domain.params.UndeployVAppParams; import org.jclouds.vcloud.director.v1_5.domain.params.UndeployVAppParams;
import org.jclouds.vcloud.director.v1_5.domain.section.NetworkConfigSection; import org.jclouds.vcloud.director.v1_5.domain.section.NetworkConfigSection;
import org.jclouds.vcloud.director.v1_5.domain.RoleReferences;
import org.jclouds.vcloud.director.v1_5.domain.Session;
import org.jclouds.vcloud.director.v1_5.domain.Task;
import org.jclouds.vcloud.director.v1_5.domain.User;
import org.jclouds.vcloud.director.v1_5.domain.VApp;
import org.jclouds.vcloud.director.v1_5.domain.VAppTemplate;
import org.jclouds.vcloud.director.v1_5.domain.Vdc;
import org.jclouds.vcloud.director.v1_5.features.TaskClient; import org.jclouds.vcloud.director.v1_5.features.TaskClient;
import org.jclouds.vcloud.director.v1_5.features.VAppClient; import org.jclouds.vcloud.director.v1_5.features.VAppClient;
import org.jclouds.vcloud.director.v1_5.features.VAppTemplateClient; import org.jclouds.vcloud.director.v1_5.features.VAppTemplateClient;
@ -75,7 +75,7 @@ import org.jclouds.vcloud.director.v1_5.predicates.TaskStatusEquals;
import org.jclouds.vcloud.director.v1_5.predicates.TaskSuccess; import org.jclouds.vcloud.director.v1_5.predicates.TaskSuccess;
import org.jclouds.vcloud.director.v1_5.user.VCloudDirectorAsyncClient; import org.jclouds.vcloud.director.v1_5.user.VCloudDirectorAsyncClient;
import org.jclouds.vcloud.director.v1_5.user.VCloudDirectorClient; import org.jclouds.vcloud.director.v1_5.user.VCloudDirectorClient;
import org.testng.annotations.AfterSuite; import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeClass;
import org.testng.annotations.Listeners; import org.testng.annotations.Listeners;
import org.testng.annotations.Test; import org.testng.annotations.Test;
@ -89,6 +89,7 @@ import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import com.google.common.io.Closeables;
import com.google.inject.Guice; import com.google.inject.Guice;
/** /**
@ -100,7 +101,7 @@ import com.google.inject.Guice;
@Listeners(FormatApiResultsListener.class) @Listeners(FormatApiResultsListener.class)
@Test(groups = "live") @Test(groups = "live")
public abstract class BaseVCloudDirectorClientLiveTest extends BaseContextLiveTest<VCloudDirectorContext> { public abstract class BaseVCloudDirectorClientLiveTest extends BaseContextLiveTest<VCloudDirectorContext> {
@Resource @Resource
protected Logger logger = Logger.CONSOLE; protected Logger logger = Logger.CONSOLE;
@ -112,7 +113,7 @@ public abstract class BaseVCloudDirectorClientLiveTest extends BaseContextLiveTe
public static final String VDC = "vdc"; public static final String VDC = "vdc";
public static final int REQUIRED_ADMIN_VM_QUOTA = 0; public static final int REQUIRED_ADMIN_VM_QUOTA = 0;
public static final int REQUIRED_USER_VM_QUOTA = 0; public static final int REQUIRED_USER_VM_QUOTA = 0;
public Predicate<Task> retryTaskSuccess; public Predicate<Task> retryTaskSuccess;
public Predicate<Task> retryTaskSuccessLong; public Predicate<Task> retryTaskSuccessLong;
@ -131,24 +132,24 @@ public abstract class BaseVCloudDirectorClientLiveTest extends BaseContextLiveTe
protected final Set<String> vAppNames = Sets.newLinkedHashSet(); protected final Set<String> vAppNames = Sets.newLinkedHashSet();
protected static final Random random = new Random(); protected static final Random random = new Random();
protected BaseVCloudDirectorClientLiveTest() { protected BaseVCloudDirectorClientLiveTest() {
provider = "vcloud-director"; provider = "vcloud-director";
} }
protected DateService dateService; protected DateService dateService;
private static VCloudDirectorTestSession testSession; protected VCloudDirectorTestSession testSession;
private static String testStamp; protected static String testStamp;
@BeforeClass(alwaysRun = true) @BeforeClass(alwaysRun = true)
protected void setupDateService() { protected void setupDateService() {
dateService = Guice.createInjector().getInstance(DateService.class); dateService = Guice.createInjector().getInstance(DateService.class);
assertNotNull(dateService); assertNotNull(dateService);
} }
// NOTE Implement as required to populate xxxClient fields, or NOP /** Implement as required to populate xxxClient fields, or NOP */
protected abstract void setupRequiredClients(); protected abstract void setupRequiredClients();
@Inject @Inject
@ -160,71 +161,62 @@ public abstract class BaseVCloudDirectorClientLiveTest extends BaseContextLiveTe
protected void initTaskSuccessLong(TaskSuccess taskSuccess) { protected void initTaskSuccessLong(TaskSuccess taskSuccess) {
retryTaskSuccessLong = new RetryablePredicate<Task>(taskSuccess, LONG_TASK_TIMEOUT_SECONDS * 1000L); retryTaskSuccessLong = new RetryablePredicate<Task>(taskSuccess, LONG_TASK_TIMEOUT_SECONDS * 1000L);
} }
//temporary until we marry up the test fixtures
protected String identity; @AfterClass(alwaysRun = true)
protected String credential;
protected String endpoint;
@Override
protected Properties setupProperties() {
Properties overrides = new Properties();
overrides.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "true");
overrides.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, "true");
identity = setIfTestSystemPropertyPresent(overrides, provider + ".identity");
credential = setIfTestSystemPropertyPresent(overrides, provider + ".credential");
endpoint = setIfTestSystemPropertyPresent(overrides, provider + ".endpoint");
setIfTestSystemPropertyPresent(overrides, provider + ".api-version");
setIfTestSystemPropertyPresent(overrides, provider + ".build-version");
return overrides;
}
@AfterSuite(alwaysRun = true)
protected void tearDownTestSession() { protected void tearDownTestSession() {
testSession.close(); Closeables.closeQuietly(testSession);
} }
@BeforeClass(alwaysRun = true)
@Override @Override
public void setupContext(){ protected void initializeContext() {
Properties overrides = setupProperties();
testSession = VCloudDirectorTestSession.builder()
.provider(provider)
.identity(identity)
.credential(credential)
.endpoint(endpoint)
.overrides(overrides)
.build();
System.err.println("*** " + endpoint + " ***");
context = testSession.getUserContext(); context = testSession.getUserContext();
adminContext = testSession.getAdminContext(); adminContext = testSession.getAdminContext();
if(adminContext != null) { if (adminContext != null) {
adminSession = adminContext.getApi().getCurrentSession(); adminSession = adminContext.getApi().getCurrentSession();
adminContext.utils().injector().injectMembers(this); adminContext.utils().injector().injectMembers(this);
} }
session = context.getApi().getCurrentSession(); session = context.getApi().getCurrentSession();
context.utils().injector().injectMembers(this); context.utils().injector().injectMembers(this);
initTestParametersFromPropertiesOrLazyDiscover(); initTestParametersFromPropertiesOrLazyDiscover();
setupRequiredClients(); setupRequiredClients();
} }
public static String getTestDateTimeStamp() { public static String getTestDateTimeStamp() {
if (testStamp == null) { if (testStamp == null) {
testStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); testStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
} }
return testStamp; return testStamp;
} }
public Reference getRoleReferenceFor(String name) { public Reference getRoleReferenceFor(String name) {
return getRoleReferenceFor(name, adminContext); return getRoleReferenceFor(name, adminContext);
} }
public static Reference getRoleReferenceFor(String name, RestContext<VCloudDirectorAdminClient, VCloudDirectorAdminAsyncClient> adminContext) { public static Reference getRoleReferenceFor(String name, RestContext<VCloudDirectorAdminClient, VCloudDirectorAdminAsyncClient> adminContext) {
RoleReferences roles = adminContext.getApi().getQueryClient().roleReferencesQueryAll(); RoleReferences roles = adminContext.getApi().getQueryClient().roleReferencesQueryAll();
// wrapped in a builder to strip out unwanted xml cruft that the api chokes on // wrapped in a builder to strip out unwanted xml cruft that the api chokes on
return Reference.builder().fromReference(Iterables.find(roles.getReferences(), ReferencePredicates.nameEquals(name))).build(); return Reference.builder().fromReference(Iterables.find(roles.getReferences(), ReferencePredicates.nameEquals(name))).build();
} }
public User randomTestUser(String prefix) { public User randomTestUser(String prefix) {
return randomTestUser(prefix, getRoleReferenceFor(DefaultRoles.USER.value())); return randomTestUser(prefix, getRoleReferenceFor(DefaultRoles.USER.value()));
} }
public User randomTestUser(String prefix, Reference role) { public User randomTestUser(String prefix, Reference role) {
return User.builder() return User.builder()
.name(name(prefix)+getTestDateTimeStamp()) .name(name(prefix)+getTestDateTimeStamp())
@ -291,19 +283,19 @@ public abstract class BaseVCloudDirectorClientLiveTest extends BaseContextLiveTe
} }
} }
} }
public URI toAdminUri(Reference ref) { public URI toAdminUri(Reference ref) {
return toAdminUri(ref.getHref()); return toAdminUri(ref.getHref());
} }
public URI toAdminUri(URI uri) { public URI toAdminUri(URI uri) {
return Reference.builder().href(uri).build().toAdminReference(endpoint).getHref(); return Reference.builder().href(uri).build().toAdminReference(endpoint).getHref();
} }
protected void assertTaskSucceeds(Task task) { protected void assertTaskSucceeds(Task task) {
assertTrue(retryTaskSuccess.apply(task), String.format(TASK_COMPLETE_TIMELY, task)); assertTrue(retryTaskSuccess.apply(task), String.format(TASK_COMPLETE_TIMELY, task));
} }
protected void assertTaskSucceedsLong(Task task) { protected void assertTaskSucceedsLong(Task task) {
assertTrue(retryTaskSuccessLong.apply(task), String.format(TASK_COMPLETE_TIMELY, task)); assertTrue(retryTaskSuccessLong.apply(task), String.format(TASK_COMPLETE_TIMELY, task));
} }
@ -314,17 +306,17 @@ public abstract class BaseVCloudDirectorClientLiveTest extends BaseContextLiveTe
RetryablePredicate<Task> retryablePredicate = new RetryablePredicate<Task>(predicate, TASK_TIMEOUT_SECONDS * 1000L); RetryablePredicate<Task> retryablePredicate = new RetryablePredicate<Task>(predicate, TASK_TIMEOUT_SECONDS * 1000L);
return retryablePredicate.apply(task); return retryablePredicate.apply(task);
} }
protected void assertTaskStatusEventually(Task task, Task.Status running, ImmutableSet<Task.Status> immutableSet) { protected void assertTaskStatusEventually(Task task, Task.Status running, ImmutableSet<Task.Status> immutableSet) {
assertTrue(taskStatusEventually(task, running, immutableSet), assertTrue(taskStatusEventually(task, running, immutableSet),
String.format("Task '%s' must reach status %s", task.getOperationName(), running)); String.format("Task '%s' must reach status %s", task.getOperationName(), running));
} }
protected boolean taskDoneEventually(Task task) { protected boolean taskDoneEventually(Task task) {
TaskClient taskClient = context.getApi().getTaskClient(); TaskClient taskClient = context.getApi().getTaskClient();
TaskStatusEquals predicate = new TaskStatusEquals( TaskStatusEquals predicate = new TaskStatusEquals(
taskClient, taskClient,
ImmutableSet.of(Task.Status.ABORTED, Task.Status.CANCELED, Task.Status.ERROR, Task.Status.SUCCESS), ImmutableSet.of(Task.Status.ABORTED, Task.Status.CANCELED, Task.Status.ERROR, Task.Status.SUCCESS),
Collections.<Task.Status>emptySet()); Collections.<Task.Status>emptySet());
RetryablePredicate<Task> retryablePredicate = new RetryablePredicate<Task>(predicate, LONG_TASK_TIMEOUT_SECONDS * 1000L); RetryablePredicate<Task> retryablePredicate = new RetryablePredicate<Task>(predicate, LONG_TASK_TIMEOUT_SECONDS * 1000L);
return retryablePredicate.apply(task); return retryablePredicate.apply(task);
@ -337,13 +329,13 @@ public abstract class BaseVCloudDirectorClientLiveTest extends BaseContextLiveTe
/** /**
* Instantiate a {@link VApp} in a {@link Vdc} using the {@link VAppTemplate} we have configured for the tests. * Instantiate a {@link VApp} in a {@link Vdc} using the {@link VAppTemplate} we have configured for the tests.
* *
* @return the VApp that is being instantiated * @return the VApp that is being instantiated
*/ */
protected VApp instantiateVApp() { protected VApp instantiateVApp() {
return instantiateVApp(name("test-vapp-")); return instantiateVApp(name("test-vapp-"));
} }
protected VApp instantiateVApp(String name) { protected VApp instantiateVApp(String name) {
InstantiateVAppTemplateParams instantiate = InstantiateVAppTemplateParams.builder() InstantiateVAppTemplateParams instantiate = InstantiateVAppTemplateParams.builder()
.name(name) .name(name)
@ -395,7 +387,7 @@ public abstract class BaseVCloudDirectorClientLiveTest extends BaseContextLiveTe
private NetworkConfiguration networkConfiguration() { private NetworkConfiguration networkConfiguration() {
Vdc vdc = context.getApi().getVdcClient().getVdc(vdcURI); Vdc vdc = context.getApi().getVdcClient().getVdc(vdcURI);
assertNotNull(vdc, String.format(ENTITY_NON_NULL, VDC)); assertNotNull(vdc, String.format(ENTITY_NON_NULL, VDC));
Set<Reference> networks = vdc.getAvailableNetworks(); Set<Reference> networks = vdc.getAvailableNetworks();
// Look up the network in the Vdc with the id configured for the tests // Look up the network in the Vdc with the id configured for the tests
@ -419,7 +411,7 @@ public abstract class BaseVCloudDirectorClientLiveTest extends BaseContextLiveTe
return networkConfiguration; return networkConfiguration;
} }
protected void cleanUpVAppTemplate(VAppTemplate vAppTemplate) { protected void cleanUpVAppTemplate(VAppTemplate vAppTemplate) {
VAppTemplateClient vappTemplateClient = context.getApi().getVAppTemplateClient(); VAppTemplateClient vappTemplateClient = context.getApi().getVAppTemplateClient();
try { try {
@ -433,7 +425,7 @@ public abstract class BaseVCloudDirectorClientLiveTest extends BaseContextLiveTe
protected void cleanUpVApp(VApp vApp) { protected void cleanUpVApp(VApp vApp) {
cleanUpVApp(vApp.getHref()); cleanUpVApp(vApp.getHref());
} }
// TODO code tidy for cleanUpVApp? Seems extremely verbose! // TODO code tidy for cleanUpVApp? Seems extremely verbose!
protected void cleanUpVApp(URI vAppURI) { protected void cleanUpVApp(URI vAppURI) {
VAppClient vAppClient = context.getApi().getVAppClient(); VAppClient vAppClient = context.getApi().getVAppClient();
@ -447,7 +439,7 @@ public abstract class BaseVCloudDirectorClientLiveTest extends BaseContextLiveTe
logger.info("Cannot find VApp at %s", vAppURI.getPath()); logger.info("Cannot find VApp at %s", vAppURI.getPath());
return; return;
} }
// Wait for busy tasks to complete (don't care if it's failed or successful) // Wait for busy tasks to complete (don't care if it's failed or successful)
// Otherwise, get error on delete "entity is busy completing an operation. // Otherwise, get error on delete "entity is busy completing an operation.
if (vApp.getTasks() != null) { if (vApp.getTasks() != null) {
@ -457,7 +449,7 @@ public abstract class BaseVCloudDirectorClientLiveTest extends BaseContextLiveTe
} }
} }
} }
// Shutdown and power off the VApp if necessary // Shutdown and power off the VApp if necessary
if (vApp.getStatus().equals(Status.POWERED_ON.getValue())) { if (vApp.getStatus().equals(Status.POWERED_ON.getValue())) {
try { try {
@ -480,7 +472,7 @@ public abstract class BaseVCloudDirectorClientLiveTest extends BaseContextLiveTe
logger.warn(e, "Continuing cleanup after error undeploying VApp %s", vApp.getName()); logger.warn(e, "Continuing cleanup after error undeploying VApp %s", vApp.getName());
} }
} }
try { try {
Task task = vAppClient.deleteVApp(vAppURI); Task task = vAppClient.deleteVApp(vAppURI);
taskDoneEventually(task); taskDoneEventually(task);

View File

@ -5,12 +5,13 @@ import static org.jclouds.vcloud.director.v1_5.VCloudDirectorLiveTestConstants.R
import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue; import static org.testng.Assert.assertTrue;
import java.io.Closeable;
import java.net.URI; import java.net.URI;
import java.util.Properties; import java.util.Properties;
import org.jclouds.logging.log4j.config.Log4JLoggingModule; import org.jclouds.logging.log4j.config.Log4JLoggingModule;
import org.jclouds.rest.RestContext; import org.jclouds.rest.RestContext;
import org.jclouds.rest.RestContextFactory; import org.jclouds.rest.internal.ContextBuilder;
import org.jclouds.sshj.config.SshjSshClientModule; import org.jclouds.sshj.config.SshjSshClientModule;
import org.jclouds.vcloud.director.v1_5.VCloudDirectorContext; import org.jclouds.vcloud.director.v1_5.VCloudDirectorContext;
import org.jclouds.vcloud.director.v1_5.admin.VCloudDirectorAdminAsyncClient; import org.jclouds.vcloud.director.v1_5.admin.VCloudDirectorAdminAsyncClient;
@ -25,16 +26,17 @@ import org.jclouds.vcloud.director.v1_5.user.VCloudDirectorClient;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import com.google.common.io.Closeables;
import com.google.inject.Module; import com.google.inject.Module;
public class VCloudDirectorTestSession { public class VCloudDirectorTestSession implements Closeable {
public static Builder builder() { public static Builder builder() {
return new Builder(); return new Builder();
} }
public static class Builder { public static class Builder {
private String provider; private String provider;
private String identity; private String identity;
private String credential; private String credential;
@ -45,65 +47,68 @@ public class VCloudDirectorTestSession {
this.provider = provider; this.provider = provider;
return this; return this;
} }
public Builder identity(String identity) { public Builder identity(String identity) {
this.identity = identity; this.identity = identity;
return this; return this;
} }
public Builder credential(String credential) { public Builder credential(String credential) {
this.credential = credential; this.credential = credential;
return this; return this;
} }
public Builder overrides(Properties overrides) { public Builder overrides(Properties overrides) {
this.overrides = overrides; this.overrides = overrides;
return this; return this;
} }
public Builder endpoint(String endpoint) { public Builder endpoint(String endpoint) {
this.endpoint = endpoint; this.endpoint = endpoint;
return this; return this;
} }
public VCloudDirectorTestSession build() { public VCloudDirectorTestSession build() {
return new VCloudDirectorTestSession(provider, identity, credential, overrides, endpoint); return new VCloudDirectorTestSession(provider, identity, credential, overrides, endpoint);
} }
} }
private RestContext<VCloudDirectorAdminClient, VCloudDirectorAdminAsyncClient> adminContext; private RestContext<VCloudDirectorAdminClient, VCloudDirectorAdminAsyncClient> adminContext;
private RestContext<VCloudDirectorClient, VCloudDirectorAsyncClient> userContext; private RestContext<VCloudDirectorClient, VCloudDirectorAsyncClient> userContext;
private User createdAdminUser; private User createdAdminUser;
private User createdUser; private User createdUser;
private VCloudDirectorTestSession(String provider, String identity, String credential, Properties overrides, String endpoint) { private VCloudDirectorTestSession(String provider, String identity, String credential, Properties overrides, String endpoint) {
VCloudDirectorContext rootContext = VCloudDirectorContext.class.cast( ContextBuilder<?, ?, ?, ?> builder = ContextBuilder.newBuilder(provider)
new RestContextFactory().createContext(provider, identity, credential, ImmutableSet.<Module> of( .credentials(identity, credential)
new Log4JLoggingModule(), new SshjSshClientModule()), overrides)); .endpoint(endpoint)
.modules(ImmutableSet.<Module> of(new Log4JLoggingModule(), new SshjSshClientModule()))
.overrides(overrides);
VCloudDirectorContext rootContext = VCloudDirectorContext.class.cast(builder.build());
if (rootContext.getApi().getCurrentSession().getLinks().contains(Link.builder() if (rootContext.getApi().getCurrentSession().getLinks().contains(Link.builder()
.rel("down") .rel("down")
.type("application/vnd.vmware.admin.vcloud+xml") .type("application/vnd.vmware.admin.vcloud+xml")
.href(URI.create(endpoint+"/admin/")) .href(URI.create(endpoint+"/admin/"))
.build())) { .build())) {
adminContext = rootContext.getAdminContext(); adminContext = rootContext.getAdminContext();
Reference orgRef = Iterables.getFirst(rootContext.getApi().getOrgClient().getOrgList().getOrgs(), null) Reference orgRef = Iterables.getFirst(rootContext.getApi().getOrgClient().getOrgList().getOrgs(), null)
.toAdminReference(endpoint); .toAdminReference(endpoint);
assertNotNull(orgRef, String.format(REF_REQ_LIVE, "admin org")); assertNotNull(orgRef, String.format(REF_REQ_LIVE, "admin org"));
Reference userRef = Iterables.find(adminContext.getApi().getOrgClient().getOrg(orgRef.getHref()).getUsers(), Reference userRef = Iterables.find(adminContext.getApi().getOrgClient().getOrg(orgRef.getHref()).getUsers(),
ReferencePredicates.nameEquals(adminContext.getApi().getCurrentSession().getUser())); ReferencePredicates.nameEquals(adminContext.getApi().getCurrentSession().getUser()));
User user = adminContext.getApi().getUserClient().getUser(userRef.getHref()); User user = adminContext.getApi().getUserClient().getUser(userRef.getHref());
Reference orgAdmin = user.getRole(); Reference orgAdmin = user.getRole();
assertTrue(equal(orgAdmin.getName(), DefaultRoles.ORG_ADMIN.value()), "must give org admin or user-only credentials"); assertTrue(equal(orgAdmin.getName(), DefaultRoles.ORG_ADMIN.value()), "must give org admin or user-only credentials");
String adminIdentity = "testAdmin"+BaseVCloudDirectorClientLiveTest.getTestDateTimeStamp(); String adminIdentity = "testAdmin"+BaseVCloudDirectorClientLiveTest.getTestDateTimeStamp();
String adminCredential = "testAdminPassword"; String adminCredential = "testAdminPassword";
createdAdminUser = rootContext.getAdminContext().getApi().getUserClient().createUser(orgRef.getHref(), User.builder() createdAdminUser = rootContext.getAdminContext().getApi().getUserClient().createUser(orgRef.getHref(), User.builder()
.name(adminIdentity) .name(adminIdentity)
.password(adminCredential) .password(adminCredential)
@ -112,14 +117,15 @@ public class VCloudDirectorTestSession {
.deployedVmQuota(BaseVCloudDirectorClientLiveTest.REQUIRED_ADMIN_VM_QUOTA) .deployedVmQuota(BaseVCloudDirectorClientLiveTest.REQUIRED_ADMIN_VM_QUOTA)
.isEnabled(true) .isEnabled(true)
.build()); .build());
rootContext.close(); rootContext = null; Closeables.closeQuietly(rootContext);
adminContext = VCloudDirectorContext.class.cast(new RestContextFactory().createContext(provider, adminIdentity, adminCredential, ImmutableSet.<Module> of( builder.credentials(adminIdentity, adminCredential);
new Log4JLoggingModule(), new SshjSshClientModule()), overrides)).getAdminContext(); adminContext = VCloudDirectorContext.class.cast(builder.build()).getAdminContext();
String userIdentity = "test"+BaseVCloudDirectorClientLiveTest.getTestDateTimeStamp(); String userIdentity = "test"+BaseVCloudDirectorClientLiveTest.getTestDateTimeStamp();
String userCredential = "testPassword"; String userCredential = "testPassword";
createdUser = adminContext.getApi().getUserClient().createUser(orgRef.getHref(), User.builder() createdUser = adminContext.getApi().getUserClient().createUser(orgRef.getHref(), User.builder()
.name(userIdentity) .name(userIdentity)
.password(userCredential) .password(userCredential)
@ -128,32 +134,31 @@ public class VCloudDirectorTestSession {
.deployedVmQuota(BaseVCloudDirectorClientLiveTest.REQUIRED_USER_VM_QUOTA) .deployedVmQuota(BaseVCloudDirectorClientLiveTest.REQUIRED_USER_VM_QUOTA)
.isEnabled(true) .isEnabled(true)
.build()); .build());
userContext = new RestContextFactory().createContext(provider, userIdentity, userCredential, ImmutableSet.<Module> of( builder.credentials(userIdentity, userCredential);
new Log4JLoggingModule(), new SshjSshClientModule()), overrides); userContext = VCloudDirectorContext.class.cast(builder.build());
} else { } else {
userContext = rootContext; userContext = rootContext;
} }
} }
@Override
public void close() { public void close() {
if (createdUser != null) { if (createdUser != null) {
adminContext.getApi().getUserClient().deleteUser(createdUser.getHref()); adminContext.getApi().getUserClient().deleteUser(createdUser.getHref());
} }
if (userContext != null) if (userContext != null) userContext.close();
userContext.close();
if (createdAdminUser != null) { if (createdAdminUser != null) {
// TODO: may have to preserve root context if we can't delete the user for it's own context here // TODO: may have to preserve root context if we can't delete the user for it's own context here
adminContext.getApi().getUserClient().deleteUser(createdAdminUser.getHref()); adminContext.getApi().getUserClient().deleteUser(createdAdminUser.getHref());
} }
if (adminContext != null) if (adminContext != null) adminContext.close();
adminContext.close();
} }
public RestContext<VCloudDirectorClient, VCloudDirectorAsyncClient> getUserContext() { public RestContext<VCloudDirectorClient, VCloudDirectorAsyncClient> getUserContext() {
return userContext; return userContext;
} }
public RestContext<VCloudDirectorAdminClient, VCloudDirectorAdminAsyncClient> getAdminContext() { public RestContext<VCloudDirectorAdminClient, VCloudDirectorAdminAsyncClient> getAdminContext() {
return adminContext; return adminContext;
} }