Pretty print in payload is now configurable

This commit is contained in:
Ignasi Barrera 2012-04-10 15:21:38 +02:00
parent b2d4a158a6
commit a059a18ada
9 changed files with 436 additions and 308 deletions

View File

@ -34,6 +34,7 @@ import org.jclouds.rest.HttpAsyncClient;
import org.jclouds.rest.HttpClient; import org.jclouds.rest.HttpClient;
import org.jclouds.ssh.SshClient; import org.jclouds.ssh.SshClient;
import org.jclouds.ssh.SshClient.Factory; import org.jclouds.ssh.SshClient.Factory;
import org.jclouds.xml.XMLParser;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.eventbus.EventBus; import com.google.common.eventbus.EventBus;
@ -51,11 +52,11 @@ public class UtilsImpl extends org.jclouds.rest.internal.UtilsImpl implements Ut
private final Function<NodeMetadata, SshClient> sshForNode; private final Function<NodeMetadata, SshClient> sshForNode;
@Inject @Inject
UtilsImpl(Injector injector, Json json, HttpClient simpleClient, HttpAsyncClient simpleAsyncClient, UtilsImpl(Injector injector, Json json, XMLParser xml, HttpClient simpleClient, HttpAsyncClient simpleAsyncClient,
Crypto encryption, DateService date, @Named(Constants.PROPERTY_USER_THREADS) ExecutorService userThreads, Crypto encryption, DateService date, @Named(Constants.PROPERTY_USER_THREADS) ExecutorService userThreads,
@Named(Constants.PROPERTY_IO_WORKER_THREADS) ExecutorService ioThreads, EventBus eventBus, @Named(Constants.PROPERTY_IO_WORKER_THREADS) ExecutorService ioThreads, EventBus eventBus,
LoggerFactory loggerFactory, Function<NodeMetadata, SshClient> sshForNode) { LoggerFactory loggerFactory, Function<NodeMetadata, SshClient> sshForNode) {
super(injector, json, simpleClient, simpleAsyncClient, encryption, date, userThreads, ioThreads, eventBus, super(injector, json, xml, simpleClient, simpleAsyncClient, encryption, date, userThreads, ioThreads, eventBus,
loggerFactory); loggerFactory);
this.sshForNode = sshForNode; this.sshForNode = sshForNode;
} }

View File

@ -260,4 +260,11 @@ public interface Constants {
*/ */
public static final String PROPERTY_TIMEOUTS_PREFIX = "jclouds.timeouts."; public static final String PROPERTY_TIMEOUTS_PREFIX = "jclouds.timeouts.";
/**
* Boolean property. Default (true).
* <p/>
* Configures the response parsers to pretty print the payload when possible.
*/
public static final String PROPERTY_PRETTY_PRINT_PAYLOADS = "jclouds.payloads.pretty-print";
} }

View File

@ -45,6 +45,7 @@ import static org.jclouds.Constants.PROPERTY_SESSION_INTERVAL;
import static org.jclouds.Constants.PROPERTY_SO_TIMEOUT; import static org.jclouds.Constants.PROPERTY_SO_TIMEOUT;
import static org.jclouds.Constants.PROPERTY_TRUST_ALL_CERTS; import static org.jclouds.Constants.PROPERTY_TRUST_ALL_CERTS;
import static org.jclouds.Constants.PROPERTY_USER_THREADS; import static org.jclouds.Constants.PROPERTY_USER_THREADS;
import static org.jclouds.Constants.PROPERTY_PRETTY_PRINT_PAYLOADS;
import java.util.Properties; import java.util.Properties;
@ -205,6 +206,14 @@ public class PropertiesBuilder {
return this; return this;
} }
/**
* @see org.jclouds.Constants.PROPERTY_PRETTY_PRINT_PAYLOADS
*/
public PropertiesBuilder prettyPrintPayloads(boolean prettyPrintPayloads) {
properties.setProperty(PROPERTY_PRETTY_PRINT_PAYLOADS, Boolean.toString(prettyPrintPayloads));
return this;
}
protected final Properties properties; protected final Properties properties;
public PropertiesBuilder() { public PropertiesBuilder() {
@ -226,6 +235,7 @@ public class PropertiesBuilder {
props.setProperty(PROPERTY_MAX_CONNECTION_REUSE, 75 + ""); props.setProperty(PROPERTY_MAX_CONNECTION_REUSE, 75 + "");
props.setProperty(PROPERTY_MAX_SESSION_FAILURES, 2 + ""); props.setProperty(PROPERTY_MAX_SESSION_FAILURES, 2 + "");
props.setProperty(PROPERTY_SESSION_INTERVAL, 60 + ""); props.setProperty(PROPERTY_SESSION_INTERVAL, 60 + "");
props.setProperty(PROPERTY_PRETTY_PRINT_PAYLOADS, "true");
return props; return props;
} }

View File

@ -25,6 +25,7 @@ import org.jclouds.date.DateService;
import org.jclouds.json.Json; import org.jclouds.json.Json;
import org.jclouds.logging.Logger.LoggerFactory; import org.jclouds.logging.Logger.LoggerFactory;
import org.jclouds.rest.internal.UtilsImpl; import org.jclouds.rest.internal.UtilsImpl;
import org.jclouds.xml.XMLParser;
import com.google.common.annotations.Beta; import com.google.common.annotations.Beta;
import com.google.common.eventbus.EventBus; import com.google.common.eventbus.EventBus;
@ -111,4 +112,11 @@ public interface Utils {
@Beta @Beta
Injector injector(); Injector injector();
XMLParser getXml();
/**
* #see #getXml
*/
XMLParser xml();
} }

View File

@ -31,6 +31,7 @@ import org.jclouds.logging.Logger.LoggerFactory;
import org.jclouds.rest.HttpAsyncClient; import org.jclouds.rest.HttpAsyncClient;
import org.jclouds.rest.HttpClient; import org.jclouds.rest.HttpClient;
import org.jclouds.rest.Utils; import org.jclouds.rest.Utils;
import org.jclouds.xml.XMLParser;
import com.google.common.annotations.Beta; import com.google.common.annotations.Beta;
import com.google.common.eventbus.EventBus; import com.google.common.eventbus.EventBus;
@ -53,9 +54,10 @@ public class UtilsImpl implements Utils {
private final EventBus eventBus; private final EventBus eventBus;
private final LoggerFactory loggerFactory; private final LoggerFactory loggerFactory;
private Injector injector; private Injector injector;
private XMLParser xml;
@Inject @Inject
protected UtilsImpl(Injector injector, Json json, HttpClient simpleClient, HttpAsyncClient simpleAsyncClient, protected UtilsImpl(Injector injector, Json json, XMLParser xml, HttpClient simpleClient, HttpAsyncClient simpleAsyncClient,
Crypto encryption, DateService date, @Named(Constants.PROPERTY_USER_THREADS) ExecutorService userThreads, Crypto encryption, DateService date, @Named(Constants.PROPERTY_USER_THREADS) ExecutorService userThreads,
@Named(Constants.PROPERTY_IO_WORKER_THREADS) ExecutorService ioThreads, EventBus eventBus, @Named(Constants.PROPERTY_IO_WORKER_THREADS) ExecutorService ioThreads, EventBus eventBus,
LoggerFactory loggerFactory) { LoggerFactory loggerFactory) {
@ -69,6 +71,7 @@ public class UtilsImpl implements Utils {
this.ioExecutor = ioThreads; this.ioExecutor = ioThreads;
this.eventBus = eventBus; this.eventBus = eventBus;
this.loggerFactory = loggerFactory; this.loggerFactory = loggerFactory;
this.xml = xml;
} }
@Override @Override
@ -173,4 +176,14 @@ public class UtilsImpl implements Utils {
return getInjector(); return getInjector();
} }
@Override
public XMLParser getXml() {
return xml;
}
@Override
public XMLParser xml() {
return xml;
}
} }

View File

@ -22,15 +22,19 @@ import java.io.IOException;
import java.io.StringReader; import java.io.StringReader;
import java.io.StringWriter; import java.io.StringWriter;
import javax.inject.Inject;
import javax.inject.Singleton; import javax.inject.Singleton;
import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException; import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller; import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller; import javax.xml.bind.Unmarshaller;
import org.jclouds.Constants;
import org.jclouds.http.functions.ParseXMLWithJAXB; import org.jclouds.http.functions.ParseXMLWithJAXB;
import org.jclouds.xml.XMLParser; import org.jclouds.xml.XMLParser;
import com.google.inject.name.Named;
/** /**
* Parses XML documents using JAXB. * Parses XML documents using JAXB.
* *
@ -39,6 +43,16 @@ import org.jclouds.xml.XMLParser;
*/ */
@Singleton @Singleton
public class JAXBParser implements XMLParser { public class JAXBParser implements XMLParser {
/** Boolean indicating if the output must be pretty printed. */
private Boolean prettyPrint;
@Inject
public JAXBParser(@Named(Constants.PROPERTY_PRETTY_PRINT_PAYLOADS) String prettyPrint) {
super();
this.prettyPrint = Boolean.valueOf(prettyPrint);
}
@Override @Override
public String toXML(final Object src) throws IOException { public String toXML(final Object src) throws IOException {
return toXML(src, src.getClass()); return toXML(src, src.getClass());
@ -49,7 +63,7 @@ public class JAXBParser implements XMLParser {
try { try {
JAXBContext context = JAXBContext.newInstance(type); JAXBContext context = JAXBContext.newInstance(type);
Marshaller marshaller = context.createMarshaller(); Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, prettyPrint);
StringWriter writer = new StringWriter(); StringWriter writer = new StringWriter();
marshaller.marshal(src, writer); marshaller.marshal(src, writer);
return writer.toString(); return writer.toString();
@ -58,6 +72,7 @@ public class JAXBParser implements XMLParser {
} }
} }
@SuppressWarnings("unchecked")
@Override @Override
public <T> T fromXML(final String xml, final Class<T> type) throws IOException { public <T> T fromXML(final String xml, final Class<T> type) throws IOException {
try { try {

View File

@ -40,7 +40,7 @@ import com.google.common.collect.Multimap;
*/ */
@Test(groups = "unit", testName = "BindToXMLPayloadTest") @Test(groups = "unit", testName = "BindToXMLPayloadTest")
public class BindToXMLPayloadTest { public class BindToXMLPayloadTest {
XMLParser xml = new JAXBParser(); XMLParser xml = new JAXBParser("true");
@Test @Test
public void testBindJAXBObject() throws SecurityException, NoSuchMethodException { public void testBindJAXBObject() throws SecurityException, NoSuchMethodException {

View File

@ -74,271 +74,329 @@ import com.google.common.collect.Iterables;
* *
* @author grkvlt@apache.org * @author grkvlt@apache.org
*/ */
public abstract class AbstractVAppClientLiveTest extends BaseVCloudDirectorClientLiveTest { public abstract class AbstractVAppClientLiveTest extends BaseVCloudDirectorClientLiveTest
{
public static final String VAPP = "vApp"; public static final String VAPP = "vApp";
public static final String VAPP_TEMPLATE = "vAppTemplate";
public static final String VDC = "vdc";
/* public static final String VAPP_TEMPLATE = "vAppTemplate";
* Convenience reference to API clients.
*/
protected CatalogClient catalogClient; public static final String VDC = "vdc";
protected QueryClient queryClient;
protected VAppClient vAppClient;
protected VAppTemplateClient vAppTemplateClient;
protected VdcClient vdcClient;
protected MetadataClient.Writeable metadataClient;
/* /*
* Objects shared between tests. * Convenience reference to API clients.
*/ */
protected Vdc vdc; protected CatalogClient catalogClient;
protected Vm vm;
protected URI vAppURI;
protected VApp vApp;
protected VAppTemplate vAppTemplate;
/** protected QueryClient queryClient;
* Retrieves the required clients from the REST API context
*
* @see BaseVCloudDirectorClientLiveTest#setupRequiredClients()
*/
@Override
@BeforeClass(alwaysRun = true, description = "Retrieves the required clients from the REST API context")
protected void setupRequiredClients() {
assertNotNull(context.getApi());
catalogClient = context.getApi().getCatalogClient(); protected VAppClient vAppClient;
queryClient = context.getApi().getQueryClient();
vAppClient = context.getApi().getVAppClient();
vAppTemplateClient = context.getApi().getVAppTemplateClient();
vdcClient = context.getApi().getVdcClient();
setupEnvironment(); protected VAppTemplateClient vAppTemplateClient;
}
/** protected VdcClient vdcClient;
* Sets up the environment.
*
* Retrieves the test {@link Vdc} and {@link VAppTemplate} from their configured {@link URI}s.
* Instantiates a new test VApp.
*/
protected void setupEnvironment() {
// Get the configured Vdc for the tests
vdc = vdcClient.getVdc(vdcURI);
assertNotNull(vdc, String.format(ENTITY_NON_NULL, VDC));
// Get the configured VAppTemplate for the tests protected MetadataClient.Writeable metadataClient;
vAppTemplate = vAppTemplateClient.getVAppTemplate(vAppTemplateURI);
assertNotNull(vAppTemplate, String.format(ENTITY_NON_NULL, VAPP_TEMPLATE));
// Instantiate a new VApp /*
VApp vAppInstantiated = instantiateVApp(); * Objects shared between tests.
assertNotNull(vAppInstantiated, String.format(ENTITY_NON_NULL, VAPP)); */
vAppURI = vAppInstantiated.getHref();
// Wait for the task to complete protected Vdc vdc;
Task instantiateTask = Iterables.getOnlyElement(vAppInstantiated.getTasks());
assertTrue(retryTaskSuccessLong.apply(instantiateTask), String.format(TASK_COMPLETE_TIMELY, "instantiateTask"));
// Get the instantiated VApp protected Vm vm;
vApp = vAppClient.getVApp(vAppURI);
// Get the Vm protected URI vAppURI;
List<Vm> vms = vApp.getChildren().getVms();
vm = Iterables.getOnlyElement(vms);
assertFalse(vms.isEmpty(), "The VApp must have a Vm");
}
protected void getGuestCustomizationSection(Function<URI, GuestCustomizationSection> getGuestCustomizationSection) { protected VApp vApp;
// Get URI for child VM
URI vmURI = Iterables.getOnlyElement(vApp.getChildren().getVms()).getHref();
// The method under test protected VAppTemplate vAppTemplate;
try {
GuestCustomizationSection section = getGuestCustomizationSection.apply(vmURI);
// Check the retrieved object is well formed /**
checkGuestCustomizationSection(section); * Retrieves the required clients from the REST API context
} catch (Exception e) { *
Throwables.propagate(e); * @see BaseVCloudDirectorClientLiveTest#setupRequiredClients()
} */
} @Override
@BeforeClass(alwaysRun = true, description = "Retrieves the required clients from the REST API context")
protected void setupRequiredClients()
{
assertNotNull(context.getApi());
protected void getNetworkConnectionSection(Function<URI, NetworkConnectionSection> getNetworkConnectionSection) { catalogClient = context.getApi().getCatalogClient();
// Get URI for child VM queryClient = context.getApi().getQueryClient();
URI vmURI = Iterables.getOnlyElement(vApp.getChildren().getVms()).getHref(); vAppClient = context.getApi().getVAppClient();
vAppTemplateClient = context.getApi().getVAppTemplateClient();
vdcClient = context.getApi().getVdcClient();
// The method under test setupEnvironment();
try { }
NetworkConnectionSection section = getNetworkConnectionSection.apply(vmURI);
// Check the retrieved object is well formed /**
checkNetworkConnectionSection(section); * Sets up the environment. Retrieves the test {@link Vdc} and {@link VAppTemplate} from their
} catch (Exception e) { * configured {@link URI}s. Instantiates a new test VApp.
Throwables.propagate(e); */
} protected void setupEnvironment()
} {
// Get the configured Vdc for the tests
vdc = vdcClient.getVdc(vdcURI);
assertNotNull(vdc, String.format(ENTITY_NON_NULL, VDC));
@AfterClass(alwaysRun = true, description = "Cleans up the environment by deleting created VApps") // Get the configured VAppTemplate for the tests
protected void cleanUp() { vAppTemplate = vAppTemplateClient.getVAppTemplate(vAppTemplateURI);
vdc = vdcClient.getVdc(vdcURI); // Refresh assertNotNull(vAppTemplate, String.format(ENTITY_NON_NULL, VAPP_TEMPLATE));
// Find references in the Vdc with the VApp type and in the list of instantiated VApp names
Iterable<Reference> vApps = Iterables.filter(
vdc.getResourceEntities(),
Predicates.and(
ReferencePredicates.<Reference>typeEquals(VCloudDirectorMediaType.VAPP),
ReferencePredicates.<Reference>nameIn(vAppNames)
)
);
// If we found any references, delete the VApp they point to // Instantiate a new VApp
if (!Iterables.isEmpty(vApps)) { VApp vAppInstantiated = instantiateVApp();
for (Reference ref : vApps) { assertNotNull(vAppInstantiated, String.format(ENTITY_NON_NULL, VAPP));
cleanUpVApp(ref.getHref()); // NOTE may fail, but should continue deleting vAppURI = vAppInstantiated.getHref();
}
} else {
logger.warn("No VApps in list found in Vdc %s (%s)", vdc.getName(), Iterables.toString(vAppNames));
}
}
protected static CimBoolean cimBoolean(boolean val) { // Wait for the task to complete
CimBoolean result = new CimBoolean(); Task instantiateTask = Iterables.getOnlyElement(vAppInstantiated.getTasks());
result.setValue(val); assertTrue(retryTaskSuccessLong.apply(instantiateTask),
return result; String.format(TASK_COMPLETE_TIMELY, "instantiateTask"));
}
protected static CimUnsignedInt cimUnsignedInt(long val) { // Get the instantiated VApp
CimUnsignedInt result = new CimUnsignedInt(); vApp = vAppClient.getVApp(vAppURI);
result.setValue(val);
return result;
}
protected static CimUnsignedLong cimUnsignedLong(BigInteger val) { // Get the Vm
CimUnsignedLong result = new CimUnsignedLong(); List<Vm> vms = vApp.getChildren().getVms();
result.setValue(val); vm = Iterables.getOnlyElement(vms);
return result; assertFalse(vms.isEmpty(), "The VApp must have a Vm");
} }
protected static CimString cimString(String value) { protected void getGuestCustomizationSection(
return new CimString(value); final Function<URI, GuestCustomizationSection> getGuestCustomizationSection)
} {
// Get URI for child VM
URI vmURI = Iterables.getOnlyElement(vApp.getChildren().getVms()).getHref();
protected void checkHasMatchingItem(final String context, final RasdItemsList items, final String instanceId, final String elementName) { // The method under test
Optional<ResourceAllocationSettingData> found = Iterables.tryFind(items.getItems(), new Predicate<ResourceAllocationSettingData>() { try
@Override {
public boolean apply(ResourceAllocationSettingData item) { GuestCustomizationSection section = getGuestCustomizationSection.apply(vmURI);
String itemInstanceId = item.getInstanceID();
if (itemInstanceId.equals(instanceId)) {
Assert.assertEquals(item.getElementName(), elementName,
String.format(OBJ_FIELD_EQ, VAPP, context + "/" + instanceId + "/elementName", elementName, item.getElementName()));
return true; // Check the retrieved object is well formed
checkGuestCustomizationSection(section);
}
catch (Exception e)
{
Throwables.propagate(e);
}
}
protected void getNetworkConnectionSection(
final Function<URI, NetworkConnectionSection> getNetworkConnectionSection)
{
// Get URI for child VM
URI vmURI = Iterables.getOnlyElement(vApp.getChildren().getVms()).getHref();
// The method under test
try
{
NetworkConnectionSection section = getNetworkConnectionSection.apply(vmURI);
// Check the retrieved object is well formed
checkNetworkConnectionSection(section);
}
catch (Exception e)
{
Throwables.propagate(e);
}
}
@AfterClass(alwaysRun = true, description = "Cleans up the environment by deleting created VApps")
protected void cleanUp()
{
vdc = vdcClient.getVdc(vdcURI); // Refresh
// Find references in the Vdc with the VApp type and in the list of instantiated VApp names
Iterable<Reference> vApps =
Iterables.filter(vdc.getResourceEntities(), Predicates.and(
ReferencePredicates.<Reference> typeEquals(VCloudDirectorMediaType.VAPP),
ReferencePredicates.<Reference> nameIn(vAppNames)));
// If we found any references, delete the VApp they point to
if (!Iterables.isEmpty(vApps))
{
for (Reference ref : vApps)
{
cleanUpVApp(ref.getHref()); // NOTE may fail, but should continue deleting
} }
return false; }
} else
}); {
assertTrue(found.isPresent(), "no " + context + " item found with id " + instanceId + "; only found " + items); logger.warn("No VApps in list found in Vdc %s (%s)", vdc.getName(),
} Iterables.toString(vAppNames));
}
}
/** protected static CimBoolean cimBoolean(final boolean val)
* Power on a {@link VApp}s {@link Vm}s. {
* CimBoolean result = new CimBoolean();
* @see #powerOn(URI) result.setValue(val);
*/ return result;
protected VApp powerOn(VApp testVApp) { }
return powerOn(testVApp.getHref());
}
/** protected static CimUnsignedInt cimUnsignedInt(final long val)
* Power on a VApp. {
*/ CimUnsignedInt result = new CimUnsignedInt();
protected VApp powerOn(URI testVAppURI) { result.setValue(val);
VApp testVApp = vAppClient.getVApp(testVAppURI); return result;
Vm vm = Iterables.getOnlyElement(testVApp.getChildren().getVms()); }
Status status = Status.fromValue(vm.getStatus());
if (status != Status.POWERED_ON) {
Task powerOn = vAppClient.powerOn(vm.getHref());
assertTaskSucceedsLong(powerOn);
}
assertVAppStatus(testVAppURI, Status.POWERED_ON);
return testVApp;
}
/** protected static CimUnsignedLong cimUnsignedLong(final BigInteger val)
* Power off a {@link VApp}s {@link Vm}s. {
* CimUnsignedLong result = new CimUnsignedLong();
* @see #powerOff(URI) result.setValue(val);
*/ return result;
protected VApp powerOff(VApp testVApp) { }
return powerOff(testVApp.getHref());
}
/** protected static CimString cimString(final String value)
* Power off a {@link VApp}s {@link Vm}s. {
*/ return new CimString(value);
protected VApp powerOff(URI testVAppURI) { }
VApp testVApp = vAppClient.getVApp(testVAppURI);
Vm vm = Iterables.getOnlyElement(testVApp.getChildren().getVms());
Status status = Status.fromValue(vm.getStatus());
if (status != Status.POWERED_OFF) {
Task powerOff = vAppClient.powerOff(vm.getHref());
assertTaskSucceedsLong(powerOff);
}
assertVAppStatus(testVAppURI, Status.POWERED_OFF);
return testVApp;
}
/** protected void checkHasMatchingItem(final String context, final RasdItemsList items,
* Suspend a {@link VApp}s {@link Vm}s. final String instanceId, final String elementName)
* {
* @see #suspend(URI) Optional<ResourceAllocationSettingData> found =
*/ Iterables.tryFind(items.getItems(), new Predicate<ResourceAllocationSettingData>()
protected VApp suspend(VApp testVApp) { {
return powerOff(testVApp.getHref()); @Override
} public boolean apply(final ResourceAllocationSettingData item)
{
String itemInstanceId = item.getInstanceID();
if (itemInstanceId.equals(instanceId))
{
Assert.assertEquals(
item.getElementName(),
elementName,
String.format(OBJ_FIELD_EQ, VAPP, context + "/" + instanceId
+ "/elementName", elementName, item.getElementName()));
/** return true;
* Suspend a {@link VApp}s {@link Vm}s. }
*/ return false;
protected VApp suspend(URI testVAppURI) { }
VApp testVApp = vAppClient.getVApp(testVAppURI); });
Vm vm = Iterables.getOnlyElement(testVApp.getChildren().getVms()); assertTrue(found.isPresent(), "no " + context + " item found with id " + instanceId
Status status = Status.fromValue(vm.getStatus()); + "; only found " + items);
if (status != Status.SUSPENDED) { }
Task suspend = vAppClient.suspend(vm.getHref());
assertTaskSucceedsLong(suspend);
}
assertVAppStatus(testVAppURI, Status.SUSPENDED);
return testVApp;
}
/** /**
* Check the {@link VApp}s {@link Vm}s current status. * Power on a {@link VApp}s {@link Vm}s.
*/ *
protected void assertVAppStatus(URI testVAppURI, Status status) { * @see #powerOn(URI)
VApp testVApp = vAppClient.getVApp(testVAppURI); */
Vm vm = Iterables.getOnlyElement(testVApp.getChildren().getVms()); protected VApp powerOn(final VApp testVApp)
assertEquals(vm.getStatus(), status.getValue(),String.format(OBJ_FIELD_EQ, VAPP, "status", status.toString(), Status.fromValue(vm.getStatus()).toString())); {
} return powerOn(testVApp.getHref());
}
/** /**
* Marshals a JAXB annotated object into XML. * Power on a VApp.
* */
* The XML is output using {@link org.jclouds.logging.Logger#debug(String)} protected VApp powerOn(final URI testVAppURI)
*/ {
protected void debug(Object object) { VApp testVApp = vAppClient.getVApp(testVAppURI);
JAXBParser parser = new JAXBParser(); Vm vm = Iterables.getOnlyElement(testVApp.getChildren().getVms());
try { Status status = Status.fromValue(vm.getStatus());
String xml = parser.toXML(object); if (status != Status.POWERED_ON)
logger.debug(Strings.padStart(Strings.padEnd(" " + object.getClass().toString() + " ", 70, '-'), 80, '-')); {
logger.debug(xml); Task powerOn = vAppClient.powerOn(vm.getHref());
logger.debug(Strings.repeat("-", 80)); assertTaskSucceedsLong(powerOn);
} catch (IOException ioe) { }
Throwables.propagate(ioe); assertVAppStatus(testVAppURI, Status.POWERED_ON);
} return testVApp;
} }
/**
* Power off a {@link VApp}s {@link Vm}s.
*
* @see #powerOff(URI)
*/
protected VApp powerOff(final VApp testVApp)
{
return powerOff(testVApp.getHref());
}
/**
* Power off a {@link VApp}s {@link Vm}s.
*/
protected VApp powerOff(final URI testVAppURI)
{
VApp testVApp = vAppClient.getVApp(testVAppURI);
Vm vm = Iterables.getOnlyElement(testVApp.getChildren().getVms());
Status status = Status.fromValue(vm.getStatus());
if (status != Status.POWERED_OFF)
{
Task powerOff = vAppClient.powerOff(vm.getHref());
assertTaskSucceedsLong(powerOff);
}
assertVAppStatus(testVAppURI, Status.POWERED_OFF);
return testVApp;
}
/**
* Suspend a {@link VApp}s {@link Vm}s.
*
* @see #suspend(URI)
*/
protected VApp suspend(final VApp testVApp)
{
return powerOff(testVApp.getHref());
}
/**
* Suspend a {@link VApp}s {@link Vm}s.
*/
protected VApp suspend(final URI testVAppURI)
{
VApp testVApp = vAppClient.getVApp(testVAppURI);
Vm vm = Iterables.getOnlyElement(testVApp.getChildren().getVms());
Status status = Status.fromValue(vm.getStatus());
if (status != Status.SUSPENDED)
{
Task suspend = vAppClient.suspend(vm.getHref());
assertTaskSucceedsLong(suspend);
}
assertVAppStatus(testVAppURI, Status.SUSPENDED);
return testVApp;
}
/**
* Check the {@link VApp}s {@link Vm}s current status.
*/
protected void assertVAppStatus(final URI testVAppURI, final Status status)
{
VApp testVApp = vAppClient.getVApp(testVAppURI);
Vm vm = Iterables.getOnlyElement(testVApp.getChildren().getVms());
assertEquals(
vm.getStatus(),
status.getValue(),
String.format(OBJ_FIELD_EQ, VAPP, "status", status.toString(),
Status.fromValue(vm.getStatus()).toString()));
}
/**
* Marshals a JAXB annotated object into XML. The XML is output using
* {@link org.jclouds.logging.Logger#debug(String)}
*/
protected void debug(final Object object)
{
JAXBParser parser = new JAXBParser("true");
try
{
String xml = parser.toXML(object);
logger.debug(Strings.padStart(
Strings.padEnd(" " + object.getClass().toString() + " ", 70, '-'), 80, '-'));
logger.debug(xml);
logger.debug(Strings.repeat("-", 80));
}
catch (IOException ioe)
{
Throwables.propagate(ioe);
}
}
} }

View File

@ -45,77 +45,93 @@ import com.google.common.collect.Iterables;
* *
* @author danikov * @author danikov
*/ */
@Test(groups = { "live", "user", "nonClient" }, singleThreaded = true, testName = "NonClientOperationsLiveTest") @Test(groups = {"live", "user", "nonClient"}, singleThreaded = true, testName = "NonClientOperationsLiveTest")
public class NonClientOperationsLiveTest extends BaseVCloudDirectorClientLiveTest { public class NonClientOperationsLiveTest extends BaseVCloudDirectorClientLiveTest
{
private JAXBParser parser = new JAXBParser(); private JAXBParser parser = new JAXBParser("true");
private SessionWithToken sessionWithToken;
@Override private SessionWithToken sessionWithToken;
protected void setupRequiredClients() throws Exception {
setupCredentials();
}
@Test(testName = "POST /login") @Override
public void testPostLogin() throws IOException { protected void setupRequiredClients() throws Exception
testLoginWithMethod("POST"); {
} setupCredentials();
}
@Test(testName = "GET /login") @Test(testName = "POST /login")
public void testGetLogin() throws IOException { public void testPostLogin() throws IOException
testLoginWithMethod("GET"); {
} testLoginWithMethod("POST");
}
private void testLoginWithMethod(String method) throws IOException { @Test(testName = "GET /login")
String user = identity.substring(0, identity.lastIndexOf('@')); public void testGetLogin() throws IOException
String org = identity.substring(identity.lastIndexOf('@') + 1); {
String password = credential; testLoginWithMethod("GET");
}
String authHeader = "Basic " + CryptoStreams.base64(String.format("%s@%s:%s", private void testLoginWithMethod(final String method) throws IOException
checkNotNull(user), {
checkNotNull(org), String user = identity.substring(0, identity.lastIndexOf('@'));
checkNotNull(password)).getBytes("UTF-8")); String org = identity.substring(identity.lastIndexOf('@') + 1);
String password = credential;
HttpResponse response = context.getUtils().getHttpClient().invoke(HttpRequest.builder() String authHeader =
.method(method) "Basic "
.endpoint(URI.create(endpoint+"/login")) + CryptoStreams.base64(String.format("%s@%s:%s", checkNotNull(user),
.headers(ImmutableMultimap.of( checkNotNull(org), checkNotNull(password)).getBytes("UTF-8"));
"Authorization", authHeader,
"Accept", "*/*"))
.build());
sessionWithToken = SessionWithToken.builder() HttpResponse response =
.session(session) context
.token(response.getFirstHeaderOrNull("x-vcloud-authorization")) .getUtils()
.build(); .getHttpClient()
.invoke(
HttpRequest
.builder()
.method(method)
.endpoint(URI.create(endpoint + "/login"))
.headers(ImmutableMultimap.of("Authorization", authHeader, "Accept", "*/*"))
.build());
assertEquals(sessionWithToken.getSession().getUser(), user); sessionWithToken =
assertEquals(sessionWithToken.getSession().getOrg(), org); SessionWithToken.builder().session(session)
assertTrue(sessionWithToken.getSession().getLinks().size() > 0); .token(response.getFirstHeaderOrNull("x-vcloud-authorization")).build();
assertNotNull(sessionWithToken.getToken());
OrgList orgList = parser.fromXML( assertEquals(sessionWithToken.getSession().getUser(), user);
Strings2.toStringAndClose(response.getPayload().getInput()), OrgList.class); assertEquals(sessionWithToken.getSession().getOrg(), org);
assertTrue(sessionWithToken.getSession().getLinks().size() > 0);
assertNotNull(sessionWithToken.getToken());
assertTrue(orgList.getOrgs().size() > 0, "must have orgs"); OrgList orgList =
parser.fromXML(Strings2.toStringAndClose(response.getPayload().getInput()),
OrgList.class);
context.getApi().getOrgClient().getOrg(Iterables.getLast(orgList.getOrgs()).getHref()); assertTrue(orgList.getOrgs().size() > 0, "must have orgs");
}
@Test(testName = "GET /schema/{schemaFileName}", context.getApi().getOrgClient().getOrg(Iterables.getLast(orgList.getOrgs()).getHref());
dependsOnMethods = {"testPostLogin", "testGetLogin"} ) }
public void testGetSchema() throws IOException {
String schemafileName = "master.xsd";
HttpResponse response = context.getUtils().getHttpClient().invoke(HttpRequest.builder()
.method("GET")
.endpoint(URI.create(endpoint+"/v1.5/schema/"+schemafileName))
.headers(ImmutableMultimap.of(
"x-vcloud-authorization", sessionWithToken.getToken(),
"Accept", "*/*"))
.build());
String schema = Strings2.toStringAndClose(response.getPayload().getInput()); @Test(testName = "GET /schema/{schemaFileName}", dependsOnMethods = {"testPostLogin",
"testGetLogin"})
public void testGetSchema() throws IOException
{
String schemafileName = "master.xsd";
HttpResponse response =
context
.getUtils()
.getHttpClient()
.invoke(
HttpRequest
.builder()
.method("GET")
.endpoint(URI.create(endpoint + "/v1.5/schema/" + schemafileName))
.headers(
ImmutableMultimap.of("x-vcloud-authorization",
sessionWithToken.getToken(), "Accept", "*/*")).build());
// TODO: asserting something about the schema String schema = Strings2.toStringAndClose(response.getPayload().getInput());
}
// TODO: asserting something about the schema
}
} }