cleanup, added test for org without vdc

This commit is contained in:
Kedar Dave 2011-03-23 23:43:30 -05:00
commit 07d5863108
71 changed files with 3228 additions and 849 deletions

View File

@ -42,8 +42,8 @@ import javax.ws.rs.Path;
import javax.ws.rs.Produces; import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import org.jclouds.ovf.OvfEnvelope; import org.jclouds.ovf.Envelope;
import org.jclouds.ovf.xml.OvfEnvelopeHandler; import org.jclouds.ovf.xml.EnvelopeHandler;
import org.jclouds.predicates.validators.DnsNameValidator; import org.jclouds.predicates.validators.DnsNameValidator;
import org.jclouds.rest.annotations.BinderParam; import org.jclouds.rest.annotations.BinderParam;
import org.jclouds.rest.annotations.Endpoint; import org.jclouds.rest.annotations.Endpoint;
@ -131,9 +131,9 @@ public interface VCloudAsyncClient extends CommonVCloudAsyncClient {
@GET @GET
@Consumes(MediaType.TEXT_XML) @Consumes(MediaType.TEXT_XML)
@Path("/ovf") @Path("/ovf")
@XMLResponseParser(OvfEnvelopeHandler.class) @XMLResponseParser(EnvelopeHandler.class)
@ExceptionParser(ReturnNullOnNotFoundOr404.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class)
ListenableFuture<? extends OvfEnvelope> getOvfEnvelopeForVAppTemplate(@EndpointParam URI vAppTemplate); ListenableFuture<? extends Envelope> getOvfEnvelopeForVAppTemplate(@EndpointParam URI vAppTemplate);
/** /**
* @see VCloudClient#findVAppTemplateInOrgCatalogNamed * @see VCloudClient#findVAppTemplateInOrgCatalogNamed

View File

@ -28,7 +28,7 @@ import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import org.jclouds.concurrent.Timeout; import org.jclouds.concurrent.Timeout;
import org.jclouds.ovf.OvfEnvelope; import org.jclouds.ovf.Envelope;
import org.jclouds.vcloud.domain.GuestCustomizationSection; import org.jclouds.vcloud.domain.GuestCustomizationSection;
import org.jclouds.vcloud.domain.NetworkConnectionSection; import org.jclouds.vcloud.domain.NetworkConnectionSection;
import org.jclouds.vcloud.domain.ReferenceType; import org.jclouds.vcloud.domain.ReferenceType;
@ -84,7 +84,7 @@ public interface VCloudClient extends CommonVCloudClient {
VAppTemplate getVAppTemplate(URI vAppTemplate); VAppTemplate getVAppTemplate(URI vAppTemplate);
OvfEnvelope getOvfEnvelopeForVAppTemplate(URI vAppTemplate); Envelope getOvfEnvelopeForVAppTemplate(URI vAppTemplate);
/** /**
* Modify the Guest Customization Section of a Virtual Machine * Modify the Guest Customization Section of a Virtual Machine

View File

@ -28,7 +28,7 @@ import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.HardwareBuilder; import org.jclouds.compute.domain.HardwareBuilder;
import org.jclouds.compute.predicates.ImagePredicates; import org.jclouds.compute.predicates.ImagePredicates;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import org.jclouds.ovf.OvfEnvelope; import org.jclouds.ovf.Envelope;
import org.jclouds.ovf.VirtualHardwareSection; import org.jclouds.ovf.VirtualHardwareSection;
import org.jclouds.vcloud.VCloudClient; import org.jclouds.vcloud.VCloudClient;
import org.jclouds.vcloud.domain.ReferenceType; import org.jclouds.vcloud.domain.ReferenceType;
@ -73,19 +73,19 @@ public class HardwareForVAppTemplate implements Function<VAppTemplate, Hardware>
return null; return null;
} }
OvfEnvelope ovf = client.getOvfEnvelopeForVAppTemplate(from.getHref()); Envelope ovf = client.getOvfEnvelopeForVAppTemplate(from.getHref());
if (ovf == null) { if (ovf == null) {
logger.warn("cannot parse hardware as no ovf envelope found for %s", from); logger.warn("cannot parse hardware as no ovf envelope found for %s", from);
return null; return null;
} }
if (ovf.getVirtualSystem().getHardware().size() == 0) { if (ovf.getVirtualSystem().getVirtualHardwareSections().size() == 0) {
logger.warn("cannot parse hardware for %s as no hardware sections exist in ovf %s", ovf); logger.warn("cannot parse hardware for %s as no hardware sections exist in ovf %s", ovf);
return null; return null;
} }
if (ovf.getVirtualSystem().getHardware().size() > 1) { if (ovf.getVirtualSystem().getVirtualHardwareSections().size() > 1) {
logger.warn("multiple hardware choices found. using first", ovf); logger.warn("multiple hardware choices found. using first", ovf);
} }
VirtualHardwareSection hardware = Iterables.get(ovf.getVirtualSystem().getHardware(), 0); VirtualHardwareSection hardware = Iterables.get(ovf.getVirtualSystem().getVirtualHardwareSections(), 0);
HardwareBuilder builder = rasdToHardwareBuilder.apply(hardware.getResourceAllocations()); HardwareBuilder builder = rasdToHardwareBuilder.apply(hardware.getResourceAllocations());
builder.location(findLocationForResource.apply(checkNotNull(parent, "parent"))); builder.location(findLocationForResource.apply(checkNotNull(parent, "parent")));
builder.ids(from.getHref().toASCIIString()).name(from.getName()).supportsImage( builder.ids(from.getHref().toASCIIString()).name(from.getName()).supportsImage(

View File

@ -27,7 +27,7 @@ import org.jclouds.compute.domain.CIMOperatingSystem;
import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.ImageBuilder; import org.jclouds.compute.domain.ImageBuilder;
import org.jclouds.compute.strategy.PopulateDefaultLoginCredentialsForImageStrategy; import org.jclouds.compute.strategy.PopulateDefaultLoginCredentialsForImageStrategy;
import org.jclouds.ovf.OvfEnvelope; import org.jclouds.ovf.Envelope;
import org.jclouds.vcloud.VCloudClient; import org.jclouds.vcloud.VCloudClient;
import org.jclouds.vcloud.domain.ReferenceType; import org.jclouds.vcloud.domain.ReferenceType;
import org.jclouds.vcloud.domain.VAppTemplate; import org.jclouds.vcloud.domain.VAppTemplate;
@ -64,7 +64,7 @@ public class ImageForVAppTemplate implements Function<VAppTemplate, Image> {
builder.name(from.getName()); builder.name(from.getName());
builder.location(findLocationForResource.apply(checkNotNull(parent, "parent"))); builder.location(findLocationForResource.apply(checkNotNull(parent, "parent")));
builder.description(from.getDescription() != null ? from.getDescription() : from.getName()); builder.description(from.getDescription() != null ? from.getDescription() : from.getName());
OvfEnvelope ovf = client.getOvfEnvelopeForVAppTemplate(from.getHref()); Envelope ovf = client.getOvfEnvelopeForVAppTemplate(from.getHref());
builder.operatingSystem(CIMOperatingSystem.toComputeOs(ovf)); builder.operatingSystem(CIMOperatingSystem.toComputeOs(ovf));
builder.defaultCredentials(credentialsProvider.execute(from)); builder.defaultCredentials(credentialsProvider.execute(from));
return builder.build(); return builder.build();

View File

@ -32,9 +32,10 @@ public class VCloudVirtualHardwareSection extends VirtualHardwareSection {
protected final String type; protected final String type;
protected final URI href; protected final URI href;
public VCloudVirtualHardwareSection(String type, URI href, String info, VirtualSystemSettingData virtualSystem, public VCloudVirtualHardwareSection(String type, URI href, String info, Iterable<String> transports,
VirtualSystemSettingData virtualSystem,
Iterable<? extends ResourceAllocationSettingData> resourceAllocations) { Iterable<? extends ResourceAllocationSettingData> resourceAllocations) {
super(info, virtualSystem, resourceAllocations); super(info, transports, virtualSystem, resourceAllocations);
this.type = type; this.type = type;
this.href = href; this.href = href;
} }

View File

@ -50,7 +50,7 @@ public class VCloudVirtualHardwareHandler extends ParseSax.HandlerWithResult<VCl
public VCloudVirtualHardwareSection getResult() { public VCloudVirtualHardwareSection getResult() {
VirtualHardwareSection hardware = hardwareHandler.getResult(); VirtualHardwareSection hardware = hardwareHandler.getResult();
return new VCloudVirtualHardwareSection(this.hardware.getType(), this.hardware.getHref(), hardware.getInfo(), hardware return new VCloudVirtualHardwareSection(this.hardware.getType(), this.hardware.getHref(), hardware.getInfo(), hardware
.getSystem(), hardware.getResourceAllocations()); .getTransports(), hardware.getSystem(), hardware.getResourceAllocations());
} }
public void startElement(String uri, String localName, String qName, Attributes attrs) { public void startElement(String uri, String localName, String qName, Attributes attrs) {

View File

@ -42,7 +42,7 @@ import org.jclouds.http.RequiresHttp;
import org.jclouds.http.functions.ParseSax; import org.jclouds.http.functions.ParseSax;
import org.jclouds.http.functions.ReleasePayloadAndReturn; import org.jclouds.http.functions.ReleasePayloadAndReturn;
import org.jclouds.http.functions.ReturnInputStream; import org.jclouds.http.functions.ReturnInputStream;
import org.jclouds.ovf.xml.OvfEnvelopeHandler; import org.jclouds.ovf.xml.EnvelopeHandler;
import org.jclouds.rest.ConfiguresRestClient; import org.jclouds.rest.ConfiguresRestClient;
import org.jclouds.rest.RestClientTest; import org.jclouds.rest.RestClientTest;
import org.jclouds.rest.RestContextFactory; import org.jclouds.rest.RestContextFactory;
@ -442,7 +442,7 @@ public class VCloudAsyncClientTest extends RestClientTest<VCloudAsyncClient> {
assertPayloadEquals(request, null, null, false); assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, ParseSax.class); assertResponseParserClassEquals(method, request, ParseSax.class);
assertSaxResponseParserClassEquals(method, OvfEnvelopeHandler.class); assertSaxResponseParserClassEquals(method, EnvelopeHandler.class);
assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class);
checkFilters(request); checkFilters(request);

View File

@ -31,7 +31,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
* /> * />
* *
*/ */
public abstract class SettingData { public abstract class SettingData implements Comparable<SettingData> {
public static Builder builder() { public static Builder builder() {
return new Builder(); return new Builder();
@ -123,4 +123,14 @@ public abstract class SettingData {
return String.format("[elementName=%s, instanceID=%s]", elementName, instanceID); return String.format("[elementName=%s, instanceID=%s]", elementName, instanceID);
} }
/**
* {@inheritDoc}
*/
@Override
public int compareTo(SettingData o) {
if (instanceID == null)
return -1;
return (this == o) ? 0 : instanceID.compareTo(o.instanceID);
}
} }

View File

@ -22,7 +22,7 @@ package org.jclouds.compute.domain;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import org.jclouds.cim.OSType; import org.jclouds.cim.OSType;
import org.jclouds.ovf.OvfEnvelope; import org.jclouds.ovf.Envelope;
import com.google.common.annotations.Beta; import com.google.common.annotations.Beta;
@ -123,8 +123,8 @@ public class CIMOperatingSystem extends OperatingSystem {
return new CIMOperatingSystem(OSType.fromValue(os.getId()), "", null, os.getDescription()); return new CIMOperatingSystem(OSType.fromValue(os.getId()), "", null, os.getDescription());
} }
public static CIMOperatingSystem toComputeOs(OvfEnvelope ovf) { public static CIMOperatingSystem toComputeOs(Envelope ovf) {
return toComputeOs(ovf.getVirtualSystem().getOperatingSystem()); return toComputeOs(ovf.getVirtualSystem().getOperatingSystemSection());
} }
private OSType osType; private OSType osType;

View File

@ -0,0 +1,120 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <description@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.ovf;
/**
*
* @author Adrian Cole
*/
public class Configuration {
public static Builder builder() {
return new Builder();
}
public static class Builder {
protected String id;
protected String label;
protected String description;
/**
* @see Configuration#getId
*/
public Builder id(String id) {
this.id = id;
return this;
}
/**
* @see Section#getLabel
*/
public Builder label(String label) {
this.label = label;
return this;
}
/**
* @see Section#getDescription
*/
public Builder description(String description) {
this.description = description;
return this;
}
public Configuration build() {
return new Configuration(id, label, description);
}
public Builder fromNetwork(Configuration in) {
return id(in.getId()).description(in.getDescription()).label(in.getLabel());
}
}
private final String id;
private final String label;
private final String description;
public Configuration(String id, String label, String description) {
this.id = id;
this.label = label;
this.description = description;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Configuration other = (Configuration) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
@Override
public String toString() {
return String.format("Configuration [id=%s, label=%s, description=%s]", id, label, description);
}
public String getId() {
return id;
}
public String getDescription() {
return description;
}
public String getLabel() {
return label;
}
}

View File

@ -0,0 +1,144 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.ovf;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Set;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
/**
* The DeploymentOptionSection specifies a discrete set of intended resource configurations. The
* author of an OVF package can include sizing metadata for different configurations. A consumer of
* the OVF shall select a configuration, for example, by prompting the user. The selected
* configuration is visible in the OVF environment, enabling guest software to adapt to the selected
* configuration.
*
* @author Adrian Cole
*/
public class DeploymentOptionSection extends Section<DeploymentOptionSection> {
@SuppressWarnings("unchecked")
public static Builder builder() {
return new Builder();
}
/**
* {@inheritDoc}
*/
@Override
public Builder toBuilder() {
return builder().fromDeploymentOptionSection(this);
}
public static class Builder extends Section.Builder<DeploymentOptionSection> {
protected Set<Configuration> configurations = Sets.newLinkedHashSet();
/**
* @see DeploymentOptionSection#getConfigurations
*/
public Builder configuration(Configuration configuration) {
this.configurations.add(checkNotNull(configuration, "configuration"));
return this;
}
/**
* @see DeploymentOptionSection#getConfigurations
*/
public Builder configurations(Iterable<Configuration> configurations) {
this.configurations = ImmutableSet.<Configuration> copyOf(checkNotNull(configurations, "configurations"));
return this;
}
/**
* {@inheritDoc}
*/
@Override
public DeploymentOptionSection build() {
return new DeploymentOptionSection(info, configurations);
}
public Builder fromDeploymentOptionSection(DeploymentOptionSection in) {
return info(in.getInfo()).configurations(in.getConfigurations());
}
/**
* {@inheritDoc}
*/
@Override
public Builder fromSection(Section<DeploymentOptionSection> in) {
return Builder.class.cast(super.fromSection(in));
}
/**
* {@inheritDoc}
*/
@Override
public Builder info(String info) {
return Builder.class.cast(super.info(info));
}
}
protected final Set<Configuration> configurations;
public DeploymentOptionSection(String info, Iterable<Configuration> configurations) {
super(info);
this.configurations = ImmutableSet.<Configuration> copyOf(checkNotNull(configurations, "configurations"));
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((configurations == null) ? 0 : configurations.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
DeploymentOptionSection other = (DeploymentOptionSection) obj;
if (configurations == null) {
if (other.configurations != null)
return false;
} else if (!configurations.equals(other.configurations))
return false;
return true;
}
@Override
public String toString() {
return String.format("[info=%s, configurations=%s]", info, configurations);
}
public Set<Configuration> getConfigurations() {
return configurations;
}
}

View File

@ -0,0 +1,237 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <description@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.ovf;
import java.net.URI;
/**
*
* @author Adrian Cole
*/
public class Disk implements Comparable<Disk>{
public static Builder builder() {
return new Builder();
}
public static class Builder {
private String id;
private Long capacity;
private String parentRef;
private String fileRef;
private URI format;
private Long populatedSize;
private String capacityAllocationUnits;
/**
* @see Disk#getId
*/
public Builder id(String id) {
this.id = id;
return this;
}
/**
* @see Disk#getCapacity
*/
public Builder capacity(Long capacity) {
this.capacity = capacity;
return this;
}
/**
* @see Disk#getParentRef
*/
public Builder parentRef(String parentRef) {
this.parentRef = parentRef;
return this;
}
/**
* @see Disk#getFileRef
*/
public Builder fileRef(String fileRef) {
this.fileRef = fileRef;
return this;
}
/**
* @see Disk#getFormat
*/
public Builder format(URI format) {
this.format = format;
return this;
}
/**
* @see Disk#getPopulatedSize
*/
public Builder populatedSize(Long populatedSize) {
this.populatedSize = populatedSize;
return this;
}
/**
* @see Disk#getCapacityAllocationUnits
*/
public Builder capacityAllocationUnits(String capacityAllocationUnits) {
this.capacityAllocationUnits = capacityAllocationUnits;
return this;
}
public Disk build() {
return new Disk(id, capacity, parentRef, fileRef, format, populatedSize, capacityAllocationUnits);
}
public Builder fromDisk(Disk in) {
return id(in.getId()).capacity(in.getCapacity()).parentRef(in.getParentRef()).fileRef(in.getFileRef()).format(
in.getFormat()).populatedSize(in.getPopulatedSize()).capacityAllocationUnits(
in.getCapacityAllocationUnits());
}
}
private final String id;
private final Long capacity;
private final String parentRef;
private final String fileRef;
private final URI format;
private final Long populatedSize;
private final String capacityAllocationUnits;
public Disk(String id, Long capacity, String parentRef, String fileRef, URI format, Long populatedSize,
String capacityAllocationUnits) {
this.id = id;
this.capacity = capacity;
this.parentRef = parentRef;
this.fileRef = fileRef;
this.format = format;
this.populatedSize = populatedSize;
this.capacityAllocationUnits = capacityAllocationUnits;
}
/**
* Each virtual disk is represented by a Disk element that shall be given a identifier using the
* {@code id} attribute, the identifier shall be unique within the {@link DiskSection}.
*/
public String getId() {
return id;
}
/**
* The capacity of a virtual disk shall be specified by the {@code capacity} attribute with an
* xs:long integer value. The default unit of allocation shall be bytes.
*/
public Long getCapacity() {
return capacity;
}
/**
* OVF allows a disk image to be represented as a set of modified blocks in comparison to a
* parent image. The use of parent disks can often significantly reduce the size of an OVF
* package, if it contains multiple disks with similar content. For a Disk element, a parent disk
* may optionally be specified using the {@code parentRef} attribute, which shall contain a valid
* ovf:id reference to a different Disk element. If a disk block does not exist locally, lookup
* for that disk block then occurs in the parent disk. In {@link DiskSection}, parent Disk
* elements shall occur before child Disk elements that refer to them.
*/
public String getParentRef() {
return parentRef;
}
/**
* The ovf:fileRef attribute denotes the virtual disk content by identifying an existing File
* element in the References element, the File element is identified by matching its {@code id}
* attribute value with the {@code fileRef} attribute value. Omitting the {@code fileRef}
* attribute shall indicate an empty disk. In this case, the disk shall be created and the entire
* disk content zeroed at installation time. The guest software will typically format empty disks
* in some file system format.
*/
public String getFileRef() {
return fileRef;
}
/**
* The format URI of a non-empty virtual disk shall be specified by the {@code format} attribute.
*/
public URI getFormat() {
return format;
}
/**
* For non-empty disks, the actual used size of the disk may optionally be specified using the
* {@code populatedSize} attribute. The unit of this attribute is always bytes. {@code
* populatedSize} is allowed to be an estimate of used disk size but shall not be larger than
* {@code capacity}.
*/
public Long getPopulatedSize() {
return populatedSize;
}
/**
* The optional string attribute {@code ovf:capacityAllocationUnits} may be used to specify a
* particular unit of allocation. Values for {@code ovf:capacityAllocationUnits} shall match the
* format for programmatic units defined in DSP0004.
*/
public String getCapacityAllocationUnits() {
return capacityAllocationUnits;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Disk other = (Disk) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
@Override
public String toString() {
return String
.format(
"[id=%s, capacity=%s, capacityAllocationUnits=%s, fileRef=%s, format=%s, parentRef=%s, populatedSize=%s]",
id, capacity, capacityAllocationUnits, fileRef, format, parentRef, populatedSize);
}
/**
* {@inheritDoc}
*/
@Override
public int compareTo(Disk o) {
if (id == null)
return -1;
return (this == o) ? 0 : id.compareTo(o.id);
}
}

View File

@ -0,0 +1,153 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.ovf;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Set;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
/**
* A DiskSection describes meta-information about virtual disks in the OVF package. Virtual disks
* and their metadata are described outside the virtual hardware to facilitate sharing between
* virtual machines within an OVF package.
*
* @author Adrian Cole
*/
public class DiskSection extends Section<DiskSection> {
@SuppressWarnings("unchecked")
public static Builder builder() {
return new Builder();
}
/**
* {@inheritDoc}
*/
@Override
public Builder toBuilder() {
return new Builder().fromDiskSection(this);
}
public static class Builder extends Section.Builder<DiskSection> {
protected Set<Disk> disks = Sets.newLinkedHashSet();
/**
* @see DiskSection#getDisks
*/
public Builder disk(Disk disk) {
this.disks.add(checkNotNull(disk, "disk"));
return this;
}
/**
* @see DiskSection#getDisks
*/
public Builder disks(Iterable<Disk> disks) {
this.disks = ImmutableSet.<Disk> copyOf(checkNotNull(disks, "disks"));
return this;
}
/**
* {@inheritDoc}
*/
@Override
public DiskSection build() {
return new DiskSection(info, disks);
}
public Builder fromDiskSection(DiskSection in) {
return disks(in.getDisks()).info(in.getInfo());
}
/**
* {@inheritDoc}
*/
@Override
public Builder fromSection(Section<DiskSection> in) {
return (Builder) super.fromSection(in);
}
/**
* {@inheritDoc}
*/
@Override
public Builder info(String info) {
return (Builder) super.info(info);
}
}
private final Set<Disk> disks;
public DiskSection(String info, Iterable<Disk> disks) {
super(info);
this.disks = ImmutableSet.<Disk> copyOf(checkNotNull(disks, "disks"));
}
/**
* All disks referred to from Connection elements in all {@link VirtualHardwareSection} elements
* shall be defined in the DiskSection.
*
* @return
*/
public Set<Disk> getDisks() {
return disks;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((info == null) ? 0 : info.hashCode());
result = prime * result + ((disks == null) ? 0 : disks.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
DiskSection other = (DiskSection) obj;
if (info == null) {
if (other.info != null)
return false;
} else if (!info.equals(other.info))
return false;
if (disks == null) {
if (other.disks != null)
return false;
} else if (!disks.equals(other.disks))
return false;
return true;
}
@Override
public String toString() {
return String.format("[info=%s, disks=%s]", info, disks);
}
}

View File

@ -0,0 +1,208 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.ovf;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Set;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;
/**
* @author Adrian Cole
*/
public class Envelope {
public static Builder builder() {
return new Builder();
}
/**
* {@inheritDoc}
*/
public Builder toBuilder() {
return new Builder().fromEnvelope(this);
}
public static class Builder {
protected Set<DiskSection> diskSections = Sets.newLinkedHashSet();
protected Set<NetworkSection> networkSections = Sets.newLinkedHashSet();
@SuppressWarnings("unchecked")
protected Multimap<String, Section> additionalSections = LinkedHashMultimap.create();
protected VirtualSystem virtualSystem;
/**
* @see Envelope#getDiskSections
*/
public Builder diskSection(DiskSection diskSection) {
this.diskSections.add(checkNotNull(diskSection, "diskSection"));
return this;
}
/**
* @see Envelope#getDiskSections
*/
public Builder diskSections(Iterable<? extends DiskSection> diskSections) {
this.diskSections = ImmutableSet.<DiskSection> copyOf(checkNotNull(diskSections, "diskSections"));
return this;
}
/**
* @see Envelope#getNetworkSections
*/
public Builder networkSection(NetworkSection networkSection) {
this.networkSections.add(checkNotNull(networkSection, "networkSection"));
return this;
}
/**
* @see Envelope#getNetworkSections
*/
public Builder networkSections(Iterable<? extends NetworkSection> networkSections) {
this.networkSections = ImmutableSet.<NetworkSection> copyOf(checkNotNull(networkSections, "networkSections"));
return this;
}
/**
* @see Envelope#getAdditionalSections
*/
@SuppressWarnings("unchecked")
public Builder additionalSection(String name, Section additionalSection) {
this.additionalSections.put(checkNotNull(name, "name"), checkNotNull(additionalSection, "additionalSection"));
return this;
}
/**
* @see Envelope#getAdditionalSections
*/
@SuppressWarnings("unchecked")
public Builder additionalSections(Multimap<String, Section> additionalSections) {
this.additionalSections = ImmutableMultimap.<String, Section> copyOf(checkNotNull(additionalSections,
"additionalSections"));
return this;
}
/**
* @see Envelope#getVirtualSystem
*/
public Builder virtualSystem(VirtualSystem virtualSystem) {
this.virtualSystem = virtualSystem;
return this;
}
/**
* {@inheritDoc}
*/
public Envelope build() {
return new Envelope(diskSections, networkSections, additionalSections, virtualSystem);
}
public Builder fromEnvelope(Envelope in) {
return virtualSystem(in.getVirtualSystem()).diskSections(in.getDiskSections())
.networkSections(networkSections).additionalSections(in.getAdditionalSections());
}
}
private final Set<DiskSection> diskSections;
private final Set<NetworkSection> networkSections;
@SuppressWarnings("unchecked")
private final Multimap<String, Section> additionalSections;
private final VirtualSystem virtualSystem;
@SuppressWarnings("unchecked")
public Envelope(Iterable<? extends DiskSection> diskSections, Iterable<? extends NetworkSection> networkSections,
Multimap<String, Section> additionalSections, VirtualSystem virtualSystem) {
this.diskSections = ImmutableSet.copyOf(checkNotNull(diskSections, "diskSections"));
this.networkSections = ImmutableSet.copyOf(checkNotNull(networkSections, "networkSections"));
this.additionalSections = ImmutableMultimap.copyOf(checkNotNull(additionalSections, "additionalSections"));
this.virtualSystem = checkNotNull(virtualSystem, "virtualSystem");
}
public VirtualSystem getVirtualSystem() {
return virtualSystem;
}
public Set<? extends DiskSection> getDiskSections() {
return diskSections;
}
@SuppressWarnings("unchecked")
public Multimap<String, Section> getAdditionalSections() {
return additionalSections;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((additionalSections == null) ? 0 : additionalSections.hashCode());
result = prime * result + ((diskSections == null) ? 0 : diskSections.hashCode());
result = prime * result + ((networkSections == null) ? 0 : networkSections.hashCode());
result = prime * result + ((virtualSystem == null) ? 0 : virtualSystem.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Envelope other = (Envelope) obj;
if (additionalSections == null) {
if (other.additionalSections != null)
return false;
} else if (!additionalSections.equals(other.additionalSections))
return false;
if (diskSections == null) {
if (other.diskSections != null)
return false;
} else if (!diskSections.equals(other.diskSections))
return false;
if (networkSections == null) {
if (other.networkSections != null)
return false;
} else if (!networkSections.equals(other.networkSections))
return false;
if (virtualSystem == null) {
if (other.virtualSystem != null)
return false;
} else if (!virtualSystem.equals(other.virtualSystem))
return false;
return true;
}
@Override
public String toString() {
return String.format("[diskSections=%s, networkSections=%s, additionalSections=%s, virtualSystem=%s]",
diskSections, networkSections, additionalSections, virtualSystem);
}
public Set<NetworkSection> getNetworkSections() {
return networkSections;
}
}

View File

@ -1,6 +1,6 @@
/** /**
* *
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com> * Copyright (C) 2010 Cloud Conscious, LLC. <description@cloudconscious.com>
* *
* ==================================================================== * ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
@ -19,11 +19,45 @@
package org.jclouds.ovf; package org.jclouds.ovf;
/** /**
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
public class Network { public class Network {
public static Builder builder() {
return new Builder();
}
public static class Builder {
protected String name;
protected String description;
/**
* @see Network#getName
*/
public Builder name(String name) {
this.name = name;
return this;
}
/**
* @see Section#getDescription
*/
public Builder description(String description) {
this.description = description;
return this;
}
public Network build() {
return new Network(name, description);
}
public Builder fromNetwork(Network in) {
return name(in.getName()).description(in.getDescription());
}
}
private final String name; private final String name;
private final String description; private final String description;
@ -65,7 +99,7 @@ public class Network {
@Override @Override
public String toString() { public String toString() {
return "Network [name=" + name + ", description=" + description + "]"; return "[name=" + name + ", description=" + description + "]";
} }
public String getName() { public String getName() {

View File

@ -19,31 +19,92 @@
package org.jclouds.ovf; package org.jclouds.ovf;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Set; import java.util.Set;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
/** /**
* The NetworkSection element shall list all logical networks used in the OVF package. * The NetworkSection element shall list all logical networks used in the OVF package.
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
public class NetworkSection { public class NetworkSection extends Section<NetworkSection> {
private final String info;
private final Set<Network> networks;
public NetworkSection(String info, Iterable<Network> networks) { @SuppressWarnings("unchecked")
this.info = info; public static Builder builder() {
this.networks = ImmutableSet.<Network> copyOf(networks); return new Builder();
}
public String getInfo() {
return info;
} }
/** /**
* All networks referred to from Connection elements in all {@link VirtualHardwareSection} elements shall * {@inheritDoc}
* be defined in the NetworkSection. */
@Override
public Builder toBuilder() {
return builder().fromNetworkSection(this);
}
public static class Builder extends Section.Builder<NetworkSection> {
protected Set<Network> networks = Sets.newLinkedHashSet();
/**
* @see NetworkSection#getNetworks
*/
public Builder network(Network network) {
this.networks.add(checkNotNull(network, "network"));
return this;
}
/**
* @see NetworkSection#getNetworks
*/
public Builder networks(Iterable<Network> networks) {
this.networks = ImmutableSet.<Network> copyOf(checkNotNull(networks, "networks"));
return this;
}
/**
* {@inheritDoc}
*/
@Override
public NetworkSection build() {
return new NetworkSection(info, networks);
}
public Builder fromNetworkSection(NetworkSection in) {
return networks(in.getNetworks()).info(in.getInfo());
}
/**
* {@inheritDoc}
*/
@Override
public Builder fromSection(Section<NetworkSection> in) {
return Builder.class.cast(super.fromSection(in));
}
/**
* {@inheritDoc}
*/
@Override
public Builder info(String info) {
return Builder.class.cast(super.info(info));
}
}
private final Set<Network> networks;
public NetworkSection(String info, Iterable<Network> networks) {
super(info);
this.networks = ImmutableSet.<Network> copyOf(checkNotNull(networks, "networks"));
}
/**
* All networks referred to from Connection elements in all {@link VirtualHardwareSection}
* elements shall be defined in the NetworkSection.
* *
* @return * @return
*/ */
@ -84,7 +145,7 @@ public class NetworkSection {
@Override @Override
public String toString() { public String toString() {
return "[info=" + info + ", networks=" + networks + "]"; return String.format("[info=%s, networks=%s]", info, networks);
} }
} }

View File

@ -28,15 +28,23 @@ import org.jclouds.cim.OSType;
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
public class OperatingSystemSection { public class OperatingSystemSection extends Section<OperatingSystemSection> {
@SuppressWarnings("unchecked")
public static Builder builder() { public static Builder builder() {
return new Builder(); return new Builder();
} }
public static class Builder { /**
* {@inheritDoc}
*/
@Override
public Builder toBuilder() {
return builder().fromOperatingSystemSection(this);
}
public static class Builder extends Section.Builder<OperatingSystemSection> {
protected Integer id; protected Integer id;
protected String info;
protected String description; protected String description;
/** /**
@ -47,14 +55,6 @@ public class OperatingSystemSection {
return this; return this;
} }
/**
* @see OperatingSystemSection#getInfo
*/
public Builder info(String info) {
this.info = info;
return this;
}
/** /**
* @see OperatingSystemSection#getDescription * @see OperatingSystemSection#getDescription
*/ */
@ -63,6 +63,10 @@ public class OperatingSystemSection {
return this; return this;
} }
/**
* {@inheritDoc}
*/
@Override
public OperatingSystemSection build() { public OperatingSystemSection build() {
return new OperatingSystemSection(id, info, description); return new OperatingSystemSection(id, info, description);
} }
@ -70,15 +74,31 @@ public class OperatingSystemSection {
public Builder fromOperatingSystemSection(OperatingSystemSection in) { public Builder fromOperatingSystemSection(OperatingSystemSection in) {
return id(in.getId()).info(in.getInfo()).description(in.getDescription()); return id(in.getId()).info(in.getInfo()).description(in.getDescription());
} }
/**
* {@inheritDoc}
*/
@Override
public Builder fromSection(Section<OperatingSystemSection> in) {
return Builder.class.cast(super.fromSection(in));
}
/**
* {@inheritDoc}
*/
@Override
public Builder info(String info) {
return Builder.class.cast(super.info(info));
}
} }
protected final Integer id; protected final Integer id;
protected final String info;
protected final String description; protected final String description;
public OperatingSystemSection(@Nullable Integer id, @Nullable String info, @Nullable String description) { public OperatingSystemSection(@Nullable Integer id, @Nullable String info, @Nullable String description) {
super(info);
this.id = id; this.id = id;
this.info = info;
this.description = description; this.description = description;
} }
@ -91,14 +111,6 @@ public class OperatingSystemSection {
return id; return id;
} }
/**
*
* @return ovf info
*/
public String getInfo() {
return info;
}
/** /**
* *
* @return description or null * @return description or null
@ -144,13 +156,9 @@ public class OperatingSystemSection {
return true; return true;
} }
public Builder toBuilder() {
return builder().fromOperatingSystemSection(this);
}
@Override @Override
public String toString() { public String toString() {
return "[id=" + getId() + ", info=" + getInfo() + ", description=" + getDescription() + "]"; return String.format("[info=%s, id=%s, description=%s]", info, id, description);
} }
} }

View File

@ -19,29 +19,62 @@
package org.jclouds.ovf; package org.jclouds.ovf;
import static com.google.common.base.Preconditions.checkNotNull; import javax.annotation.Nullable;
/** /**
* * Metadata about a virtual machine or grouping of them
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
public class OvfEnvelope { public class Section<T extends Section<T>> {
private final VirtualSystem virtualSystem;
public OvfEnvelope(VirtualSystem virtualSystem) { public static <T extends Section<T>> Builder<T> builder() {
this.virtualSystem = checkNotNull(virtualSystem, "virtualSystem"); return new Builder<T>();
} }
public VirtualSystem getVirtualSystem() { public Builder<T> toBuilder() {
return virtualSystem; return new Builder<T>().fromSection(this);
}
public static class Builder<T extends Section<T>> {
protected String info;
/**
* @see Section#getInfo
*/
public Builder<T> info(String info) {
this.info = info;
return this;
}
public Section<T> build() {
return new Section<T>(info);
}
public Builder<T> fromSection(Section<T> in) {
return info(in.getInfo());
}
}
protected final String info;
public Section(@Nullable String info) {
this.info = info;
}
/**
*
* @return ovf info
*/
public String getInfo() {
return info;
} }
@Override @Override
public int hashCode() { public int hashCode() {
final int prime = 31; final int prime = 31;
int result = 1; int result = 1;
result = prime * result + ((virtualSystem == null) ? 0 : virtualSystem.hashCode()); result = prime * result + ((info == null) ? 0 : info.hashCode());
return result; return result;
} }
@ -53,17 +86,18 @@ public class OvfEnvelope {
return false; return false;
if (getClass() != obj.getClass()) if (getClass() != obj.getClass())
return false; return false;
OvfEnvelope other = (OvfEnvelope) obj; Section<?> other = (Section<?>) obj;
if (virtualSystem == null) { if (info == null) {
if (other.virtualSystem != null) if (other.info != null)
return false; return false;
} else if (!virtualSystem.equals(other.virtualSystem)) } else if (!info.equals(other.info))
return false; return false;
return true; return true;
} }
@Override @Override
public String toString() { public String toString() {
return "[virtualSystem=" + virtualSystem + "]"; return "[info=" + getInfo() + "]";
} }
} }

View File

@ -27,30 +27,141 @@ import org.jclouds.cim.ResourceAllocationSettingData;
import org.jclouds.cim.VirtualSystemSettingData; import org.jclouds.cim.VirtualSystemSettingData;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
/** /**
*
* The virtual hardware required by a virtual machine is specified in VirtualHardwareSection. * The virtual hardware required by a virtual machine is specified in VirtualHardwareSection.
* <p/> * <p/>
* This specification supports abstract or incomplete hardware descriptions in which only the major * This specification supports abstract or incomplete hardware descriptions in which only the major
* devices are described. The hypervisor is allowed to create additional virtual hardware * devices are described. The hypervisor is allowed to create additional virtual hardware
* controllers and devices, as long as the required devices listed in the descriptor are realized. * controllers and devices, as long as the required devices listed in the descriptor are realized.
*
* @author Adrian Cole
*/ */
public class VirtualHardwareSection { public class VirtualHardwareSection extends Section<VirtualHardwareSection> {
protected final String info; @SuppressWarnings("unchecked")
protected final VirtualSystemSettingData virtualSystem; public static Builder builder() {
protected final Set<ResourceAllocationSettingData> resourceAllocations; return new Builder();
public VirtualHardwareSection(String info, VirtualSystemSettingData virtualSystem,
Iterable<? extends ResourceAllocationSettingData> resourceAllocations) {
this.info = info;
this.virtualSystem = virtualSystem;
this.resourceAllocations = ImmutableSet.copyOf(checkNotNull(resourceAllocations, "resourceAllocations"));
} }
public String getInfo() { /**
return info; * {@inheritDoc}
*/
@Override
public Builder toBuilder() {
return builder().fromVirtualHardwareSection(this);
}
public static class Builder extends Section.Builder<VirtualHardwareSection> {
protected VirtualSystemSettingData virtualSystem;
protected Set<String> transports = Sets.newLinkedHashSet();
protected Set<ResourceAllocationSettingData> resourceAllocations = Sets.newLinkedHashSet();
/**
* @see VirtualHardwareSection#getSystem
*/
public Builder system(VirtualSystemSettingData virtualSystem) {
this.virtualSystem = virtualSystem;
return this;
}
/**
* @see VirtualHardwareSection#getTransports
*/
public Builder transport(String transport) {
this.transports.add(checkNotNull(transport, "transport"));
return this;
}
/**
* @see VirtualHardwareSection#getTransports
*/
public Builder transports(Iterable<String> transports) {
this.transports = ImmutableSet.<String> copyOf(checkNotNull(transports, "transports"));
return this;
}
/**
* @see VirtualHardwareSection#getResourceAllocations
*/
public Builder resourceAllocation(ResourceAllocationSettingData resourceAllocation) {
this.resourceAllocations.add(checkNotNull(resourceAllocation, "resourceAllocation"));
return this;
}
/**
* @see VirtualHardwareSection#getResourceAllocations
*/
public Builder resourceAllocations(Iterable<? extends ResourceAllocationSettingData> resourceAllocations) {
this.resourceAllocations = ImmutableSet.<ResourceAllocationSettingData> copyOf(checkNotNull(
resourceAllocations, "resourceAllocations"));
return this;
}
/**
* {@inheritDoc}
*/
@Override
public VirtualHardwareSection build() {
return new VirtualHardwareSection(info, transports, virtualSystem, resourceAllocations);
}
public Builder fromVirtualHardwareSection(VirtualHardwareSection in) {
return resourceAllocations(in.getResourceAllocations()).transports(in.getTransports()).system(
in.getSystem()).info(in.getInfo());
}
/**
* {@inheritDoc}
*/
@Override
public Builder fromSection(Section<VirtualHardwareSection> in) {
return Builder.class.cast(super.fromSection(in));
}
/**
* {@inheritDoc}
*/
@Override
public Builder info(String info) {
return Builder.class.cast(super.info(info));
}
}
protected final VirtualSystemSettingData virtualSystem;
protected final Set<String> transports;
protected final Set<ResourceAllocationSettingData> resourceAllocations;
public VirtualHardwareSection(String info, Iterable<String> transports, VirtualSystemSettingData virtualSystem,
Iterable<? extends ResourceAllocationSettingData> resourceAllocations) {
super(info);
this.virtualSystem = virtualSystem;
this.transports = ImmutableSet.<String> copyOf(checkNotNull(transports, "transports"));
this.resourceAllocations = ImmutableSet.<ResourceAllocationSettingData> copyOf(checkNotNull(resourceAllocations,
"resourceAllocations"));
}
/**
* transport types define methods by which the environment document is communicated from the
* deployment platform to the guest software.
* <p/>
* To enable interoperability, this specification defines an "iso" transport type which all
* implementations that support CD-ROM devices are required to support. The iso transport
* communicates the environment 1346 document by making a dynamically generated ISO image
* available to the guest software. To support the iso transport type, prior to booting a virtual
* machine, an implementation shall make an ISO 9660 read-only disk image available as backing
* for a disconnected CD-ROM. If the iso transport is selected for a VirtualHardwareSection, at
* least one disconnected CD-ROM device shall be present in this section.
* <p/>
* Support for the "iso" transport type is not a requirement for virtual hardware architectures
* or guest 1351 operating systems which do not have CD-ROM device support.
*
* @return
*/
public Set<String> getTransports() {
return transports;
} }
public VirtualSystemSettingData getSystem() { public VirtualSystemSettingData getSystem() {
@ -61,17 +172,12 @@ public class VirtualHardwareSection {
return resourceAllocations; return resourceAllocations;
} }
@Override
public String toString() {
return "[info=" + getInfo() + ", virtualSystem=" + getSystem() + "]";
}
@Override @Override
public int hashCode() { public int hashCode() {
final int prime = 31; final int prime = 31;
int result = 1; int result = super.hashCode();
result = prime * result + ((info == null) ? 0 : info.hashCode());
result = prime * result + ((resourceAllocations == null) ? 0 : resourceAllocations.hashCode()); result = prime * result + ((resourceAllocations == null) ? 0 : resourceAllocations.hashCode());
result = prime * result + ((transports == null) ? 0 : transports.hashCode());
result = prime * result + ((virtualSystem == null) ? 0 : virtualSystem.hashCode()); result = prime * result + ((virtualSystem == null) ? 0 : virtualSystem.hashCode());
return result; return result;
} }
@ -80,21 +186,21 @@ public class VirtualHardwareSection {
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (this == obj) if (this == obj)
return true; return true;
if (obj == null) if (!super.equals(obj))
return false; return false;
if (getClass() != obj.getClass()) if (getClass() != obj.getClass())
return false; return false;
VirtualHardwareSection other = (VirtualHardwareSection) obj; VirtualHardwareSection other = (VirtualHardwareSection) obj;
if (info == null) {
if (other.info != null)
return false;
} else if (!info.equals(other.info))
return false;
if (resourceAllocations == null) { if (resourceAllocations == null) {
if (other.resourceAllocations != null) if (other.resourceAllocations != null)
return false; return false;
} else if (!resourceAllocations.equals(other.resourceAllocations)) } else if (!resourceAllocations.equals(other.resourceAllocations))
return false; return false;
if (transports == null) {
if (other.transports != null)
return false;
} else if (!transports.equals(other.transports))
return false;
if (virtualSystem == null) { if (virtualSystem == null) {
if (other.virtualSystem != null) if (other.virtualSystem != null)
return false; return false;
@ -103,4 +209,10 @@ public class VirtualHardwareSection {
return true; return true;
} }
@Override
public String toString() {
return String.format("[info=%s, resourceAllocations=%s, transports=%s, virtualSystem=%s]", info,
resourceAllocations, transports, virtualSystem);
}
} }

View File

@ -23,63 +23,178 @@ import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Set; import java.util.Set;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables; import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
/** /**
* @author Adrian Cole * @author Adrian Cole
*/ */
public class VirtualSystem { public class VirtualSystem extends Section<VirtualSystem> {
@SuppressWarnings("unchecked")
public static Builder builder() {
return new Builder();
}
/**
* {@inheritDoc}
*/
@Override
public Builder toBuilder() {
return new Builder().fromVirtualSystem(this);
}
public static class Builder extends Section.Builder<VirtualSystem> {
protected String id;
protected String name;
protected OperatingSystemSection operatingSystem;
protected Set<VirtualHardwareSection> hardwareSections = Sets.newLinkedHashSet();
@SuppressWarnings("unchecked")
protected Multimap<String, Section> additionalSections = LinkedHashMultimap.create();
/**
* @see VirtualSystem#getName
*/
public Builder name(String name) {
this.name = name;
return this;
}
/**
* @see VirtualSystem#getId
*/
public Builder id(String id) {
this.id = id;
return this;
}
/**
* @see VirtualSystem#getOperatingSystemSection
*/
public Builder operatingSystemSection(OperatingSystemSection operatingSystem) {
this.operatingSystem = operatingSystem;
return this;
}
/**
* @see VirtualSystem#getVirtualHardwareSections
*/
public Builder hardwareSection(VirtualHardwareSection hardwareSection) {
this.hardwareSections.add(checkNotNull(hardwareSection, "hardwareSection"));
return this;
}
/**
* @see VirtualSystem#getVirtualHardwareSections
*/
public Builder hardwareSections(Iterable<? extends VirtualHardwareSection> hardwareSections) {
this.hardwareSections = ImmutableSet.<VirtualHardwareSection> copyOf(checkNotNull(hardwareSections,
"hardwareSections"));
return this;
}
/**
* @see VirtualSystem#getAdditionalSections
*/
@SuppressWarnings("unchecked")
public Builder additionalSection(String name, Section additionalSection) {
this.additionalSections.put(checkNotNull(name, "name"), checkNotNull(additionalSection, "additionalSection"));
return this;
}
/**
* @see VirtualSystem#getAdditionalSections
*/
@SuppressWarnings("unchecked")
public Builder additionalSections(Multimap<String, Section> additionalSections) {
this.additionalSections = ImmutableMultimap.<String, Section> copyOf(checkNotNull(additionalSections,
"additionalSections"));
return this;
}
/**
* {@inheritDoc}
*/
@Override
public VirtualSystem build() {
return new VirtualSystem(id, info, name, operatingSystem, hardwareSections, additionalSections);
}
public Builder fromVirtualSystem(VirtualSystem in) {
return fromSection(in).id(in.getId()).name(in.getName())
.operatingSystemSection(in.getOperatingSystemSection()).hardwareSections(
in.getVirtualHardwareSections()).additionalSections(in.getAdditionalSections());
}
/**
* {@inheritDoc}
*/
@Override
public Builder fromSection(Section<VirtualSystem> in) {
return (Builder) super.fromSection(in);
}
/**
* {@inheritDoc}
*/
@Override
public Builder info(String info) {
return (Builder) super.info(info);
}
}
private final String id; private final String id;
private final String info;
private final String name; private final String name;
private final OperatingSystemSection operatingSystem; private final OperatingSystemSection operatingSystem;
private final Set<VirtualHardwareSection> hardware = Sets.newLinkedHashSet(); private final Set<VirtualHardwareSection> hardwareSections;
@SuppressWarnings("unchecked")
private final Multimap<String, Section> additionalSections;
@SuppressWarnings("unchecked")
public VirtualSystem(String id, String info, String name, OperatingSystemSection operatingSystem, public VirtualSystem(String id, String info, String name, OperatingSystemSection operatingSystem,
Iterable<? extends VirtualHardwareSection> hardware) { Iterable<? extends VirtualHardwareSection> hardwareSections, Multimap<String, Section> additionalSections) {
super(info);
this.id = id; this.id = id;
this.info = info;
this.name = name; this.name = name;
this.operatingSystem = checkNotNull(operatingSystem, "operatingSystem"); this.operatingSystem = checkNotNull(operatingSystem, "operatingSystem");
Iterables.addAll(this.hardware, checkNotNull(hardware, "hardware")); this.hardwareSections = ImmutableSet.copyOf(checkNotNull(hardwareSections, "hardwareSections"));
this.additionalSections = ImmutableMultimap.copyOf(checkNotNull(additionalSections, "additionalSections"));
} }
public String getId() { public String getId() {
return id; return id;
} }
public String getInfo() {
return info;
}
public String getName() { public String getName() {
return name; return name;
} }
public OperatingSystemSection getOperatingSystem() { public OperatingSystemSection getOperatingSystemSection() {
return operatingSystem; return operatingSystem;
} }
/** /**
* Each VirtualSystem element may contain one or more VirtualHardwareSection elements, each of * Each VirtualSystem element may contain one or more VirtualHardwareSection elements, each of
* which describes the virtual hardware required by the virtual system. * which describes the virtual hardwareSections required by the virtual system.
* */ * */
public Set<? extends VirtualHardwareSection> getHardware() { public Set<? extends VirtualHardwareSection> getVirtualHardwareSections() {
return hardware; return hardwareSections;
}
@SuppressWarnings("unchecked")
public Multimap<String, Section> getAdditionalSections() {
return additionalSections;
} }
@Override @Override
public int hashCode() { public int hashCode() {
final int prime = 31; final int prime = 31;
int result = 1; int result = 1;
result = prime * result + ((hardware == null) ? 0 : hardware.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((info == null) ? 0 : info.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((operatingSystem == null) ? 0 : operatingSystem.hashCode());
return result; return result;
} }
@ -92,37 +207,17 @@ public class VirtualSystem {
if (getClass() != obj.getClass()) if (getClass() != obj.getClass())
return false; return false;
VirtualSystem other = (VirtualSystem) obj; VirtualSystem other = (VirtualSystem) obj;
if (hardware == null) {
if (other.hardware != null)
return false;
} else if (!hardware.equals(other.hardware))
return false;
if (id == null) { if (id == null) {
if (other.id != null) if (other.id != null)
return false; return false;
} else if (!id.equals(other.id)) } else if (!id.equals(other.id))
return false; return false;
if (info == null) {
if (other.info != null)
return false;
} else if (!info.equals(other.info))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (operatingSystem == null) {
if (other.operatingSystem != null)
return false;
} else if (!operatingSystem.equals(other.operatingSystem))
return false;
return true; return true;
} }
@Override @Override
public String toString() { public String toString() {
return "[id=" + getId() + ", name=" + getName() + ", info=" + getInfo() + ", os=" + getOperatingSystem() return String.format("[id=%s, name=%s, info=%s, operatingSystem=%s, hardwareSections=%s, additionalSections=%s]",
+ ", hardware=" + getHardware() + "]"; id, name, info, operatingSystem, hardwareSections, additionalSections);
} }
} }

View File

@ -0,0 +1,72 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.ovf.xml;
import static org.jclouds.util.SaxUtils.currentOrNull;
import static org.jclouds.util.SaxUtils.equalsOrSuffix;
import java.util.Map;
import javax.inject.Inject;
import javax.inject.Provider;
import org.jclouds.ovf.Configuration;
import org.jclouds.ovf.DeploymentOptionSection;
import org.jclouds.util.SaxUtils;
import org.xml.sax.Attributes;
/**
* @author Adrian Cole
*/
public class DeploymentOptionSectionHandler extends
SectionHandler<DeploymentOptionSection, DeploymentOptionSection.Builder> {
protected Configuration.Builder configBuilder = Configuration.builder();
@Inject
public DeploymentOptionSectionHandler(Provider<DeploymentOptionSection.Builder> builderProvider) {
super(builderProvider);
}
public void startElement(String uri, String localName, String qName, Attributes attrs) {
Map<String, String> attributes = SaxUtils.cleanseAttributes(attrs);
if (equalsOrSuffix(qName, "Configuration")) {
configBuilder.id(attributes.get("id"));
// TODO default;
}
}
@Override
public void endElement(String uri, String localName, String qName) {
if (equalsOrSuffix(qName, "Info")) {
builder.info(currentOrNull(currentText));
} else if (equalsOrSuffix(qName, "Label")) {
configBuilder.label(currentOrNull(currentText));
} else if (equalsOrSuffix(qName, "Description")) {
configBuilder.description(currentOrNull(currentText));
} else if (equalsOrSuffix(qName, "Configuration")) {
try {
builder.configuration(configBuilder.build());
} finally {
configBuilder = Configuration.builder();
}
}
super.endElement(uri, localName, qName);
}
}

View File

@ -0,0 +1,93 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.ovf.xml;
import static org.jclouds.util.SaxUtils.currentOrNull;
import static org.jclouds.util.SaxUtils.equalsOrSuffix;
import java.net.URI;
import java.util.Map;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Provider;
import org.jclouds.logging.Logger;
import org.jclouds.ovf.Disk;
import org.jclouds.ovf.DiskSection;
import org.jclouds.util.SaxUtils;
import org.xml.sax.Attributes;
/**
* @author Adrian Cole
*/
public class DiskSectionHandler extends SectionHandler<DiskSection, DiskSection.Builder> {
@Resource
protected Logger logger = Logger.NULL;
protected Disk.Builder diskBuilder = Disk.builder();
@Inject
public DiskSectionHandler(Provider<DiskSection.Builder> builderProvider) {
super(builderProvider);
}
public void startElement(String uri, String localName, String qName, Attributes attrs) {
Map<String, String> attributes = SaxUtils.cleanseAttributes(attrs);
if (equalsOrSuffix(qName, "Disk")) {
diskBuilder.id(attributes.get("diskId"));
diskBuilder.capacity(attemptToParse(attributes.get("capacity"), "capacity", attributes.get("diskId")));
diskBuilder.parentRef(attributes.get("parentRef"));
diskBuilder.fileRef(attributes.get("fileRef"));
if (attributes.containsKey("format"))
diskBuilder.format(URI.create(attributes.get("format")));
diskBuilder.populatedSize(attemptToParse(attributes.get("populatedSize"), "populatedSize", attributes
.get("diskId")));
diskBuilder.capacityAllocationUnits(attributes.get("capacityAllocationUnits"));
}
}
private Long attemptToParse(String toParse, String key, String diskId) {
Long val = null;
if (toParse != null) {
try {
val = new Long(toParse);
} catch (NumberFormatException e) {
logger.warn("%s for disk %s not a number [%s]", key, diskId, toParse);
}
}
return val;
}
@Override
public void endElement(String uri, String localName, String qName) {
if (equalsOrSuffix(qName, "Info")) {
builder.info(currentOrNull(currentText));
} else if (equalsOrSuffix(qName, "Disk")) {
try {
builder.disk(diskBuilder.build());
} finally {
diskBuilder = Disk.builder();
}
}
super.endElement(uri, localName, qName);
}
}

View File

@ -0,0 +1,165 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.ovf.xml;
import static org.jclouds.util.SaxUtils.equalsOrSuffix;
import java.util.Map;
import javax.inject.Named;
import javax.inject.Provider;
import org.jclouds.http.functions.ParseSax;
import org.jclouds.ovf.Envelope;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Inject;
/**
* @author Adrian Cole
*/
public class EnvelopeHandler extends ParseSax.HandlerWithResult<Envelope> {
protected Envelope.Builder builder = Envelope.builder();
public Envelope getResult() {
try {
return builder.build();
} finally {
builder = Envelope.builder();
}
}
private final VirtualSystemHandler virtualSystemHandler;
private final DiskSectionHandler diskHandler;
private final NetworkSectionHandler networkHandler;
@Inject
public EnvelopeHandler(DiskSectionHandler diskHandler, NetworkSectionHandler networkHandler,
VirtualSystemHandler osHandler) {
this.virtualSystemHandler = osHandler;
this.diskHandler = diskHandler;
this.networkHandler = networkHandler;
}
@SuppressWarnings("unchecked")
protected SectionHandler defaultSectionHandler = SectionHandler.create();
@SuppressWarnings("unchecked")
@Inject(optional = true)
@Named("VirtualSystem")
Map<String, Provider<? extends SectionHandler>> extensionHandlers = ImmutableMap
.<String, Provider<? extends SectionHandler>> of();
@SuppressWarnings("unchecked")
protected SectionHandler extensionHandler;
private boolean inDisk;
private boolean inNetwork;
private boolean inVirtualSystem;
private boolean inSection;
private boolean inExtensionSection;
private int depth = 0;
public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException {
depth++;
if (depth == 2) {
if (equalsOrSuffix(qName, "DiskSection")) {
inDisk = true;
} else if (equalsOrSuffix(qName, "NetworkSection")) {
inNetwork = true;
} else if (equalsOrSuffix(qName, "VirtualSystem")) {
inVirtualSystem = true;
} else if (extensionHandlers.containsKey(qName)) {
inExtensionSection = true;
extensionHandler = extensionHandlers.get(qName).get();
} else if (qName.endsWith("Section")) {
inSection = true;
}
}
if (inDisk) {
diskHandler.startElement(uri, localName, qName, attrs);
} else if (inNetwork) {
networkHandler.startElement(uri, localName, qName, attrs);
} else if (inVirtualSystem) {
virtualSystemHandler.startElement(uri, localName, qName, attrs);
} else if (inExtensionSection) {
extensionHandler.startElement(uri, localName, qName, attrs);
} else if (inSection) {
defaultSectionHandler.startElement(uri, localName, qName, attrs);
}
}
@Override
public void endElement(String uri, String localName, String qName) {
depth--;
if (depth == 1) {
if (equalsOrSuffix(qName, "DiskSection")) {
inDisk = false;
builder.diskSection(diskHandler.getResult());
} else if (equalsOrSuffix(qName, "NetworkSection")) {
inNetwork = false;
builder.networkSection(networkHandler.getResult());
} else if (equalsOrSuffix(qName, "VirtualSystem")) {
inVirtualSystem = false;
builder.virtualSystem(virtualSystemHandler.getResult());
} else if (extensionHandlers.containsKey(qName)) {
builder.additionalSection(qName, extensionHandler.getResult());
inExtensionSection = false;
} else if (qName.endsWith("Section")) {
builder.additionalSection(qName, defaultSectionHandler.getResult());
inSection = false;
}
}
if (inDisk) {
diskHandler.endElement(uri, localName, qName);
} else if (inNetwork) {
networkHandler.endElement(uri, localName, qName);
} else if (inVirtualSystem) {
virtualSystemHandler.endElement(uri, localName, qName);
} else if (inExtensionSection) {
extensionHandler.endElement(uri, localName, qName);
} else if (inSection) {
defaultSectionHandler.endElement(uri, localName, qName);
}
}
@Override
public void characters(char ch[], int start, int length) {
if (inDisk) {
diskHandler.characters(ch, start, length);
} else if (inNetwork) {
networkHandler.characters(ch, start, length);
} else if (inVirtualSystem) {
virtualSystemHandler.characters(ch, start, length);
} else if (inExtensionSection) {
extensionHandler.characters(ch, start, length);
} else if (inSection) {
defaultSectionHandler.characters(ch, start, length);
}
}
}

View File

@ -23,56 +23,46 @@ import static org.jclouds.util.SaxUtils.currentOrNull;
import static org.jclouds.util.SaxUtils.equalsOrSuffix; import static org.jclouds.util.SaxUtils.equalsOrSuffix;
import java.util.Map; import java.util.Map;
import java.util.Set;
import org.jclouds.http.functions.ParseSax; import javax.inject.Inject;
import javax.inject.Provider;
import org.jclouds.ovf.Network; import org.jclouds.ovf.Network;
import org.jclouds.ovf.NetworkSection; import org.jclouds.ovf.NetworkSection;
import org.jclouds.util.SaxUtils; import org.jclouds.util.SaxUtils;
import org.xml.sax.Attributes; import org.xml.sax.Attributes;
import com.google.common.collect.Sets;
/** /**
* @author Adrian Cole * @author Adrian Cole
*/ */
public class NetworkSectionHandler extends ParseSax.HandlerWithResult<NetworkSection> { public class NetworkSectionHandler extends SectionHandler<NetworkSection, NetworkSection.Builder> {
protected StringBuilder currentText = new StringBuilder(); protected Network.Builder networkBuilder = Network.builder();
protected String info; @Inject
protected String name; public NetworkSectionHandler(Provider<NetworkSection.Builder> builderProvider) {
protected String description; super(builderProvider);
protected Set<Network> networks = Sets.newLinkedHashSet();
public NetworkSection getResult() {
NetworkSection system = new NetworkSection(info, networks);
this.info = null;
this.networks = Sets.newLinkedHashSet();
return system;
} }
public void startElement(String uri, String localName, String qName, Attributes attrs) { public void startElement(String uri, String localName, String qName, Attributes attrs) {
Map<String, String> attributes = SaxUtils.cleanseAttributes(attrs); Map<String, String> attributes = SaxUtils.cleanseAttributes(attrs);
if (equalsOrSuffix(qName, "Network")) { if (equalsOrSuffix(qName, "Network")) {
name = attributes.get("name"); networkBuilder.name(attributes.get("name"));
} }
} }
@Override @Override
public void endElement(String uri, String localName, String qName) { public void endElement(String uri, String localName, String qName) {
if (equalsOrSuffix(qName, "Info")) { if (equalsOrSuffix(qName, "Info")) {
this.info = currentOrNull(currentText); builder.info(currentOrNull(currentText));
} else if (equalsOrSuffix(qName, "Description")) { } else if (equalsOrSuffix(qName, "Description")) {
this.description = currentOrNull(currentText); networkBuilder.description(currentOrNull(currentText));
} else if (equalsOrSuffix(qName, "Network")) { } else if (equalsOrSuffix(qName, "Network")) {
this.networks.add(new Network(name, description)); try {
builder.network(networkBuilder.build());
} finally {
networkBuilder = Network.builder();
}
} }
currentText = new StringBuilder(); super.endElement(uri, localName, qName);
} }
public void characters(char ch[], int start, int length) {
currentText.append(ch, start, length);
}
} }

View File

@ -25,26 +25,20 @@ import static org.jclouds.util.SaxUtils.equalsOrSuffix;
import java.util.Map; import java.util.Map;
import org.jclouds.http.functions.ParseSax; import javax.inject.Inject;
import javax.inject.Provider;
import org.jclouds.ovf.OperatingSystemSection; import org.jclouds.ovf.OperatingSystemSection;
import org.xml.sax.Attributes; import org.xml.sax.Attributes;
/** /**
* @author Adrian Cole * @author Adrian Cole
*/ */
public class OperatingSystemSectionHandler extends ParseSax.HandlerWithResult<OperatingSystemSection> { public class OperatingSystemSectionHandler extends
private StringBuilder currentText = new StringBuilder(); SectionHandler<OperatingSystemSection, OperatingSystemSection.Builder> {
@Inject
protected Integer id; public OperatingSystemSectionHandler(Provider<OperatingSystemSection.Builder> builderProvider) {
protected String info; super(builderProvider);
protected String description;
public OperatingSystemSection getResult() {
OperatingSystemSection system = new OperatingSystemSection(id, info, description);
id = null;
info = null;
description = null;
return system;
} }
@Override @Override
@ -52,21 +46,17 @@ public class OperatingSystemSectionHandler extends ParseSax.HandlerWithResult<Op
Map<String, String> attributes = cleanseAttributes(attrs); Map<String, String> attributes = cleanseAttributes(attrs);
if (equalsOrSuffix(qName, "OperatingSystemSection")) { if (equalsOrSuffix(qName, "OperatingSystemSection")) {
if (attributes.containsKey("id")) if (attributes.containsKey("id"))
this.id = Integer.parseInt(attributes.get("id")); builder.id(Integer.parseInt(attributes.get("id")));
} }
} }
@Override @Override
public void endElement(String uri, String localName, String qName) { public void endElement(String uri, String localName, String qName) {
if (equalsOrSuffix(qName, "Info")) { if (equalsOrSuffix(qName, "Info")) {
this.info = currentOrNull(currentText); builder.info(currentOrNull(currentText));
} else if (equalsOrSuffix(qName, "Description")) { } else if (equalsOrSuffix(qName, "Description")) {
this.description = currentOrNull(currentText); builder.description(currentOrNull(currentText));
} }
currentText = new StringBuilder(); super.endElement(uri, localName, qName);
}
public void characters(char ch[], int start, int length) {
currentText.append(ch, start, length);
} }
} }

View File

@ -1,87 +0,0 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.vdc/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.ovf.xml;
//import static org.jclouds.vcloud.util.Utils.cleanseAttributes;
import javax.inject.Inject;
import org.jclouds.http.functions.ParseSax;
import org.jclouds.ovf.OvfEnvelope;
import org.jclouds.ovf.VirtualSystem;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
/**
* @author Adrian Cole
*/
public class OvfEnvelopeHandler extends ParseSax.HandlerWithResult<OvfEnvelope> {
protected final VirtualSystemHandler virtualSystemHandler;
@Inject
public OvfEnvelopeHandler(VirtualSystemHandler virtualSystemHandler) {
this.virtualSystemHandler = virtualSystemHandler;
}
protected StringBuilder currentText = new StringBuilder();
private VirtualSystem virtualSystem;
private boolean inVirtualSystem;
public OvfEnvelope getResult() {
return new OvfEnvelope(virtualSystem);
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException {
// Map<String, String> attributes = cleanseAttributes(attrs);
if (qName.endsWith("VirtualSystem")) {
inVirtualSystem = true;
}
if (inVirtualSystem) {
virtualSystemHandler.startElement(uri, localName, qName, attrs);
}
}
public void endElement(String uri, String name, String qName) {
if (qName.endsWith("VirtualSystem")) {
inVirtualSystem = false;
virtualSystem = virtualSystemHandler.getResult();
}
if (inVirtualSystem) {
virtualSystemHandler.endElement(uri, name, qName);
}
currentText = new StringBuilder();
}
public void characters(char ch[], int start, int length) {
if (inVirtualSystem)
virtualSystemHandler.characters(ch, start, length);
else
currentText.append(ch, start, length);
}
protected String currentOrNull() {
String returnVal = currentText.toString().trim();
return returnVal.equals("") ? null : returnVal;
}
}

View File

@ -0,0 +1,76 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.ovf.xml;
import static org.jclouds.util.SaxUtils.currentOrNull;
import static org.jclouds.util.SaxUtils.equalsOrSuffix;
import javax.inject.Provider;
import org.jclouds.http.functions.ParseSax;
import org.jclouds.ovf.Section;
import org.jclouds.ovf.Section.Builder;
/**
* @author Adrian Cole
*/
public class SectionHandler<T extends Section<T>, B extends Section.Builder<T>> extends ParseSax.HandlerWithResult<T> {
@SuppressWarnings("unchecked")
public static SectionHandler create() {
return new SectionHandler(new Provider<Section.Builder>() {
@Override
public Builder get() {
return new Section.Builder();
}
});
}
protected final Provider<? extends Section.Builder<T>> builderProvider;
protected StringBuilder currentText = new StringBuilder();
protected B builder;
public SectionHandler(Provider<B> builderProvider) {
this.builderProvider = builderProvider;
this.builder = builderProvider.get();
}
@SuppressWarnings("unchecked")
public T getResult() {
try {
return (T) builder.build();
} finally {
builder = (B) builderProvider.get();
}
}
@Override
public void endElement(String uri, String localName, String qName) {
if (equalsOrSuffix(qName, "Info")) {
builder.info(currentOrNull(currentText));
}
currentText = new StringBuilder();
}
public void characters(char ch[], int start, int length) {
currentText.append(ch, start, length);
}
}

View File

@ -19,53 +19,53 @@
package org.jclouds.ovf.xml; package org.jclouds.ovf.xml;
import java.util.Set; import static org.jclouds.util.SaxUtils.cleanseAttributes;
import static org.jclouds.util.SaxUtils.currentOrNull;
import static org.jclouds.util.SaxUtils.equalsOrSuffix;
import java.util.Map;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Provider;
import org.jclouds.cim.ResourceAllocationSettingData;
import org.jclouds.cim.VirtualSystemSettingData;
import org.jclouds.cim.xml.ResourceAllocationSettingDataHandler; import org.jclouds.cim.xml.ResourceAllocationSettingDataHandler;
import org.jclouds.cim.xml.VirtualSystemSettingDataHandler; import org.jclouds.cim.xml.VirtualSystemSettingDataHandler;
import org.jclouds.http.functions.ParseSax;
import org.jclouds.ovf.VirtualHardwareSection; import org.jclouds.ovf.VirtualHardwareSection;
import org.xml.sax.Attributes; import org.xml.sax.Attributes;
import com.google.common.collect.Sets; import com.google.common.base.Splitter;
/** /**
* @author Adrian Cole * @author Adrian Cole
*/ */
public class VirtualHardwareSectionHandler extends ParseSax.HandlerWithResult<VirtualHardwareSection> { public class VirtualHardwareSectionHandler extends
protected StringBuilder currentText = new StringBuilder(); SectionHandler<VirtualHardwareSection, VirtualHardwareSection.Builder> {
private final VirtualSystemSettingDataHandler systemHandler; private final VirtualSystemSettingDataHandler systemHandler;
private final ResourceAllocationSettingDataHandler allocationHandler; private final ResourceAllocationSettingDataHandler allocationHandler;
@Inject @Inject
public VirtualHardwareSectionHandler(VirtualSystemSettingDataHandler systemHandler, public VirtualHardwareSectionHandler(Provider<VirtualHardwareSection.Builder> builderProvider,
ResourceAllocationSettingDataHandler allocationHandler) { VirtualSystemSettingDataHandler systemHandler, ResourceAllocationSettingDataHandler allocationHandler) {
super(builderProvider);
this.systemHandler = systemHandler; this.systemHandler = systemHandler;
this.allocationHandler = allocationHandler; this.allocationHandler = allocationHandler;
} }
private String info;
protected VirtualSystemSettingData system;
protected Set<ResourceAllocationSettingData> allocations = Sets.newLinkedHashSet();
private boolean inItem; private boolean inItem;
private boolean inSystem; private boolean inSystem;
public VirtualHardwareSection getResult() {
return new VirtualHardwareSection(info, system, allocations);
}
public void startElement(String uri, String localName, String qName, Attributes attrs) { public void startElement(String uri, String localName, String qName, Attributes attrs) {
if (qName.endsWith("System")) { Map<String, String> attributes = cleanseAttributes(attrs);
if (equalsOrSuffix(qName, "VirtualHardwareSection")) {
if (attributes.containsKey("transport"))
builder.transports(Splitter.on(' ').split(attributes.get("transport")));
} else if (equalsOrSuffix(qName, "System")) {
inSystem = true; inSystem = true;
} else if (!inSystem && qName.endsWith("Item")) { } else if (!inSystem && equalsOrSuffix(qName, "Item")) {
inItem = true; inItem = true;
} }
if (inSystem) { if (inSystem) {
systemHandler.startElement(uri, localName, qName, attrs); systemHandler.startElement(uri, localName, qName, attrs);
} else if (inItem) { } else if (inItem) {
@ -75,30 +75,33 @@ public class VirtualHardwareSectionHandler extends ParseSax.HandlerWithResult<Vi
@Override @Override
public void endElement(String uri, String localName, String qName) { public void endElement(String uri, String localName, String qName) {
if (qName.endsWith("System")) { if (equalsOrSuffix(qName, "System")) {
inSystem = false; inSystem = false;
system = systemHandler.getResult(); builder.system(systemHandler.getResult());
} else if (qName.endsWith("Item")) { } else if (equalsOrSuffix(qName, "Item")) {
inItem = false; inItem = false;
allocations.add(allocationHandler.getResult()); builder.resourceAllocation(allocationHandler.getResult());
} }
if (inSystem) { if (inSystem) {
systemHandler.endElement(uri, localName, qName); systemHandler.endElement(uri, localName, qName);
} else if (inItem) { } else if (inItem) {
allocationHandler.endElement(uri, localName, qName); allocationHandler.endElement(uri, localName, qName);
} else if (qName.endsWith("Info")) { } else {
this.info = currentText.toString().trim(); if (equalsOrSuffix(qName, "Info"))
builder.info(currentOrNull(currentText));
super.endElement(uri, localName, qName);
} }
currentText = new StringBuilder();
} }
@Override @Override
public void characters(char ch[], int start, int length) { public void characters(char ch[], int start, int length) {
currentText.append(ch, start, length); if (inSystem) {
if (inSystem)
systemHandler.characters(ch, start, length); systemHandler.characters(ch, start, length);
if (inItem) } else if (inItem) {
allocationHandler.characters(ch, start, length); allocationHandler.characters(ch, start, length);
} else {
super.characters(ch, start, length);
}
} }
} }

View File

@ -20,122 +20,134 @@
package org.jclouds.ovf.xml; package org.jclouds.ovf.xml;
import static org.jclouds.util.SaxUtils.cleanseAttributes; import static org.jclouds.util.SaxUtils.cleanseAttributes;
import static org.jclouds.util.SaxUtils.currentOrNull;
import static org.jclouds.util.SaxUtils.equalsOrSuffix; import static org.jclouds.util.SaxUtils.equalsOrSuffix;
import java.util.Map; import java.util.Map;
import java.util.Set;
import javax.inject.Inject; import javax.inject.Named;
import javax.inject.Provider;
import org.jclouds.http.functions.ParseSax;
import org.jclouds.ovf.OperatingSystemSection;
import org.jclouds.ovf.VirtualHardwareSection;
import org.jclouds.ovf.VirtualSystem; import org.jclouds.ovf.VirtualSystem;
import org.xml.sax.Attributes; import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import com.google.common.collect.Sets; import com.google.common.collect.ImmutableMap;
import com.google.inject.Inject;
/** /**
* @author Adrian Cole * @author Adrian Cole
*/ */
public class VirtualSystemHandler extends ParseSax.HandlerWithResult<VirtualSystem> { public class VirtualSystemHandler extends SectionHandler<VirtualSystem, VirtualSystem.Builder> {
protected StringBuilder currentText = new StringBuilder();
private final OperatingSystemSectionHandler osHandler; private final OperatingSystemSectionHandler osHandler;
private final VirtualHardwareSectionHandler hardwareHandler; private final VirtualHardwareSectionHandler hardwareHandler;
@Inject @Inject
public VirtualSystemHandler(OperatingSystemSectionHandler osHandler, VirtualHardwareSectionHandler hardwareHandler) { public VirtualSystemHandler(Provider<VirtualSystem.Builder> builderProvider,
OperatingSystemSectionHandler osHandler, VirtualHardwareSectionHandler hardwareHandler) {
super(builderProvider);
this.osHandler = osHandler; this.osHandler = osHandler;
this.hardwareHandler = hardwareHandler; this.hardwareHandler = hardwareHandler;
} }
protected String id; @SuppressWarnings("unchecked")
protected String info; protected SectionHandler defaultSectionHandler = SectionHandler.create();
protected String name;
protected OperatingSystemSection operatingSystem; @SuppressWarnings("unchecked")
protected Set<VirtualHardwareSection> hardware = Sets.newLinkedHashSet(); @Inject(optional = true)
@Named("VirtualSystem")
Map<String, Provider<? extends SectionHandler>> extensionHandlers = ImmutableMap
.<String, Provider<? extends SectionHandler>> of();
@SuppressWarnings("unchecked")
protected SectionHandler extensionHandler;
private boolean inHardware; private boolean inHardware;
private boolean inOs; private boolean inOs;
private boolean inNetwork; private boolean inSection;
private boolean inGuest; private boolean inExtensionSection;
private int depth;
public VirtualSystem getResult() { public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException {
VirtualSystem vs = new VirtualSystem(id, info, name, operatingSystem, hardware);
id = null;
info = null;
name = null;
operatingSystem = null;
hardware = Sets.newLinkedHashSet();
return vs;
}
public void startElement(String uri, String localName, String qName, Attributes attrs) {
Map<String, String> attributes = cleanseAttributes(attrs); Map<String, String> attributes = cleanseAttributes(attrs);
if (equalsOrSuffix(qName, "VirtualHardwareSection")) { depth++;
inHardware = true; if (depth == 2) {
} else if (equalsOrSuffix(qName, "OperatingSystemSection")) { if (equalsOrSuffix(qName, "VirtualHardwareSection")) {
inOs = true; inHardware = true;
} else if (equalsOrSuffix(qName, "NetworkConnectionSection")) { } else if (equalsOrSuffix(qName, "OperatingSystemSection")) {
inNetwork = true; inOs = true;
} else if (equalsOrSuffix(qName, "GuestCustomizationSection")) { } else if (extensionHandlers.containsKey(qName)) {
inGuest = true; inExtensionSection = true;
extensionHandler = extensionHandlers.get(qName).get();
} else if (qName.endsWith("Section")) {
inSection = true;
}
} }
if (inHardware) { if (inHardware) {
hardwareHandler.startElement(uri, localName, qName, attrs); hardwareHandler.startElement(uri, localName, qName, attrs);
} else if (inOs) { } else if (inOs) {
osHandler.startElement(uri, localName, qName, attrs); osHandler.startElement(uri, localName, qName, attrs);
} else if (inNetwork) { } else if (inExtensionSection) {
// TODO extensionHandler.startElement(uri, localName, qName, attrs);
} else if (inGuest) { } else if (inSection) {
// TODO defaultSectionHandler.startElement(uri, localName, qName, attrs);
} else if (equalsOrSuffix(qName, "VirtualSystem")) { } else if (equalsOrSuffix(qName, "VirtualSystem")) {
id = attributes.get("id"); builder.id(attributes.get("id"));
} }
} }
@Override @Override
public void endElement(String uri, String localName, String qName) { public void endElement(String uri, String localName, String qName) {
if (equalsOrSuffix(qName, "VirtualHardwareSection")) { depth--;
inHardware = false; if (depth == 1) {
hardware.add(hardwareHandler.getResult()); if (equalsOrSuffix(qName, "VirtualHardwareSection")) {
} else if (equalsOrSuffix(qName, "OperatingSystemSection")) { inHardware = false;
inOs = false; builder.hardwareSection(hardwareHandler.getResult());
operatingSystem = osHandler.getResult(); } else if (equalsOrSuffix(qName, "OperatingSystemSection")) {
} else if (equalsOrSuffix(qName, "NetworkConnectionSection")) { inOs = false;
inNetwork = false; builder.operatingSystemSection(osHandler.getResult());
// TODO } else if (extensionHandlers.containsKey(qName)) {
} else if (equalsOrSuffix(qName, "GuestCustomizationSection")) { builder.additionalSection(qName, extensionHandler.getResult());
inNetwork = false; inExtensionSection = false;
// TODO } else if (qName.endsWith("Section")) {
builder.additionalSection(qName, defaultSectionHandler.getResult());
inSection = false;
}
} }
if (inHardware) { if (inHardware) {
hardwareHandler.endElement(uri, localName, qName); hardwareHandler.endElement(uri, localName, qName);
} else if (inOs) { } else if (inOs) {
osHandler.endElement(uri, localName, qName); osHandler.endElement(uri, localName, qName);
} else if (inNetwork) { } else if (inExtensionSection) {
// TODO extensionHandler.endElement(uri, localName, qName);
} else if (inGuest) { } else if (inSection) {
// TODO defaultSectionHandler.endElement(uri, localName, qName);
} else if (equalsOrSuffix(qName, "Info")) { } else {
info = currentText.toString().trim(); if (equalsOrSuffix(qName, "Info")) {
} else if (equalsOrSuffix(qName, "Name")) { builder.info(currentOrNull(currentText));
name = currentText.toString().trim(); } else if (equalsOrSuffix(qName, "Name")) {
builder.name(currentOrNull(currentText));
}
super.endElement(uri, localName, qName);
} }
currentText = new StringBuilder();
} }
@Override @Override
public void characters(char ch[], int start, int length) { public void characters(char ch[], int start, int length) {
if (inHardware) if (inHardware) {
hardwareHandler.characters(ch, start, length); hardwareHandler.characters(ch, start, length);
else if (inOs) } else if (inOs) {
osHandler.characters(ch, start, length); osHandler.characters(ch, start, length);
else } else if (inExtensionSection) {
currentText.append(ch, start, length); extensionHandler.characters(ch, start, length);
} else if (inSection) {
defaultSectionHandler.characters(ch, start, length);
} else {
super.characters(ch, start, length);
}
} }
} }

View File

@ -75,8 +75,8 @@ public class VirtualSystemSettingDataHandlerTest extends BaseHandlerTest {
assertEquals(result.getId(), "Ubuntu1004"); assertEquals(result.getId(), "Ubuntu1004");
assertEquals(result.getName(), "Ubuntu1004"); assertEquals(result.getName(), "Ubuntu1004");
assertEquals(result.getInfo(), "A virtual machine:"); assertEquals(result.getInfo(), "A virtual machine:");
checkHardware(Iterables.get(result.getHardware(), 0)); checkHardware(Iterables.get(result.getVirtualHardwareSections(), 0));
checkOs(result.getOperatingSystem()); checkOs(result.getOperatingSystemSection());
} }
@Test(enabled = false) @Test(enabled = false)

View File

@ -0,0 +1,61 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.ovf.xml;
import static org.testng.Assert.assertEquals;
import java.io.InputStream;
import java.net.URI;
import org.jclouds.http.functions.ParseSax;
import org.jclouds.http.functions.ParseSax.Factory;
import org.jclouds.http.functions.config.SaxParserModule;
import org.jclouds.ovf.Disk;
import org.jclouds.ovf.DiskSection;
import org.testng.annotations.Test;
import com.google.inject.Guice;
import com.google.inject.Injector;
/**
* Tests behavior of {@code DiskSectionHandler}
*
* @author Adrian Cole
*/
@Test(groups = "unit")
public class DiskSectionHandlerTest {
public void test() {
InputStream is = getClass().getResourceAsStream("/disksection.xml");
Injector injector = Guice.createInjector(new SaxParserModule());
Factory factory = injector.getInstance(ParseSax.Factory.class);
DiskSection result = factory.create(injector.getInstance(DiskSectionHandler.class)).parse(is);
assertEquals(result.toString(), DiskSection.builder().info("Describes the set of virtual disks").disk(
Disk.builder().id("vmdisk1")
.fileRef("file1").capacity(8589934592l).populatedSize(3549324972l).format(
URI.create("http://www.vmware.com/interfaces/specifications/vmdk.html#sparse")).build()).disk(
Disk.builder().id("vmdisk2").capacity(536870912l).build()).disk(
Disk.builder().id("vmdisk3").capacityAllocationUnits("byte * 2^30").build())
.build().toString()
);
}
}

View File

@ -25,29 +25,28 @@ import org.jclouds.cim.xml.VirtualSystemSettingDataHandlerTest;
import org.jclouds.http.functions.ParseSax; import org.jclouds.http.functions.ParseSax;
import org.jclouds.http.functions.ParseSax.Factory; import org.jclouds.http.functions.ParseSax.Factory;
import org.jclouds.http.functions.config.SaxParserModule; import org.jclouds.http.functions.config.SaxParserModule;
import org.jclouds.ovf.OvfEnvelope; import org.jclouds.ovf.Envelope;
import org.jclouds.ovf.xml.OvfEnvelopeHandler;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.inject.Guice; import com.google.inject.Guice;
import com.google.inject.Injector; import com.google.inject.Injector;
/** /**
* Tests behavior of {@code OvfEnvelopeHandler} * Tests behavior of {@code EnvelopeHandler}
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
@Test(groups = "unit") @Test(groups = "unit")
public class OvfEnvelopeHandlerTest { public class EnvelopeHandlerTest {
public void testVCloud1_0() { public void testVCloud1_0() {
InputStream is = getClass().getResourceAsStream("/ovf.xml"); InputStream is = getClass().getResourceAsStream("/ovf.xml");
Injector injector = Guice.createInjector(new SaxParserModule()); Injector injector = Guice.createInjector(new SaxParserModule());
Factory factory = injector.getInstance(ParseSax.Factory.class); Factory factory = injector.getInstance(ParseSax.Factory.class);
OvfEnvelope result = factory.create(injector.getInstance(OvfEnvelopeHandler.class)).parse(is); Envelope result = factory.create(injector.getInstance(EnvelopeHandler.class)).parse(is);
checkOvfEnvelope(result); checkOvfEnvelope(result);
} }
static void checkOvfEnvelope(OvfEnvelope result) { static void checkOvfEnvelope(Envelope result) {
VirtualSystemSettingDataHandlerTest.checkVirtualSystem(result.getVirtualSystem()); VirtualSystemSettingDataHandlerTest.checkVirtualSystem(result.getVirtualSystem());
} }

View File

@ -0,0 +1,58 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.ovf.xml;
import static org.testng.Assert.assertEquals;
import java.io.InputStream;
import org.jclouds.http.functions.ParseSax;
import org.jclouds.http.functions.ParseSax.Factory;
import org.jclouds.http.functions.config.SaxParserModule;
import org.jclouds.ovf.Network;
import org.jclouds.ovf.NetworkSection;
import org.testng.annotations.Test;
import com.google.inject.Guice;
import com.google.inject.Injector;
/**
* Tests behavior of {@code NetworkSectionHandler}
*
* @author Adrian Cole
*/
@Test(groups = "unit")
public class NetworkSectionHandlerTest {
public void test() {
InputStream is = getClass().getResourceAsStream("/networksection.xml");
Injector injector = Guice.createInjector(new SaxParserModule());
Factory factory = injector.getInstance(ParseSax.Factory.class);
NetworkSection result = factory.create(injector.getInstance(NetworkSectionHandler.class)).parse(is);
assertEquals(result.toString(), NetworkSection.builder().info("List of logical networks used in the package")
.network(
Network.builder().name("red").description("The network the Red service is available on")
.build()).network(
Network.builder().name("blue").description("The network the Blue service is available on")
.build())
.build().toString()
);
}
}

View File

@ -0,0 +1,53 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.ovf.xml;
import static org.testng.Assert.assertEquals;
import java.io.InputStream;
import org.jclouds.http.functions.ParseSax;
import org.jclouds.http.functions.ParseSax.Factory;
import org.jclouds.http.functions.config.SaxParserModule;
import org.jclouds.ovf.OperatingSystemSection;
import org.testng.annotations.Test;
import com.google.inject.Guice;
import com.google.inject.Injector;
/**
* Tests behavior of {@code OperatingSystemSectionHandler}
*
* @author Adrian Cole
*/
@Test(groups = "unit")
public class OperatingSystemSectionHandlerTest {
public void test() {
InputStream is = getClass().getResourceAsStream("/operatingsystemsection.xml");
Injector injector = Guice.createInjector(new SaxParserModule());
Factory factory = injector.getInstance(ParseSax.Factory.class);
OperatingSystemSection result = factory.create(injector.getInstance(OperatingSystemSectionHandler.class)).parse(
is);
assertEquals(result.toString(), OperatingSystemSection.builder().info("Specifies the operating system installed")
.description("Microsoft Windows Server 2008").id(76).build().toString()
);
}
}

View File

@ -0,0 +1,10 @@
<DiskSection>
<Info>Describes the set of virtual disks</Info>
<Disk ovf:diskId="vmdisk1" ovf:fileRef="file1" ovf:capacity="8589934592"
ovf:populatedSize="3549324972"
ovf:format="http://www.vmware.com/interfaces/specifications/vmdk.html#sparse">
</Disk>
<Disk ovf:diskId="vmdisk2" ovf:capacity="536870912" />
<Disk ovf:diskId="vmdisk3" ovf:capacity="${disk.size}"
ovf:capacityAllocationUnits="byte * 2^30" />
</DiskSection>

View File

@ -0,0 +1,11 @@
<NetworkSection>
<Info>List of logical networks used in the package</Info>
<Network ovf:name="red">
<Description>The network the Red service is available on
</Description>
</Network>
<Network ovf:name="blue">
<Description>The network the Blue service is available on
</Description>
</Network>
</NetworkSection>

View File

@ -0,0 +1,4 @@
<OperatingSystemSection ovf:id="76">
<Info>Specifies the operating system installed</Info>
<Description>Microsoft Windows Server 2008</Description>
</OperatingSystemSection>

View File

@ -132,7 +132,7 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions
credentialsMap.put(key, pair); credentialsMap.put(key, pair);
} else { } else {
if (hasPublicKeyMaterial.apply(options)) { if (hasPublicKeyMaterial.apply(options)) {
logger.warn("to avoid creating extra keys in aws-ec2, use templateOption overrideLoginCredentialWith(id_rsa)"); logger.warn("to avoid creating temporary keys in aws-ec2, use templateOption overrideLoginCredentialWith(id_rsa)");
} }
return createUniqueKeyPairAndPutIntoMap(region, group); return createUniqueKeyPairAndPutIntoMap(region, group);
} }

View File

@ -56,6 +56,8 @@
<test.savvis-symphonyvpdc.apiversion>0.8</test.savvis-symphonyvpdc.apiversion> <test.savvis-symphonyvpdc.apiversion>0.8</test.savvis-symphonyvpdc.apiversion>
<test.savvis-symphonyvpdc.identity>FIXME</test.savvis-symphonyvpdc.identity> <test.savvis-symphonyvpdc.identity>FIXME</test.savvis-symphonyvpdc.identity>
<test.savvis-symphonyvpdc.credential>FIXME</test.savvis-symphonyvpdc.credential> <test.savvis-symphonyvpdc.credential>FIXME</test.savvis-symphonyvpdc.credential>
<test.savvis-symphonyvpdc.loginUser>FIXME</test.savvis-symphonyvpdc.loginUser>
<test.savvis-symphonyvpdc.loginPassword>FIXME</test.savvis-symphonyvpdc.loginPassword>
</properties> </properties>
<dependencies> <dependencies>
<dependency> <dependency>
@ -100,6 +102,11 @@
<version>${project.version}</version> <version>${project.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>com.jamesmurty.utils</groupId>
<artifactId>java-xmlbuilder</artifactId>
<version>0.3</version>
</dependency>
</dependencies> </dependencies>
<profiles> <profiles>
<profile> <profile>
@ -134,6 +141,14 @@
<name>test.savvis-symphonyvpdc.credential</name> <name>test.savvis-symphonyvpdc.credential</name>
<value>${test.savvis-symphonyvpdc.credential}</value> <value>${test.savvis-symphonyvpdc.credential}</value>
</property> </property>
<property>
<name>test.savvis-symphonyvpdc.loginUser</name>
<value>${test.savvis-symphonyvpdc.loginUser}</value>
</property>
<property>
<name>test.savvis-symphonyvpdc.loginPassword</name>
<value>${test.savvis-symphonyvpdc.loginPassword}</value>
</property>
<property> <property>
<name>jclouds.compute.blacklist-nodes</name> <name>jclouds.compute.blacklist-nodes</name>
<value>${jclouds.compute.blacklist-nodes}</value> <value>${jclouds.compute.blacklist-nodes}</value>

View File

@ -25,6 +25,7 @@ import org.jclouds.compute.domain.CIMOperatingSystem;
import org.jclouds.rest.annotations.Delegate; import org.jclouds.rest.annotations.Delegate;
import org.jclouds.savvis.vpdc.domain.Resource; import org.jclouds.savvis.vpdc.domain.Resource;
import org.jclouds.savvis.vpdc.features.BrowsingAsyncClient; import org.jclouds.savvis.vpdc.features.BrowsingAsyncClient;
import org.jclouds.savvis.vpdc.features.VMAsyncClient;
import org.jclouds.savvis.vpdc.internal.Org; import org.jclouds.savvis.vpdc.internal.Org;
import com.google.inject.Provides; import com.google.inject.Provides;
@ -45,6 +46,12 @@ public interface VPDCAsyncClient {
@Delegate @Delegate
BrowsingAsyncClient getBrowsingClient(); BrowsingAsyncClient getBrowsingClient();
/**
* Provides asynchronous access to VM Operation features.
*/
@Delegate
VMAsyncClient getVMClient();
/** /**
* *
* @return a listing of all orgs that the current user has access to. * @return a listing of all orgs that the current user has access to.
@ -54,8 +61,8 @@ public interface VPDCAsyncClient {
Set<Resource> listOrgs(); Set<Resource> listOrgs();
/** /**
* predefined by default in the classpath resource {@code * predefined by default in the classpath resource
* /savvis-symphonyvpdc/predefined_operatingsystems.json} * {@code /savvis-symphonyvpdc/predefined_operatingsystems.json}
* *
* @return the operating systems that are predefined in the provider * @return the operating systems that are predefined in the provider
* @see <a href="https://api.sandbox.symphonyvpdc.savvis.net/doc/spec/api/addSingleVM.html" /> * @see <a href="https://api.sandbox.symphonyvpdc.savvis.net/doc/spec/api/addSingleVM.html" />

View File

@ -27,6 +27,7 @@ import org.jclouds.concurrent.Timeout;
import org.jclouds.rest.annotations.Delegate; import org.jclouds.rest.annotations.Delegate;
import org.jclouds.savvis.vpdc.domain.Resource; import org.jclouds.savvis.vpdc.domain.Resource;
import org.jclouds.savvis.vpdc.features.BrowsingClient; import org.jclouds.savvis.vpdc.features.BrowsingClient;
import org.jclouds.savvis.vpdc.features.VMClient;
/** /**
* Provides synchronous access to VPDC. * Provides synchronous access to VPDC.
@ -45,6 +46,12 @@ public interface VPDCClient {
@Delegate @Delegate
BrowsingClient getBrowsingClient(); BrowsingClient getBrowsingClient();
/**
* Provides synchronous access to VM Operation features.
*/
@Delegate
VMClient getVMClient();
/** /**
* *
* @return a listing of all orgs that the current user has access to. * @return a listing of all orgs that the current user has access to.
@ -52,8 +59,8 @@ public interface VPDCClient {
Set<Resource> listOrgs(); Set<Resource> listOrgs();
/** /**
* predefined by default in the classpath resource {@code * predefined by default in the classpath resource
* /savvis-symphonyvpdc/predefined_operatingsystems.json} * {@code /savvis-symphonyvpdc/predefined_operatingsystems.json}
* *
* @return the operating systems that are predefined in the provider * @return the operating systems that are predefined in the provider
* @see <a href="https://api.sandbox.symphonyvpdc.savvis.net/doc/spec/api/addSingleVM.html" /> * @see <a href="https://api.sandbox.symphonyvpdc.savvis.net/doc/spec/api/addSingleVM.html" />

View File

@ -0,0 +1,201 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.savvis.vpdc.binders;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import javax.inject.Singleton;
import javax.ws.rs.core.MediaType;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import org.jclouds.cim.ResourceAllocationSettingData.ResourceType;
import org.jclouds.compute.domain.CIMOperatingSystem;
import org.jclouds.http.HttpRequest;
import org.jclouds.rest.MapBinder;
import org.jclouds.rest.binders.BindToStringPayload;
import org.jclouds.rest.internal.GeneratedHttpRequest;
import org.jclouds.savvis.vpdc.domain.VMSpec;
import com.jamesmurty.utils.XMLBuilder;
/**
*
* @author Adrian Cole
*
*/
@Singleton
public class BindVMSpecToXmlPayload extends BindToStringPayload implements MapBinder {
@Override
public <R extends HttpRequest> R bindToRequest(R request, Object toBind) {
throw new IllegalStateException("BindVMSpecToXmlPayload needs parameters");
}
protected VMSpec findSpecInArgsOrNull(GeneratedHttpRequest<?> gRequest) {
for (Object arg : gRequest.getArgs()) {
if (arg instanceof VMSpec) {
return (VMSpec) arg;
} else if (arg instanceof VMSpec[]) {
VMSpec[] configuration = (VMSpec[]) arg;
return (configuration.length > 0) ? configuration[0] : null;
}
}
return null;
}
@Override
public <R extends HttpRequest> R bindToRequest(R request, Map<String, String> postParams) {
checkArgument(checkNotNull(request, "request") instanceof GeneratedHttpRequest<?>,
"this binder is only valid for GeneratedHttpRequests!");
GeneratedHttpRequest<?> gRequest = (GeneratedHttpRequest<?>) request;
checkState(gRequest.getArgs() != null, "args should be initialized at this point");
request = super.bindToRequest(request,
generateXml(findSpecInArgsOrNull(gRequest), postParams.get("name"), postParams.get("networkName")));
request.getPayload().getContentMetadata().setContentType(MediaType.APPLICATION_XML);
return request;
}
public String generateXml(VMSpec spec, String name, String networkName) {
checkNotNull(spec, "VMSpec");
checkNotNull(name, "name");
checkNotNull(networkName, "networkName");
try {
XMLBuilder rootBuilder = buildRootForName(name);
addOperatingSystemSection(rootBuilder, spec.getOperatingSystem());
addVirtualHardwareSection(rootBuilder, name, networkName, spec);
Properties outputProperties = new Properties();
outputProperties.put(javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION, "yes");
return rootBuilder.asString(outputProperties);
} catch (Exception e) {
return null;
}
}
void addVirtualHardwareSection(XMLBuilder rootBuilder, String name, String networkName, VMSpec spec) {
XMLBuilder virtualHardwareSectionBuilder = rootBuilder.e("ovf:VirtualHardwareSection");
virtualHardwareSectionBuilder.e("ovf:Info").t("Virtual Hardware");
addSystem(virtualHardwareSectionBuilder, name);
addItems(virtualHardwareSectionBuilder, spec, networkName);
}
void addItems(XMLBuilder virtualHardwareSectionBuilder, VMSpec spec, String networkName) {
//todo make this work with fractional, which I think means setting speed to half
addCPU(virtualHardwareSectionBuilder, (int)spec.getProcessorCount());
addMemory(virtualHardwareSectionBuilder, spec.getMemoryInGig());
addNetwork(virtualHardwareSectionBuilder, networkName);
addDisks(virtualHardwareSectionBuilder, spec);
}
private void addSystem(XMLBuilder virtualHardwareSectionBuilder, String name) {
XMLBuilder systemBuilder = virtualHardwareSectionBuilder.e("ovf:System");
systemBuilder.e("vssd:Description").t("Virtual Hardware Family");
systemBuilder.e("vssd:ElementName").t(name);
systemBuilder.e("vssd:InstanceID").t("1");
systemBuilder.e("vssd:VirtualSystemIdentifier").t(name);
}
private void addOperatingSystemSection(XMLBuilder rootBuilder, CIMOperatingSystem operatingSystem) {
XMLBuilder sectionBuilder = rootBuilder.e("ovf:OperatingSystemSection").a("ovf:id",
operatingSystem.getOsType().getCode() + "");
sectionBuilder.e("ovf:Info").t("Specifies the operating system installed");
sectionBuilder.e("ovf:Description").t(operatingSystem.getDescription());
}
private void addCPU(XMLBuilder sectionBuilder, int processorCount) {
XMLBuilder cpuBuilder = sectionBuilder.e("ovf:Item");
cpuBuilder.e("rasd:AllocationUnits").t("3 GHz");
cpuBuilder.e("rasd:Description").t("Number of Virtual CPUs");
cpuBuilder.e("rasd:ElementName").t(processorCount + " CPU");
cpuBuilder.e("rasd:InstanceID").t("1");
cpuBuilder.e("rasd:ResourceType").t(ResourceType.PROCESSOR.value());
cpuBuilder.e("rasd:VirtualQuantity").t(processorCount + "");
}
private void addMemory(XMLBuilder sectionBuilder, int memoryInGig) {
XMLBuilder memoryBuilder = sectionBuilder.e("ovf:Item");
memoryBuilder.e("rasd:AllocationUnits").t("Gigabytes");
memoryBuilder.e("rasd:Description").t("Memory Size");
memoryBuilder.e("rasd:ElementName").t("Memory");
memoryBuilder.e("rasd:InstanceID").t("2");
memoryBuilder.e("rasd:ResourceType").t(ResourceType.MEMORY.value());
memoryBuilder.e("rasd:VirtualQuantity").t(memoryInGig + "");
}
private void addNetwork(XMLBuilder sectionBuilder, String networkName) {
XMLBuilder networkBuilder = sectionBuilder.e("ovf:Item");
networkBuilder.e("rasd:Caption").t("false");
networkBuilder.e("rasd:Connection").t(networkName);
networkBuilder.e("rasd:ElementName").t("Network");
networkBuilder.e("rasd:InstanceID").t("3");
networkBuilder.e("rasd:ResourceType").t(ResourceType.ETHERNET_ADAPTER.value());
networkBuilder.e("rasd:VirtualQuantity").t("1");
}
private void addDisks(XMLBuilder sectionBuilder, VMSpec spec) {
XMLBuilder bootDiskBuilder = sectionBuilder.e("ovf:Item");
bootDiskBuilder.e("rasd:AllocationUnits").t("Gigabytes");
bootDiskBuilder.e("rasd:Caption").t("");
bootDiskBuilder.e("rasd:Description").t("Hard Disk");
bootDiskBuilder.e("rasd:ElementName").t(spec.getBootDeviceName());
bootDiskBuilder.e("rasd:HostResource").t("boot");
bootDiskBuilder.e("rasd:InstanceID").t("4");
bootDiskBuilder.e("rasd:ResourceType").t(ResourceType.BASE_PARTITIONABLE_UNIT.value());
bootDiskBuilder.e("rasd:VirtualQuantity").t(spec.getBootDiskSize() + "");
int instanceId = 5;
for (Entry<String, Integer> dataDisk : spec.getDataDiskDeviceNameToSizeInGig().entrySet()) {
XMLBuilder dataDiskBuilder = sectionBuilder.e("ovf:Item");
dataDiskBuilder.e("rasd:AllocationUnits").t("Gigabytes");
dataDiskBuilder.e("rasd:Caption").t("");
dataDiskBuilder.e("rasd:Description").t("Hard Disk");
dataDiskBuilder.e("rasd:ElementName").t(dataDisk.getKey());
dataDiskBuilder.e("rasd:HostResource").t("data");
dataDiskBuilder.e("rasd:InstanceID").t("" + instanceId++);
dataDiskBuilder.e("rasd:ResourceType").t(ResourceType.PARTITIONABLE_UNIT.value());
dataDiskBuilder.e("rasd:VirtualQuantity").t(dataDisk.getValue() + "");
}
}
protected XMLBuilder buildRootForName(String name) throws ParserConfigurationException, FactoryConfigurationError {
XMLBuilder rootBuilder = XMLBuilder.create("vApp:VApp")
.a("xmlns:common", "http://schemas.dmtf.org/wbem/wscim/1/common")
.a("xmlns:vApp", "http://www.vmware.com/vcloud/v0.8")
.a("xmlns:rasd", "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData")
.a("xmlns:vssd", "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData")
.a("xmlns:ovf", "http://schemas.dmtf.org/ovf/envelope/1").a("name", name)
.a("type", "application/vnd.vmware.vcloud.vApp+xml").a("href", "");
return rootBuilder;
}
protected String ifNullDefaultTo(String value, String defaultValue) {
return value != null ? value : checkNotNull(defaultValue, "defaultValue");
}
}

View File

@ -25,7 +25,7 @@ import javax.inject.Singleton;
import org.jclouds.compute.config.BaseComputeServiceContextModule; import org.jclouds.compute.config.BaseComputeServiceContextModule;
import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.NodeState;
import org.jclouds.savvis.vpdc.domain.VApp; import org.jclouds.savvis.vpdc.domain.VM;
import com.google.common.annotations.VisibleForTesting; import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
@ -38,15 +38,15 @@ import com.google.inject.Provides;
public class VPDCComputeServiceContextModule extends BaseComputeServiceContextModule { public class VPDCComputeServiceContextModule extends BaseComputeServiceContextModule {
@VisibleForTesting @VisibleForTesting
public static final Map<VApp.Status, NodeState> VAPPSTATUS_TO_NODESTATE = ImmutableMap public static final Map<VM.Status, NodeState> VAPPSTATUS_TO_NODESTATE = ImmutableMap
.<VApp.Status, NodeState> builder().put(VApp.Status.OFF, NodeState.SUSPENDED) .<VM.Status, NodeState> builder().put(VM.Status.OFF, NodeState.SUSPENDED)
.put(VApp.Status.ON, NodeState.RUNNING).put(VApp.Status.RESOLVED, NodeState.PENDING) .put(VM.Status.ON, NodeState.RUNNING).put(VM.Status.RESOLVED, NodeState.PENDING)
.put(VApp.Status.UNRECOGNIZED, NodeState.UNRECOGNIZED).put(VApp.Status.UNKNOWN, NodeState.UNRECOGNIZED) .put(VM.Status.UNRECOGNIZED, NodeState.UNRECOGNIZED).put(VM.Status.UNKNOWN, NodeState.UNRECOGNIZED)
.put(VApp.Status.SUSPENDED, NodeState.SUSPENDED).put(VApp.Status.UNRESOLVED, NodeState.PENDING).build(); .put(VM.Status.SUSPENDED, NodeState.SUSPENDED).put(VM.Status.UNRESOLVED, NodeState.PENDING).build();
@Singleton @Singleton
@Provides @Provides
protected Map<VApp.Status, NodeState> provideVAppStatusToNodeState() { protected Map<VM.Status, NodeState> provideVAppStatusToNodeState() {
return VAPPSTATUS_TO_NODESTATE; return VAPPSTATUS_TO_NODESTATE;
} }

View File

@ -53,6 +53,8 @@ import org.jclouds.savvis.vpdc.domain.Resource;
import org.jclouds.savvis.vpdc.domain.internal.VCloudSession; import org.jclouds.savvis.vpdc.domain.internal.VCloudSession;
import org.jclouds.savvis.vpdc.features.BrowsingAsyncClient; import org.jclouds.savvis.vpdc.features.BrowsingAsyncClient;
import org.jclouds.savvis.vpdc.features.BrowsingClient; import org.jclouds.savvis.vpdc.features.BrowsingClient;
import org.jclouds.savvis.vpdc.features.VMAsyncClient;
import org.jclouds.savvis.vpdc.features.VMClient;
import org.jclouds.savvis.vpdc.handlers.VPDCErrorHandler; import org.jclouds.savvis.vpdc.handlers.VPDCErrorHandler;
import org.jclouds.savvis.vpdc.internal.LoginAsyncClient; import org.jclouds.savvis.vpdc.internal.LoginAsyncClient;
import org.jclouds.savvis.vpdc.internal.VCloudToken; import org.jclouds.savvis.vpdc.internal.VCloudToken;
@ -89,7 +91,7 @@ public class VPDCRestClientModule extends RestClientModule<VPDCClient, VPDCAsync
@org.jclouds.savvis.vpdc.internal.Org @org.jclouds.savvis.vpdc.internal.Org
@Singleton @Singleton
protected Set<org.jclouds.savvis.vpdc.domain.Resource> provideOrgs(Supplier<VCloudSession> cache, protected Set<org.jclouds.savvis.vpdc.domain.Resource> provideOrgs(Supplier<VCloudSession> cache,
@Named(PROPERTY_IDENTITY) String user) { @Named(PROPERTY_IDENTITY) String user) {
VCloudSession discovery = cache.get(); VCloudSession discovery = cache.get();
checkState(discovery.getOrgs().size() > 0, "No orgs present for user: " + user); checkState(discovery.getOrgs().size() > 0, "No orgs present for user: " + user);
return discovery.getOrgs(); return discovery.getOrgs();
@ -107,13 +109,14 @@ public class VPDCRestClientModule extends RestClientModule<VPDCClient, VPDCAsync
@Provides @Provides
@Singleton @Singleton
protected Predicate<String> successTester(Injector injector, protected Predicate<String> successTester(Injector injector,
@Named(PROPERTY_VCLOUD_TIMEOUT_TASK_COMPLETED) long completed) { @Named(PROPERTY_VCLOUD_TIMEOUT_TASK_COMPLETED) long completed) {
return new RetryablePredicate<String>(injector.getInstance(TaskSuccess.class), completed); return new RetryablePredicate<String>(injector.getInstance(TaskSuccess.class), completed);
} }
public static final Map<Class<?>, Class<?>> DELEGATE_MAP = ImmutableMap.<Class<?>, Class<?>> builder()// public static final Map<Class<?>, Class<?>> DELEGATE_MAP = ImmutableMap.<Class<?>, Class<?>> builder()//
.put(BrowsingClient.class, BrowsingAsyncClient.class)// .put(BrowsingClient.class, BrowsingAsyncClient.class)//
.build(); .put(VMClient.class, VMAsyncClient.class)//
.build();
public VPDCRestClientModule() { public VPDCRestClientModule() {
super(VPDCClient.class, VPDCAsyncClient.class, DELEGATE_MAP); super(VPDCClient.class, VPDCAsyncClient.class, DELEGATE_MAP);
@ -122,31 +125,33 @@ public class VPDCRestClientModule extends RestClientModule<VPDCClient, VPDCAsync
@Singleton @Singleton
@Provides @Provides
protected Set<CIMOperatingSystem> provideOperatingSystems(Json json, @Provider String providerName) protected Set<CIMOperatingSystem> provideOperatingSystems(Json json, @Provider String providerName)
throws IOException { throws IOException {
return json.fromJson(Strings2.toStringAndClose(getClass().getResourceAsStream( return json.fromJson(
"/" + providerName + "/predefined_operatingsystems.json")), new TypeLiteral<Set<CIMOperatingSystem>>() { Strings2.toStringAndClose(getClass().getResourceAsStream(
}.getType()); "/" + providerName + "/predefined_operatingsystems.json")),
new TypeLiteral<Set<CIMOperatingSystem>>() {
}.getType());
} }
@Provides @Provides
@Singleton @Singleton
protected Supplier<VCloudSession> provideVCloudTokenCache(@Named(PROPERTY_SESSION_INTERVAL) long seconds, protected Supplier<VCloudSession> provideVCloudTokenCache(@Named(PROPERTY_SESSION_INTERVAL) long seconds,
final LoginAsyncClient login) { final LoginAsyncClient login) {
return new MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier<VCloudSession>(authException, seconds, return new MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier<VCloudSession>(authException, seconds,
new Supplier<VCloudSession>() { new Supplier<VCloudSession>() {
@Override @Override
public VCloudSession get() { public VCloudSession get() {
try { try {
return login.login().get(10, TimeUnit.SECONDS); return login.login().get(10, TimeUnit.SECONDS);
} catch (Exception e) { } catch (Exception e) {
propagate(e); propagate(e);
assert false : e; assert false : e;
return null; return null;
}
} }
}
}); });
} }
@Override @Override

View File

@ -95,78 +95,6 @@ public class FirewallRule extends Resource {
return this; return this;
} }
public boolean isEnabled() {
return isEnabled;
}
public void setEnabled(boolean isEnabled) {
this.isEnabled = isEnabled;
}
public String getFirewallType() {
return firewallType;
}
public void setFirewallType(String firewallType) {
this.firewallType = firewallType;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getDestination() {
return destination;
}
public void setDestination(String destination) {
this.destination = destination;
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
public String getPolicy() {
return policy;
}
public void setPolicy(String policy) {
this.policy = policy;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isLogged() {
return isLogged;
}
public void setLogged(boolean isLogged) {
this.isLogged = isLogged;
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public static Builder fromFirewallRule(FirewallRule in) { public static Builder fromFirewallRule(FirewallRule in) {
return new Builder().id(in.getId()).name(in.getName()).type(in.getType()).href(in.getHref()) return new Builder().id(in.getId()).name(in.getName()).type(in.getType()).href(in.getHref())
.firewallType(in.getFirewallType()).isEnabled(in.isEnabled()).source(in.getSource()) .firewallType(in.getFirewallType()).isEnabled(in.isEnabled()).source(in.getSource())
@ -196,15 +124,15 @@ public class FirewallRule extends Resource {
} }
private String firewallType; private final String firewallType;
private boolean isEnabled; private final boolean isEnabled;
private String source; private final String source;
private String destination; private final String destination;
private String port; private final String port;
private String policy; private final String policy;
private String description; private final String description;
private boolean isLogged; private final boolean isLogged;
private String protocol; private final String protocol;
public FirewallRule(String id, String name, String type, URI href, String firewallType, boolean isEnabled, public FirewallRule(String id, String name, String type, URI href, String firewallType, boolean isEnabled,
String source, String destination, String port, String policy, String description, boolean isLogged, String protocol) { String source, String destination, String port, String policy, String description, boolean isLogged, String protocol) {
@ -271,74 +199,38 @@ public class FirewallRule extends Resource {
return isEnabled; return isEnabled;
} }
public void setEnabled(boolean isEnabled) {
this.isEnabled = isEnabled;
}
public String getSource() { public String getSource() {
return source; return source;
} }
public void setSource(String source) {
this.source = source;
}
public String getDestination() { public String getDestination() {
return destination; return destination;
} }
public void setDestination(String destination) {
this.destination = destination;
}
public String getFirewallType() { public String getFirewallType() {
return firewallType; return firewallType;
} }
public void setFirewallType(String firewallType) {
this.firewallType = firewallType;
}
public String getPort() { public String getPort() {
return port; return port;
} }
public void setPort(String port) {
this.port = port;
}
public String getPolicy() { public String getPolicy() {
return policy; return policy;
} }
public void setPolicy(String policy) {
this.policy = policy;
}
public String getDescription() { public String getDescription() {
return description; return description;
} }
public void setDescription(String description) {
this.description = description;
}
public boolean isLogged() { public boolean isLogged() {
return isLogged; return isLogged;
} }
public void setLogged(boolean isLogged) {
this.isLogged = isLogged;
}
public String getProtocol() { public String getProtocol() {
return protocol; return protocol;
} }
public void setProtocol(String protocol) {
this.protocol = protocol;
}
@Override @Override
public String toString() { public String toString() {
return "[firewallType=" + firewallType + ", description=" + description + ", source=" + source + ", destination=" + destination return "[firewallType=" + firewallType + ", description=" + description + ", source=" + source + ", destination=" + destination

View File

@ -67,22 +67,6 @@ public class FirewallService extends Resource {
.isEnabled(in.isEnabled()).firewallRules(in.getFirewallRules()); .isEnabled(in.isEnabled()).firewallRules(in.getFirewallRules());
} }
public Set<FirewallRule> getFirewallRules() {
return firewallRules;
}
public void setFirewallRules(Set<FirewallRule> firewallRules) {
this.firewallRules = firewallRules;
}
public boolean isEnabled() {
return isEnabled;
}
public void setEnabled(boolean isEnabled) {
this.isEnabled = isEnabled;
}
@Override @Override
public Builder id(String id) { public Builder id(String id) {
return Builder.class.cast(super.id(id)); return Builder.class.cast(super.id(id));
@ -105,8 +89,8 @@ public class FirewallService extends Resource {
} }
private boolean isEnabled; private final boolean isEnabled;
private Set<FirewallRule> firewallRules; private final Set<FirewallRule> firewallRules;
public FirewallService(String id, String name, String type, URI href, boolean isEnabled, Set<FirewallRule> firewallRules) { public FirewallService(String id, String name, String type, URI href, boolean isEnabled, Set<FirewallRule> firewallRules) {
super(id, name, type, href); super(id, name, type, href);
@ -123,16 +107,8 @@ public class FirewallService extends Resource {
return firewallRules; return firewallRules;
} }
public void setFirewallRules(Set<FirewallRule> firewallRules) {
this.firewallRules = firewallRules;
}
public boolean isEnabled() { public boolean isEnabled() {
return isEnabled; return isEnabled;
} }
public void setEnabled(boolean isEnabled) {
this.isEnabled = isEnabled;
}
} }

View File

@ -1,209 +0,0 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <name@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.savvis.vpdc.domain;
import org.jclouds.cim.OSType;
import org.jclouds.compute.domain.OsFamily;
/**
* Savvis Operating System Specification
*
* @see <a href="https://api.sandbox.symphonyvpdc.savvis.net/doc/spec/api/addSingleVM.html" />
* @author Adrian Cole
*/
public class SavvisOperatingSystemSpecification {
public static Builder builder() {
return new Builder();
}
public static class Builder {
private int savvisId;
private int typeId;
private String name;
private OsFamily family;
private String description;
private boolean supportedBySavvis;
/**
* @see SavvisOperatingSystemSpecification#getSavvisId
*/
public Builder savvisId(int savvisId) {
this.savvisId = savvisId;
return this;
}
/**
* @see SavvisOperatingSystemSpecification#getTypeId
*/
public Builder typeId(int typeId) {
this.typeId = typeId;
return this;
}
/**
* @see SavvisOperatingSystemSpecification#getOsFamily
*/
public Builder family(OsFamily family) {
this.family = family;
return this;
}
/**
* @see SavvisOperatingSystemSpecification#getInfo
*/
public Builder name(String name) {
this.name = name;
return this;
}
/**
* @see SavvisOperatingSystemSpecification#getDescription
*/
public Builder description(String description) {
this.description = description;
return this;
}
/**
* @see SavvisOperatingSystemSpecification#isSupportedBySavvis
*/
public Builder supportedBySavvis(boolean supportedBySavvis) {
this.supportedBySavvis = supportedBySavvis;
return this;
}
public SavvisOperatingSystemSpecification build() {
return new SavvisOperatingSystemSpecification(savvisId, typeId, family, name, description, supportedBySavvis);
}
public Builder fromSavvisOperatingSystemSpecification(SavvisOperatingSystemSpecification in) {
return savvisId(in.getSavvisId()).typeId(in.getTypeId()).family(in.getFamily()).name(in.getName())
.description(in.getDescription()).supportedBySavvis(in.isSupportedBySavvis());
}
}
private final int savvisId;
private final int typeId;
private final OsFamily family;
private final String name;
private final String description;
private final boolean supportedBySavvis;
public SavvisOperatingSystemSpecification(int savvisId, int typeId, OsFamily family, String name,
String description, boolean supportedBySavvis) {
this.savvisId = savvisId;
this.typeId = typeId;
this.family = family;
this.name = name;
this.description = description;
this.supportedBySavvis = supportedBySavvis;
}
/**
* @return Internal name used by Savvis
*/
public int getSavvisId() {
return savvisId;
}
/**
*
* @return CIM OS Type Id
* @see OSType#getCode()
*/
public int getTypeId() {
return typeId;
}
/**
*
* @return the name of the OS
*/
public String getName() {
return name;
}
/**
*
* @return the operating system family
*/
public OsFamily getFamily() {
return family;
}
/**
*
* @return description
*/
public String getDescription() {
return description;
}
/**
*
* @return whether or not this operating system is supported by Savvis
*/
public boolean isSupportedBySavvis() {
return supportedBySavvis;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + typeId;
result = prime * result + savvisId;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
SavvisOperatingSystemSpecification other = (SavvisOperatingSystemSpecification) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (typeId != other.typeId)
return false;
if (savvisId != other.savvisId)
return false;
return true;
}
public Builder toBuilder() {
return builder().fromSavvisOperatingSystemSpecification(this);
}
@Override
public String toString() {
return String.format("[description=%s, family=%s, name=%s, typeId=%s, savvisId=%s, supportedBySavvis=%s]",
description, family, name, typeId, savvisId, supportedBySavvis);
}
}

View File

@ -18,7 +18,7 @@ import com.google.common.collect.Sets;
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
public class VApp extends Resource { public class VM extends Resource {
/** /**
* Objects such as vAppTemplate, vApp, and Vm have a status attribute whose value indicates the * Objects such as vAppTemplate, vApp, and Vm have a status attribute whose value indicates the
* state of the object. Status for an object, such as a vAppTemplate or vApp, whose Children (Vm * state of the object. Status for an object, such as a vAppTemplate or vApp, whose Children (Vm
@ -161,12 +161,12 @@ public class VApp extends Resource {
} }
@Override @Override
public VApp build() { public VM build() {
return new VApp(id, name, type, href, status, ipAddress, osType, osDescripton, networkSection, return new VM(id, name, type, href, status, ipAddress, osType, osDescripton, networkSection,
resourceAllocations); resourceAllocations);
} }
public static Builder fromVApp(VApp in) { public static Builder fromVApp(VM in) {
return new Builder().id(in.getId()).name(in.getName()).type(in.getType()).href(in.getHref()) return new Builder().id(in.getId()).name(in.getName()).type(in.getType()).href(in.getHref())
.status(in.getStatus()).ipAddress(in.getIpAddress()).osType(in.getOsType()) .status(in.getStatus()).ipAddress(in.getIpAddress()).osType(in.getOsType())
.networkSection(in.getNetworkSection()).resourceAllocations(in.getResourceAllocations()) .networkSection(in.getNetworkSection()).resourceAllocations(in.getResourceAllocations())
@ -202,7 +202,7 @@ public class VApp extends Resource {
private final NetworkSection networkSection; private final NetworkSection networkSection;
private final Set<ResourceAllocationSettingData> resourceAllocations; private final Set<ResourceAllocationSettingData> resourceAllocations;
public VApp(String id, String name, String type, URI href, Status status, String ipAddress, Integer osType, public VM(String id, String name, String type, URI href, Status status, String ipAddress, Integer osType,
String osDescripton, NetworkSection networkSection, Set<ResourceAllocationSettingData> resourceAllocations) { String osDescripton, NetworkSection networkSection, Set<ResourceAllocationSettingData> resourceAllocations) {
super(id, name, type, href); super(id, name, type, href);
this.status = status; this.status = status;

View File

@ -0,0 +1,214 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.savvis.vpdc.domain;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Map;
import org.jclouds.compute.domain.CIMOperatingSystem;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
/**
* A specification to launch a virtual machine
*
* @author Adrian Cole
*/
public class VMSpec {
public static Builder builder() {
return new Builder();
}
public static class Builder {
private CIMOperatingSystem operatingSystem;
// TODO docs suggest fractions are possible, but xml isn't accepted on add
private float processorCount = 1f;
private int memoryInGig = 1;
private String bootDeviceName = "/";
// TODO doesn't seem to be changeable
private int bootDriveSize = 25;
private Map<String, Integer> dataDriveDeviceNameToSizeInGig = Maps.newLinkedHashMap();
public Builder operatingSystem(CIMOperatingSystem operatingSystem) {
this.operatingSystem = checkNotNull(operatingSystem, "operatingSystem");
return this;
}
public Builder memoryInGig(int memoryInGig) {
checkArgument(memoryInGig > 0, "memoryInGig must be positive");
this.memoryInGig = memoryInGig;
return this;
}
public Builder processorCount(float processorCount) {
checkProcessorCount(processorCount);
this.processorCount = processorCount;
return this;
}
public Builder bootDeviceName(String bootDeviceName) {
this.bootDeviceName = checkNotNull(bootDeviceName, "bootDeviceName");
return this;
}
public Builder bootDiskSize(int bootDriveSize) {
checkArgument(bootDriveSize > 0, "bootDriveSize must be positive");
this.bootDriveSize = bootDriveSize;
return this;
}
public Builder addDataDrive(String dataDriveDeviceName, int sizeInGig) {
checkArgument(sizeInGig > 0, "sizeInGig must be positive");
this.dataDriveDeviceNameToSizeInGig.put(checkNotNull(dataDriveDeviceName, "dataDriveDeviceName"), sizeInGig);
return this;
}
public Builder addDataDrives(Map<String, Integer> dataDriveDeviceNameToSizeInGig) {
this.dataDriveDeviceNameToSizeInGig = ImmutableMap.copyOf(checkNotNull(dataDriveDeviceNameToSizeInGig,
"dataDriveDeviceNameToSizeInGig"));
return this;
}
public VMSpec build() {
return new VMSpec(operatingSystem, processorCount, memoryInGig, bootDeviceName, bootDriveSize,
dataDriveDeviceNameToSizeInGig);
}
public static Builder fromVMSpec(VMSpec in) {
return new Builder().operatingSystem(in.getOperatingSystem()).memoryInGig(in.getMemoryInGig())
.bootDeviceName(in.getBootDeviceName()).bootDiskSize(in.getBootDiskSize())
.addDataDrives(in.getDataDiskDeviceNameToSizeInGig()).processorCount(in.getProcessorCount());
}
}
static void checkProcessorCount(float processorCount) {
checkArgument(processorCount > 0, "processorCount must be positive and an increment of 0.5");
checkArgument(processorCount % .5 == 0, "processorCount must be an increment of 0.5");
}
private final CIMOperatingSystem operatingSystem;
private final float processorCount;
private final int memoryInGig;
private final String bootDeviceName;
private final int bootDriveSize;
private final Map<String, Integer> dataDriveDeviceNameToSizeInGig;
protected VMSpec(CIMOperatingSystem operatingSystem, float processorCount, int memoryInGig, String bootDeviceName,
int bootDriveSize, Map<String, Integer> dataDriveDeviceNameToSizeInGig) {
this.operatingSystem = checkNotNull(operatingSystem, "operatingSystem not specified");
checkProcessorCount(processorCount);
this.processorCount = processorCount;
checkArgument(memoryInGig > 0, "memoryInGig must be positive");
this.memoryInGig = memoryInGig;
this.bootDeviceName = checkNotNull(bootDeviceName, "bootDeviceName name not specified");
checkArgument(bootDriveSize > 0, "bootDriveSize must be positive");
this.bootDriveSize = bootDriveSize;
this.dataDriveDeviceNameToSizeInGig = ImmutableMap.copyOf(checkNotNull(dataDriveDeviceNameToSizeInGig,
"dataDriveDeviceNameToSizeInGig"));
}
public CIMOperatingSystem getOperatingSystem() {
return operatingSystem;
}
public float getProcessorCount() {
return processorCount;
}
public int getMemoryInGig() {
return memoryInGig;
}
public Builder toBuilder() {
return Builder.fromVMSpec(this);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((bootDeviceName == null) ? 0 : bootDeviceName.hashCode());
result = prime * result + bootDriveSize;
result = prime * result
+ ((dataDriveDeviceNameToSizeInGig == null) ? 0 : dataDriveDeviceNameToSizeInGig.hashCode());
result = prime * result + memoryInGig;
result = prime * result + ((operatingSystem == null) ? 0 : operatingSystem.hashCode());
result = prime * result + Float.floatToIntBits(processorCount);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
VMSpec other = (VMSpec) obj;
if (bootDeviceName == null) {
if (other.bootDeviceName != null)
return false;
} else if (!bootDeviceName.equals(other.bootDeviceName))
return false;
if (bootDriveSize != other.bootDriveSize)
return false;
if (dataDriveDeviceNameToSizeInGig == null) {
if (other.dataDriveDeviceNameToSizeInGig != null)
return false;
} else if (!dataDriveDeviceNameToSizeInGig.equals(other.dataDriveDeviceNameToSizeInGig))
return false;
if (memoryInGig != other.memoryInGig)
return false;
if (operatingSystem == null) {
if (other.operatingSystem != null)
return false;
} else if (!operatingSystem.equals(other.operatingSystem))
return false;
if (Float.floatToIntBits(processorCount) != Float.floatToIntBits(other.processorCount))
return false;
return true;
}
public String getBootDeviceName() {
return bootDeviceName;
}
public int getBootDiskSize() {
return bootDriveSize;
}
public Map<String, Integer> getDataDiskDeviceNameToSizeInGig() {
return dataDriveDeviceNameToSizeInGig;
}
@Override
public String toString() {
return "[operatingSystem=" + operatingSystem + ", processorCount=" + processorCount + ", memoryInGig="
+ memoryInGig + ", bootDeviceName=" + bootDeviceName + ", bootDriveSize=" + bootDriveSize
+ ", dataDriveDeviceNameToSizeInGig=" + dataDriveDeviceNameToSizeInGig + "]";
}
}

View File

@ -1,3 +1,22 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.savvis.vpdc.domain.vapp; package org.jclouds.savvis.vpdc.domain.vapp;
/** /**

View File

@ -34,18 +34,18 @@ import org.jclouds.savvis.vpdc.domain.FirewallService;
import org.jclouds.savvis.vpdc.domain.Network; import org.jclouds.savvis.vpdc.domain.Network;
import org.jclouds.savvis.vpdc.domain.Org; import org.jclouds.savvis.vpdc.domain.Org;
import org.jclouds.savvis.vpdc.domain.Task; import org.jclouds.savvis.vpdc.domain.Task;
import org.jclouds.savvis.vpdc.domain.VApp;
import org.jclouds.savvis.vpdc.domain.VDC; import org.jclouds.savvis.vpdc.domain.VDC;
import org.jclouds.savvis.vpdc.domain.VM;
import org.jclouds.savvis.vpdc.filters.SetVCloudTokenCookie; import org.jclouds.savvis.vpdc.filters.SetVCloudTokenCookie;
import org.jclouds.savvis.vpdc.functions.DefaultOrgIfNull; import org.jclouds.savvis.vpdc.functions.DefaultOrgIfNull;
import org.jclouds.savvis.vpdc.options.BindGetVAppOptions; import org.jclouds.savvis.vpdc.options.BindGetVMOptions;
import org.jclouds.savvis.vpdc.options.GetVAppOptions; import org.jclouds.savvis.vpdc.options.GetVMOptions;
import org.jclouds.savvis.vpdc.xml.FirewallServiceHandler; import org.jclouds.savvis.vpdc.xml.FirewallServiceHandler;
import org.jclouds.savvis.vpdc.xml.NetworkHandler; import org.jclouds.savvis.vpdc.xml.NetworkHandler;
import org.jclouds.savvis.vpdc.xml.OrgHandler; import org.jclouds.savvis.vpdc.xml.OrgHandler;
import org.jclouds.savvis.vpdc.xml.TaskHandler; import org.jclouds.savvis.vpdc.xml.TaskHandler;
import org.jclouds.savvis.vpdc.xml.VAppHandler;
import org.jclouds.savvis.vpdc.xml.VDCHandler; import org.jclouds.savvis.vpdc.xml.VDCHandler;
import org.jclouds.savvis.vpdc.xml.VMHandler;
import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListenableFuture;
@ -82,27 +82,27 @@ public interface BrowsingAsyncClient {
@PathParam("vpdcId") String vpdcId); @PathParam("vpdcId") String vpdcId);
/** /**
* @see BrowsingClient#getNetworkInOrgAndVDC * @see BrowsingClient#getNetworkInVDC
*/ */
@GET @GET
@XMLResponseParser(NetworkHandler.class) @XMLResponseParser(NetworkHandler.class)
@ExceptionParser(ReturnNullOnNotFoundOr404.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class)
@Path("org/{billingSiteId}/vdc/{vpdcId}/network/{network-tier-name}") @Path("org/{billingSiteId}/vdc/{vpdcId}/network/{network-tier-name}")
ListenableFuture<Network> getNetworkInOrgAndVDC( ListenableFuture<Network> getNetworkInVDC(
@PathParam("billingSiteId") @Nullable @ParamParser(DefaultOrgIfNull.class) String billingSiteId, @PathParam("billingSiteId") @Nullable @ParamParser(DefaultOrgIfNull.class) String billingSiteId,
@PathParam("vpdcId") String vpdcId, @PathParam("network-tier-name") String networkTierName); @PathParam("vpdcId") String vpdcId, @PathParam("network-tier-name") String networkTierName);
/** /**
* @see BrowsingClient#getVAppInOrgAndVDC * @see BrowsingClient#getVMInVDC
*/ */
@GET @GET
@XMLResponseParser(VAppHandler.class) @XMLResponseParser(VMHandler.class)
@ExceptionParser(ReturnNullOnNotFoundOr404.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class)
@Path("org/{billingSiteId}/vdc/{vpdcId}/vApp/{vAppId}") @Path("org/{billingSiteId}/vdc/{vpdcId}/vApp/{vAppId}")
ListenableFuture<VApp> getVAppInOrgAndVDC( ListenableFuture<VM> getVMInVDC(
@PathParam("billingSiteId") @Nullable @ParamParser(DefaultOrgIfNull.class) String billingSiteId, @PathParam("billingSiteId") @Nullable @ParamParser(DefaultOrgIfNull.class) String billingSiteId,
@PathParam("vpdcId") String vpdcId, @PathParam("vAppId") String vAppId, @PathParam("vpdcId") String vpdcId, @PathParam("vAppId") String vAppId,
@BinderParam(BindGetVAppOptions.class) GetVAppOptions... options); @BinderParam(BindGetVMOptions.class) GetVMOptions... options);
/** /**
* @see BrowsingClient#getTask * @see BrowsingClient#getTask
@ -114,13 +114,13 @@ public interface BrowsingAsyncClient {
ListenableFuture<Task> getTask(@PathParam("taskId") String taskId); ListenableFuture<Task> getTask(@PathParam("taskId") String taskId);
/** /**
* @see BrowsingClient#getFirewallRules * @see BrowsingClient#listFirewallRules
*/ */
@GET @GET
@XMLResponseParser(FirewallServiceHandler.class) @XMLResponseParser(FirewallServiceHandler.class)
@ExceptionParser(ReturnNullOnNotFoundOr404.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class)
@Path("org/{billingSiteId}/vdc/{vpdcId}/FirewallService") @Path("org/{billingSiteId}/vdc/{vpdcId}/FirewallService")
ListenableFuture<FirewallService> getFirewallRules(@PathParam("billingSiteId") @Nullable @ParamParser(DefaultOrgIfNull.class) String billingSiteId, ListenableFuture<FirewallService> listFirewallRules(@PathParam("billingSiteId") @Nullable @ParamParser(DefaultOrgIfNull.class) String billingSiteId,
@PathParam("vpdcId") String vpdcId); @PathParam("vpdcId") String vpdcId);
} }

View File

@ -28,9 +28,9 @@ import org.jclouds.savvis.vpdc.domain.FirewallService;
import org.jclouds.savvis.vpdc.domain.Network; import org.jclouds.savvis.vpdc.domain.Network;
import org.jclouds.savvis.vpdc.domain.Org; import org.jclouds.savvis.vpdc.domain.Org;
import org.jclouds.savvis.vpdc.domain.Task; import org.jclouds.savvis.vpdc.domain.Task;
import org.jclouds.savvis.vpdc.domain.VApp; import org.jclouds.savvis.vpdc.domain.VM;
import org.jclouds.savvis.vpdc.domain.VDC; import org.jclouds.savvis.vpdc.domain.VDC;
import org.jclouds.savvis.vpdc.options.GetVAppOptions; import org.jclouds.savvis.vpdc.options.GetVMOptions;
/** /**
* Provides access to Symphony VPDC resources via their REST API. * Provides access to Symphony VPDC resources via their REST API.
@ -74,7 +74,7 @@ public interface BrowsingClient {
* @return network detail if it used any one deployed VM and NetworkConfigSection defines various * @return network detail if it used any one deployed VM and NetworkConfigSection defines various
* network features such NAT Public IP, Gateway and Netmask, or null if not present * network features such NAT Public IP, Gateway and Netmask, or null if not present
*/ */
Network getNetworkInOrgAndVDC(String billingSiteId, String vpdcId, String networkTierName); Network getNetworkInVDC(String billingSiteId, String vpdcId, String networkTierName);
/** /**
* VAPP is a software solution, the API returns details of virtual machine configuration such as * VAPP is a software solution, the API returns details of virtual machine configuration such as
@ -93,14 +93,14 @@ public interface BrowsingClient {
* machines, all of which are deployed, managed, and maintained as a unit, or null if not * machines, all of which are deployed, managed, and maintained as a unit, or null if not
* present * present
*/ */
VApp getVAppInOrgAndVDC(String billingSiteId, String vpdcId, String vAppId, GetVAppOptions... options); VM getVMInVDC(String billingSiteId, String vpdcId, String vAppId, GetVMOptions... options);
/** /**
* Gets an existing task. * Gets an existing task.
* *
* @param taskId * @param taskId
* task id * task id
* @return If the request is successful, caller could get the VApp/VMDK details as specified in * @return If the request is successful, caller could get the VM/VMDK details as specified in
* the result element and if the request is not successful, caller would get empty * the result element and if the request is not successful, caller would get empty
* VAPP/VMDK URL and respective validation (error) message. * VAPP/VMDK URL and respective validation (error) message.
*/ */
@ -118,6 +118,6 @@ public interface BrowsingClient {
* result element and if the request is not successful, caller would get empty * result element and if the request is not successful, caller would get empty
* rules list and respective validation (error) message. * rules list and respective validation (error) message.
*/ */
FirewallService getFirewallRules(String billingSiteId, String vpdcId); FirewallService listFirewallRules(String billingSiteId, String vpdcId);
} }

View File

@ -0,0 +1,78 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.savvis.vpdc.features;
import javax.annotation.Nullable;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import org.jclouds.rest.annotations.ExceptionParser;
import org.jclouds.rest.annotations.MapBinder;
import org.jclouds.rest.annotations.ParamParser;
import org.jclouds.rest.annotations.PayloadParam;
import org.jclouds.rest.annotations.RequestFilters;
import org.jclouds.rest.annotations.XMLResponseParser;
import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404;
import org.jclouds.savvis.vpdc.binders.BindVMSpecToXmlPayload;
import org.jclouds.savvis.vpdc.domain.Task;
import org.jclouds.savvis.vpdc.domain.VMSpec;
import org.jclouds.savvis.vpdc.filters.SetVCloudTokenCookie;
import org.jclouds.savvis.vpdc.functions.DefaultOrgIfNull;
import org.jclouds.savvis.vpdc.xml.TaskHandler;
import com.google.common.util.concurrent.ListenableFuture;
/**
* Provides access to Symphony VPDC resources via their REST API.
* <p/>
*
* @see <a href="https://api.sandbox.symphonyvpdc.savvis.net/doc/spec/api/index.html" />
* @author Adrian Cole
*/
@RequestFilters(SetVCloudTokenCookie.class)
@Path("v{jclouds.api-version}")
public interface VMAsyncClient {
/**
* @see VMClient#addVMIntoVDC
*/
@GET
@XMLResponseParser(TaskHandler.class)
@Path("org/{billingSiteId}/vdc/{vpdcId}/vApp/")
@MapBinder(BindVMSpecToXmlPayload.class)
ListenableFuture<Task> addVMIntoVDC(
@PathParam("billingSiteId") @Nullable @ParamParser(DefaultOrgIfNull.class) String billingSiteId,
@PathParam("vpdcId") String vpdcId, @PayloadParam("networkName") String networkTierName,
@PayloadParam("name") String vAppName, VMSpec spec);
/**
* @see VMClient#removeVMFromVDC
*/
@DELETE
@XMLResponseParser(TaskHandler.class)
@Path("org/{billingSiteId}/vdc/{vpdcId}/vApp/{vAppId}")
@ExceptionParser(ReturnNullOnNotFoundOr404.class)
ListenableFuture<Task> removeVMFromVDC(
@PathParam("billingSiteId") @Nullable @ParamParser(DefaultOrgIfNull.class) String billingSiteId,
@PathParam("vpdcId") String vpdcId, @PathParam("vAppId") String vAppId);
}

View File

@ -0,0 +1,72 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.savvis.vpdc.features;
import java.util.concurrent.TimeUnit;
import org.jclouds.concurrent.Timeout;
import org.jclouds.savvis.vpdc.domain.Task;
import org.jclouds.savvis.vpdc.domain.VMSpec;
/**
* Provides access to Symphony VPDC resources via their REST API.
* <p/>
*
* @see <a href="https://api.sandbox.symphonyvpdc.savvis.net/doc/spec/api/" />
* @author Adrian Cole
*/
@Timeout(duration = 300, timeUnit = TimeUnit.SECONDS)
public interface VMClient {
/**
* Add/Deploy new VM into VDC
*
* @param billingSiteId
* billing site Id, or null for default
* @param vpdcId
* vpdc Id
* @param networkTierName
* network tier name
* @param spec
* how to
*
* @return VM in progress
*/
Task addVMIntoVDC(String billingSiteId, String vpdcId, String networkTierName, String name, VMSpec spec);
/**
* Remove a VM
* <p/>
* <h4>Pre-conditions:</h4>
*
* <ul>
* <li>No snapshot has been created for the VM.</li>
* <li>For Balanced profile, the VM must not be associated with any firewall rule and/or included
* in a load balancing pool.</li>
* </ul>
*
* @param billingSiteId
* @param vpdcId
* @param vAppId
* @return
*/
Task removeVMFromVDC(String billingSiteId, String vpdcId, String vAppId);
}

View File

@ -15,19 +15,19 @@ import org.jclouds.rest.Binder;
* @author Adrian Cole * @author Adrian Cole
*/ */
@Singleton @Singleton
public class BindGetVAppOptions implements Binder { public class BindGetVMOptions implements Binder {
private final Provider<UriBuilder> uriBuilder; private final Provider<UriBuilder> uriBuilder;
@Inject @Inject
public BindGetVAppOptions(Provider<UriBuilder> uriBuilder) { public BindGetVMOptions(Provider<UriBuilder> uriBuilder) {
this.uriBuilder = uriBuilder; this.uriBuilder = uriBuilder;
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public <R extends HttpRequest> R bindToRequest(R request, Object input) { public <R extends HttpRequest> R bindToRequest(R request, Object input) {
checkArgument(input instanceof GetVAppOptions[], "this binder is only valid for GetVAppOptions!"); checkArgument(input instanceof GetVMOptions[], "this binder is only valid for GetVAppOptions!");
GetVAppOptions[] options = GetVAppOptions[].class.cast(input); GetVMOptions[] options = GetVMOptions[].class.cast(input);
if (options.length > 0 && options[0].isWithPowerState()) if (options.length > 0 && options[0].isWithPowerState())
return (R) request.toBuilder().endpoint( return (R) request.toBuilder().endpoint(
uriBuilder.get().uri(request.getEndpoint()).path("withpowerstate").build()).build(); uriBuilder.get().uri(request.getEndpoint()).path("withpowerstate").build()).build();

View File

@ -30,21 +30,21 @@ package org.jclouds.savvis.vpdc.options;
* import static org.jclouds.savvis.vpdc.options.GetVAppOptions.Builder.* * import static org.jclouds.savvis.vpdc.options.GetVAppOptions.Builder.*
* <p/> * <p/>
* *
* vApp = context.getApi().getBrowsingClient().getVAppInOrgAndVDC(orgId, vdcId, vAppId, withPowerState()); * vApp = context.getApi().getBrowsingClient().getVAppInVDC(orgId, vdcId, vAppId, withPowerState());
* <code> * <code>
* *
* @author Adrian Cole * @author Adrian Cole
* @see <a href= "https://api.sandbox.symphonyvpdc.savvis.net/doc/spec/api/getVAppPowerState.html" * @see <a href= "https://api.sandbox.symphonyvpdc.savvis.net/doc/spec/api/getVAppPowerState.html"
* /> * />
*/ */
public class GetVAppOptions { public class GetVMOptions {
public static final GetVAppOptions NONE = new GetVAppOptions(); public static final GetVMOptions NONE = new GetVMOptions();
private boolean withPowerState; private boolean withPowerState;
/** /**
* The VM State is the real time state. * The VM State is the real time state.
*/ */
public GetVAppOptions withPowerState() { public GetVMOptions withPowerState() {
this.withPowerState = true; this.withPowerState = true;
return this; return this;
} }
@ -56,10 +56,10 @@ public class GetVAppOptions {
public static class Builder { public static class Builder {
/** /**
* @see GetVAppOptions#withPowerState() * @see GetVMOptions#withPowerState()
*/ */
public static GetVAppOptions withPowerState() { public static GetVMOptions withPowerState() {
GetVAppOptions options = new GetVAppOptions(); GetVMOptions options = new GetVMOptions();
return options.withPowerState(); return options.withPowerState();
} }

View File

@ -58,10 +58,6 @@ public class FirewallServiceHandler extends ParseSax.HandlerWithResult<FirewallS
inFirewallRule = true; inFirewallRule = true;
firewallRuleHandler.startElement(uri, localName, qName, attrs); firewallRuleHandler.startElement(uri, localName, qName, attrs);
} }
else{
// firewallRuleHandler.startElement(uri, localName, qName, attrs);
}
} }
@Override @Override

View File

@ -29,7 +29,7 @@ import org.jclouds.cim.xml.ResourceAllocationSettingDataHandler;
import org.jclouds.http.functions.ParseSax; import org.jclouds.http.functions.ParseSax;
import org.jclouds.ovf.xml.NetworkSectionHandler; import org.jclouds.ovf.xml.NetworkSectionHandler;
import org.jclouds.savvis.vpdc.domain.Resource; import org.jclouds.savvis.vpdc.domain.Resource;
import org.jclouds.savvis.vpdc.domain.VApp; import org.jclouds.savvis.vpdc.domain.VM;
import org.jclouds.savvis.vpdc.util.Utils; import org.jclouds.savvis.vpdc.util.Utils;
import org.xml.sax.Attributes; import org.xml.sax.Attributes;
import org.xml.sax.SAXException; import org.xml.sax.SAXException;
@ -39,25 +39,25 @@ import com.google.common.collect.ImmutableMap;
/** /**
* @author Kedar Dave * @author Kedar Dave
*/ */
public class VAppHandler extends ParseSax.HandlerWithResult<VApp> { public class VMHandler extends ParseSax.HandlerWithResult<VM> {
protected StringBuilder currentText = new StringBuilder(); protected StringBuilder currentText = new StringBuilder();
private final NetworkSectionHandler networkSectionHandler; private final NetworkSectionHandler networkSectionHandler;
private final ResourceAllocationSettingDataHandler allocationHandler; private final ResourceAllocationSettingDataHandler allocationHandler;
@Inject @Inject
public VAppHandler(NetworkSectionHandler networkSectionHandler, ResourceAllocationSettingDataHandler allocationHandler) { public VMHandler(NetworkSectionHandler networkSectionHandler, ResourceAllocationSettingDataHandler allocationHandler) {
this.networkSectionHandler = networkSectionHandler; this.networkSectionHandler = networkSectionHandler;
this.allocationHandler = allocationHandler; this.allocationHandler = allocationHandler;
} }
private VApp.Builder builder = VApp.builder(); private VM.Builder builder = VM.builder();
protected boolean inOs; protected boolean inOs;
public VApp getResult() { public VM getResult() {
try { try {
return builder.build(); return builder.build();
} finally { } finally {
builder = VApp.builder(); builder = VM.builder();
} }
} }
@ -70,7 +70,7 @@ public class VAppHandler extends ParseSax.HandlerWithResult<VApp> {
.put("href", getRequest().getEndpoint().toASCIIString()).build(); .put("href", getRequest().getEndpoint().toASCIIString()).build();
Resource vApp = newResource(attributes); Resource vApp = newResource(attributes);
builder.name(vApp.getName()).type(vApp.getType()).id(vApp.getId()).href(vApp.getHref()); builder.name(vApp.getName()).type(vApp.getType()).id(vApp.getId()).href(vApp.getHref());
builder.status(VApp.Status.fromValue(attributes.get("status"))); builder.status(VM.Status.fromValue(attributes.get("status")));
} else if (qName.endsWith("OperatingSystemSection")) { } else if (qName.endsWith("OperatingSystemSection")) {
inOs = true; inOs = true;
if (attributes.containsKey("id")) if (attributes.containsKey("id"))

View File

@ -16,7 +16,7 @@
"osType": "RHEL" "osType": "RHEL"
}, },
{ {
"family": "RHEL_64", "family": "RHEL",
"name": "rhel5_64Guest", "name": "rhel5_64Guest",
"version": "5", "version": "5",
"description": "Red Hat Enterprise Linux 5.x 64bit", "description": "Red Hat Enterprise Linux 5.x 64bit",

View File

@ -45,6 +45,7 @@ public class VPDCAsyncClientTest extends BaseVPDCAsyncClientTest<VPDCAsyncClient
public void testSync() { public void testSync() {
assert syncClient.getBrowsingClient() != null; assert syncClient.getBrowsingClient() != null;
assert syncClient.getVMClient() != null;
assertEquals(syncClient.listOrgs().size(), 1); assertEquals(syncClient.listOrgs().size(), 1);
assertEquals(syncClient.listPredefinedOperatingSystems().size(), 3); assertEquals(syncClient.listPredefinedOperatingSystems().size(), 3);
@ -52,6 +53,7 @@ public class VPDCAsyncClientTest extends BaseVPDCAsyncClientTest<VPDCAsyncClient
public void testAsync() { public void testAsync() {
assert asyncClient.getBrowsingClient() != null; assert asyncClient.getBrowsingClient() != null;
assert asyncClient.getVMClient() != null;
assertEquals(asyncClient.listOrgs().size(), 1); assertEquals(asyncClient.listOrgs().size(), 1);
assertEquals(asyncClient.listPredefinedOperatingSystems().size(), 3); assertEquals(asyncClient.listPredefinedOperatingSystems().size(), 3);

View File

@ -0,0 +1,66 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.savvis.vpdc.binders;
import static org.testng.Assert.assertEquals;
import java.io.IOException;
import java.util.Set;
import org.jclouds.cim.OSType;
import org.jclouds.compute.domain.CIMOperatingSystem;
import org.jclouds.savvis.vpdc.domain.VMSpec;
import org.jclouds.util.Strings2;
import org.testng.annotations.Test;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.gson.Gson;
import com.google.inject.TypeLiteral;
/**
* Tests behavior of {@code BindVMSpecToXmlPayload}
*
* @author Adrian Cole
*/
@Test(groups = "unit")
public class BindVMSpecToXmlPayloadTest {
public void test() throws IOException {
CIMOperatingSystem os = Iterables.find(new Gson().<Set<CIMOperatingSystem>> fromJson(
Strings2.toStringAndClose(getClass().getResourceAsStream(
"/savvis-symphonyvpdc/predefined_operatingsystems.json")),
new TypeLiteral<Set<CIMOperatingSystem>>() {
}.getType()), new Predicate<CIMOperatingSystem>() {
@Override
public boolean apply(CIMOperatingSystem arg0) {
return arg0.getOsType() == OSType.RHEL_64;
}
});
String expected = Strings2.toStringAndClose(getClass().getResourceAsStream("/vm-default.xml"));
VMSpec spec = VMSpec.builder().operatingSystem(os).build();
assertEquals(new BindVMSpecToXmlPayload().generateXml(spec, "DemoHost-1", "VM Tier01"), expected);
}
}

View File

@ -28,12 +28,16 @@ import org.jclouds.rest.RestContext;
import org.jclouds.rest.RestContextFactory; import org.jclouds.rest.RestContextFactory;
import org.jclouds.savvis.vpdc.VPDCAsyncClient; import org.jclouds.savvis.vpdc.VPDCAsyncClient;
import org.jclouds.savvis.vpdc.VPDCClient; import org.jclouds.savvis.vpdc.VPDCClient;
import org.jclouds.ssh.jsch.config.JschSshClientModule;
import org.testng.annotations.AfterGroups; import org.testng.annotations.AfterGroups;
import org.testng.annotations.BeforeGroups; import org.testng.annotations.BeforeGroups;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Module; import com.google.inject.Module;
import com.google.inject.TypeLiteral;
/** /**
* Tests behavior of {@code VPDCClient} * Tests behavior of {@code VPDCClient}
@ -49,11 +53,12 @@ public class BaseVPDCClientLiveTest {
protected String credential; protected String credential;
protected String endpoint; protected String endpoint;
protected String apiversion; protected String apiversion;
protected Injector injector;
protected void setupCredentials() { protected void setupCredentials() {
identity = checkNotNull(System.getProperty("test." + provider + ".identity"), "test." + provider + ".identity"); identity = checkNotNull(System.getProperty("test." + provider + ".identity"), "test." + provider + ".identity");
credential = checkNotNull(System.getProperty("test." + provider + ".credential"), "test." + provider credential = checkNotNull(System.getProperty("test." + provider + ".credential"), "test." + provider
+ ".credential"); + ".credential");
endpoint = System.getProperty("test." + provider + ".endpoint"); endpoint = System.getProperty("test." + provider + ".endpoint");
apiversion = System.getProperty("test." + provider + ".apiversion"); apiversion = System.getProperty("test." + provider + ".apiversion");
} }
@ -73,8 +78,13 @@ public class BaseVPDCClientLiveTest {
public void setupClient() { public void setupClient() {
setupCredentials(); setupCredentials();
Properties overrides = setupProperties(); Properties overrides = setupProperties();
context = new RestContextFactory().createContext(provider, ImmutableSet.<Module> of(new Log4JLoggingModule()), // context = new RestContextFactory().createContext(provider, ImmutableSet.<Module> of(new
overrides); // Log4JLoggingModule()),
// overrides);
injector = new RestContextFactory().createContextBuilder(provider,
ImmutableSet.<Module> of(new Log4JLoggingModule(), new JschSshClientModule()), overrides).buildInjector();
context = injector.getInstance(Key.get(new TypeLiteral<RestContext<VPDCClient, VPDCAsyncClient>>() {
}));
} }
@AfterGroups(groups = "live") @AfterGroups(groups = "live")

View File

@ -26,12 +26,13 @@ import org.jclouds.http.HttpRequest;
import org.jclouds.http.functions.ParseSax; import org.jclouds.http.functions.ParseSax;
import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404;
import org.jclouds.rest.internal.RestAnnotationProcessor; import org.jclouds.rest.internal.RestAnnotationProcessor;
import org.jclouds.savvis.vpdc.options.GetVAppOptions; import org.jclouds.savvis.vpdc.options.GetVMOptions;
import org.jclouds.savvis.vpdc.xml.FirewallServiceHandler;
import org.jclouds.savvis.vpdc.xml.NetworkHandler; import org.jclouds.savvis.vpdc.xml.NetworkHandler;
import org.jclouds.savvis.vpdc.xml.OrgHandler; import org.jclouds.savvis.vpdc.xml.OrgHandler;
import org.jclouds.savvis.vpdc.xml.TaskHandler; import org.jclouds.savvis.vpdc.xml.TaskHandler;
import org.jclouds.savvis.vpdc.xml.VAppHandler;
import org.jclouds.savvis.vpdc.xml.VDCHandler; import org.jclouds.savvis.vpdc.xml.VDCHandler;
import org.jclouds.savvis.vpdc.xml.VMHandler;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.inject.TypeLiteral; import com.google.inject.TypeLiteral;
@ -105,7 +106,7 @@ public class BrowsingAsyncClientTest extends BaseVPDCAsyncClientTest<BrowsingAsy
} }
public void testNetwork() throws SecurityException, NoSuchMethodException, IOException { public void testNetwork() throws SecurityException, NoSuchMethodException, IOException {
Method method = BrowsingAsyncClient.class.getMethod("getNetworkInOrgAndVDC", String.class, String.class, Method method = BrowsingAsyncClient.class.getMethod("getNetworkInVDC", String.class, String.class,
String.class); String.class);
HttpRequest request = processor.createRequest(method, "11", "22", "VM-Tier01"); HttpRequest request = processor.createRequest(method, "11", "22", "VM-Tier01");
@ -122,7 +123,7 @@ public class BrowsingAsyncClientTest extends BaseVPDCAsyncClientTest<BrowsingAsy
} }
public void testNetworkWhenOrgNull() throws SecurityException, NoSuchMethodException, IOException { public void testNetworkWhenOrgNull() throws SecurityException, NoSuchMethodException, IOException {
Method method = BrowsingAsyncClient.class.getMethod("getNetworkInOrgAndVDC", String.class, String.class, Method method = BrowsingAsyncClient.class.getMethod("getNetworkInVDC", String.class, String.class,
String.class); String.class);
HttpRequest request = processor.createRequest(method, (String) null, "22", "VM-Tier01"); HttpRequest request = processor.createRequest(method, (String) null, "22", "VM-Tier01");
@ -138,9 +139,9 @@ public class BrowsingAsyncClientTest extends BaseVPDCAsyncClientTest<BrowsingAsy
checkFilters(request); checkFilters(request);
} }
public void testVApp() throws SecurityException, NoSuchMethodException, IOException { public void testVM() throws SecurityException, NoSuchMethodException, IOException {
Method method = BrowsingAsyncClient.class.getMethod("getVAppInOrgAndVDC", String.class, String.class, Method method = BrowsingAsyncClient.class.getMethod("getVMInVDC", String.class, String.class,
String.class, GetVAppOptions[].class); String.class, GetVMOptions[].class);
HttpRequest request = processor.createRequest(method, "11", "22", "VM-Tier01"); HttpRequest request = processor.createRequest(method, "11", "22", "VM-Tier01");
assertRequestLineEquals(request, assertRequestLineEquals(request,
@ -149,16 +150,16 @@ public class BrowsingAsyncClientTest extends BaseVPDCAsyncClientTest<BrowsingAsy
assertPayloadEquals(request, null, null, false); assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, ParseSax.class); assertResponseParserClassEquals(method, request, ParseSax.class);
assertSaxResponseParserClassEquals(method, VAppHandler.class); assertSaxResponseParserClassEquals(method, VMHandler.class);
assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class);
checkFilters(request); checkFilters(request);
} }
public void testVAppWithPowerState() throws SecurityException, NoSuchMethodException, IOException { public void testVMWithPowerState() throws SecurityException, NoSuchMethodException, IOException {
Method method = BrowsingAsyncClient.class.getMethod("getVAppInOrgAndVDC", String.class, String.class, Method method = BrowsingAsyncClient.class.getMethod("getVMInVDC", String.class, String.class,
String.class, GetVAppOptions[].class); String.class, GetVMOptions[].class);
HttpRequest request = processor.createRequest(method, "11", "22", "VM-Tier01", GetVAppOptions.Builder HttpRequest request = processor.createRequest(method, "11", "22", "VM-Tier01", GetVMOptions.Builder
.withPowerState()); .withPowerState());
assertRequestLineEquals(request, assertRequestLineEquals(request,
@ -167,15 +168,15 @@ public class BrowsingAsyncClientTest extends BaseVPDCAsyncClientTest<BrowsingAsy
assertPayloadEquals(request, null, null, false); assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, ParseSax.class); assertResponseParserClassEquals(method, request, ParseSax.class);
assertSaxResponseParserClassEquals(method, VAppHandler.class); assertSaxResponseParserClassEquals(method, VMHandler.class);
assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class);
checkFilters(request); checkFilters(request);
} }
public void testVAppWhenOrgNull() throws SecurityException, NoSuchMethodException, IOException { public void testVMWhenOrgNull() throws SecurityException, NoSuchMethodException, IOException {
Method method = BrowsingAsyncClient.class.getMethod("getVAppInOrgAndVDC", String.class, String.class, Method method = BrowsingAsyncClient.class.getMethod("getVMInVDC", String.class, String.class,
String.class, GetVAppOptions[].class); String.class, GetVMOptions[].class);
HttpRequest request = processor.createRequest(method, (String) null, "22", "VM-Tier01"); HttpRequest request = processor.createRequest(method, (String) null, "22", "VM-Tier01");
assertRequestLineEquals(request, assertRequestLineEquals(request,
@ -184,7 +185,7 @@ public class BrowsingAsyncClientTest extends BaseVPDCAsyncClientTest<BrowsingAsy
assertPayloadEquals(request, null, null, false); assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, ParseSax.class); assertResponseParserClassEquals(method, request, ParseSax.class);
assertSaxResponseParserClassEquals(method, VAppHandler.class); assertSaxResponseParserClassEquals(method, VMHandler.class);
assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class);
checkFilters(request); checkFilters(request);
@ -205,6 +206,22 @@ public class BrowsingAsyncClientTest extends BaseVPDCAsyncClientTest<BrowsingAsy
checkFilters(request); checkFilters(request);
} }
public void testListFirewallRules() throws SecurityException, NoSuchMethodException, IOException {
Method method = BrowsingAsyncClient.class.getMethod("listFirewallRules", String.class, String.class);
HttpRequest request = processor.createRequest(method, "11", "22");
assertRequestLineEquals(request,
"GET https://api.symphonyvpdc.savvis.net/rest/api/v0.8/org/11/vdc/22/FirewallService HTTP/1.1");
assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, ParseSax.class);
assertSaxResponseParserClassEquals(method, FirewallServiceHandler.class);
assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class);
checkFilters(request);
}
@Override @Override
protected TypeLiteral<RestAnnotationProcessor<BrowsingAsyncClient>> createTypeLiteral() { protected TypeLiteral<RestAnnotationProcessor<BrowsingAsyncClient>> createTypeLiteral() {
return new TypeLiteral<RestAnnotationProcessor<BrowsingAsyncClient>>() { return new TypeLiteral<RestAnnotationProcessor<BrowsingAsyncClient>>() {

View File

@ -19,7 +19,7 @@
package org.jclouds.savvis.vpdc.features; package org.jclouds.savvis.vpdc.features;
import static org.jclouds.savvis.vpdc.options.GetVAppOptions.Builder.withPowerState; import static org.jclouds.savvis.vpdc.options.GetVMOptions.Builder.withPowerState;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNotNull;
@ -31,7 +31,7 @@ import org.jclouds.savvis.vpdc.domain.FirewallService;
import org.jclouds.savvis.vpdc.domain.Network; import org.jclouds.savvis.vpdc.domain.Network;
import org.jclouds.savvis.vpdc.domain.Org; import org.jclouds.savvis.vpdc.domain.Org;
import org.jclouds.savvis.vpdc.domain.Resource; import org.jclouds.savvis.vpdc.domain.Resource;
import org.jclouds.savvis.vpdc.domain.VApp; import org.jclouds.savvis.vpdc.domain.VM;
import org.jclouds.savvis.vpdc.domain.VDC; import org.jclouds.savvis.vpdc.domain.VDC;
import org.jclouds.savvis.vpdc.reference.VCloudMediaType; import org.jclouds.savvis.vpdc.reference.VCloudMediaType;
import org.testng.annotations.BeforeGroups; import org.testng.annotations.BeforeGroups;
@ -65,7 +65,7 @@ public class BrowsingClientLiveTest extends BaseVPDCClientLiveTest {
assertEquals(response.getType(), null); assertEquals(response.getType(), null);
assert response.getImages().size() >= 0; assert response.getImages().size() >= 0;
assert response.getDescription() != null; assert response.getDescription() != null;
assert response.getVDCs().size() >= 1; assert response.getVDCs().size() >= 0;
assertEquals(client.getOrg(response.getId()).toString(), response.toString()); assertEquals(client.getOrg(response.getId()).toString(), response.toString());
} }
} }
@ -97,7 +97,7 @@ public class BrowsingClientLiveTest extends BaseVPDCClientLiveTest {
for (Resource vdc : org.getVDCs()) { for (Resource vdc : org.getVDCs()) {
VDC VDC = client.getVDCInOrg(org.getId(), vdc.getId()); VDC VDC = client.getVDCInOrg(org.getId(), vdc.getId());
for (Resource vApp : VDC.getAvailableNetworks()) { for (Resource vApp : VDC.getAvailableNetworks()) {
Network response = client.getNetworkInOrgAndVDC(org.getId(), vdc.getId(), vApp.getId()); Network response = client.getNetworkInVDC(org.getId(), vdc.getId(), vApp.getId());
assertNotNull(response); assertNotNull(response);
assertNotNull(response.getId()); assertNotNull(response.getId());
assertNotNull(response.getHref()); assertNotNull(response.getHref());
@ -106,7 +106,7 @@ public class BrowsingClientLiveTest extends BaseVPDCClientLiveTest {
assertNotNull(response.getNetmask()); assertNotNull(response.getNetmask());
assertNotNull(response.getGateway()); assertNotNull(response.getGateway());
assertNotNull(response.getInternalToExternalNATRules()); assertNotNull(response.getInternalToExternalNATRules());
assertEquals(client.getNetworkInOrgAndVDC(org.getId(), vdc.getId(), response.getId()).toString(), assertEquals(client.getNetworkInVDC(org.getId(), vdc.getId(), response.getId()).toString(),
response.toString()); response.toString());
} }
} }
@ -114,7 +114,7 @@ public class BrowsingClientLiveTest extends BaseVPDCClientLiveTest {
} }
@Test @Test
public void testVApp() throws Exception { public void testVM() throws Exception {
for (Resource org1 : context.getApi().listOrgs()) { for (Resource org1 : context.getApi().listOrgs()) {
Org org = client.getOrg(org1.getId()); Org org = client.getOrg(org1.getId());
for (Resource vdc : org.getVDCs()) { for (Resource vdc : org.getVDCs()) {
@ -127,7 +127,7 @@ public class BrowsingClientLiveTest extends BaseVPDCClientLiveTest {
} }
})) { })) {
VApp response = client.getVAppInOrgAndVDC(org.getId(), vdc.getId(), vApp.getId()); VM response = client.getVMInVDC(org.getId(), vdc.getId(), vApp.getId());
assertNotNull(response); assertNotNull(response);
assertNotNull(response.getId()); assertNotNull(response.getId());
assertNotNull(response.getHref()); assertNotNull(response.getHref());
@ -140,7 +140,7 @@ public class BrowsingClientLiveTest extends BaseVPDCClientLiveTest {
assertNotNull(response.getNetworkSection()); assertNotNull(response.getNetworkSection());
assertNotNull(response.getResourceAllocations()); assertNotNull(response.getResourceAllocations());
// power state is the only thing that should change // power state is the only thing that should change
assertEquals(client.getVAppInOrgAndVDC(org.getId(), vdc.getId(), response.getId(), withPowerState()) assertEquals(client.getVMInVDC(org.getId(), vdc.getId(), response.getId(), withPowerState())
.toString().replaceFirst("status=[A-Z]+", ""), response.toString().replaceFirst( .toString().replaceFirst("status=[A-Z]+", ""), response.toString().replaceFirst(
"status=[A-Z]+", "")); "status=[A-Z]+", ""));
} }
@ -154,7 +154,7 @@ public class BrowsingClientLiveTest extends BaseVPDCClientLiveTest {
for (Resource org1 : context.getApi().listOrgs()) { for (Resource org1 : context.getApi().listOrgs()) {
Org org = client.getOrg(org1.getId()); Org org = client.getOrg(org1.getId());
for (Resource vdc : org.getVDCs()) { for (Resource vdc : org.getVDCs()) {
FirewallService response = client.getFirewallRules(org.getId(), vdc.getId()); FirewallService response = client.listFirewallRules(org.getId(), vdc.getId());
Set<FirewallRule> firewallRules = response.getFirewallRules(); Set<FirewallRule> firewallRules = response.getFirewallRules();
if(firewallRules != null){ if(firewallRules != null){
Iterator<FirewallRule> iter = firewallRules.iterator(); Iterator<FirewallRule> iter = firewallRules.iterator();

View File

@ -0,0 +1,103 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.savvis.vpdc.features;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Set;
import org.jclouds.cim.OSType;
import org.jclouds.compute.domain.CIMOperatingSystem;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.functions.ParseSax;
import org.jclouds.rest.functions.MapHttp4xxCodesToExceptions;
import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404;
import org.jclouds.rest.internal.RestAnnotationProcessor;
import org.jclouds.savvis.vpdc.domain.VMSpec;
import org.jclouds.savvis.vpdc.xml.TaskHandler;
import org.jclouds.util.Strings2;
import org.testng.annotations.Test;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
/**
* Tests annotation parsing of {@code VMAsyncClient}
*
* @author Adrian Cole
*/
@Test(groups = "unit")
public class VMAsyncClientTest extends BaseVPDCAsyncClientTest<VMAsyncClient> {
public void testAddVMIntoVDC() throws SecurityException, NoSuchMethodException, IOException {
Method method = VMAsyncClient.class.getMethod("addVMIntoVDC", String.class, String.class, String.class,
String.class, VMSpec.class);
CIMOperatingSystem os = Iterables.find(injector.getInstance(Key.get(new TypeLiteral<Set<CIMOperatingSystem>>() {
})), new Predicate<CIMOperatingSystem>() {
@Override
public boolean apply(CIMOperatingSystem arg0) {
return arg0.getOsType() == OSType.RHEL_64;
}
});
HttpRequest request = processor.createRequest(method, "11", "22", "VM Tier01", "DemoHost-1", VMSpec.builder()
.operatingSystem(os).build());
assertRequestLineEquals(request,
"GET https://api.symphonyvpdc.savvis.net/rest/api/v0.8/org/11/vdc/22/vApp/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request, Strings2.toStringAndClose(getClass().getResourceAsStream("/vm-default.xml")),
"application/xml", false);
assertResponseParserClassEquals(method, request, ParseSax.class);
assertSaxResponseParserClassEquals(method, TaskHandler.class);
assertExceptionParserClassEquals(method, MapHttp4xxCodesToExceptions.class);
checkFilters(request);
}
public void testRemoveVM() throws SecurityException, NoSuchMethodException, IOException {
Method method = VMAsyncClient.class.getMethod("removeVMFromVDC", String.class, String.class, String.class);
HttpRequest request = processor.createRequest(method, "11", "22", "VM-Tier01");
assertRequestLineEquals(request,
"DELETE https://api.symphonyvpdc.savvis.net/rest/api/v0.8/org/11/vdc/22/vApp/VM-Tier01 HTTP/1.1");
assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, ParseSax.class);
assertSaxResponseParserClassEquals(method, TaskHandler.class);
assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class);
checkFilters(request);
}
@Override
protected TypeLiteral<RestAnnotationProcessor<VMAsyncClient>> createTypeLiteral() {
return new TypeLiteral<RestAnnotationProcessor<VMAsyncClient>>() {
};
}
}

View File

@ -0,0 +1,140 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.savvis.vpdc.features;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.testng.Assert.assertEquals;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.jclouds.cim.OSType;
import org.jclouds.compute.domain.CIMOperatingSystem;
import org.jclouds.compute.domain.ExecResponse;
import org.jclouds.domain.Credentials;
import org.jclouds.net.IPSocket;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.predicates.SocketOpen;
import org.jclouds.savvis.vpdc.domain.Task;
import org.jclouds.savvis.vpdc.domain.VM;
import org.jclouds.savvis.vpdc.domain.VMSpec;
import org.jclouds.savvis.vpdc.predicates.TaskSuccess;
import org.jclouds.ssh.SshClient;
import org.jclouds.ssh.SshClient.Factory;
import org.jclouds.util.InetAddresses2;
import org.testng.annotations.AfterGroups;
import org.testng.annotations.BeforeGroups;
import org.testng.annotations.Test;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.net.HostSpecifier;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
@Test(groups = "live")
public class VMClientLiveTest extends BaseVPDCClientLiveTest {
private VMClient client;
private Factory sshFactory;
private VM vm;
private RetryablePredicate<IPSocket> socketTester;
private RetryablePredicate<String> taskTester;
private String username = checkNotNull(System.getProperty("test." + provider + ".loginUser"), "test." + provider
+ ".loginUser");
private String password = checkNotNull(System.getProperty("test." + provider + ".loginPassword"), "test." + provider
+ ".loginPassword");
@Override
@BeforeGroups(groups = { "live" })
public void setupClient() {
super.setupClient();
client = context.getApi().getVMClient();
sshFactory = injector.getInstance(SshClient.Factory.class);
socketTester = new RetryablePredicate<IPSocket>(injector.getInstance(SocketOpen.class), 130, 10, TimeUnit.SECONDS);// make
taskTester = new RetryablePredicate<String>(injector.getInstance(TaskSuccess.class), 650, 10, TimeUnit.SECONDS);
}
protected String prefix = System.getProperty("user.name");
private String billingSiteId;
private String vpdcId;
public void testCreateVirtualMachine() throws Exception {
billingSiteId = context.getApi().getBrowsingClient().getOrg(null).getId();// default
vpdcId = Iterables.get(context.getApi().getBrowsingClient().getOrg(billingSiteId).getVDCs(), 0).getId();
String networkTierName = Iterables.get(
context.getApi().getBrowsingClient().getVDCInOrg(billingSiteId, vpdcId).getAvailableNetworks(), 0)
.getName();
String name = prefix;
CIMOperatingSystem os = Iterables.find(injector.getInstance(Key.get(new TypeLiteral<Set<CIMOperatingSystem>>() {
})), new Predicate<CIMOperatingSystem>() {
@Override
public boolean apply(CIMOperatingSystem arg0) {
return arg0.getOsType() == OSType.RHEL_64;
}
});
System.out.printf("vpdcId %s, networkName %s, name %s, os %s%n", vpdcId, networkTierName, name, os);
Task task = client.addVMIntoVDC(billingSiteId, vpdcId, networkTierName, name, VMSpec.builder()
.operatingSystem(os).build());
assert this.taskTester.apply(task.getId());
vm = context.getApi().getBrowsingClient().getVMInVDC(billingSiteId, vpdcId, task.getOwner().getId());
conditionallyCheckSSH();
}
private void conditionallyCheckSSH() {
assert HostSpecifier.isValid(vm.getIpAddress());
if (!InetAddresses2.isPrivateIPAddress(vm.getIpAddress())) {
// not sure if the network is public or not, so we have to test
IPSocket socket = new IPSocket(vm.getIpAddress(), 22);
System.err.printf("testing socket %s%n", socket);
System.err.printf("testing ssh %s%n", socket);
checkSSH(socket);
} else {
System.err.printf("skipping ssh %s, as private%n", vm.getIpAddress());
}
}
protected void checkSSH(IPSocket socket) {
socketTester.apply(socket);
SshClient client = sshFactory.create(socket, new Credentials(username, password));
try {
client.connect();
ExecResponse exec = client.exec("echo hello");
System.out.println(exec);
assertEquals(exec.getOutput().trim(), "hello");
} finally {
if (client != null)
client.disconnect();
}
}
@AfterGroups(groups = "live")
protected void tearDown() {
if (vm != null) {
assert taskTester.apply(client.removeVMFromVDC(billingSiteId, vpdcId, vm.getId()).getId()) : vm;
}
super.tearDown();
}
}

View File

@ -42,6 +42,11 @@ import com.google.inject.Injector;
@Test(groups = "unit") @Test(groups = "unit")
public class FirewallServiceHandlerTest { public class FirewallServiceHandlerTest {
/*new FirewallRule(null, null, null, null, "SERVER_TIER_FIREWALL", true, "internet" , "VM Tier01" ,
"22", "allow", "Server Tier Firewall Rule", false, "Tcp"),
new FirewallRule(null, null, null, null, "SERVER_TIER_FIREWALL", true, "VM Tier03" , "VM Tier03" ,
null, "allow", "Server Tier Firewall Rule", false, "Icmp-ping")));*/
public void test() { public void test() {
InputStream is = getClass().getResourceAsStream("/firewallService.xml"); InputStream is = getClass().getResourceAsStream("/firewallService.xml");
Injector injector = Guice.createInjector(new SaxParserModule()); Injector injector = Guice.createInjector(new SaxParserModule());
@ -51,10 +56,10 @@ public class FirewallServiceHandlerTest {
assertEquals( assertEquals(
result.getFirewallRules(), result.getFirewallRules(),
ImmutableSet.<FirewallRule> of( ImmutableSet.<FirewallRule> of(
new FirewallRule(null, null, null, null, "SERVER_TIER_FIREWALL", true, "internet" , "VM Tier01" , FirewallRule.builder().firewallType("SERVER_TIER_FIREWALL").isEnabled(true).source("internet")
"22", "allow", "Server Tier Firewall Rule", false, "Tcp"), .destination("VM Tier01").port("22").protocol("Tcp").policy("allow").description("Server Tier Firewall Rule").isLogged(false).build(),
new FirewallRule(null, null, null, null, "SERVER_TIER_FIREWALL", true, "VM Tier03" , "VM Tier03" , FirewallRule.builder().firewallType("SERVER_TIER_FIREWALL").isEnabled(true).source("VM Tier03")
null, "allow", "Server Tier Firewall Rule", false, "Icmp-ping"))); .destination("VM Tier03").protocol("Icmp-ping").policy("allow").description("Server Tier Firewall Rule").isLogged(false).build()));
} }
} }

View File

@ -57,4 +57,17 @@ public class OrgHandlerTest {
"down")).build().toString()); "down")).build().toString());
} }
public void testOrgWithoutVDC() {
InputStream is = getClass().getResourceAsStream("/org_no_vdc.xml");
Injector injector = Guice.createInjector(new SaxParserModule());
Factory factory = injector.getInstance(ParseSax.Factory.class);
Org result = factory.create(injector.getInstance(OrgHandler.class)).parse(is);
assertEquals(
result.toString(),
Org.builder()
.name("100000.0")
.description("SAVVISStation Integration Testing").build().toString());
}
} }

View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<vApp:Org xmlns:common="http://schemas.dmtf.org/wbem/wscim/1/common" xmlns:vApp="http://www.vmware.com/vcloud/v0.8" xmlns:rasd="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData" xmlns:vssd="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData" xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1" name="100000.0">
<vApp:Description>SAVVISStation Integration Testing</vApp:Description>
</vApp:Org>

View File

@ -0,0 +1 @@
<vApp:VApp xmlns:vApp="http://www.vmware.com/vcloud/v0.8" xmlns:common="http://schemas.dmtf.org/wbem/wscim/1/common" xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1" xmlns:rasd="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData" xmlns:vssd="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData" href="" name="DemoHost-1" type="application/vnd.vmware.vcloud.vApp+xml"><ovf:OperatingSystemSection ovf:id="80"><ovf:Info>Specifies the operating system installed</ovf:Info><ovf:Description>Red Hat Enterprise Linux 5.x 64bit</ovf:Description></ovf:OperatingSystemSection><ovf:VirtualHardwareSection><ovf:Info>Virtual Hardware</ovf:Info><ovf:System><vssd:Description>Virtual Hardware Family</vssd:Description><vssd:ElementName>DemoHost-1</vssd:ElementName><vssd:InstanceID>1</vssd:InstanceID><vssd:VirtualSystemIdentifier>DemoHost-1</vssd:VirtualSystemIdentifier></ovf:System><ovf:Item><rasd:AllocationUnits>3 GHz</rasd:AllocationUnits><rasd:Description>Number of Virtual CPUs</rasd:Description><rasd:ElementName>1 CPU</rasd:ElementName><rasd:InstanceID>1</rasd:InstanceID><rasd:ResourceType>3</rasd:ResourceType><rasd:VirtualQuantity>1</rasd:VirtualQuantity></ovf:Item><ovf:Item><rasd:AllocationUnits>Gigabytes</rasd:AllocationUnits><rasd:Description>Memory Size</rasd:Description><rasd:ElementName>Memory</rasd:ElementName><rasd:InstanceID>2</rasd:InstanceID><rasd:ResourceType>4</rasd:ResourceType><rasd:VirtualQuantity>1</rasd:VirtualQuantity></ovf:Item><ovf:Item><rasd:Caption>false</rasd:Caption><rasd:Connection>VM Tier01</rasd:Connection><rasd:ElementName>Network</rasd:ElementName><rasd:InstanceID>3</rasd:InstanceID><rasd:ResourceType>10</rasd:ResourceType><rasd:VirtualQuantity>1</rasd:VirtualQuantity></ovf:Item><ovf:Item><rasd:AllocationUnits>Gigabytes</rasd:AllocationUnits><rasd:Caption/><rasd:Description>Hard Disk</rasd:Description><rasd:ElementName>/</rasd:ElementName><rasd:HostResource>boot</rasd:HostResource><rasd:InstanceID>4</rasd:InstanceID><rasd:ResourceType>27</rasd:ResourceType><rasd:VirtualQuantity>10</rasd:VirtualQuantity></ovf:Item></ovf:VirtualHardwareSection></vApp:VApp>

View File

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<vApp:Network xmlns:common="http://schemas.dmtf.org/wbem/wscim/1/common" xmlns:vApp="http://www.vmware.com/vcloud/v0.8"
xmlns:rasd="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData"
xmlns:vssd="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData"
xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1" name="VM Tier01"
type="application/vnd.vmware.vcloud.network+xml">
<vApp:Configuration>
<vApp:Gateway>1.1.1.1</vApp:Gateway>
<vApp:Netmask>2.2.2.2</vApp:Netmask>
</vApp:Configuration>
<vApp:Features>
<vApp:FenceMode>allowInOut</vApp:FenceMode>
<vApp:Nat>
<vApp:NatRule internalIP="3.3.3.3" externalIP="4.4.4.4"/>
<vApp:NatRule internalIP="3.3.3.4" externalIP="4.4.4.5"/>
</vApp:Nat>
</vApp:Features>
</vApp:Network>