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

@ -259,5 +259,12 @@ public interface Constants {
* </code> * </code>
*/ */
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;
@ -204,6 +205,14 @@ public class PropertiesBuilder {
properties.setProperty(PROPERTY_MAX_CONNECTIONS_PER_HOST, Integer.toString(connectionLimit)); properties.setProperty(PROPERTY_MAX_CONNECTIONS_PER_HOST, Integer.toString(connectionLimit));
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;
@ -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;
@ -110,5 +111,12 @@ 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
@ -172,5 +175,15 @@ public class UtilsImpl implements Utils {
public Injector injector() { public Injector injector() {
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;
* 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 VdcClient vdcClient;
vAppTemplate = vAppTemplateClient.getVAppTemplate(vAppTemplateURI);
assertNotNull(vAppTemplate, String.format(ENTITY_NON_NULL, VAPP_TEMPLATE));
// Instantiate a new VApp protected MetadataClient.Writeable metadataClient;
VApp vAppInstantiated = instantiateVApp();
assertNotNull(vAppInstantiated, String.format(ENTITY_NON_NULL, VAPP));
vAppURI = vAppInstantiated.getHref();
// Wait for the task to complete /*
Task instantiateTask = Iterables.getOnlyElement(vAppInstantiated.getTasks()); * Objects shared between tests.
assertTrue(retryTaskSuccessLong.apply(instantiateTask), String.format(TASK_COMPLETE_TIMELY, "instantiateTask")); */
// Get the instantiated VApp protected Vdc vdc;
vApp = vAppClient.getVApp(vAppURI);
// Get the Vm protected Vm vm;
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 URI vAppURI;
// Get URI for child VM
URI vmURI = Iterables.getOnlyElement(vApp.getChildren().getVms()).getHref();
// The method under test protected VApp vApp;
try {
GuestCustomizationSection section = getGuestCustomizationSection.apply(vmURI);
// Check the retrieved object is well formed protected VAppTemplate vAppTemplate;
checkGuestCustomizationSection(section);
} catch (Exception e) {
Throwables.propagate(e);
}
}
protected void getNetworkConnectionSection(Function<URI, NetworkConnectionSection> getNetworkConnectionSection) { /**
// Get URI for child VM * Retrieves the required clients from the REST API context
URI vmURI = Iterables.getOnlyElement(vApp.getChildren().getVms()).getHref(); *
* @see BaseVCloudDirectorClientLiveTest#setupRequiredClients()
*/
@Override
@BeforeClass(alwaysRun = true, description = "Retrieves the required clients from the REST API context")
protected void setupRequiredClients()
{
assertNotNull(context.getApi());
// The method under test catalogClient = context.getApi().getCatalogClient();
try { queryClient = context.getApi().getQueryClient();
NetworkConnectionSection section = getNetworkConnectionSection.apply(vmURI); vAppClient = context.getApi().getVAppClient();
vAppTemplateClient = context.getApi().getVAppTemplateClient();
vdcClient = context.getApi().getVdcClient();
// Check the retrieved object is well formed setupEnvironment();
checkNetworkConnectionSection(section); }
} catch (Exception e) {
Throwables.propagate(e);
}
}
@AfterClass(alwaysRun = true, description = "Cleans up the environment by deleting created VApps") /**
protected void cleanUp() { * Sets up the environment. Retrieves the test {@link Vdc} and {@link VAppTemplate} from their
vdc = vdcClient.getVdc(vdcURI); // Refresh * configured {@link URI}s. Instantiates a new test VApp.
// Find references in the Vdc with the VApp type and in the list of instantiated VApp names */
Iterable<Reference> vApps = Iterables.filter( protected void setupEnvironment()
vdc.getResourceEntities(), {
Predicates.and( // Get the configured Vdc for the tests
ReferencePredicates.<Reference>typeEquals(VCloudDirectorMediaType.VAPP), vdc = vdcClient.getVdc(vdcURI);
ReferencePredicates.<Reference>nameIn(vAppNames) assertNotNull(vdc, String.format(ENTITY_NON_NULL, VDC));
)
);
// If we found any references, delete the VApp they point to // Get the configured VAppTemplate for the tests
if (!Iterables.isEmpty(vApps)) { vAppTemplate = vAppTemplateClient.getVAppTemplate(vAppTemplateURI);
for (Reference ref : vApps) { assertNotNull(vAppTemplate, String.format(ENTITY_NON_NULL, VAPP_TEMPLATE));
cleanUpVApp(ref.getHref()); // NOTE may fail, but should continue deleting
}
} else {
logger.warn("No VApps in list found in Vdc %s (%s)", vdc.getName(), Iterables.toString(vAppNames));
}
}
protected static CimBoolean cimBoolean(boolean val) { // Instantiate a new VApp
CimBoolean result = new CimBoolean(); VApp vAppInstantiated = instantiateVApp();
result.setValue(val); assertNotNull(vAppInstantiated, String.format(ENTITY_NON_NULL, VAPP));
return result; vAppURI = vAppInstantiated.getHref();
}
protected static CimUnsignedInt cimUnsignedInt(long val) { // Wait for the task to complete
CimUnsignedInt result = new CimUnsignedInt(); Task instantiateTask = Iterables.getOnlyElement(vAppInstantiated.getTasks());
result.setValue(val); assertTrue(retryTaskSuccessLong.apply(instantiateTask),
return result; String.format(TASK_COMPLETE_TIMELY, "instantiateTask"));
}
protected static CimUnsignedLong cimUnsignedLong(BigInteger val) { // Get the instantiated VApp
CimUnsignedLong result = new CimUnsignedLong(); vApp = vAppClient.getVApp(vAppURI);
result.setValue(val);
return result;
}
protected static CimString cimString(String value) { // Get the Vm
return new CimString(value); List<Vm> vms = vApp.getChildren().getVms();
} vm = Iterables.getOnlyElement(vms);
assertFalse(vms.isEmpty(), "The VApp must have a Vm");
}
protected void checkHasMatchingItem(final String context, final RasdItemsList items, final String instanceId, final String elementName) { protected void getGuestCustomizationSection(
Optional<ResourceAllocationSettingData> found = Iterables.tryFind(items.getItems(), new Predicate<ResourceAllocationSettingData>() { final Function<URI, GuestCustomizationSection> getGuestCustomizationSection)
@Override {
public boolean apply(ResourceAllocationSettingData item) { // Get URI for child VM
String itemInstanceId = item.getInstanceID(); URI vmURI = Iterables.getOnlyElement(vApp.getChildren().getVms()).getHref();
if (itemInstanceId.equals(instanceId)) {
Assert.assertEquals(item.getElementName(), elementName,
String.format(OBJ_FIELD_EQ, VAPP, context + "/" + instanceId + "/elementName", elementName, item.getElementName()));
return true; // The method under test
try
{
GuestCustomizationSection section = getGuestCustomizationSection.apply(vmURI);
// 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 SessionWithToken sessionWithToken;
@Override private JAXBParser parser = new JAXBParser("true");
protected void setupRequiredClients() throws Exception {
setupCredentials(); private SessionWithToken sessionWithToken;
}
@Override
@Test(testName = "POST /login") protected void setupRequiredClients() throws Exception
public void testPostLogin() throws IOException { {
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 {
String user = identity.substring(0, identity.lastIndexOf('@')); @Test(testName = "GET /login")
String org = identity.substring(identity.lastIndexOf('@') + 1); public void testGetLogin() throws IOException
String password = credential; {
testLoginWithMethod("GET");
String authHeader = "Basic " + CryptoStreams.base64(String.format("%s@%s:%s", }
checkNotNull(user),
checkNotNull(org), private void testLoginWithMethod(final String method) throws IOException
checkNotNull(password)).getBytes("UTF-8")); {
String user = identity.substring(0, identity.lastIndexOf('@'));
HttpResponse response = context.getUtils().getHttpClient().invoke(HttpRequest.builder() String org = identity.substring(identity.lastIndexOf('@') + 1);
.method(method) String password = credential;
.endpoint(URI.create(endpoint+"/login"))
.headers(ImmutableMultimap.of( String authHeader =
"Authorization", authHeader, "Basic "
"Accept", "*/*")) + CryptoStreams.base64(String.format("%s@%s:%s", checkNotNull(user),
.build()); checkNotNull(org), checkNotNull(password)).getBytes("UTF-8"));
sessionWithToken = SessionWithToken.builder() HttpResponse response =
.session(session) context
.token(response.getFirstHeaderOrNull("x-vcloud-authorization")) .getUtils()
.build(); .getHttpClient()
.invoke(
assertEquals(sessionWithToken.getSession().getUser(), user); HttpRequest
assertEquals(sessionWithToken.getSession().getOrg(), org); .builder()
assertTrue(sessionWithToken.getSession().getLinks().size() > 0); .method(method)
assertNotNull(sessionWithToken.getToken()); .endpoint(URI.create(endpoint + "/login"))
.headers(ImmutableMultimap.of("Authorization", authHeader, "Accept", "*/*"))
OrgList orgList = parser.fromXML( .build());
Strings2.toStringAndClose(response.getPayload().getInput()), OrgList.class);
sessionWithToken =
assertTrue(orgList.getOrgs().size() > 0, "must have orgs"); SessionWithToken.builder().session(session)
.token(response.getFirstHeaderOrNull("x-vcloud-authorization")).build();
context.getApi().getOrgClient().getOrg(Iterables.getLast(orgList.getOrgs()).getHref());
} assertEquals(sessionWithToken.getSession().getUser(), user);
assertEquals(sessionWithToken.getSession().getOrg(), org);
@Test(testName = "GET /schema/{schemaFileName}", assertTrue(sessionWithToken.getSession().getLinks().size() > 0);
dependsOnMethods = {"testPostLogin", "testGetLogin"} ) assertNotNull(sessionWithToken.getToken());
public void testGetSchema() throws IOException {
String schemafileName = "master.xsd"; OrgList orgList =
HttpResponse response = context.getUtils().getHttpClient().invoke(HttpRequest.builder() parser.fromXML(Strings2.toStringAndClose(response.getPayload().getInput()),
.method("GET") OrgList.class);
.endpoint(URI.create(endpoint+"/v1.5/schema/"+schemafileName))
.headers(ImmutableMultimap.of( assertTrue(orgList.getOrgs().size() > 0, "must have orgs");
"x-vcloud-authorization", sessionWithToken.getToken(),
"Accept", "*/*")) context.getApi().getOrgClient().getOrg(Iterables.getLast(orgList.getOrgs()).getHref());
.build()); }
String schema = Strings2.toStringAndClose(response.getPayload().getInput()); @Test(testName = "GET /schema/{schemaFileName}", dependsOnMethods = {"testPostLogin",
"testGetLogin"})
// TODO: asserting something about the schema 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());
// TODO: asserting something about the schema
}
} }