Merge pull request #552 from nacx/configurable-prettyprint

Pretty print in payload is now configurable
This commit is contained in:
Adrian Cole 2012-04-10 08:47:23 -07:00
commit 54184914c5
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.ssh.SshClient;
import org.jclouds.ssh.SshClient.Factory;
import org.jclouds.xml.XMLParser;
import com.google.common.base.Function;
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;
@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,
@Named(Constants.PROPERTY_IO_WORKER_THREADS) ExecutorService ioThreads, EventBus eventBus,
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);
this.sshForNode = sshForNode;
}

View File

@ -259,5 +259,12 @@ public interface Constants {
* </code>
*/
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_TRUST_ALL_CERTS;
import static org.jclouds.Constants.PROPERTY_USER_THREADS;
import static org.jclouds.Constants.PROPERTY_PRETTY_PRINT_PAYLOADS;
import java.util.Properties;
@ -204,6 +205,14 @@ public class PropertiesBuilder {
properties.setProperty(PROPERTY_MAX_CONNECTIONS_PER_HOST, Integer.toString(connectionLimit));
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;
@ -226,6 +235,7 @@ public class PropertiesBuilder {
props.setProperty(PROPERTY_MAX_CONNECTION_REUSE, 75 + "");
props.setProperty(PROPERTY_MAX_SESSION_FAILURES, 2 + "");
props.setProperty(PROPERTY_SESSION_INTERVAL, 60 + "");
props.setProperty(PROPERTY_PRETTY_PRINT_PAYLOADS, "true");
return props;
}

View File

@ -25,6 +25,7 @@ import org.jclouds.date.DateService;
import org.jclouds.json.Json;
import org.jclouds.logging.Logger.LoggerFactory;
import org.jclouds.rest.internal.UtilsImpl;
import org.jclouds.xml.XMLParser;
import com.google.common.annotations.Beta;
import com.google.common.eventbus.EventBus;
@ -110,5 +111,12 @@ public interface Utils {
*/
@Beta
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.HttpClient;
import org.jclouds.rest.Utils;
import org.jclouds.xml.XMLParser;
import com.google.common.annotations.Beta;
import com.google.common.eventbus.EventBus;
@ -53,9 +54,10 @@ public class UtilsImpl implements Utils {
private final EventBus eventBus;
private final LoggerFactory loggerFactory;
private Injector injector;
private XMLParser xml;
@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,
@Named(Constants.PROPERTY_IO_WORKER_THREADS) ExecutorService ioThreads, EventBus eventBus,
LoggerFactory loggerFactory) {
@ -69,6 +71,7 @@ public class UtilsImpl implements Utils {
this.ioExecutor = ioThreads;
this.eventBus = eventBus;
this.loggerFactory = loggerFactory;
this.xml = xml;
}
@Override
@ -172,5 +175,15 @@ public class UtilsImpl implements Utils {
public Injector injector() {
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.StringWriter;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import org.jclouds.Constants;
import org.jclouds.http.functions.ParseXMLWithJAXB;
import org.jclouds.xml.XMLParser;
import com.google.inject.name.Named;
/**
* Parses XML documents using JAXB.
*
@ -39,6 +43,16 @@ import org.jclouds.xml.XMLParser;
*/
@Singleton
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
public String toXML(final Object src) throws IOException {
return toXML(src, src.getClass());
@ -49,7 +63,7 @@ public class JAXBParser implements XMLParser {
try {
JAXBContext context = JAXBContext.newInstance(type);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, prettyPrint);
StringWriter writer = new StringWriter();
marshaller.marshal(src, writer);
return writer.toString();
@ -58,6 +72,7 @@ public class JAXBParser implements XMLParser {
}
}
@SuppressWarnings("unchecked")
@Override
public <T> T fromXML(final String xml, final Class<T> type) throws IOException {
try {

View File

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

View File

@ -74,271 +74,329 @@ import com.google.common.collect.Iterables;
*
* @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_TEMPLATE = "vAppTemplate";
public static final String VDC = "vdc";
public static final String VAPP = "vApp";
/*
* Convenience reference to API clients.
*/
public static final String VAPP_TEMPLATE = "vAppTemplate";
protected CatalogClient catalogClient;
protected QueryClient queryClient;
protected VAppClient vAppClient;
protected VAppTemplateClient vAppTemplateClient;
protected VdcClient vdcClient;
protected MetadataClient.Writeable metadataClient;
public static final String VDC = "vdc";
/*
* Objects shared between tests.
*/
/*
* Convenience reference to API clients.
*/
protected Vdc vdc;
protected Vm vm;
protected URI vAppURI;
protected VApp vApp;
protected VAppTemplate vAppTemplate;
protected CatalogClient catalogClient;
/**
* 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());
protected QueryClient queryClient;
catalogClient = context.getApi().getCatalogClient();
queryClient = context.getApi().getQueryClient();
vAppClient = context.getApi().getVAppClient();
vAppTemplateClient = context.getApi().getVAppTemplateClient();
vdcClient = context.getApi().getVdcClient();
setupEnvironment();
}
protected VAppClient vAppClient;
/**
* 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));
protected VAppTemplateClient vAppTemplateClient;
// Get the configured VAppTemplate for the tests
vAppTemplate = vAppTemplateClient.getVAppTemplate(vAppTemplateURI);
assertNotNull(vAppTemplate, String.format(ENTITY_NON_NULL, VAPP_TEMPLATE));
protected VdcClient vdcClient;
// Instantiate a new VApp
VApp vAppInstantiated = instantiateVApp();
assertNotNull(vAppInstantiated, String.format(ENTITY_NON_NULL, VAPP));
vAppURI = vAppInstantiated.getHref();
protected MetadataClient.Writeable metadataClient;
// Wait for the task to complete
Task instantiateTask = Iterables.getOnlyElement(vAppInstantiated.getTasks());
assertTrue(retryTaskSuccessLong.apply(instantiateTask), String.format(TASK_COMPLETE_TIMELY, "instantiateTask"));
/*
* Objects shared between tests.
*/
// Get the instantiated VApp
vApp = vAppClient.getVApp(vAppURI);
protected Vdc vdc;
// Get the Vm
List<Vm> vms = vApp.getChildren().getVms();
vm = Iterables.getOnlyElement(vms);
assertFalse(vms.isEmpty(), "The VApp must have a Vm");
}
protected Vm vm;
protected void getGuestCustomizationSection(Function<URI, GuestCustomizationSection> getGuestCustomizationSection) {
// Get URI for child VM
URI vmURI = Iterables.getOnlyElement(vApp.getChildren().getVms()).getHref();
protected URI vAppURI;
// The method under test
try {
GuestCustomizationSection section = getGuestCustomizationSection.apply(vmURI);
protected VApp vApp;
// Check the retrieved object is well formed
checkGuestCustomizationSection(section);
} catch (Exception e) {
Throwables.propagate(e);
}
}
protected VAppTemplate vAppTemplate;
protected void getNetworkConnectionSection(Function<URI, NetworkConnectionSection> getNetworkConnectionSection) {
// Get URI for child VM
URI vmURI = Iterables.getOnlyElement(vApp.getChildren().getVms()).getHref();
/**
* 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());
// The method under test
try {
NetworkConnectionSection section = getNetworkConnectionSection.apply(vmURI);
catalogClient = context.getApi().getCatalogClient();
queryClient = context.getApi().getQueryClient();
vAppClient = context.getApi().getVAppClient();
vAppTemplateClient = context.getApi().getVAppTemplateClient();
vdcClient = context.getApi().getVdcClient();
// Check the retrieved object is well formed
checkNetworkConnectionSection(section);
} catch (Exception e) {
Throwables.propagate(e);
}
}
setupEnvironment();
}
@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)
)
);
/**
* 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));
// 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
}
} else {
logger.warn("No VApps in list found in Vdc %s (%s)", vdc.getName(), Iterables.toString(vAppNames));
}
}
// Get the configured VAppTemplate for the tests
vAppTemplate = vAppTemplateClient.getVAppTemplate(vAppTemplateURI);
assertNotNull(vAppTemplate, String.format(ENTITY_NON_NULL, VAPP_TEMPLATE));
protected static CimBoolean cimBoolean(boolean val) {
CimBoolean result = new CimBoolean();
result.setValue(val);
return result;
}
// Instantiate a new VApp
VApp vAppInstantiated = instantiateVApp();
assertNotNull(vAppInstantiated, String.format(ENTITY_NON_NULL, VAPP));
vAppURI = vAppInstantiated.getHref();
protected static CimUnsignedInt cimUnsignedInt(long val) {
CimUnsignedInt result = new CimUnsignedInt();
result.setValue(val);
return result;
}
// Wait for the task to complete
Task instantiateTask = Iterables.getOnlyElement(vAppInstantiated.getTasks());
assertTrue(retryTaskSuccessLong.apply(instantiateTask),
String.format(TASK_COMPLETE_TIMELY, "instantiateTask"));
protected static CimUnsignedLong cimUnsignedLong(BigInteger val) {
CimUnsignedLong result = new CimUnsignedLong();
result.setValue(val);
return result;
}
// Get the instantiated VApp
vApp = vAppClient.getVApp(vAppURI);
protected static CimString cimString(String value) {
return new CimString(value);
}
// Get the Vm
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) {
Optional<ResourceAllocationSettingData> found = Iterables.tryFind(items.getItems(), new Predicate<ResourceAllocationSettingData>() {
@Override
public boolean apply(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()));
protected void getGuestCustomizationSection(
final Function<URI, GuestCustomizationSection> getGuestCustomizationSection)
{
// Get URI for child VM
URI vmURI = Iterables.getOnlyElement(vApp.getChildren().getVms()).getHref();
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;
}
});
assertTrue(found.isPresent(), "no " + context + " item found with id " + instanceId + "; only found " + items);
}
}
else
{
logger.warn("No VApps in list found in Vdc %s (%s)", vdc.getName(),
Iterables.toString(vAppNames));
}
}
/**
* Power on a {@link VApp}s {@link Vm}s.
*
* @see #powerOn(URI)
*/
protected VApp powerOn(VApp testVApp) {
return powerOn(testVApp.getHref());
}
protected static CimBoolean cimBoolean(final boolean val)
{
CimBoolean result = new CimBoolean();
result.setValue(val);
return result;
}
/**
* Power on a VApp.
*/
protected VApp powerOn(URI testVAppURI) {
VApp testVApp = vAppClient.getVApp(testVAppURI);
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 CimUnsignedInt cimUnsignedInt(final long val)
{
CimUnsignedInt result = new CimUnsignedInt();
result.setValue(val);
return result;
}
/**
* Power off a {@link VApp}s {@link Vm}s.
*
* @see #powerOff(URI)
*/
protected VApp powerOff(VApp testVApp) {
return powerOff(testVApp.getHref());
}
protected static CimUnsignedLong cimUnsignedLong(final BigInteger val)
{
CimUnsignedLong result = new CimUnsignedLong();
result.setValue(val);
return result;
}
/**
* Power off a {@link VApp}s {@link Vm}s.
*/
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 static CimString cimString(final String value)
{
return new CimString(value);
}
/**
* Suspend a {@link VApp}s {@link Vm}s.
*
* @see #suspend(URI)
*/
protected VApp suspend(VApp testVApp) {
return powerOff(testVApp.getHref());
}
protected void checkHasMatchingItem(final String context, final RasdItemsList items,
final String instanceId, final String elementName)
{
Optional<ResourceAllocationSettingData> found =
Iterables.tryFind(items.getItems(), new Predicate<ResourceAllocationSettingData>()
{
@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()));
/**
* Suspend a {@link VApp}s {@link Vm}s.
*/
protected VApp suspend(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;
}
return true;
}
return false;
}
});
assertTrue(found.isPresent(), "no " + context + " item found with id " + instanceId
+ "; only found " + items);
}
/**
* Check the {@link VApp}s {@link Vm}s current status.
*/
protected void assertVAppStatus(URI testVAppURI, 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()));
}
/**
* Power on a {@link VApp}s {@link Vm}s.
*
* @see #powerOn(URI)
*/
protected VApp powerOn(final VApp testVApp)
{
return powerOn(testVApp.getHref());
}
/**
* Marshals a JAXB annotated object into XML.
*
* The XML is output using {@link org.jclouds.logging.Logger#debug(String)}
*/
protected void debug(Object object) {
JAXBParser parser = new JAXBParser();
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);
}
}
/**
* Power on a VApp.
*/
protected VApp powerOn(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_ON)
{
Task powerOn = vAppClient.powerOn(vm.getHref());
assertTaskSucceedsLong(powerOn);
}
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
*/
@Test(groups = { "live", "user", "nonClient" }, singleThreaded = true, testName = "NonClientOperationsLiveTest")
public class NonClientOperationsLiveTest extends BaseVCloudDirectorClientLiveTest {
private JAXBParser parser = new JAXBParser();
private SessionWithToken sessionWithToken;
@Test(groups = {"live", "user", "nonClient"}, singleThreaded = true, testName = "NonClientOperationsLiveTest")
public class NonClientOperationsLiveTest extends BaseVCloudDirectorClientLiveTest
{
@Override
protected void setupRequiredClients() throws Exception {
setupCredentials();
}
@Test(testName = "POST /login")
public void testPostLogin() throws IOException {
testLoginWithMethod("POST");
}
@Test(testName = "GET /login")
public void testGetLogin() throws IOException {
testLoginWithMethod("GET");
}
private void testLoginWithMethod(String method) throws IOException {
String user = identity.substring(0, identity.lastIndexOf('@'));
String org = identity.substring(identity.lastIndexOf('@') + 1);
String password = credential;
String authHeader = "Basic " + CryptoStreams.base64(String.format("%s@%s:%s",
checkNotNull(user),
checkNotNull(org),
checkNotNull(password)).getBytes("UTF-8"));
HttpResponse response = context.getUtils().getHttpClient().invoke(HttpRequest.builder()
.method(method)
.endpoint(URI.create(endpoint+"/login"))
.headers(ImmutableMultimap.of(
"Authorization", authHeader,
"Accept", "*/*"))
.build());
sessionWithToken = SessionWithToken.builder()
.session(session)
.token(response.getFirstHeaderOrNull("x-vcloud-authorization"))
.build();
assertEquals(sessionWithToken.getSession().getUser(), user);
assertEquals(sessionWithToken.getSession().getOrg(), org);
assertTrue(sessionWithToken.getSession().getLinks().size() > 0);
assertNotNull(sessionWithToken.getToken());
OrgList orgList = parser.fromXML(
Strings2.toStringAndClose(response.getPayload().getInput()), OrgList.class);
assertTrue(orgList.getOrgs().size() > 0, "must have orgs");
context.getApi().getOrgClient().getOrg(Iterables.getLast(orgList.getOrgs()).getHref());
}
@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());
String schema = Strings2.toStringAndClose(response.getPayload().getInput());
// TODO: asserting something about the schema
}
private JAXBParser parser = new JAXBParser("true");
private SessionWithToken sessionWithToken;
@Override
protected void setupRequiredClients() throws Exception
{
setupCredentials();
}
@Test(testName = "POST /login")
public void testPostLogin() throws IOException
{
testLoginWithMethod("POST");
}
@Test(testName = "GET /login")
public void testGetLogin() throws IOException
{
testLoginWithMethod("GET");
}
private void testLoginWithMethod(final String method) throws IOException
{
String user = identity.substring(0, identity.lastIndexOf('@'));
String org = identity.substring(identity.lastIndexOf('@') + 1);
String password = credential;
String authHeader =
"Basic "
+ CryptoStreams.base64(String.format("%s@%s:%s", checkNotNull(user),
checkNotNull(org), checkNotNull(password)).getBytes("UTF-8"));
HttpResponse response =
context
.getUtils()
.getHttpClient()
.invoke(
HttpRequest
.builder()
.method(method)
.endpoint(URI.create(endpoint + "/login"))
.headers(ImmutableMultimap.of("Authorization", authHeader, "Accept", "*/*"))
.build());
sessionWithToken =
SessionWithToken.builder().session(session)
.token(response.getFirstHeaderOrNull("x-vcloud-authorization")).build();
assertEquals(sessionWithToken.getSession().getUser(), user);
assertEquals(sessionWithToken.getSession().getOrg(), org);
assertTrue(sessionWithToken.getSession().getLinks().size() > 0);
assertNotNull(sessionWithToken.getToken());
OrgList orgList =
parser.fromXML(Strings2.toStringAndClose(response.getPayload().getInput()),
OrgList.class);
assertTrue(orgList.getOrgs().size() > 0, "must have orgs");
context.getApi().getOrgClient().getOrg(Iterables.getLast(orgList.getOrgs()).getHref());
}
@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());
String schema = Strings2.toStringAndClose(response.getPayload().getInput());
// TODO: asserting something about the schema
}
}