From df54677e20669e28824ee32edf080a21c72bc523 Mon Sep 17 00:00:00 2001 From: Adrian Cole Date: Tue, 22 Jun 2010 15:26:10 -0700 Subject: [PATCH] Issue 285: implemented terremark extensions including ssh key support --- .../terremark/TerremarkVCloudAsyncClient.java | 279 +++++--- .../terremark/TerremarkVCloudClient.java | 88 +-- .../terremark/TerremarkVCloudMediaType.java | 90 +++ .../TerremarkVCloudPropertiesBuilder.java | 11 +- .../binders/BindCreateKeyToXmlPayload.java | 66 ++ ...ernetServiceConfigurationToXmlPayload.java | 92 --- .../BindNodeConfigurationToXmlPayload.java | 26 +- ...antiateVAppTemplateParamsToXmlPayload.java | 46 +- .../compute/TerremarkVCloudComputeClient.java | 8 + .../TerremarkVCloudComputeService.java | 108 +++ ...markVCloudComputeServiceContextModule.java | 163 ++++- .../ComputeOptionsToSizeProvider.java | 88 --- .../terremark/compute/domain/OrgAndName.java | 78 +++ .../functions/CreateUniqueKeyPair.java | 89 +++ .../functions/NodeMetadataToOrgAndName.java | 68 ++ .../TerremarkVCloudTemplateOptions.java | 280 ++++++++ .../compute/strategy/CleanupOrphanKeys.java | 71 ++ ...ewKeyPairUnlessUserSpecifiedOtherwise.java | 70 ++ .../compute/strategy/DeleteKeyPair.java | 67 ++ ...IdIntoNameRunNodesAndAddToSetStrategy.java | 75 ++ ...erremarkVCloudGetNodeMetadataStrategy.java | 114 +++ .../TerremarkVCloudRestClientModule.java | 34 +- .../terremark/domain/ComputeOptions.java | 97 --- .../domain/CustomizationParameters.java | 19 +- .../domain/InternetServiceConfiguration.java | 107 --- .../vcloud/terremark/domain/KeyPair.java | 132 ++++ .../vcloud/terremark/domain/Protocol.java | 2 +- .../domain/TerremarkOrganization.java | 39 ++ .../internal/TerremarkOrganizationImpl.java | 51 ++ .../vcloud/terremark/endpoints/KeysList.java | 39 ++ ...rremarkInstantiateVAppTemplateOptions.java | 98 ++- .../xml/CustomizationParametersHandler.java | 6 +- ...OptionHandler.java => KeyPairHandler.java} | 42 +- ...tionsHandler.java => KeyPairsHandler.java} | 20 +- .../terremark/xml/TerremarkOrgHandler.java | 57 ++ .../terremark/CreateInternetService.xml | 16 +- .../main/resources/terremark/CreateKey.xml | 5 + .../resources/terremark/CreateNodeService.xml | 15 +- .../terremark/InternetServiceLiveTest.java | 18 - .../TerremarkVCloudAsyncClientTest.java | 655 ++++++++++-------- .../TerremarkVCloudClientLiveTest.java | 282 ++++---- ...indAddInternetServiceToXmlPayloadTest.java | 2 +- .../BindAddNodeServiceToXmlPayloadTest.java | 2 +- ...tServiceConfigurationToXmlPayloadTest.java | 123 ---- ...BindNodeConfigurationToXmlPayloadTest.java | 12 +- .../TerremarkVCloudTemplateOptionsTest.java | 211 ++++++ .../strategy/CleanupOrphanKeysTest.java | 195 ++++++ ...yPairUnlessUserSpecifiedOtherwiseTest.java | 179 +++++ .../compute/strategy/DeleteKeyPairTest.java | 135 ++++ .../CustomizationParametersHandlerTest.java | 10 +- ...onHandlerTest.java => KeyHandlerTest.java} | 21 +- ...sHandlerTest.java => KeysHandlerTest.java} | 32 +- .../xml/TerremarkOrgHandlerTest.java | 107 +++ .../CreateInternetService-options-test.xml | 16 +- .../terremark/CreateInternetService-test.xml | 16 +- .../terremark/CreateInternetService-test2.xml | 16 +- .../CreateNodeService-options-test.xml | 15 +- .../terremark/CreateNodeService-test.xml | 15 +- .../terremark/CreateNodeService-test2.xml | 15 +- .../terremark/CustomizationParameters.xml | 7 +- ...antiateVAppTemplateParams-options-test.xml | 2 +- .../InstantiateVAppTemplateParams-test.xml | 2 +- .../src/test/resources/terremark/key.xml | 9 + .../src/test/resources/terremark/keysList.xml | 9 + .../src/test/resources/terremark/org.xml | 17 + 65 files changed, 3575 insertions(+), 1304 deletions(-) create mode 100644 vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/TerremarkVCloudMediaType.java create mode 100644 vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/binders/BindCreateKeyToXmlPayload.java delete mode 100644 vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/binders/BindInternetServiceConfigurationToXmlPayload.java create mode 100644 vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/TerremarkVCloudComputeService.java delete mode 100644 vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/config/providers/ComputeOptionsToSizeProvider.java create mode 100644 vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/domain/OrgAndName.java create mode 100644 vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/functions/CreateUniqueKeyPair.java create mode 100644 vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/functions/NodeMetadataToOrgAndName.java create mode 100644 vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/options/TerremarkVCloudTemplateOptions.java create mode 100644 vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/strategy/CleanupOrphanKeys.java create mode 100644 vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/strategy/CreateNewKeyPairUnlessUserSpecifiedOtherwise.java create mode 100644 vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/strategy/DeleteKeyPair.java create mode 100644 vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/strategy/TerremarkEncodeTemplateIdIntoNameRunNodesAndAddToSetStrategy.java create mode 100644 vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/strategy/TerremarkVCloudGetNodeMetadataStrategy.java delete mode 100644 vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/domain/ComputeOptions.java delete mode 100644 vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/domain/InternetServiceConfiguration.java create mode 100644 vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/domain/KeyPair.java create mode 100644 vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/domain/TerremarkOrganization.java create mode 100644 vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/domain/internal/TerremarkOrganizationImpl.java create mode 100644 vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/endpoints/KeysList.java rename vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/xml/{ComputeOptionHandler.java => KeyPairHandler.java} (55%) rename vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/xml/{ComputeOptionsHandler.java => KeyPairsHandler.java} (77%) create mode 100644 vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/xml/TerremarkOrgHandler.java create mode 100644 vcloud/terremark/src/main/resources/terremark/CreateKey.xml delete mode 100644 vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/binders/BindInternetServiceConfigurationToXmlPayloadTest.java create mode 100644 vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/TerremarkVCloudTemplateOptionsTest.java create mode 100644 vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/strategy/CleanupOrphanKeysTest.java create mode 100644 vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/strategy/CreateNewKeyPairUnlessUserSpecifiedOtherwiseTest.java create mode 100644 vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/strategy/DeleteKeyPairTest.java rename vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/{ComputeOptionHandlerTest.java => KeyHandlerTest.java} (63%) rename vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/{ComputeOptionsHandlerTest.java => KeysHandlerTest.java} (55%) create mode 100644 vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/TerremarkOrgHandlerTest.java create mode 100644 vcloud/terremark/src/test/resources/terremark/key.xml create mode 100644 vcloud/terremark/src/test/resources/terremark/keysList.xml create mode 100644 vcloud/terremark/src/test/resources/terremark/org.xml diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/TerremarkVCloudAsyncClient.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/TerremarkVCloudAsyncClient.java index 9025270711..25fc99041b 100644 --- a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/TerremarkVCloudAsyncClient.java +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/TerremarkVCloudAsyncClient.java @@ -20,9 +20,18 @@ package org.jclouds.vcloud.terremark; import static javax.ws.rs.core.MediaType.APPLICATION_XML; import static org.jclouds.vcloud.VCloudMediaType.CATALOG_XML; +import static org.jclouds.vcloud.VCloudMediaType.ORG_XML; import static org.jclouds.vcloud.VCloudMediaType.VAPP_XML; import static org.jclouds.vcloud.VCloudMediaType.VDC_XML; +import static org.jclouds.vcloud.terremark.TerremarkVCloudMediaType.CATALOGITEMCUSTOMIZATIONPARAMETERS_XML; +import static org.jclouds.vcloud.terremark.TerremarkVCloudMediaType.INTERNETSERVICESLIST_XML; +import static org.jclouds.vcloud.terremark.TerremarkVCloudMediaType.INTERNETSERVICE_XML; +import static org.jclouds.vcloud.terremark.TerremarkVCloudMediaType.KEYSLIST_XML; +import static org.jclouds.vcloud.terremark.TerremarkVCloudMediaType.NODESERVICE_XML; +import static org.jclouds.vcloud.terremark.TerremarkVCloudMediaType.PUBLICIPSLIST_XML; +import static org.jclouds.vcloud.terremark.TerremarkVCloudMediaType.PUBLICIP_XML; +import java.util.Set; import java.util.SortedSet; import javax.ws.rs.Consumes; @@ -52,37 +61,39 @@ import org.jclouds.vcloud.domain.Catalog; import org.jclouds.vcloud.domain.Task; import org.jclouds.vcloud.domain.VApp; import org.jclouds.vcloud.domain.VDC; +import org.jclouds.vcloud.endpoints.Org; import org.jclouds.vcloud.filters.SetVCloudTokenCookie; import org.jclouds.vcloud.functions.CatalogIdToUri; import org.jclouds.vcloud.functions.VAppId; import org.jclouds.vcloud.options.InstantiateVAppTemplateOptions; -import org.jclouds.vcloud.terremark.binders.BindInternetServiceConfigurationToXmlPayload; +import org.jclouds.vcloud.terremark.binders.BindCreateKeyToXmlPayload; import org.jclouds.vcloud.terremark.binders.BindNodeConfigurationToXmlPayload; import org.jclouds.vcloud.terremark.binders.BindVAppConfigurationToXmlPayload; import org.jclouds.vcloud.terremark.binders.TerremarkBindInstantiateVAppTemplateParamsToXmlPayload; -import org.jclouds.vcloud.terremark.domain.ComputeOptions; import org.jclouds.vcloud.terremark.domain.CustomizationParameters; import org.jclouds.vcloud.terremark.domain.InternetService; -import org.jclouds.vcloud.terremark.domain.InternetServiceConfiguration; -import org.jclouds.vcloud.terremark.domain.IpAddress; +import org.jclouds.vcloud.terremark.domain.KeyPair; import org.jclouds.vcloud.terremark.domain.Node; import org.jclouds.vcloud.terremark.domain.NodeConfiguration; import org.jclouds.vcloud.terremark.domain.Protocol; import org.jclouds.vcloud.terremark.domain.PublicIpAddress; +import org.jclouds.vcloud.terremark.domain.TerremarkOrganization; import org.jclouds.vcloud.terremark.domain.VAppConfiguration; +import org.jclouds.vcloud.terremark.endpoints.KeysList; import org.jclouds.vcloud.terremark.functions.ParseTaskFromLocationHeader; import org.jclouds.vcloud.terremark.functions.ReturnEmptySetOnUnauthorized; import org.jclouds.vcloud.terremark.functions.ReturnVoidOnDeleteDefaultIp; import org.jclouds.vcloud.terremark.options.AddInternetServiceOptions; import org.jclouds.vcloud.terremark.options.AddNodeOptions; -import org.jclouds.vcloud.terremark.xml.ComputeOptionsHandler; import org.jclouds.vcloud.terremark.xml.CustomizationParametersHandler; import org.jclouds.vcloud.terremark.xml.InternetServiceHandler; import org.jclouds.vcloud.terremark.xml.InternetServicesHandler; -import org.jclouds.vcloud.terremark.xml.IpAddressesHandler; +import org.jclouds.vcloud.terremark.xml.KeyPairHandler; +import org.jclouds.vcloud.terremark.xml.KeyPairsHandler; import org.jclouds.vcloud.terremark.xml.NodeHandler; import org.jclouds.vcloud.terremark.xml.NodesHandler; import org.jclouds.vcloud.terremark.xml.PublicIpAddressesHandler; +import org.jclouds.vcloud.terremark.xml.TerremarkOrgHandler; import org.jclouds.vcloud.terremark.xml.TerremarkVDCHandler; import org.jclouds.vcloud.xml.CatalogHandler; import org.jclouds.vcloud.xml.VAppHandler; @@ -93,12 +104,30 @@ import com.google.common.util.concurrent.ListenableFuture; * Provides access to VCloud resources via their REST API. *

* - * @see + * @see * @author Adrian Cole */ @RequestFilters(SetVCloudTokenCookie.class) public interface TerremarkVCloudAsyncClient extends VCloudAsyncClient { + @GET + @Endpoint(Org.class) + @Consumes(ORG_XML) + @XMLResponseParser(TerremarkOrgHandler.class) + @Override + ListenableFuture getDefaultOrganization(); + + @GET + @Endpoint(org.jclouds.vcloud.endpoints.VCloudApi.class) + @Path("/org/{orgId}") + @XMLResponseParser(TerremarkOrgHandler.class) + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + @Consumes(ORG_XML) + @Override + ListenableFuture getOrganization( + @PathParam("orgId") String orgId); + /** * @see TerremarkVCloudClient#getDefaultVDC */ @@ -143,58 +172,63 @@ public interface TerremarkVCloudAsyncClient extends VCloudAsyncClient { @XMLResponseParser(VAppHandler.class) @MapBinder(TerremarkBindInstantiateVAppTemplateParamsToXmlPayload.class) @Override - ListenableFuture instantiateVAppTemplateInVDC(@PathParam("vDCId") String vDCId, - @MapPayloadParam("name") @ParamValidators(DnsNameValidator.class) String appName, - @MapPayloadParam("template") @ParamParser(CatalogIdToUri.class) String templateId, - InstantiateVAppTemplateOptions... options); + ListenableFuture instantiateVAppTemplateInVDC( + @PathParam("vDCId") String vDCId, + @MapPayloadParam("name") @ParamValidators(DnsNameValidator.class) String appName, + @MapPayloadParam("template") @ParamParser(CatalogIdToUri.class) String templateId, + InstantiateVAppTemplateOptions... options); /** * @see TerremarkVCloudClient#addInternetService */ @POST @Endpoint(org.jclouds.vcloud.endpoints.VCloudApi.class) - @Path("/vdc/{vDCId}/internetServices") - @Produces(APPLICATION_XML) - @Consumes(APPLICATION_XML) + @Path("/extensions/vdc/{vDCId}/internetServices") + @Produces(INTERNETSERVICE_XML) + @Consumes(INTERNETSERVICE_XML) @XMLResponseParser(InternetServiceHandler.class) @MapBinder(AddInternetServiceOptions.class) ListenableFuture addInternetServiceToVDC( - @PathParam("vDCId") String vDCId, @MapPayloadParam("name") String serviceName, - @MapPayloadParam("protocol") Protocol protocol, @MapPayloadParam("port") int port, - AddInternetServiceOptions... options); + @PathParam("vDCId") String vDCId, + @MapPayloadParam("name") String serviceName, + @MapPayloadParam("protocol") Protocol protocol, + @MapPayloadParam("port") int port, + AddInternetServiceOptions... options); /** * @see TerremarkVCloudClient#getAllInternetServices */ @GET @Endpoint(org.jclouds.vcloud.endpoints.VCloudApi.class) - @Path("/vdc/{vDCId}/internetServices") - @Consumes(APPLICATION_XML) + @Path("/extensions/vdc/{vDCId}/internetServices") + @Consumes(INTERNETSERVICESLIST_XML) @XMLResponseParser(InternetServicesHandler.class) ListenableFuture> getAllInternetServicesInVDC( - @PathParam("vDCId") String vDCId); + @PathParam("vDCId") String vDCId); /** * @see TerremarkVCloudClient#addInternetServiceToExistingIp */ @POST @Endpoint(org.jclouds.vcloud.endpoints.VCloudApi.class) - @Path("/publicIps/{ipId}/InternetServices") - @Produces(APPLICATION_XML) - @Consumes(APPLICATION_XML) + @Path("/extensions/publicIp/{ipId}/internetServices") + @Produces(INTERNETSERVICE_XML) + @Consumes(INTERNETSERVICE_XML) @XMLResponseParser(InternetServiceHandler.class) @MapBinder(AddInternetServiceOptions.class) ListenableFuture addInternetServiceToExistingIp( - @PathParam("ipId") int existingIpId, @MapPayloadParam("name") String serviceName, - @MapPayloadParam("protocol") Protocol protocol, @MapPayloadParam("port") int port, - AddInternetServiceOptions... options); + @PathParam("ipId") int existingIpId, + @MapPayloadParam("name") String serviceName, + @MapPayloadParam("protocol") Protocol protocol, + @MapPayloadParam("port") int port, + AddInternetServiceOptions... options); /** * @see TerremarkVCloudClient#deletePublicIp */ @DELETE @Endpoint(org.jclouds.vcloud.endpoints.VCloudApi.class) - @Path("/publicIps/{ipId}") + @Path("/extensions/publicIp/{ipId}") @ExceptionParser(ReturnVoidOnDeleteDefaultIp.class) ListenableFuture deletePublicIp(@PathParam("ipId") int ipId); @@ -203,103 +237,93 @@ public interface TerremarkVCloudAsyncClient extends VCloudAsyncClient { */ @GET @Endpoint(org.jclouds.vcloud.endpoints.VCloudApi.class) - @Path("/publicIps/{ipId}/InternetServices") - @Consumes(APPLICATION_XML) + @Path("/extensions/publicIp/{ipId}/internetServices") + @Consumes(INTERNETSERVICESLIST_XML) @XMLResponseParser(InternetServicesHandler.class) ListenableFuture> getInternetServicesOnPublicIp( - @PathParam("ipId") int ipId); + @PathParam("ipId") int ipId); /** * @see TerremarkVCloudClient#getPublicIp */ @GET @Endpoint(org.jclouds.vcloud.endpoints.VCloudApi.class) - @Path("/publicIps/{ipId}") - @Consumes(APPLICATION_XML) + @Path("/extensions/publicIp/{ipId}") + @Consumes(PUBLICIP_XML) @XMLResponseParser(InternetServicesHandler.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class) - ListenableFuture> getPublicIp(@PathParam("ipId") int ipId); + ListenableFuture> getPublicIp( + @PathParam("ipId") int ipId); /** * @see TerremarkVCloudClient#getPublicIpsAssociatedWithVDC */ @GET @Endpoint(org.jclouds.vcloud.endpoints.VCloudApi.class) - @Path("/vdc/{vDCId}/publicIps") - @Consumes(APPLICATION_XML) + @Path("/extensions/vdc/{vDCId}/publicIps") + @Consumes(PUBLICIPSLIST_XML) @XMLResponseParser(PublicIpAddressesHandler.class) ListenableFuture> getPublicIpsAssociatedWithVDC( - @PathParam("vDCId") String vDCId); + @PathParam("vDCId") String vDCId); /** * @see TerremarkVCloudClient#deleteInternetService */ @DELETE @Endpoint(org.jclouds.vcloud.endpoints.VCloudApi.class) - @Path("/internetServices/{internetServiceId}") + @Path("/extensions/internetService/{internetServiceId}") @ExceptionParser(ReturnVoidOnNotFoundOr404.class) ListenableFuture deleteInternetService( - @PathParam("internetServiceId") int internetServiceId); - - /** - * @see TerremarkVCloudClient#configureInternetService - */ - @PUT - @Endpoint(org.jclouds.vcloud.endpoints.VCloudApi.class) - @Path("/internetServices/{internetServiceId}") - @Produces(APPLICATION_XML) - @Consumes(APPLICATION_XML) - @XMLResponseParser(InternetServiceHandler.class) - ListenableFuture configureInternetService( - @PathParam("internetServiceId") int internetServiceId, - @BinderParam(BindInternetServiceConfigurationToXmlPayload.class) InternetServiceConfiguration nodeConfiguration); + @PathParam("internetServiceId") int internetServiceId); /** * @see TerremarkVCloudClient#getInternetService */ @GET @Endpoint(org.jclouds.vcloud.endpoints.VCloudApi.class) - @Path("/internetServices/{internetServiceId}") - @Consumes(APPLICATION_XML) + @Path("/extensions/internetService/{internetServiceId}") + @Consumes(INTERNETSERVICESLIST_XML) @XMLResponseParser(InternetServiceHandler.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class) ListenableFuture getInternetService( - @PathParam("internetServiceId") int internetServiceId); + @PathParam("internetServiceId") int internetServiceId); /** * @see TerremarkVCloudClient#addNode */ @POST @Endpoint(org.jclouds.vcloud.endpoints.VCloudApi.class) - @Path("/internetServices/{internetServiceId}/nodes") - @Produces(APPLICATION_XML) - @Consumes(APPLICATION_XML) + @Path("/extensions/internetService/{internetServiceId}/nodeServices") + @Produces(NODESERVICE_XML) + @Consumes(NODESERVICE_XML) @XMLResponseParser(NodeHandler.class) @MapBinder(AddNodeOptions.class) - ListenableFuture addNode(@PathParam("internetServiceId") int internetServiceId, - @MapPayloadParam("ipAddress") String ipAddress, @MapPayloadParam("name") String name, - @MapPayloadParam("port") int port, AddNodeOptions... options); + ListenableFuture addNode( + @PathParam("internetServiceId") int internetServiceId, + @MapPayloadParam("ipAddress") String ipAddress, + @MapPayloadParam("name") String name, + @MapPayloadParam("port") int port, AddNodeOptions... options); /** * @see TerremarkVCloudClient#getNodes */ @GET @Endpoint(org.jclouds.vcloud.endpoints.VCloudApi.class) - @Path("/internetServices/{internetServiceId}/nodes") + @Path("/extensions/internetService/{internetServiceId}/nodeServices") @XMLResponseParser(NodesHandler.class) @ExceptionParser(ReturnEmptySetOnUnauthorized.class) - @Consumes(APPLICATION_XML) + @Consumes(NODESERVICE_XML) ListenableFuture> getNodes( - @PathParam("internetServiceId") int internetServiceId); + @PathParam("internetServiceId") int internetServiceId); /** * @see TerremarkVCloudClient#getNode */ @GET @Endpoint(org.jclouds.vcloud.endpoints.VCloudApi.class) - @Path("/nodeServices/{nodeId}") + @Path("/extensions/nodeService/{nodeId}") @XMLResponseParser(NodeHandler.class) - @Consumes(APPLICATION_XML) + @Consumes(NODESERVICE_XML) @ExceptionParser(ReturnNullOnNotFoundOr404.class) ListenableFuture getNode(@PathParam("nodeId") int nodeId); @@ -308,20 +332,20 @@ public interface TerremarkVCloudAsyncClient extends VCloudAsyncClient { */ @PUT @Endpoint(org.jclouds.vcloud.endpoints.VCloudApi.class) - @Path("/nodeServices/{nodeId}") - @Produces(APPLICATION_XML) - @Consumes(APPLICATION_XML) + @Path("/extensions/nodeService/{nodeId}") + @Produces(NODESERVICE_XML) + @Consumes(NODESERVICE_XML) @XMLResponseParser(NodeHandler.class) ListenableFuture configureNode( - @PathParam("nodeId") int nodeId, - @BinderParam(BindNodeConfigurationToXmlPayload.class) NodeConfiguration nodeConfiguration); + @PathParam("nodeId") int nodeId, + @BinderParam(BindNodeConfigurationToXmlPayload.class) NodeConfiguration nodeConfiguration); /** * @see TerremarkVCloudClient#deleteNode */ @DELETE @Endpoint(org.jclouds.vcloud.endpoints.VCloudApi.class) - @Path("/nodeServices/{nodeId}") + @Path("/extensions/nodeService/{nodeId}") @ExceptionParser(ReturnVoidOnNotFoundOr404.class) ListenableFuture deleteNode(@PathParam("nodeId") int nodeId); @@ -336,61 +360,88 @@ public interface TerremarkVCloudAsyncClient extends VCloudAsyncClient { @MapBinder(BindVAppConfigurationToXmlPayload.class) @ResponseParser(ParseTaskFromLocationHeader.class) ListenableFuture configureVApp( - @PathParam("vAppId") @ParamParser(VAppId.class) VApp vApp, - VAppConfiguration configuration); - - /** - * @see TerremarkVCloudClient#getComputeOptionsOfVApp - */ - @GET - @Endpoint(org.jclouds.vcloud.endpoints.VCloudApi.class) - @Path("/vapp/{vAppId}/options/compute") - @XMLResponseParser(ComputeOptionsHandler.class) - @Consumes(APPLICATION_XML) - ListenableFuture> getComputeOptionsOfVApp( - @PathParam("vAppId") String vAppId); - - /** - * @see TerremarkVCloudClient#getCustomizationOptionsOfVApp - */ - @GET - @Endpoint(org.jclouds.vcloud.endpoints.VCloudApi.class) - @Path("/vapp/{vAppId}/options/customization") - @XMLResponseParser(CustomizationParametersHandler.class) - @Consumes(APPLICATION_XML) - ListenableFuture getCustomizationOptionsOfVApp( - @PathParam("vAppId") String vAppId); - - /** - * @see TerremarkVCloudClient#getComputeOptionsOfCatalogItem - */ - @GET - @Endpoint(org.jclouds.vcloud.endpoints.VCloudApi.class) - @Path("/catalogItem/{catalogItemId}/options/compute") - @XMLResponseParser(ComputeOptionsHandler.class) - @Consumes(APPLICATION_XML) - ListenableFuture> getComputeOptionsOfCatalogItem( - @PathParam("catalogItemId") String catalogItemId); + @PathParam("vAppId") @ParamParser(VAppId.class) VApp vApp, + VAppConfiguration configuration); /** * @see TerremarkVCloudClient#getCustomizationOptionsOfCatalogItem */ @GET @Endpoint(org.jclouds.vcloud.endpoints.VCloudApi.class) - @Path("/catalogItem/{catalogItemId}/options/customization") + @Path("/extensions/template/{catalogItemId}/options/customization") @XMLResponseParser(CustomizationParametersHandler.class) - @Consumes(APPLICATION_XML) + @Consumes(CATALOGITEMCUSTOMIZATIONPARAMETERS_XML) ListenableFuture getCustomizationOptionsOfCatalogItem( - @PathParam("catalogItemId") String catalogItemId); + @PathParam("catalogItemId") String catalogItemId); /** - * @see TerremarkVCloudClient#getIpAddressesForNetwork + * @see TerremarkVCloudClient#listKeyPairs + */ + @GET + @Endpoint(KeysList.class) + @Consumes(KEYSLIST_XML) + @XMLResponseParser(KeyPairsHandler.class) + ListenableFuture> listKeyPairs(); + + /** + * @see TerremarkVCloudClient#listKeyPairsInOrg */ @GET @Endpoint(org.jclouds.vcloud.endpoints.VCloudApi.class) - @Path("/network/{networkId}/ipAddresses") + @Path("/extensions/org/{orgId}/keys") + @Consumes(KEYSLIST_XML) + @XMLResponseParser(KeyPairsHandler.class) + ListenableFuture> listKeyPairsInOrg( + @PathParam("orgId") String orgId); + + /** + * @see TerremarkVCloudClient#generateKeyPairInOrg + */ + @POST + @Endpoint(org.jclouds.vcloud.endpoints.VCloudApi.class) + @Path("/extensions/org/{orgId}/keys") + @Produces(KEYSLIST_XML) + @Consumes(KEYSLIST_XML) + @XMLResponseParser(KeyPairHandler.class) + @MapBinder(BindCreateKeyToXmlPayload.class) + ListenableFuture generateKeyPairInOrg( + @PathParam("orgId") String orgId, + @MapPayloadParam("name") String name, + @MapPayloadParam("isDefault") boolean makeDefault); + + /** + * @see TerremarkVCloudClient#getKeyPair + */ + @GET + @Endpoint(org.jclouds.vcloud.endpoints.VCloudApi.class) + @Path("/extensions/key/{keyId}") + @XMLResponseParser(KeyPairHandler.class) @Consumes(APPLICATION_XML) - @XMLResponseParser(IpAddressesHandler.class) - ListenableFuture> getIpAddressesForNetwork( - @PathParam("networkId") String networkId); + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + ListenableFuture getKeyPair(@PathParam("keyId") int keyId); + + // TODO + // /** + // * @see TerremarkVCloudClient#configureKeyPair + // */ + // @PUT + // @Endpoint(org.jclouds.vcloud.endpoints.VCloudApi.class) + // @Path("/extensions/key/{keyId}") + // @Produces(APPLICATION_XML) + // @Consumes(APPLICATION_XML) + // @XMLResponseParser(KeyPairHandler.class) + // ListenableFuture configureKeyPair( + // @PathParam("keyId") int keyId, + // @BinderParam(BindKeyPairConfigurationToXmlPayload.class) + // KeyPairConfiguration keyConfiguration); + + /** + * @see TerremarkVCloudClient#deleteKeyPair + */ + @DELETE + @Endpoint(org.jclouds.vcloud.endpoints.VCloudApi.class) + @Path("/extensions/key/{keyId}") + @ExceptionParser(ReturnVoidOnNotFoundOr404.class) + ListenableFuture deleteKeyPair(@PathParam("keyId") int keyId); + } diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/TerremarkVCloudClient.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/TerremarkVCloudClient.java index 02947d75b7..2320b4ba63 100644 --- a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/TerremarkVCloudClient.java +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/TerremarkVCloudClient.java @@ -18,6 +18,7 @@ */ package org.jclouds.vcloud.terremark; +import java.util.Set; import java.util.SortedSet; import java.util.concurrent.TimeUnit; @@ -25,15 +26,14 @@ import org.jclouds.concurrent.Timeout; import org.jclouds.vcloud.VCloudClient; import org.jclouds.vcloud.domain.Task; import org.jclouds.vcloud.domain.VApp; -import org.jclouds.vcloud.terremark.domain.ComputeOptions; import org.jclouds.vcloud.terremark.domain.CustomizationParameters; import org.jclouds.vcloud.terremark.domain.InternetService; -import org.jclouds.vcloud.terremark.domain.InternetServiceConfiguration; -import org.jclouds.vcloud.terremark.domain.IpAddress; +import org.jclouds.vcloud.terremark.domain.KeyPair; import org.jclouds.vcloud.terremark.domain.Node; import org.jclouds.vcloud.terremark.domain.NodeConfiguration; import org.jclouds.vcloud.terremark.domain.Protocol; import org.jclouds.vcloud.terremark.domain.PublicIpAddress; +import org.jclouds.vcloud.terremark.domain.TerremarkOrganization; import org.jclouds.vcloud.terremark.domain.VAppConfiguration; import org.jclouds.vcloud.terremark.options.AddInternetServiceOptions; import org.jclouds.vcloud.terremark.options.AddNodeOptions; @@ -42,29 +42,21 @@ import org.jclouds.vcloud.terremark.options.AddNodeOptions; * Provides access to VCloud resources via their REST API. *

* - * @see + * @see * @author Adrian Cole */ @Timeout(duration = 300, timeUnit = TimeUnit.SECONDS) public interface TerremarkVCloudClient extends VCloudClient { - /** - * This call returns the compute options for the vApp. The compute options are the CPU and memory - * configurations supported by Terremark and by the guest operating system of the vApp. This call - * also returns the cost per hour for each configuration. - */ - SortedSet getComputeOptionsOfVApp(String vAppId); + @Override + TerremarkOrganization getDefaultOrganization(); - SortedSet getComputeOptionsOfCatalogItem(String catalogItemId); + @Override + TerremarkOrganization getOrganization(String orgId); - /** - * This call returns the customization options for the vApp. The response lists which - * customization options are supported for this particular vApp. The possible customization - * options are Network and Password. - */ - CustomizationParameters getCustomizationOptionsOfVApp(String vAppId); - - CustomizationParameters getCustomizationOptionsOfCatalogItem(String catalogItemId); + CustomizationParameters getCustomizationOptionsOfCatalogItem( + String catalogItemId); /** * This call returns a list of public IP addresses. @@ -74,28 +66,27 @@ public interface TerremarkVCloudClient extends VCloudClient { void deletePublicIp(int ipId); /** - * The call creates a new internet server, including protocol and port information. The public IP - * is dynamically allocated. + * The call creates a new internet server, including protocol and port + * information. The public IP is dynamically allocated. * */ - InternetService addInternetServiceToVDC(String vDCId, String serviceName, Protocol protocol, - int port, AddInternetServiceOptions... options); + InternetService addInternetServiceToVDC(String vDCId, String serviceName, + Protocol protocol, int port, AddInternetServiceOptions... options); /** - * This call adds an internet service to a known, existing public IP. This call is identical to - * Add Internet Service except you specify the public IP in the request. + * This call adds an internet service to a known, existing public IP. This + * call is identical to Add Internet Service except you specify the public IP + * in the request. * */ - InternetService addInternetServiceToExistingIp(int existingIpId, String serviceName, - Protocol protocol, int port, AddInternetServiceOptions... options); + InternetService addInternetServiceToExistingIp(int existingIpId, + String serviceName, Protocol protocol, int port, + AddInternetServiceOptions... options); void deleteInternetService(int internetServiceId); InternetService getInternetService(int internetServiceId); - InternetService configureInternetService(int internetServiceId, - InternetServiceConfiguration nodeConfiguration); - SortedSet getAllInternetServicesInVDC(String vDCId); /** @@ -108,9 +99,10 @@ public interface TerremarkVCloudClient extends VCloudClient { /** * This call adds a node to an existing internet service. *

- * Every vDC is assigned a network of 60 IP addresses that can be used as nodes. Each node can - * associated with multiple internet service. You can get a list of the available IP addresses by - * calling Get IP Addresses for a Network. + * Every vDC is assigned a network of 60 IP addresses that can be used as + * nodes. Each node can associated with multiple internet service. You can + * get a list of the available IP addresses by calling Get IP Addresses for a + * Network. * * @param internetServiceId * @param ipAddress @@ -120,7 +112,7 @@ public interface TerremarkVCloudClient extends VCloudClient { * @return */ Node addNode(int internetServiceId, String ipAddress, String name, int port, - AddNodeOptions... options); + AddNodeOptions... options); Node getNode(int nodeId); @@ -130,11 +122,10 @@ public interface TerremarkVCloudClient extends VCloudClient { SortedSet getNodes(int internetServiceId); - SortedSet getIpAddressesForNetwork(String networkId); - /** - * This call configures the settings of an existing vApp by passing the new configuration. The - * existing vApp must be in a powered off state (status = 2). + * This call configures the settings of an existing vApp by passing the new + * configuration. The existing vApp must be in a powered off state (status = + * 2). *

* You can change the following items for a vApp. *

    @@ -143,8 +134,9 @@ public interface TerremarkVCloudClient extends VCloudClient { *
  1. Add a virtual disk
  2. *
  3. Delete a virtual disk
  4. *
- * You can make more than one change in a single request. For example, you can increase the - * number of virtual CPUs and the amount of virtual memory in the same request. + * You can make more than one change in a single request. For example, you + * can increase the number of virtual CPUs and the amount of virtual memory + * in the same request. * * @param vApp * vApp to change in power state off @@ -154,4 +146,20 @@ public interface TerremarkVCloudClient extends VCloudClient { */ Task configureVApp(VApp vApp, VAppConfiguration configuration); + /** + * This call returns the keys previously created for your organization. + */ + Set listKeyPairs(); + + Set listKeyPairsInOrg(String orgId); + + KeyPair generateKeyPairInOrg(String orgId, String name, boolean makeDefault); + + KeyPair getKeyPair(int keyPairId); + + // TODO + // KeyPair configureKeyPair(int keyPairId, KeyPairConfiguration + // keyPairConfiguration); + + void deleteKeyPair(int keyPairId); } diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/TerremarkVCloudMediaType.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/TerremarkVCloudMediaType.java new file mode 100644 index 0000000000..3f1f949e49 --- /dev/null +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/TerremarkVCloudMediaType.java @@ -0,0 +1,90 @@ +package org.jclouds.vcloud.terremark; + +import javax.ws.rs.core.MediaType; + +import org.jclouds.vcloud.VCloudMediaType; + +/** + * Resource Types used in Terremark VCloud express + * + * @see MediaType + */ +public class TerremarkVCloudMediaType extends VCloudMediaType { + /** + * "application/vnd.tmrk.vcloudExpress.keysList+xml" + */ + public final static String KEYSLIST_XML = "application/vnd.tmrk.vcloudExpress.keysList+xml"; + + /** + * "application/vnd.tmrk.vCloudExpress.keysList+xml" + */ + public final static MediaType KEYSLIST_XML_TYPE = new MediaType( + "application", "vnd.tmrk.vcloudExpress.keysList+xml"); + + /** + * "application/vnd.tmrk.vCloud.publicIp+xml" + */ + public final static String PUBLICIP_XML = "application/vnd.tmrk.vCloud.publicIp+xml"; + + /** + * "application/vnd.tmrk.vCloud.publicIp+xml" + */ + public final static MediaType PUBLICIP_XML_TYPE = new MediaType( + "application", "vnd.tmrk.vCloud.publicIp+xml"); + + /** + * "application/vnd.tmrk.vCloud.publicIpsList+xml" + */ + public final static String PUBLICIPSLIST_XML = "application/vnd.tmrk.vCloud.publicIpsList+xml"; + + /** + * "application/vnd.tmrk.vCloud.publicIpsList+xml" + */ + public final static MediaType PUBLICIPSLIST_XML_TYPE = new MediaType( + "application", "vnd.tmrk.vCloud.publicIpsList+xml"); + + /** + * "application/vnd.tmrk.vCloud.internetService+xml" + */ + public final static String INTERNETSERVICE_XML = "application/vnd.tmrk.vCloud.internetService+xml"; + + /** + * "application/vnd.tmrk.vCloud.internetService+xml" + */ + public final static MediaType INTERNETSERVICE_XML_TYPE = new MediaType( + "application", "vnd.tmrk.vCloud.internetService+xml"); + + /** + * "application/vnd.tmrk.vCloud.internetServicesList+xml" + */ + public final static String INTERNETSERVICESLIST_XML = "application/vnd.tmrk.vCloud.internetServicesList+xml"; + + /** + * "application/vnd.tmrk.vCloud.internetServicesList+xml" + */ + public final static MediaType INTERNETSERVICESLIST_XML_TYPE = new MediaType( + "application", "vnd.tmrk.vCloud.internetServicesList+xml"); + + /** + * "application/vnd.tmrk.vCloud.nodeService+xml" + */ + public final static String NODESERVICE_XML = "application/vnd.tmrk.vCloud.nodeService+xml"; + + /** + * "application/vnd.tmrk.vCloud.nodeService+xml" + */ + public final static MediaType NODESERVICE_XML_TYPE = new MediaType( + "application", "vnd.tmrk.vCloud.nodeService+xml"); + + /** + * "application/vnd.tmrk.vCloud.catalogItemCustomizationParameters+xml" + */ + public final static String CATALOGITEMCUSTOMIZATIONPARAMETERS_XML = "application/vnd.tmrk.vCloud.catalogItemCustomizationParameters+xml"; + + /** + * "application/vnd.tmrk.vCloud.catalogItemCustomizationParameters+xml" + */ + public final static MediaType CATALOGITEMCUSTOMIZATIONPARAMETERS_XML_TYPE = new MediaType( + "application", + "vnd.tmrk.vCloud.catalogItemCustomizationParameters+xml"); +} diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/TerremarkVCloudPropertiesBuilder.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/TerremarkVCloudPropertiesBuilder.java index 575815e6c5..2883dc9578 100644 --- a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/TerremarkVCloudPropertiesBuilder.java +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/TerremarkVCloudPropertiesBuilder.java @@ -18,9 +18,8 @@ */ package org.jclouds.vcloud.terremark; -import static org.jclouds.vcloud.reference.VCloudConstants.PROPERTY_VCLOUD_DEFAULT_CPUCOUNT; -import static org.jclouds.vcloud.reference.VCloudConstants.PROPERTY_VCLOUD_DEFAULT_MEMORY; import static org.jclouds.vcloud.reference.VCloudConstants.PROPERTY_VCLOUD_ENDPOINT; +import static org.jclouds.vcloud.reference.VCloudConstants.PROPERTY_VCLOUD_VERSION_API; import java.net.URI; import java.util.Properties; @@ -36,10 +35,9 @@ public class TerremarkVCloudPropertiesBuilder extends VCloudPropertiesBuilder { @Override protected Properties defaultProperties() { Properties properties = super.defaultProperties(); - properties.setProperty(PROPERTY_VCLOUD_DEFAULT_CPUCOUNT, "1"); - properties.setProperty(PROPERTY_VCLOUD_DEFAULT_MEMORY, "512"); + properties.setProperty(PROPERTY_VCLOUD_VERSION_API, "0.8a-ext1.6"); properties.setProperty(PROPERTY_VCLOUD_ENDPOINT, - "https://services.vcloudexpress.terremark.com/api"); + "https://services.vcloudexpress.terremark.com/api"); properties.setProperty("jclouds.dns_name_length_min", "1"); properties.setProperty("jclouds.dns_name_length_max", "15"); return properties; @@ -50,6 +48,7 @@ public class TerremarkVCloudPropertiesBuilder extends VCloudPropertiesBuilder { } public TerremarkVCloudPropertiesBuilder(String id, String secret) { - super(URI.create("https://services.vcloudexpress.terremark.com/api"), id, secret); + super(URI.create("https://services.vcloudexpress.terremark.com/api"), id, + secret); } } diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/binders/BindCreateKeyToXmlPayload.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/binders/BindCreateKeyToXmlPayload.java new file mode 100644 index 0000000000..ca11f5e42f --- /dev/null +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/binders/BindCreateKeyToXmlPayload.java @@ -0,0 +1,66 @@ +/** + * + * Copyright (C) 2009 Cloud Conscious, LLC. + * + * ==================================================================== + * 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.vcloud.terremark.binders; + +import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.util.Utils.replaceTokens; + +import java.util.Map; + +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; + +import org.jclouds.http.HttpRequest; +import org.jclouds.rest.MapBinder; +import org.jclouds.rest.binders.BindToStringPayload; + +import com.google.common.collect.ImmutableMap; + +/** + * + * @author Adrian Cole + * + */ +@Singleton +public class BindCreateKeyToXmlPayload implements MapBinder { + + @Inject + @Named("CreateKey") + private String xmlTemplate; + @Inject + private BindToStringPayload stringBinder; + + public void bindToRequest(HttpRequest request, Map postParams) { + String name = checkNotNull(postParams.get("name"), + "name parameter not present"); + String isDefault = checkNotNull(postParams.get("isDefault"), + "isDefault parameter not present"); + + String payload = replaceTokens(xmlTemplate, ImmutableMap.of("name", name, + "isDefault", isDefault)); + stringBinder.bindToRequest(request, payload); + } + + public void bindToRequest(HttpRequest request, Object input) { + throw new IllegalStateException("CreateKey needs parameters"); + + } + +} diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/binders/BindInternetServiceConfigurationToXmlPayload.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/binders/BindInternetServiceConfigurationToXmlPayload.java deleted file mode 100644 index 2b58e982c8..0000000000 --- a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/binders/BindInternetServiceConfigurationToXmlPayload.java +++ /dev/null @@ -1,92 +0,0 @@ -/** - * - * Copyright (C) 2009 Cloud Conscious, LLC. - * - * ==================================================================== - * 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.vcloud.terremark.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.Properties; - -import javax.inject.Singleton; -import javax.xml.parsers.FactoryConfigurationError; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.TransformerException; - -import org.jclouds.http.HttpRequest; -import org.jclouds.rest.binders.BindToStringPayload; -import org.jclouds.rest.internal.GeneratedHttpRequest; -import org.jclouds.vcloud.terremark.domain.InternetServiceConfiguration; - -import com.jamesmurty.utils.XMLBuilder; - -/** - * - * @author Adrian Cole - * - */ -@Singleton -public class BindInternetServiceConfigurationToXmlPayload extends BindToStringPayload { - - @SuppressWarnings("unchecked") - @Override - public void bindToRequest(HttpRequest request, Object input) { - 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"); - InternetServiceConfiguration internetServiceConfiguration = (InternetServiceConfiguration) checkNotNull( - input, "configuration"); - checkArgument(internetServiceConfiguration.getDescription() != null - || internetServiceConfiguration.getEnabled() != null - || internetServiceConfiguration.getName() != null || internetServiceConfiguration.getTimeout() != null, "no configuration set"); - try { - super.bindToRequest(request, generateXml(internetServiceConfiguration)); - } catch (ParserConfigurationException e) { - throw new RuntimeException(e); - } catch (FactoryConfigurationError e) { - throw new RuntimeException(e); - } catch (TransformerException e) { - throw new RuntimeException(e); - } - - } - - protected String generateXml(InternetServiceConfiguration internetServiceConfiguration) - throws ParserConfigurationException, FactoryConfigurationError, TransformerException { - XMLBuilder rootBuilder = XMLBuilder.create("InternetService").a("xmlns", - "urn:tmrk:vCloudExpress-1.0").a("xmlns:i", - "http://www.w3.org/2001/XMLSchema-instance"); - if (internetServiceConfiguration.getDescription() != null) - rootBuilder.e("Description").t(internetServiceConfiguration.getDescription()); - if (internetServiceConfiguration.getName() != null) - rootBuilder.e("Name").t(internetServiceConfiguration.getName()); - if (internetServiceConfiguration.getEnabled() != null) - rootBuilder.e("Enabled").t(internetServiceConfiguration.getEnabled()); - if (internetServiceConfiguration.getTimeout() != null) - rootBuilder.e("Timeout").t(internetServiceConfiguration.getTimeout()); - Properties outputProperties = new Properties(); - outputProperties.put(javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION, "yes"); - return rootBuilder.asString(outputProperties); - } - - protected String ifNullDefaultTo(String value, String defaultValue) { - return value != null ? value : checkNotNull(defaultValue, "defaultValue"); - } -} diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/binders/BindNodeConfigurationToXmlPayload.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/binders/BindNodeConfigurationToXmlPayload.java index 66eafc2be0..5d88411900 100644 --- a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/binders/BindNodeConfigurationToXmlPayload.java +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/binders/BindNodeConfigurationToXmlPayload.java @@ -47,15 +47,17 @@ public class BindNodeConfigurationToXmlPayload extends BindToStringPayload { @SuppressWarnings("unchecked") @Override public void bindToRequest(HttpRequest request, Object input) { - checkArgument(checkNotNull(request, "request") instanceof GeneratedHttpRequest, - "this binder is only valid for GeneratedHttpRequests!"); + 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"); - NodeConfiguration nodeConfiguration = (NodeConfiguration) checkNotNull(input, - "nodeConfiguration"); + checkState(gRequest.getArgs() != null, + "args should be initialized at this point"); + NodeConfiguration nodeConfiguration = (NodeConfiguration) checkNotNull( + input, "nodeConfiguration"); checkArgument(nodeConfiguration.getDescription() != null - || nodeConfiguration.getEnabled() != null || nodeConfiguration.getName() != null, - "no configuration set"); + || nodeConfiguration.getEnabled() != null + || nodeConfiguration.getName() != null, "no configuration set"); try { super.bindToRequest(request, generateXml(nodeConfiguration)); } catch (ParserConfigurationException e) { @@ -69,10 +71,11 @@ public class BindNodeConfigurationToXmlPayload extends BindToStringPayload { } protected String generateXml(NodeConfiguration nodeConfiguration) - throws ParserConfigurationException, FactoryConfigurationError, TransformerException { + throws ParserConfigurationException, FactoryConfigurationError, + TransformerException { XMLBuilder rootBuilder = XMLBuilder.create("NodeService").a("xmlns", - "urn:tmrk:vCloudExpress-1.0").a("xmlns:i", - "http://www.w3.org/2001/XMLSchema-instance"); + "urn:tmrk:vCloudExpressExtensions-1.6").a("xmlns:i", + "http://www.w3.org/2001/XMLSchema-instance"); if (nodeConfiguration.getDescription() != null) rootBuilder.e("Description").t(nodeConfiguration.getDescription()); if (nodeConfiguration.getName() != null) @@ -80,7 +83,8 @@ public class BindNodeConfigurationToXmlPayload extends BindToStringPayload { if (nodeConfiguration.getEnabled() != null) rootBuilder.e("Enabled").t(nodeConfiguration.getEnabled()); Properties outputProperties = new Properties(); - outputProperties.put(javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION, "yes"); + outputProperties.put(javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION, + "yes"); return rootBuilder.asString(outputProperties); } diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/binders/TerremarkBindInstantiateVAppTemplateParamsToXmlPayload.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/binders/TerremarkBindInstantiateVAppTemplateParamsToXmlPayload.java index adfef6c648..bbaffb6d62 100644 --- a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/binders/TerremarkBindInstantiateVAppTemplateParamsToXmlPayload.java +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/binders/TerremarkBindInstantiateVAppTemplateParamsToXmlPayload.java @@ -18,8 +18,6 @@ */ package org.jclouds.vcloud.terremark.binders; -import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.vcloud.reference.VCloudConstants.PROPERTY_VCLOUD_DEFAULT_DHCP_ENABLED; import static org.jclouds.vcloud.reference.VCloudConstants.PROPERTY_VCLOUD_DEFAULT_FENCEMODE; import static org.jclouds.vcloud.reference.VCloudConstants.PROPERTY_VCLOUD_DEFAULT_NETWORK; import static org.jclouds.vcloud.reference.VCloudConstants.PROPERTY_VCLOUD_XML_NAMESPACE; @@ -29,6 +27,7 @@ import java.net.URI; import java.util.Map; import java.util.SortedMap; +import javax.annotation.Nullable; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; @@ -38,7 +37,6 @@ import javax.xml.transform.TransformerException; import org.jclouds.rest.binders.BindToStringPayload; import org.jclouds.vcloud.binders.BindInstantiateVAppTemplateParamsToXmlPayload; -import org.jclouds.vcloud.domain.FenceMode; import org.jclouds.vcloud.domain.ResourceType; import com.jamesmurty.utils.XMLBuilder; @@ -50,39 +48,35 @@ import com.jamesmurty.utils.XMLBuilder; */ @Singleton public class TerremarkBindInstantiateVAppTemplateParamsToXmlPayload extends - BindInstantiateVAppTemplateParamsToXmlPayload { + BindInstantiateVAppTemplateParamsToXmlPayload { @Inject - public TerremarkBindInstantiateVAppTemplateParamsToXmlPayload(BindToStringPayload stringBinder, - @Named(PROPERTY_VCLOUD_XML_NAMESPACE) String ns, - @Named(PROPERTY_VCLOUD_XML_SCHEMA) String schema, - @Named(PROPERTY_VCLOUD_DEFAULT_DHCP_ENABLED) String defaultDhcpEnabled, - @Named(PROPERTY_VCLOUD_DEFAULT_FENCEMODE) String defaultFenceMode, - @Named(PROPERTY_VCLOUD_DEFAULT_NETWORK) String network, - OptionalConstantsHolder optionalDefaults) { - super(stringBinder, ns, schema, defaultDhcpEnabled, defaultFenceMode, network, - optionalDefaults); + public TerremarkBindInstantiateVAppTemplateParamsToXmlPayload( + BindToStringPayload stringBinder, + @Named(PROPERTY_VCLOUD_XML_NAMESPACE) String ns, + @Named(PROPERTY_VCLOUD_XML_SCHEMA) String schema, + @Named(PROPERTY_VCLOUD_DEFAULT_NETWORK) String network, + @Named(PROPERTY_VCLOUD_DEFAULT_FENCEMODE) String fenceMode) { + super(stringBinder, ns, schema, network, fenceMode); } @Override - protected String generateXml(String name, String template, Map properties, - SortedMap virtualHardwareQuantity, String networkName, - FenceMode fenceMode, boolean dhcp, URI network) throws ParserConfigurationException, - FactoryConfigurationError, TransformerException { - checkNotNull(virtualHardwareQuantity.get(ResourceType.PROCESSOR), - "cpuCount must be present in instantiateVapp on terremark"); - checkNotNull(virtualHardwareQuantity.get(ResourceType.MEMORY), - "memorySizeMegabytes must be present in instantiateVapp on terremark"); - return super.generateXml(name, template, properties, virtualHardwareQuantity, networkName, - fenceMode, dhcp, network); + protected String generateXml(String name, String template, + Map properties, + SortedMap virtualHardwareQuantity, + String networkName, @Nullable String fenceMode, URI network) + throws ParserConfigurationException, FactoryConfigurationError, + TransformerException { + return super.generateXml(name, template, properties, + virtualHardwareQuantity, networkName, fenceMode, network); } @Override protected void addPropertiesifPresent(XMLBuilder instantiationParamsBuilder, - Map properties) { + Map properties) { if (properties.size() == 0) { // terremark requires the product section. - instantiationParamsBuilder.e("ProductSection").a("xmlns:q1", ns).a("xmlns:ovf", - "http://schemas.dmtf.org/ovf/envelope/1"); + instantiationParamsBuilder.e("ProductSection").a("xmlns:q1", ns).a( + "xmlns:ovf", "http://schemas.dmtf.org/ovf/envelope/1"); } else { super.addPropertiesifPresent(instantiationParamsBuilder, properties); } diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/TerremarkVCloudComputeClient.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/TerremarkVCloudComputeClient.java index 96a22de993..9ce8a8c99f 100644 --- a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/TerremarkVCloudComputeClient.java +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/TerremarkVCloudComputeClient.java @@ -234,12 +234,20 @@ public class TerremarkVCloudComputeClient extends BaseVCloudComputeClient { logger.debug("<< deleted vApp(%s))", vApp.getId()); } + /** + * @throws NullPointerException + * if the node is not found + */ @Override public Set getPrivateAddresses(String id) { VApp vApp = client.getVApp(id); return Sets.newHashSet(vApp.getNetworkToAddresses().values()); } + /** + * @throws NullPointerException + * if the node is not found + */ @Override public Set getPublicAddresses(String id) { VApp vApp = client.getVApp(id); diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/TerremarkVCloudComputeService.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/TerremarkVCloudComputeService.java new file mode 100644 index 0000000000..bc24e20168 --- /dev/null +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/TerremarkVCloudComputeService.java @@ -0,0 +1,108 @@ +/** + * + * Copyright (C) 2009 Cloud Conscious, LLC. + * + * ==================================================================== + * 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.vcloud.terremark.compute; + +import java.util.Set; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.ExecutorService; + +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Provider; +import javax.inject.Singleton; + +import org.jclouds.Constants; +import org.jclouds.compute.ComputeServiceContext; +import org.jclouds.compute.domain.Image; +import org.jclouds.compute.domain.NodeMetadata; +import org.jclouds.compute.domain.Size; +import org.jclouds.compute.domain.TemplateBuilder; +import org.jclouds.compute.internal.BaseComputeService; +import org.jclouds.compute.options.TemplateOptions; +import org.jclouds.compute.strategy.DestroyNodeStrategy; +import org.jclouds.compute.strategy.GetNodeMetadataStrategy; +import org.jclouds.compute.strategy.ListNodesStrategy; +import org.jclouds.compute.strategy.RebootNodeStrategy; +import org.jclouds.compute.strategy.RunNodesAndAddToSetStrategy; +import org.jclouds.compute.util.ComputeUtils; +import org.jclouds.domain.Location; +import org.jclouds.vcloud.terremark.compute.domain.OrgAndName; +import org.jclouds.vcloud.terremark.compute.functions.NodeMetadataToOrgAndName; +import org.jclouds.vcloud.terremark.compute.options.TerremarkVCloudTemplateOptions; +import org.jclouds.vcloud.terremark.compute.strategy.CleanupOrphanKeys; +import org.jclouds.vcloud.terremark.domain.KeyPair; + +import com.google.common.base.Predicate; + +/** + * @author Adrian Cole + */ +@Singleton +public class TerremarkVCloudComputeService extends BaseComputeService { + private final CleanupOrphanKeys cleanupOrphanKeys; + + @Inject + protected TerremarkVCloudComputeService(ComputeServiceContext context, + Provider> images, + Provider> sizes, + Provider> locations, + ListNodesStrategy listNodesStrategy, + GetNodeMetadataStrategy getNodeMetadataStrategy, + RunNodesAndAddToSetStrategy runNodesAndAddToSetStrategy, + RebootNodeStrategy rebootNodeStrategy, + DestroyNodeStrategy destroyNodeStrategy, + Provider templateBuilderProvider, + Provider templateOptionsProvider, + @Named("NODE_RUNNING") Predicate nodeRunning, + @Named("NODE_TERMINATED") Predicate nodeTerminated, + ComputeUtils utils, + @Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor, + CleanupOrphanKeys cleanupOrphanKeys, + ConcurrentMap credentialsMap, + NodeMetadataToOrgAndName nodeToOrgAndName) { + super(context, images, sizes, locations, listNodesStrategy, + getNodeMetadataStrategy, runNodesAndAddToSetStrategy, + rebootNodeStrategy, destroyNodeStrategy, templateBuilderProvider, + templateOptionsProvider, nodeRunning, nodeTerminated, utils, + executor); + this.cleanupOrphanKeys = cleanupOrphanKeys; + } + + /** + * like {@link BaseComputeService#destroyNodesMatching} except that this will + * clean implicit keypairs. + */ + @Override + public Set destroyNodesMatching( + Predicate filter) { + Set deadOnes = super.destroyNodesMatching(filter); + cleanupOrphanKeys.execute(deadOnes); + return deadOnes; + } + + /** + * returns template options, except of type + * {@link TerremarkVCloudTemplateOptions}. + */ + @Override + public TerremarkVCloudTemplateOptions templateOptions() { + return TerremarkVCloudTemplateOptions.class.cast(super.templateOptions()); + } + +} \ No newline at end of file diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/config/TerremarkVCloudComputeServiceContextModule.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/config/TerremarkVCloudComputeServiceContextModule.java index 95a50a6acd..e5fa0cb726 100755 --- a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/config/TerremarkVCloudComputeServiceContextModule.java +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/config/TerremarkVCloudComputeServiceContextModule.java @@ -18,23 +18,59 @@ */ package org.jclouds.vcloud.terremark.compute.config; +import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.vcloud.terremark.options.TerremarkInstantiateVAppTemplateOptions.Builder.processorCount; + import java.security.SecureRandom; +import java.util.Map; import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import javax.inject.Inject; import javax.inject.Named; +import javax.inject.Singleton; +import org.jclouds.compute.ComputeService; +import org.jclouds.compute.ComputeServiceContext; +import org.jclouds.compute.config.ComputeServiceTimeoutsModule; import org.jclouds.compute.domain.Image; +import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.OsFamily; -import org.jclouds.compute.domain.Size; +import org.jclouds.compute.domain.Template; import org.jclouds.compute.domain.TemplateBuilder; +import org.jclouds.compute.internal.ComputeServiceContextImpl; +import org.jclouds.compute.options.TemplateOptions; +import org.jclouds.compute.strategy.AddNodeWithTagStrategy; +import org.jclouds.compute.strategy.DestroyNodeStrategy; +import org.jclouds.compute.strategy.GetNodeMetadataStrategy; +import org.jclouds.compute.strategy.ListNodesStrategy; import org.jclouds.compute.strategy.PopulateDefaultLoginCredentialsForImageStrategy; +import org.jclouds.compute.strategy.RebootNodeStrategy; +import org.jclouds.compute.strategy.RunNodesAndAddToSetStrategy; +import org.jclouds.vcloud.VCloudAsyncClient; +import org.jclouds.vcloud.VCloudClient; import org.jclouds.vcloud.compute.VCloudComputeClient; import org.jclouds.vcloud.compute.config.VCloudComputeServiceContextModule; +import org.jclouds.vcloud.compute.strategy.VCloudDestroyNodeStrategy; +import org.jclouds.vcloud.compute.strategy.VCloudListNodesStrategy; +import org.jclouds.vcloud.compute.strategy.VCloudRebootNodeStrategy; +import org.jclouds.vcloud.endpoints.VCloud; +import org.jclouds.vcloud.terremark.TerremarkVCloudClient; import org.jclouds.vcloud.terremark.compute.TerremarkVCloudComputeClient; -import org.jclouds.vcloud.terremark.compute.config.providers.ComputeOptionsToSizeProvider; +import org.jclouds.vcloud.terremark.compute.TerremarkVCloudComputeService; import org.jclouds.vcloud.terremark.compute.config.providers.QueryCatalogForVAppTemplatesAndConvertToImagesProvider; +import org.jclouds.vcloud.terremark.compute.domain.OrgAndName; +import org.jclouds.vcloud.terremark.compute.functions.NodeMetadataToOrgAndName; +import org.jclouds.vcloud.terremark.compute.options.TerremarkVCloudTemplateOptions; import org.jclouds.vcloud.terremark.compute.strategy.ParseVAppTemplateDescriptionToGetDefaultLoginCredentials; +import org.jclouds.vcloud.terremark.compute.strategy.TerremarkEncodeTemplateIdIntoNameRunNodesAndAddToSetStrategy; +import org.jclouds.vcloud.terremark.compute.strategy.TerremarkVCloudGetNodeMetadataStrategy; +import org.jclouds.vcloud.terremark.domain.KeyPair; +import org.jclouds.vcloud.terremark.options.TerremarkInstantiateVAppTemplateOptions; +import com.google.common.base.Function; +import com.google.common.base.Supplier; import com.google.inject.Provides; import com.google.inject.Scopes; import com.google.inject.TypeLiteral; @@ -45,18 +81,120 @@ import com.google.inject.TypeLiteral; * * @author Adrian Cole */ -public class TerremarkVCloudComputeServiceContextModule extends VCloudComputeServiceContextModule { +public class TerremarkVCloudComputeServiceContextModule extends + VCloudComputeServiceContextModule { public TerremarkVCloudComputeServiceContextModule(String providerName) { super(providerName); } + @Provides + @Singleton + Supplier provideSuffix(final SecureRandom random) { + return new Supplier() { + @Override + public String get() { + return random.nextInt(100) + ""; + } + }; + + } + + @Singleton + public static class TerremarkVCloudAddNodeWithTagStrategy implements + AddNodeWithTagStrategy { + protected final TerremarkVCloudClient client; + protected final TerremarkVCloudComputeClient computeClient; + protected final GetNodeMetadataStrategy getNode; + protected final TemplateToInstantiateOptions getOptions; + + @Inject + protected TerremarkVCloudAddNodeWithTagStrategy( + TerremarkVCloudClient client, + TerremarkVCloudComputeClient computeClient, + GetNodeMetadataStrategy getNode, + TemplateToInstantiateOptions getOptions) { + this.client = client; + this.computeClient = computeClient; + this.getNode = getNode; + this.getOptions = checkNotNull(getOptions, "getOptions"); + } + + @Override + public NodeMetadata execute(String tag, String name, Template template) { + TerremarkInstantiateVAppTemplateOptions options = getOptions + .apply(template); + Map metaMap = computeClient.start(template + .getLocation().getId(), name, template.getImage() + .getProviderId(), options, template.getOptions() + .getInboundPorts()); + return getNode.execute(metaMap.get("id")); + } + + } + + @Singleton + public static class TemplateToInstantiateOptions implements + Function { + + @Override + public TerremarkInstantiateVAppTemplateOptions apply(Template from) { + TerremarkInstantiateVAppTemplateOptions options = processorCount( + Double.valueOf(from.getSize().getCores()).intValue()).memory( + from.getSize().getRam()); + if (!from.getOptions().shouldBlockUntilRunning()) + options.blockOnDeploy(false); + String sshKeyFingerprint = TerremarkVCloudTemplateOptions.class.cast( + from.getOptions()).getSshKeyFingerprint(); + if (sshKeyFingerprint != null) + options.sshKeyFingerprint(sshKeyFingerprint); + + return options; + } + } + @Override protected void configure() { - super.configure(); + install(new ComputeServiceTimeoutsModule()); + bind(String.class).annotatedWith(VCloud.class).toInstance(providerName); + // NOTE + bind(AddNodeWithTagStrategy.class).to( + TerremarkVCloudAddNodeWithTagStrategy.class); + bind(new TypeLiteral() { + }) + .to( + new TypeLiteral>() { + }).in(Scopes.SINGLETON); + // NOTE + bind(RunNodesAndAddToSetStrategy.class).to( + TerremarkEncodeTemplateIdIntoNameRunNodesAndAddToSetStrategy.class); + bind(ListNodesStrategy.class).to(VCloudListNodesStrategy.class); + // NOTE + bind(GetNodeMetadataStrategy.class).to( + TerremarkVCloudGetNodeMetadataStrategy.class); + bind(RebootNodeStrategy.class).to(VCloudRebootNodeStrategy.class); + bind(DestroyNodeStrategy.class).to(VCloudDestroyNodeStrategy.class); + bindLoadBalancer(); + bindSizes(); + bindImages(); + bindLocations(); + // MORE specifics... + bind(new TypeLiteral>() { + }).to(new TypeLiteral() { + }); + bind(TemplateOptions.class).to(TerremarkVCloudTemplateOptions.class); + bind(ComputeService.class).to(TerremarkVCloudComputeService.class); bind(VCloudComputeClient.class).to(TerremarkVCloudComputeClient.class); bind(PopulateDefaultLoginCredentialsForImageStrategy.class).to( - ParseVAppTemplateDescriptionToGetDefaultLoginCredentials.class); + ParseVAppTemplateDescriptionToGetDefaultLoginCredentials.class); + bind(SecureRandom.class).toInstance(new SecureRandom()); + + } + + @Provides + @Singleton + ConcurrentMap credentialsMap() { + return new ConcurrentHashMap(); } // TODO @@ -69,8 +207,8 @@ public class TerremarkVCloudComputeServiceContextModule extends VCloudComputeSer @Named("PASSWORD") @Provides - String providePassword() { - return new SecureRandom().nextLong() + ""; + String providePassword(SecureRandom random) { + return random.nextLong() + ""; } @Override @@ -81,14 +219,9 @@ public class TerremarkVCloudComputeServiceContextModule extends VCloudComputeSer @Override protected void bindImages() { bind(new TypeLiteral>() { - }).toProvider(QueryCatalogForVAppTemplatesAndConvertToImagesProvider.class).in( - Scopes.SINGLETON); - } - - @Override - protected void bindSizes() { - bind(new TypeLiteral>() { - }).toProvider(ComputeOptionsToSizeProvider.class).in(Scopes.SINGLETON); + }).toProvider( + QueryCatalogForVAppTemplatesAndConvertToImagesProvider.class).in( + Scopes.SINGLETON); } } diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/config/providers/ComputeOptionsToSizeProvider.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/config/providers/ComputeOptionsToSizeProvider.java deleted file mode 100644 index 039086ef46..0000000000 --- a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/config/providers/ComputeOptionsToSizeProvider.java +++ /dev/null @@ -1,88 +0,0 @@ -/** - * - * Copyright (C) 2009 Cloud Conscious, LLC. - * - * ==================================================================== - * 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.vcloud.terremark.compute.config.providers; - -import java.util.Set; -import java.util.SortedSet; - -import javax.annotation.Resource; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Provider; -import javax.inject.Singleton; - -import org.jclouds.compute.domain.Image; -import org.jclouds.compute.domain.Size; -import org.jclouds.compute.domain.internal.SizeImpl; -import org.jclouds.compute.predicates.ImagePredicates; -import org.jclouds.compute.reference.ComputeServiceConstants; -import org.jclouds.logging.Logger; -import org.jclouds.vcloud.terremark.TerremarkVCloudClient; -import org.jclouds.vcloud.terremark.domain.ComputeOptions; - -import com.google.common.base.Function; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Iterables; -import com.google.common.collect.Sets; - -/** - * @author Adrian Cole - */ -@Singleton -public class ComputeOptionsToSizeProvider implements Provider> { - @Resource - @Named(ComputeServiceConstants.COMPUTE_LOGGER) - public Logger logger = Logger.NULL; - private final TerremarkVCloudClient client; - private final ComputeOptionsToSize sizeConverter; - private final Provider> imageProvider; - - @Inject - ComputeOptionsToSizeProvider(TerremarkVCloudClient client, ComputeOptionsToSize sizeConverter, - Provider> imageProvider) { - this.client = client; - this.sizeConverter = sizeConverter; - this.imageProvider = imageProvider; - } - - @Singleton - private static class ComputeOptionsToSize implements Function { - @Override - public Size apply(ComputeOptions from) { - return new SizeImpl(from.toString(), from.toString(), from.toString(), null, null, - ImmutableMap. of(), from.getProcessorCount(), from.getMemory(), - 10, ImagePredicates.any()); - } - } - - /** - * TODO this implementation isn't purely correct, as the sizes for image 0 are not - * necessarily the same for all other images - */ - @Override - public Set get() { - Image anyImage = Iterables.get(imageProvider.get(), 0); - logger.debug(">> providing sizes"); - SortedSet sizes = Sets.newTreeSet(Iterables.transform(client - .getComputeOptionsOfCatalogItem(anyImage.getProviderId()), sizeConverter)); - logger.debug("<< sizes(%d)", sizes.size()); - return sizes; - } - -} \ No newline at end of file diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/domain/OrgAndName.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/domain/OrgAndName.java new file mode 100644 index 0000000000..4be5325ae8 --- /dev/null +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/domain/OrgAndName.java @@ -0,0 +1,78 @@ +/** + * + * Copyright (C) 2009 Cloud Conscious, LLC. + * + * ==================================================================== + * 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.vcloud.terremark.compute.domain; + +/** + * + * @author Adrian Cole + */ +public class OrgAndName { + protected final String org; + protected final String name; + + public OrgAndName(String org, String name) { + this.org = org; + this.name = name; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((org == null) ? 0 : org.hashCode()); + result = prime * result + ((name == null) ? 0 : name.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; + OrgAndName other = (OrgAndName) obj; + if (org == null) { + if (other.org != null) + return false; + } else if (!org.equals(other.org)) + return false; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } + + public String getOrg() { + return org; + } + + public String getName() { + return name; + } + + @Override + public String toString() { + return "OrgTag [org=" + org + ", name=" + name + "]"; + } + +} diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/functions/CreateUniqueKeyPair.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/functions/CreateUniqueKeyPair.java new file mode 100644 index 0000000000..1f8a5e444a --- /dev/null +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/functions/CreateUniqueKeyPair.java @@ -0,0 +1,89 @@ +/** + * + * Copyright (C) 2009 Cloud Conscious, LLC. + * + * ==================================================================== + * 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.vcloud.terremark.compute.functions; + +import static com.google.common.base.Preconditions.checkNotNull; + +import javax.annotation.Resource; +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; + +import org.jclouds.compute.reference.ComputeServiceConstants; +import org.jclouds.http.HttpResponseException; +import org.jclouds.logging.Logger; +import org.jclouds.util.Utils; +import org.jclouds.vcloud.terremark.TerremarkVCloudClient; +import org.jclouds.vcloud.terremark.compute.domain.OrgAndName; +import org.jclouds.vcloud.terremark.domain.KeyPair; + +import com.google.common.base.Function; +import com.google.common.base.Supplier; + +/** + * + * @author Adrian Cole + */ +@Singleton +public class CreateUniqueKeyPair implements Function { + @Resource + @Named(ComputeServiceConstants.COMPUTE_LOGGER) + protected Logger logger = Logger.NULL; + protected final TerremarkVCloudClient trmkClient; + protected Supplier randomSuffix; + + @Inject + CreateUniqueKeyPair(TerremarkVCloudClient trmkClient, + Supplier randomSuffix) { + this.trmkClient = trmkClient; + this.randomSuffix = randomSuffix; + } + + @Override + public KeyPair apply(OrgAndName from) { + return createNewKeyPairInRegion(from.getOrg(), from.getName()); + } + + private KeyPair createNewKeyPairInRegion(String org, String keyPairName) { + checkNotNull(org, "org"); + checkNotNull(keyPairName, "keyPairName"); + logger.debug(">> creating keyPair org(%s) name(%s)", org, keyPairName); + KeyPair keyPair = null; + while (keyPair == null) { + try { + keyPair = trmkClient.generateKeyPairInOrg(org, + getNextName(keyPairName), false); + logger.debug("<< created keyPair(%s)", keyPair.getName()); + } catch (RuntimeException e) { + HttpResponseException ht = Utils.getFirstThrowableOfType(e, + HttpResponseException.class); + if (ht == null + || ht.getContent() == null + || ht.getContent().indexOf( + "Security key with same name exists") == -1) + throw e; + } + } + return keyPair; + } + + private String getNextName(String keyPairName) { + return "jclouds#" + keyPairName + "-" + randomSuffix.get(); + } +} diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/functions/NodeMetadataToOrgAndName.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/functions/NodeMetadataToOrgAndName.java new file mode 100644 index 0000000000..0077484729 --- /dev/null +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/functions/NodeMetadataToOrgAndName.java @@ -0,0 +1,68 @@ +/** + * + * Copyright (C) 2009 Cloud Conscious, LLC. + * + * ==================================================================== + * 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.vcloud.terremark.compute.functions; + +import java.util.Map; + +import javax.annotation.Resource; +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; + +import org.jclouds.compute.domain.NodeMetadata; +import org.jclouds.compute.reference.ComputeServiceConstants; +import org.jclouds.logging.Logger; +import org.jclouds.vcloud.terremark.compute.domain.OrgAndName; + +import com.google.common.base.Function; + +/** + * + * @author Adrian Cole + * + */ +@Singleton +public class NodeMetadataToOrgAndName implements + Function { + + @Resource + @Named(ComputeServiceConstants.COMPUTE_LOGGER) + protected Logger logger = Logger.NULL; + + final Map vdcToOrg; + + @Inject + NodeMetadataToOrgAndName(@Named("VDC_TO_ORG") Map vdcToOrg) { + this.vdcToOrg = vdcToOrg; + } + + @Override + public OrgAndName apply(NodeMetadata from) { + if (from.getTag() != null) { + String org = vdcToOrg.get(from.getLocation().getId()); + if (org == null) { + logger.warn("did not find an association for vdc %s in %s", from + .getLocation().getId(), vdcToOrg); + } else { + return new OrgAndName(org, from.getTag()); + } + } + return null; + } +} \ No newline at end of file diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/options/TerremarkVCloudTemplateOptions.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/options/TerremarkVCloudTemplateOptions.java new file mode 100644 index 0000000000..d2cdd07df5 --- /dev/null +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/options/TerremarkVCloudTemplateOptions.java @@ -0,0 +1,280 @@ +/** + * + * Copyright (C) 2009 Cloud Conscious, LLC. + * + * ==================================================================== + * 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.vcloud.terremark.compute.options; + +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkState; + +import java.util.Arrays; + +import org.jclouds.compute.options.TemplateOptions; +import org.jclouds.util.Utils; + +/** + * Contains options supported in the {@code ComputeService#runNode} operation on + * the "ec2" provider.

+ * Usage

The recommended way to instantiate a + * TerremarkVCloudTemplateOptions object is to statically import + * TerremarkVCloudTemplateOptions.* and invoke a static creation method followed + * by an instance mutator (if needed): + *

+ * + * import static org.jclouds.vcloud.terremark.compute.options.TerremarkVCloudTemplateOptions.Builder.*; + *

+ * ComputeService client = // get connection + * templateBuilder.options(inboundPorts(22, 80, 8080, 443)); + * Set set = client.runNodesWithTag(tag, 2, templateBuilder.build()); + * + * + * @author Adrian Cole + */ +public class TerremarkVCloudTemplateOptions extends TemplateOptions { + + private String keyPair = null; + private boolean noKeyPair; + + public static final TerremarkVCloudTemplateOptions NONE = new TerremarkVCloudTemplateOptions(); + + /** + * Specifies the keypair used to run instances with + */ + public TerremarkVCloudTemplateOptions sshKeyFingerprint(String keyPair) { + checkNotNull(keyPair, + "use noKeyPair option to request boot without a keypair"); + checkState(!noKeyPair, + "you cannot specify both options keyPair and noKeyPair"); + Utils.checkNotEmpty(keyPair, "keypair must be non-empty"); + this.keyPair = keyPair; + return this; + } + + /** + * Do not use a keypair on instances + */ + public TerremarkVCloudTemplateOptions noKeyPair() { + checkState(keyPair == null, + "you cannot specify both options keyPair and noKeyPair"); + this.noKeyPair = true; + return this; + } + + public static class Builder { + + /** + * @see TerremarkVCloudTemplateOptions#sshKeyFingerprint + */ + public static TerremarkVCloudTemplateOptions sshKeyFingerprint( + String keyPair) { + TerremarkVCloudTemplateOptions options = new TerremarkVCloudTemplateOptions(); + return TerremarkVCloudTemplateOptions.class.cast(options + .sshKeyFingerprint(keyPair)); + } + + /** + * @see TerremarkVCloudTemplateOptions#noKeyPair + */ + public static TerremarkVCloudTemplateOptions noKeyPair() { + TerremarkVCloudTemplateOptions options = new TerremarkVCloudTemplateOptions(); + return TerremarkVCloudTemplateOptions.class.cast(options.noKeyPair()); + } + + // methods that only facilitate returning the correct object type + /** + * @see TemplateOptions#inboundPorts + */ + public static TerremarkVCloudTemplateOptions inboundPorts(int... ports) { + TerremarkVCloudTemplateOptions options = new TerremarkVCloudTemplateOptions(); + return TerremarkVCloudTemplateOptions.class.cast(options + .inboundPorts(ports)); + } + + /** + * @see TemplateOptions#port + */ + public static TerremarkVCloudTemplateOptions blockOnPort(int port, + int seconds) { + TerremarkVCloudTemplateOptions options = new TerremarkVCloudTemplateOptions(); + return TerremarkVCloudTemplateOptions.class.cast(options.blockOnPort( + port, seconds)); + } + + /** + * @see TemplateOptions#blockUntilRunning + */ + public static TerremarkVCloudTemplateOptions blockUntilRunning( + boolean blockUntilRunning) { + TerremarkVCloudTemplateOptions options = new TerremarkVCloudTemplateOptions(); + return TerremarkVCloudTemplateOptions.class.cast(options + .blockUntilRunning(blockUntilRunning)); + } + + /** + * @see TemplateOptions#runScript + */ + public static TerremarkVCloudTemplateOptions runScript(byte[] script) { + TerremarkVCloudTemplateOptions options = new TerremarkVCloudTemplateOptions(); + return TerremarkVCloudTemplateOptions.class.cast(options + .runScript(script)); + } + + /** + * @see TemplateOptions#installPrivateKey + */ + public static TerremarkVCloudTemplateOptions installPrivateKey( + String rsaKey) { + TerremarkVCloudTemplateOptions options = new TerremarkVCloudTemplateOptions(); + return TerremarkVCloudTemplateOptions.class.cast(options + .installPrivateKey(rsaKey)); + } + + /** + * @see TemplateOptions#authorizePublicKey + */ + public static TerremarkVCloudTemplateOptions authorizePublicKey( + String rsaKey) { + TerremarkVCloudTemplateOptions options = new TerremarkVCloudTemplateOptions(); + return TerremarkVCloudTemplateOptions.class.cast(options + .authorizePublicKey(rsaKey)); + } + + /** + * @see TemplateOptions#withDetails + */ + public static TerremarkVCloudTemplateOptions withDetails() { + TerremarkVCloudTemplateOptions options = new TerremarkVCloudTemplateOptions(); + return TerremarkVCloudTemplateOptions.class.cast(options + .withMetadata()); + } + + } + + // methods that only facilitate returning the correct object type + + /** + * @see TemplateOptions#authorizePublicKey + */ + @Override + public TerremarkVCloudTemplateOptions authorizePublicKey(String publicKey) { + return TerremarkVCloudTemplateOptions.class.cast(super + .authorizePublicKey(publicKey)); + } + + /** + * @see TemplateOptions#blockOnPort + */ + @Override + public TerremarkVCloudTemplateOptions blockOnPort(int port, int seconds) { + return TerremarkVCloudTemplateOptions.class.cast(super.blockOnPort(port, + seconds)); + } + + /** + * + * special thing is that we do assume if you are passing groups that you have + * everything you need already defined. for example, our option inboundPorts + * normally creates ingress rules accordingly but if we notice you've + * specified securityGroups, we do not mess with rules at all + * + * @see TemplateOptions#inboundPorts + */ + @Override + public TerremarkVCloudTemplateOptions inboundPorts(int... ports) { + return TerremarkVCloudTemplateOptions.class.cast(super + .inboundPorts(ports)); + } + + /** + * @see TemplateOptions#installPrivateKey + */ + @Override + public TerremarkVCloudTemplateOptions installPrivateKey(String privateKey) { + return TerremarkVCloudTemplateOptions.class.cast(super + .installPrivateKey(privateKey)); + } + + /** + * @see TemplateOptions#runScript + */ + @Override + public TerremarkVCloudTemplateOptions runScript(byte[] script) { + return TerremarkVCloudTemplateOptions.class.cast(super.runScript(script)); + } + + /** + * @see TemplateOptions#withMetadata + */ + @Override + public TerremarkVCloudTemplateOptions withMetadata() { + return TerremarkVCloudTemplateOptions.class.cast(super.withMetadata()); + } + + /** + * @return keyPair to use when running the instance or null, to generate a + * keypair. + */ + public String getSshKeyFingerprint() { + return keyPair; + } + + /** + * @return true (default) if we are supposed to use a keypair + */ + public boolean shouldAutomaticallyCreateKeyPair() { + return !noKeyPair; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + ((keyPair == null) ? 0 : keyPair.hashCode()); + result = prime * result + (noKeyPair ? 1231 : 1237); + 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; + TerremarkVCloudTemplateOptions other = (TerremarkVCloudTemplateOptions) obj; + if (keyPair == null) { + if (other.keyPair != null) + return false; + } else if (!keyPair.equals(other.keyPair)) + return false; + if (noKeyPair != other.noKeyPair) + return false; + return true; + } + + @Override + public String toString() { + return "TerremarkVCloudTemplateOptions [keyPair=" + keyPair + + ", noKeyPair=" + noKeyPair + ", inboundPorts=" + + Arrays.toString(inboundPorts) + ", privateKey=" + + (privateKey != null) + ", publicKey=" + (publicKey != null) + + ", runScript=" + (script != null) + ", port:seconds=" + port + + ":" + seconds + ", metadata/details: " + includeMetadata + "]"; + } + +} diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/strategy/CleanupOrphanKeys.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/strategy/CleanupOrphanKeys.java new file mode 100644 index 0000000000..5449cd00fc --- /dev/null +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/strategy/CleanupOrphanKeys.java @@ -0,0 +1,71 @@ +/** + * + * Copyright (C) 2009 Cloud Conscious, LLC. + * + * ==================================================================== + * 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.vcloud.terremark.compute.strategy; + +import static com.google.common.base.Predicates.notNull; +import static com.google.common.collect.Iterables.all; +import static com.google.common.collect.Iterables.filter; +import static com.google.common.collect.Iterables.size; +import static com.google.common.collect.Iterables.transform; +import static org.jclouds.compute.predicates.NodePredicates.TERMINATED; +import static org.jclouds.compute.predicates.NodePredicates.parentLocationId; +import static org.jclouds.compute.predicates.NodePredicates.withTag; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.compute.domain.NodeMetadata; +import org.jclouds.compute.strategy.ListNodesStrategy; +import org.jclouds.vcloud.terremark.compute.domain.OrgAndName; + +import com.google.common.base.Function; + +/** + * + * @author Adrian Cole + * + */ +@Singleton +public class CleanupOrphanKeys { + final Function nodeToOrgAndName; + final DeleteKeyPair deleteKeyPair; + final ListNodesStrategy listNodes; + + @Inject + CleanupOrphanKeys(Function nodeToOrgAndName, + DeleteKeyPair deleteKeyPair, ListNodesStrategy listNodes) { + this.nodeToOrgAndName = nodeToOrgAndName; + this.deleteKeyPair = deleteKeyPair; + this.listNodes = listNodes; + } + + public void execute(Iterable deadOnes) { + Iterable orgTags = filter(transform(deadOnes, + nodeToOrgAndName), notNull()); + for (OrgAndName orgTag : orgTags) { + Iterable nodesInOrg = listNodes + .listDetailsOnNodesMatching(parentLocationId(orgTag.getOrg())); + Iterable nodesWithTag = filter(nodesInOrg, + withTag(orgTag.getName())); + if (size(nodesWithTag) == 0 || all(nodesWithTag, TERMINATED)) + deleteKeyPair.execute(orgTag); + } + } + +} \ No newline at end of file diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/strategy/CreateNewKeyPairUnlessUserSpecifiedOtherwise.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/strategy/CreateNewKeyPairUnlessUserSpecifiedOtherwise.java new file mode 100644 index 0000000000..bd85556ac2 --- /dev/null +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/strategy/CreateNewKeyPairUnlessUserSpecifiedOtherwise.java @@ -0,0 +1,70 @@ +/** + * + * Copyright (C) 2009 Cloud Conscious, LLC. + * + * ==================================================================== + * 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.vcloud.terremark.compute.strategy; + +import java.util.concurrent.ConcurrentMap; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.vcloud.terremark.compute.domain.OrgAndName; +import org.jclouds.vcloud.terremark.compute.functions.CreateUniqueKeyPair; +import org.jclouds.vcloud.terremark.compute.options.TerremarkVCloudTemplateOptions; +import org.jclouds.vcloud.terremark.domain.KeyPair; + +import com.google.common.annotations.VisibleForTesting; + +/** + * + * @author Adrian Cole + * + */ +@Singleton +public class CreateNewKeyPairUnlessUserSpecifiedOtherwise { + final ConcurrentMap credentialsMap; + @VisibleForTesting + final CreateUniqueKeyPair createUniqueKeyPair; + + @Inject + CreateNewKeyPairUnlessUserSpecifiedOtherwise( + ConcurrentMap credentialsMap, + CreateUniqueKeyPair createUniqueKeyPair) { + this.credentialsMap = credentialsMap; + this.createUniqueKeyPair = createUniqueKeyPair; + } + + @VisibleForTesting + public void execute(String org, String tag, + TerremarkVCloudTemplateOptions options) { + String sshKeyFingerprint = options.getSshKeyFingerprint(); + boolean shouldAutomaticallyCreateKeyPair = options + .shouldAutomaticallyCreateKeyPair(); + if (sshKeyFingerprint == null && shouldAutomaticallyCreateKeyPair) { + OrgAndName orgAndName = new OrgAndName(org, tag); + if (credentialsMap.containsKey(orgAndName)) { + options.sshKeyFingerprint(credentialsMap.get(orgAndName) + .getFingerPrint()); + } else { + KeyPair keyPair = createUniqueKeyPair.apply(orgAndName); + credentialsMap.put(orgAndName, keyPair); + options.sshKeyFingerprint(keyPair.getFingerPrint()); + } + } + } +} \ No newline at end of file diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/strategy/DeleteKeyPair.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/strategy/DeleteKeyPair.java new file mode 100644 index 0000000000..65ec33b40b --- /dev/null +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/strategy/DeleteKeyPair.java @@ -0,0 +1,67 @@ +/** + * + * Copyright (C) 2009 Cloud Conscious, LLC. + * + * ==================================================================== + * 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.vcloud.terremark.compute.strategy; + +import java.util.concurrent.ConcurrentMap; + +import javax.annotation.Resource; +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; + +import org.jclouds.compute.reference.ComputeServiceConstants; +import org.jclouds.logging.Logger; +import org.jclouds.vcloud.terremark.TerremarkVCloudClient; +import org.jclouds.vcloud.terremark.compute.domain.OrgAndName; +import org.jclouds.vcloud.terremark.domain.KeyPair; + +/** + * + * @author Adrian Cole + * + */ +@Singleton +public class DeleteKeyPair { + @Resource + @Named(ComputeServiceConstants.COMPUTE_LOGGER) + protected Logger logger = Logger.NULL; + + final TerremarkVCloudClient terremarkClient; + final ConcurrentMap credentialsMap; + + @Inject + DeleteKeyPair(TerremarkVCloudClient terremarkClient, + ConcurrentMap credentialsMap) { + this.terremarkClient = terremarkClient; + this.credentialsMap = credentialsMap; + } + + public void execute(OrgAndName orgTag) { + for (KeyPair keyPair : terremarkClient.listKeyPairsInOrg(orgTag.getOrg())) { + if (keyPair.getName().matches( + "jclouds#" + orgTag.getName() + "-[0-9]+")) { + logger.debug(">> deleting keyPair(%s)", keyPair.getName()); + terremarkClient.deleteKeyPair(keyPair.getId()); + // TODO: test this clear happens + credentialsMap.remove(orgTag); + logger.debug("<< deleted keyPair(%s)", keyPair.getName()); + } + } + } +} \ No newline at end of file diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/strategy/TerremarkEncodeTemplateIdIntoNameRunNodesAndAddToSetStrategy.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/strategy/TerremarkEncodeTemplateIdIntoNameRunNodesAndAddToSetStrategy.java new file mode 100644 index 0000000000..bfdd319a2e --- /dev/null +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/strategy/TerremarkEncodeTemplateIdIntoNameRunNodesAndAddToSetStrategy.java @@ -0,0 +1,75 @@ +/** + * + * Copyright (C) 2009 Cloud Conscious, LLC. + * + * ==================================================================== + * 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.vcloud.terremark.compute.strategy; + +import java.security.SecureRandom; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ExecutorService; + +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; + +import org.jclouds.Constants; +import org.jclouds.compute.domain.NodeMetadata; +import org.jclouds.compute.domain.Template; +import org.jclouds.compute.strategy.AddNodeWithTagStrategy; +import org.jclouds.compute.strategy.ListNodesStrategy; +import org.jclouds.compute.util.ComputeUtils; +import org.jclouds.vcloud.compute.strategy.EncodeTemplateIdIntoNameRunNodesAndAddToSetStrategy; +import org.jclouds.vcloud.terremark.compute.options.TerremarkVCloudTemplateOptions; + +import com.google.common.util.concurrent.ListenableFuture; + +/** + * creates futures that correlate to + * + * @author Adrian Cole + */ +@Singleton +public class TerremarkEncodeTemplateIdIntoNameRunNodesAndAddToSetStrategy + extends EncodeTemplateIdIntoNameRunNodesAndAddToSetStrategy { + + private final CreateNewKeyPairUnlessUserSpecifiedOtherwise createNewKeyPairUnlessUserSpecifiedOtherwise; + + @Inject + protected TerremarkEncodeTemplateIdIntoNameRunNodesAndAddToSetStrategy( + AddNodeWithTagStrategy addNodeWithTagStrategy, + ListNodesStrategy listNodesStrategy, + @Named("NAMING_CONVENTION") String nodeNamingConvention, + ComputeUtils utils, + @Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor, + SecureRandom random, + CreateNewKeyPairUnlessUserSpecifiedOtherwise createNewKeyPairUnlessUserSpecifiedOtherwise) { + super(addNodeWithTagStrategy, listNodesStrategy, nodeNamingConvention, + utils, executor, random); + this.createNewKeyPairUnlessUserSpecifiedOtherwise = createNewKeyPairUnlessUserSpecifiedOtherwise; + } + + @Override + public Map> execute(String tag, int count, + Template template, Set nodes, + Map badNodes) { + createNewKeyPairUnlessUserSpecifiedOtherwise.execute(template + .getLocation().getParent().getId(), tag, template.getOptions().as( + TerremarkVCloudTemplateOptions.class)); + return super.execute(tag, count, template, nodes, badNodes); + } +} \ No newline at end of file diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/strategy/TerremarkVCloudGetNodeMetadataStrategy.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/strategy/TerremarkVCloudGetNodeMetadataStrategy.java new file mode 100644 index 0000000000..6d7f330e1e --- /dev/null +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/strategy/TerremarkVCloudGetNodeMetadataStrategy.java @@ -0,0 +1,114 @@ +/** + * + * Copyright (C) 2009 Cloud Conscious, LLC. + * + * ==================================================================== + * 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.vcloud.terremark.compute.strategy; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.concurrent.ConcurrentMap; + +import javax.annotation.Resource; +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; + +import org.jclouds.compute.domain.NodeMetadata; +import org.jclouds.compute.reference.ComputeServiceConstants; +import org.jclouds.compute.util.ComputeUtils; +import org.jclouds.domain.Credentials; +import org.jclouds.logging.Logger; +import org.jclouds.vcloud.compute.functions.VCloudGetNodeMetadata; +import org.jclouds.vcloud.compute.strategy.VCloudGetNodeMetadataStrategy; +import org.jclouds.vcloud.terremark.compute.domain.OrgAndName; +import org.jclouds.vcloud.terremark.domain.KeyPair; + +/** + * @author Adrian Cole + */ +@Singleton +public class TerremarkVCloudGetNodeMetadataStrategy extends + VCloudGetNodeMetadataStrategy { + @Resource + @Named(ComputeServiceConstants.COMPUTE_LOGGER) + protected Logger logger = Logger.NULL; + + private final ConcurrentMap credentialsMap; + + @Inject + protected TerremarkVCloudGetNodeMetadataStrategy( + VCloudGetNodeMetadata getNodeMetadata, + ConcurrentMap credentialsMap) { + super(getNodeMetadata); + this.credentialsMap = credentialsMap; + } + + @Override + public NodeMetadata execute(String id) { + try { + NodeMetadata node = checkNotNull(getNodeMetadata.execute(checkNotNull(id, "node.id")), + "node: " + id); + if (node.getTag() != null) { + node = installCredentialsFromCache(node); + } + if (node.getCredentials() == null) + node = installDefaultCredentialsFromImage(node); + return node; + } catch (NullPointerException e) { + if (logger.isTraceEnabled()) + logger.warn(e, "node %s not found during execution", id); + return null; + } + } + + NodeMetadata installCredentialsFromCache(NodeMetadata node) { + OrgAndName orgAndName = getOrgAndNameFromNode(node); + if (credentialsMap.containsKey(orgAndName)) { + String account = getLoginAccountForNode(node); + if (account != null) { + String privateKey = credentialsMap.get(orgAndName).getPrivateKey(); + Credentials creds = new Credentials(account, privateKey); + node = ComputeUtils.installNewCredentials(node, creds); + } + } + return node; + } + + OrgAndName getOrgAndNameFromNode(NodeMetadata node) { + String orgId = node.getLocation().getParent().getId(); + OrgAndName orgAndName = new OrgAndName(orgId, node.getTag()); + return orgAndName; + } + + String getLoginAccountForNode(NodeMetadata node) { + String account = null; + if (node.getCredentials() != null) + account = node.getCredentials().account; + else if (node.getImage() != null + && node.getImage().getDefaultCredentials() != null) + account = node.getImage().getDefaultCredentials().account; + return account; + } + + NodeMetadata installDefaultCredentialsFromImage(NodeMetadata node) { + if (node.getImage() != null + && node.getImage().getDefaultCredentials() != null) + node = ComputeUtils.installNewCredentials(node, node.getImage() + .getDefaultCredentials()); + return node; + } +} \ No newline at end of file diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/config/TerremarkVCloudRestClientModule.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/config/TerremarkVCloudRestClientModule.java index 66fafa5cba..340e2f03a4 100644 --- a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/config/TerremarkVCloudRestClientModule.java +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/config/TerremarkVCloudRestClientModule.java @@ -19,6 +19,7 @@ package org.jclouds.vcloud.terremark.config; import java.io.IOException; +import java.net.URI; import javax.inject.Named; import javax.inject.Singleton; @@ -29,20 +30,25 @@ import org.jclouds.util.Utils; import org.jclouds.vcloud.VCloudAsyncClient; import org.jclouds.vcloud.VCloudClient; import org.jclouds.vcloud.config.BaseVCloudRestClientModule; +import org.jclouds.vcloud.domain.Organization; import org.jclouds.vcloud.terremark.TerremarkVCloudAsyncClient; import org.jclouds.vcloud.terremark.TerremarkVCloudClient; +import org.jclouds.vcloud.terremark.domain.TerremarkOrganization; +import org.jclouds.vcloud.terremark.endpoints.KeysList; import com.google.inject.Provides; /** - * Configures the VCloud authentication service connection, including logging and http transport. + * Configures the VCloud authentication service connection, including logging + * and http transport. * * @author Adrian Cole */ @RequiresHttp @ConfiguresRestClient -public class TerremarkVCloudRestClientModule extends - BaseVCloudRestClientModule { +public class TerremarkVCloudRestClientModule + extends + BaseVCloudRestClientModule { public TerremarkVCloudRestClientModule() { super(TerremarkVCloudClient.class, TerremarkVCloudAsyncClient.class); @@ -50,7 +56,8 @@ public class TerremarkVCloudRestClientModule extends @Provides @Singleton - protected VCloudAsyncClient provideVCloudAsyncClient(TerremarkVCloudAsyncClient in) { + protected VCloudAsyncClient provideVCloudAsyncClient( + TerremarkVCloudAsyncClient in) { return in; } @@ -60,12 +67,19 @@ public class TerremarkVCloudRestClientModule extends return in; } + @Provides + @KeysList + @Singleton + protected URI provideDefaultKeysList(Organization org) { + return TerremarkOrganization.class.cast(org).getKeysList().getLocation(); + } + @Singleton @Provides @Named("CreateInternetService") String provideCreateInternetService() throws IOException { return Utils.toStringAndClose(getClass().getResourceAsStream( - "/terremark/CreateInternetService.xml")); + "/terremark/CreateInternetService.xml")); } @Singleton @@ -73,6 +87,14 @@ public class TerremarkVCloudRestClientModule extends @Named("CreateNodeService") String provideCreateNodeService() throws IOException { return Utils.toStringAndClose(getClass().getResourceAsStream( - "/terremark/CreateNodeService.xml")); + "/terremark/CreateNodeService.xml")); + } + + @Singleton + @Provides + @Named("CreateKey") + String provideCreateKey() throws IOException { + return Utils.toStringAndClose(getClass().getResourceAsStream( + "/terremark/CreateKey.xml")); } } diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/domain/ComputeOptions.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/domain/ComputeOptions.java deleted file mode 100644 index a1599db684..0000000000 --- a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/domain/ComputeOptions.java +++ /dev/null @@ -1,97 +0,0 @@ -/** - * - * Copyright (C) 2009 Cloud Conscious, LLC. - * - * ==================================================================== - * 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.vcloud.terremark.domain; - -/** - * The compute options are the CPU and memory configurations supported by Terremark and by the guest - * operating system of the vApp. - * - * @author Adrian Cole - * @see Terremark documentation - */ -public class ComputeOptions implements Comparable { - private final int processorCount; - private final int memory; - private final float costPerHour; - - public ComputeOptions(int processorCount, int memory, float costPerHour) { - this.processorCount = processorCount; - this.memory = memory; - this.costPerHour = costPerHour; - } - - public int getProcessorCount() { - return processorCount; - } - - public int getMemory() { - return memory; - } - - public float getCostPerHour() { - return costPerHour; - } - - /** - * orders by cost - */ - public int compareTo(ComputeOptions that) { - if (this == that) - return 0; - if (this.costPerHour < that.costPerHour) - return -1; - return 1; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + Float.floatToIntBits(costPerHour); - result = prime * result + (int) (memory ^ (memory >>> 32)); - result = prime * result + 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; - ComputeOptions other = (ComputeOptions) obj; - if (Float.floatToIntBits(costPerHour) != Float.floatToIntBits(other.costPerHour)) - return false; - if (memory != other.memory) - return false; - if (processorCount != other.processorCount) - return false; - return true; - } - - @Override - public String toString() { - return "ComputeOption [costPerHour=" + costPerHour + ", memory=" + memory - + ", processorCount=" + processorCount + "]"; - } -} \ No newline at end of file diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/domain/CustomizationParameters.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/domain/CustomizationParameters.java index 52e85fa5f4..fef1f993d3 100644 --- a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/domain/CustomizationParameters.java +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/domain/CustomizationParameters.java @@ -19,8 +19,8 @@ package org.jclouds.vcloud.terremark.domain; /** - * The response lists which customization options are supported for this particular vApp. The - * possible customization options are Network and Password. + * The response lists which customization options are supported for this + * particular vApp. The possible customization options are Network and Password. * * @author Adrian Cole * @see - * - * ==================================================================== - * 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.vcloud.terremark.domain; - -/** - * - * @author Adrian Cole - * - */ -public class InternetServiceConfiguration extends NodeConfiguration { - - private String timeout = null; - - /** - * One factor that affects the load balancing is the timeout, or persistence. The timeout is the - * number of minutes that the task can remain idle on a given node before the underlying software - * attempts to rebalance the node by possibly assigning that task to a different node. The - * default timeout is one minute. You can change the value using this call. - */ - public InternetServiceConfiguration changeTimeoutTo(int timeout) { - this.timeout = timeout + ""; - return this; - } - - @Override - public InternetServiceConfiguration changeDescriptionTo(String description) { - return (InternetServiceConfiguration) super.changeDescriptionTo(description); - } - - @Override - public InternetServiceConfiguration changeNameTo(String name) { - return (InternetServiceConfiguration) super.changeNameTo(name); - } - - @Override - public InternetServiceConfiguration disableTraffic() { - return (InternetServiceConfiguration) super.disableTraffic(); - } - - @Override - public InternetServiceConfiguration enableTraffic() { - return (InternetServiceConfiguration) super.enableTraffic(); - } - - public static class Builder { - /** - * @see InternetServiceConfiguration#changeTimeoutTo(int) - */ - public static InternetServiceConfiguration changeTimeoutTo(int timeout) { - InternetServiceConfiguration options = new InternetServiceConfiguration(); - return options.changeTimeoutTo(timeout); - } - - /** - * @see InternetServiceConfiguration#changeNameTo(String) - */ - public static InternetServiceConfiguration changeNameTo(String name) { - InternetServiceConfiguration options = new InternetServiceConfiguration(); - return options.changeNameTo(name); - } - - /** - * @see InternetServiceConfiguration#changeDescriptionTo(String) - */ - public static InternetServiceConfiguration changeDescriptionTo(String description) { - InternetServiceConfiguration options = new InternetServiceConfiguration(); - return options.changeDescriptionTo(description); - } - - /** - * @see InternetServiceConfiguration#enableTraffic() - */ - public static InternetServiceConfiguration enableTraffic() { - InternetServiceConfiguration options = new InternetServiceConfiguration(); - return options.enableTraffic(); - } - - /** - * @see InternetServiceConfiguration#disableTraffic() - */ - public static InternetServiceConfiguration disableTraffic() { - InternetServiceConfiguration options = new InternetServiceConfiguration(); - return options.disableTraffic(); - } - } - - public String getTimeout() { - return timeout; - } - -} diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/domain/KeyPair.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/domain/KeyPair.java new file mode 100644 index 0000000000..0905ef8f3b --- /dev/null +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/domain/KeyPair.java @@ -0,0 +1,132 @@ +/** + * + * Copyright (C) 2009 Cloud Conscious, LLC. + * + * ==================================================================== + * 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.vcloud.terremark.domain; + +import java.net.URI; + +import javax.annotation.Nullable; + +/** + * an SSH keypair + * + * @author Adrian Cole + */ +public class KeyPair { + private final int id; + private final URI location; + private final String name; + private final boolean isDefault; + @Nullable + private final String privateKey; + private final String fingerPrint; + + public KeyPair(int id, URI location, String name, boolean isDefault, + @Nullable String privateKey, String fingerPrint) { + this.id = id; + this.location = location; + this.name = name; + this.isDefault = isDefault; + this.privateKey = privateKey; + this.fingerPrint = fingerPrint; + } + + public int getId() { + return id; + } + + public URI getLocation() { + return location; + } + + public String getName() { + return name; + } + + public boolean isDefault() { + return isDefault; + } + + @Nullable + public String getPrivateKey() { + return privateKey; + } + + public String getFingerPrint() { + return fingerPrint; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + + ((fingerPrint == null) ? 0 : fingerPrint.hashCode()); + result = prime * result + ((location == null) ? 0 : location.hashCode()); + result = prime * result + id; + result = prime * result + (isDefault ? 1231 : 1237); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + result = prime * result + + ((privateKey == null) ? 0 : privateKey.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; + KeyPair other = (KeyPair) obj; + if (fingerPrint == null) { + if (other.fingerPrint != null) + return false; + } else if (!fingerPrint.equals(other.fingerPrint)) + return false; + if (location == null) { + if (other.location != null) + return false; + } else if (!location.equals(other.location)) + return false; + if (id != other.id) + return false; + if (isDefault != other.isDefault) + return false; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + if (privateKey == null) { + if (other.privateKey != null) + return false; + } else if (!privateKey.equals(other.privateKey)) + return false; + return true; + } + + @Override + public String toString() { + return "Key [fingerPrint=" + fingerPrint + ", location=" + location + ", id=" + + id + ", isDefault=" + isDefault + ", name=" + name + + ", privateKey=" + (privateKey != null) + "]"; + } + +} \ No newline at end of file diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/domain/Protocol.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/domain/Protocol.java index 77b94f0be8..756cd1c2ab 100644 --- a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/domain/Protocol.java +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/domain/Protocol.java @@ -27,6 +27,6 @@ package org.jclouds.vcloud.terremark.domain; */ public enum Protocol { - FTP, HTTP, HTTPS, TCP, UDP; + FTP, HTTP, HTTPS, TCP, UDP, PPTP, IPSEC; } \ No newline at end of file diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/domain/TerremarkOrganization.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/domain/TerremarkOrganization.java new file mode 100644 index 0000000000..2d1b842ba9 --- /dev/null +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/domain/TerremarkOrganization.java @@ -0,0 +1,39 @@ +/** + * + * Copyright (C) 2009 Cloud Conscious, LLC. + * + * ==================================================================== + * 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.vcloud.terremark.domain; + +import org.jclouds.vcloud.domain.NamedResource; +import org.jclouds.vcloud.domain.Organization; +import org.jclouds.vcloud.endpoints.Org; +import org.jclouds.vcloud.terremark.domain.internal.TerremarkOrganizationImpl; +import org.jclouds.vcloud.terremark.endpoints.KeysList; + +import com.google.inject.ImplementedBy; + +/** + * @author Adrian Cole + */ +@Org +@ImplementedBy(TerremarkOrganizationImpl.class) +public interface TerremarkOrganization extends Organization { + + @KeysList + NamedResource getKeysList(); + +} \ No newline at end of file diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/domain/internal/TerremarkOrganizationImpl.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/domain/internal/TerremarkOrganizationImpl.java new file mode 100644 index 0000000000..2a4c87a2f1 --- /dev/null +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/domain/internal/TerremarkOrganizationImpl.java @@ -0,0 +1,51 @@ +/** + * + * Copyright (C) 2009 Cloud Conscious, LLC. + * + * ==================================================================== + * 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.vcloud.terremark.domain.internal; + +import java.net.URI; +import java.util.Map; + +import org.jclouds.vcloud.domain.NamedResource; +import org.jclouds.vcloud.domain.internal.OrganizationImpl; +import org.jclouds.vcloud.terremark.domain.TerremarkOrganization; + +/** + * Locations of resources in a Terremark vCloud + * + * @author Adrian Cole + * + */ +public class TerremarkOrganizationImpl extends OrganizationImpl implements + TerremarkOrganization { + + private final NamedResource keysList; + + public TerremarkOrganizationImpl(String id, String name, URI location, + Map catalogs, Map vdcs, + Map tasksLists, NamedResource keysList) { + super(id, name, location, catalogs, vdcs, tasksLists); + this.keysList = keysList; + } + + @Override + public NamedResource getKeysList() { + return keysList; + } + +} \ No newline at end of file diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/endpoints/KeysList.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/endpoints/KeysList.java new file mode 100644 index 0000000000..981db6f6ac --- /dev/null +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/endpoints/KeysList.java @@ -0,0 +1,39 @@ +/** + * + * Copyright (C) 2009 Cloud Conscious, LLC. + * + * ==================================================================== + * 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.vcloud.terremark.endpoints; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import javax.inject.Qualifier; + +/** + * Related to Terremark SSH Keys List. + * + * @author Adrian Cole + * + */ +@Retention(value = RetentionPolicy.RUNTIME) +@Target(value = { ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD }) +@Qualifier +public @interface KeysList { + +} \ No newline at end of file diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/options/TerremarkInstantiateVAppTemplateOptions.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/options/TerremarkInstantiateVAppTemplateOptions.java index e6dcd2c8b5..2ef0ab6128 100644 --- a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/options/TerremarkInstantiateVAppTemplateOptions.java +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/options/TerremarkInstantiateVAppTemplateOptions.java @@ -28,7 +28,25 @@ import org.jclouds.vcloud.options.InstantiateVAppTemplateOptions; * @author Adrian Cole * */ -public class TerremarkInstantiateVAppTemplateOptions extends InstantiateVAppTemplateOptions { +public class TerremarkInstantiateVAppTemplateOptions extends + InstantiateVAppTemplateOptions { + + public TerremarkInstantiateVAppTemplateOptions sshKeyFingerprint( + String sshKeyFingerprint) { + productProperty("sshKeyFingerprint", sshKeyFingerprint); + return this; + } + + public TerremarkInstantiateVAppTemplateOptions primaryDNS(String primaryDNS) { + productProperty("primaryDNS", primaryDNS); + return this; + } + + public TerremarkInstantiateVAppTemplateOptions secondaryDNS( + String secondaryDNS) { + productProperty("secondaryDNS", secondaryDNS); + return this; + } public TerremarkInstantiateVAppTemplateOptions withPassword(String password) { productProperty("password", password); @@ -50,7 +68,8 @@ public class TerremarkInstantiateVAppTemplateOptions extends InstantiateVAppTemp /** * @see TerremarkInstantiateVAppTemplateOptions#processorCount(int) */ - public static TerremarkInstantiateVAppTemplateOptions processorCount(int cpuCount) { + public static TerremarkInstantiateVAppTemplateOptions processorCount( + int cpuCount) { TerremarkInstantiateVAppTemplateOptions options = new TerremarkInstantiateVAppTemplateOptions(); return options.processorCount(cpuCount); } @@ -58,7 +77,8 @@ public class TerremarkInstantiateVAppTemplateOptions extends InstantiateVAppTemp /** * @see TerremarkInstantiateVAppTemplateOptions#memory(long) */ - public static TerremarkInstantiateVAppTemplateOptions memory(long megabytes) { + public static TerremarkInstantiateVAppTemplateOptions memory( + long megabytes) { TerremarkInstantiateVAppTemplateOptions options = new TerremarkInstantiateVAppTemplateOptions(); return options.memory(megabytes); } @@ -74,7 +94,8 @@ public class TerremarkInstantiateVAppTemplateOptions extends InstantiateVAppTemp /** * @see TerremarkInstantiateVAppTemplateOptions#inNetwork(URI) */ - public static TerremarkInstantiateVAppTemplateOptions inNetwork(URI networkLocation) { + public static TerremarkInstantiateVAppTemplateOptions inNetwork( + URI networkLocation) { TerremarkInstantiateVAppTemplateOptions options = new TerremarkInstantiateVAppTemplateOptions(); return options.inNetwork(networkLocation); } @@ -82,7 +103,8 @@ public class TerremarkInstantiateVAppTemplateOptions extends InstantiateVAppTemp /** * @see TerremarkInstantiateVAppTemplateOptions#withPassword(String) */ - public static TerremarkInstantiateVAppTemplateOptions withPassword(String password) { + public static TerremarkInstantiateVAppTemplateOptions withPassword( + String password) { TerremarkInstantiateVAppTemplateOptions options = new TerremarkInstantiateVAppTemplateOptions(); return options.withPassword(password); } @@ -104,32 +126,67 @@ public class TerremarkInstantiateVAppTemplateOptions extends InstantiateVAppTemp } /** - * @see TerremarkInstantiateVAppTemplateOptions#productProperty(String, String) + * @see TerremarkInstantiateVAppTemplateOptions#sshKeyFingerprint(String) */ - public static TerremarkInstantiateVAppTemplateOptions productProperty(String key, String value) { + public static TerremarkInstantiateVAppTemplateOptions sshKeyFingerprint( + String sshKeyFingerprint) { TerremarkInstantiateVAppTemplateOptions options = new TerremarkInstantiateVAppTemplateOptions(); - return (TerremarkInstantiateVAppTemplateOptions) options.productProperty(key, value); + return options.sshKeyFingerprint(sshKeyFingerprint); } /** - * @see TerremarkInstantiateVAppTemplateOptions#productProperties(Map) + * @see TerremarkInstantiateVAppTemplateOptions#primaryDNS(String) + */ + public static TerremarkInstantiateVAppTemplateOptions primaryDNS( + String primaryDNS) { + TerremarkInstantiateVAppTemplateOptions options = new TerremarkInstantiateVAppTemplateOptions(); + return options.primaryDNS(primaryDNS); + } + + /** + * @see TerremarkInstantiateVAppTemplateOptions#secondaryDNS(String) + */ + public static TerremarkInstantiateVAppTemplateOptions secondaryDNS( + String secondaryDNS) { + TerremarkInstantiateVAppTemplateOptions options = new TerremarkInstantiateVAppTemplateOptions(); + return options.secondaryDNS(secondaryDNS); + } + + /** + * @see TerremarkInstantiateVAppTemplateOptions#productProperty(String, + * String) + */ + public static TerremarkInstantiateVAppTemplateOptions productProperty( + String key, String value) { + TerremarkInstantiateVAppTemplateOptions options = new TerremarkInstantiateVAppTemplateOptions(); + return (TerremarkInstantiateVAppTemplateOptions) options + .productProperty(key, value); + } + + /** + * @see + * TerremarkInstantiateVAppTemplateOptions#productProperties(Map) */ public static TerremarkInstantiateVAppTemplateOptions productProperties( - Map properties) { + Map properties) { TerremarkInstantiateVAppTemplateOptions options = new TerremarkInstantiateVAppTemplateOptions(); - return (TerremarkInstantiateVAppTemplateOptions) options.productProperties(properties); + return (TerremarkInstantiateVAppTemplateOptions) options + .productProperties(properties); } } @Override public TerremarkInstantiateVAppTemplateOptions processorCount(int cpuCount) { - return (TerremarkInstantiateVAppTemplateOptions) super.processorCount(cpuCount); + return (TerremarkInstantiateVAppTemplateOptions) super + .processorCount(cpuCount); } @Override public TerremarkInstantiateVAppTemplateOptions inNetwork(URI networkLocation) { - return (TerremarkInstantiateVAppTemplateOptions) super.inNetwork(networkLocation); + return (TerremarkInstantiateVAppTemplateOptions) super + .inNetwork(networkLocation); } @Override @@ -139,16 +196,21 @@ public class TerremarkInstantiateVAppTemplateOptions extends InstantiateVAppTemp @Override public TerremarkInstantiateVAppTemplateOptions disk(long kilobytes) { - throw new IllegalArgumentException("changing the boot disk size is unsupported in terremark"); + throw new IllegalArgumentException( + "changing the boot disk size is unsupported in terremark"); } @Override - public TerremarkInstantiateVAppTemplateOptions productProperties(Map properties) { - return (TerremarkInstantiateVAppTemplateOptions) super.productProperties(properties); + public TerremarkInstantiateVAppTemplateOptions productProperties( + Map properties) { + return (TerremarkInstantiateVAppTemplateOptions) super + .productProperties(properties); } @Override - public TerremarkInstantiateVAppTemplateOptions productProperty(String key, String value) { - return (TerremarkInstantiateVAppTemplateOptions) super.productProperty(key, value); + public TerremarkInstantiateVAppTemplateOptions productProperty(String key, + String value) { + return (TerremarkInstantiateVAppTemplateOptions) super.productProperty( + key, value); } } diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/xml/CustomizationParametersHandler.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/xml/CustomizationParametersHandler.java index 82487d1df9..b4a9554ce1 100644 --- a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/xml/CustomizationParametersHandler.java +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/xml/CustomizationParametersHandler.java @@ -29,6 +29,7 @@ public class CustomizationParametersHandler extends HandlerWithResult { +public class KeyPairHandler extends HandlerWithResult { + @Resource + protected Logger logger = Logger.NULL; private StringBuilder currentText = new StringBuilder(); - int processorCount; - int memory; - float costPerHour; + private int id; + private URI location; + private String name; + private boolean isDefault; + private String privateKey; + private String fingerPrint; protected String currentOrNull() { String returnVal = currentText.toString().trim(); @@ -38,17 +48,23 @@ public class ComputeOptionHandler extends HandlerWithResult { } @Override - public ComputeOptions getResult() { - return new ComputeOptions(processorCount, memory, costPerHour); + public KeyPair getResult() { + return new KeyPair(id, location, name, isDefault, privateKey, fingerPrint); } public void endElement(String uri, String name, String qName) { - if (qName.equals("ProcessorCount")) { - processorCount = Integer.parseInt(currentOrNull()); - } else if (qName.equals("Memory")) { - memory = Integer.parseInt(currentOrNull()); - } else if (qName.equals("CostPerHour")) { - costPerHour = Float.parseFloat(currentOrNull()); + if (qName.equals("Id")) { + id = Integer.parseInt(currentOrNull()); + } else if (qName.equals("Href") && currentOrNull() != null) { + location = URI.create(currentOrNull()); + } else if (qName.equals("Name")) { + this.name = currentOrNull(); + } else if (qName.equals("IsDefault")) { + isDefault = Boolean.parseBoolean(currentOrNull()); + } else if (qName.equals("PrivateKey")) { + privateKey = currentOrNull(); + } else if (qName.equals("FingerPrint")) { + fingerPrint = currentOrNull(); } currentText = new StringBuilder(); } diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/xml/ComputeOptionsHandler.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/xml/KeyPairsHandler.java similarity index 77% rename from vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/xml/ComputeOptionsHandler.java rename to vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/xml/KeyPairsHandler.java index 4276f5a8df..33da7d8a1b 100644 --- a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/xml/ComputeOptionsHandler.java +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/xml/KeyPairsHandler.java @@ -18,14 +18,14 @@ */ package org.jclouds.vcloud.terremark.xml; -import java.util.SortedSet; +import java.util.Set; import javax.annotation.Resource; import javax.inject.Inject; import org.jclouds.http.functions.ParseSax.HandlerWithResult; import org.jclouds.logging.Logger; -import org.jclouds.vcloud.terremark.domain.ComputeOptions; +import org.jclouds.vcloud.terremark.domain.KeyPair; import org.xml.sax.Attributes; import org.xml.sax.SAXException; @@ -34,32 +34,32 @@ import com.google.common.collect.Sets; /** * @author Adrian Cole */ -public class ComputeOptionsHandler extends HandlerWithResult> { +public class KeyPairsHandler extends HandlerWithResult> { @Resource protected Logger logger = Logger.NULL; - private final ComputeOptionHandler handler; - SortedSet result = Sets.newTreeSet(); + private final KeyPairHandler handler; + Set result = Sets.newLinkedHashSet(); @Inject - public ComputeOptionsHandler(ComputeOptionHandler handler) { + public KeyPairsHandler(KeyPairHandler handler) { this.handler = handler; } @Override - public SortedSet getResult() { + public Set getResult() { return result; } @Override - public void startElement(String uri, String localName, String qName, Attributes attributes) - throws SAXException { + public void startElement(String uri, String localName, String qName, + Attributes attributes) throws SAXException { handler.startElement(uri, localName, qName, attributes); } public void endElement(String uri, String name, String qName) { handler.endElement(uri, name, qName); - if (qName.equals("ComputeOption")) { + if (qName.equals("Key")) { result.add(handler.getResult()); } } diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/xml/TerremarkOrgHandler.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/xml/TerremarkOrgHandler.java new file mode 100644 index 0000000000..a71cbeecf8 --- /dev/null +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/xml/TerremarkOrgHandler.java @@ -0,0 +1,57 @@ +/** + * + * Copyright (C) 2009 Cloud Conscious, LLC. + * + * ==================================================================== + * 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.vcloud.terremark.xml; + +import static org.jclouds.vcloud.terremark.TerremarkVCloudMediaType.KEYSLIST_XML; +import static org.jclouds.vcloud.util.Utils.newNamedResource; + +import org.jclouds.vcloud.domain.NamedResource; +import org.jclouds.vcloud.terremark.domain.TerremarkOrganization; +import org.jclouds.vcloud.terremark.domain.internal.TerremarkOrganizationImpl; +import org.jclouds.vcloud.xml.OrgHandler; +import org.xml.sax.Attributes; +import org.xml.sax.SAXException; + +/** + * @author Adrian Cole + */ +public class TerremarkOrgHandler extends OrgHandler { + + private NamedResource keysList; + + public TerremarkOrganization getResult() { + return new TerremarkOrganizationImpl(org.getId(), org.getName(), org + .getLocation(), catalogs, vdcs, tasksLists, keysList); + } + + @Override + public void startElement(String uri, String localName, String qName, + Attributes attributes) throws SAXException { + super.startElement(uri, localName, qName, attributes); + if (qName.equals("Link")) { + int typeIndex = attributes.getIndex("type"); + if (typeIndex != -1) { + if (attributes.getValue(typeIndex).equals(KEYSLIST_XML)) { + keysList = newNamedResource(attributes); + } + } + } + } + +} diff --git a/vcloud/terremark/src/main/resources/terremark/CreateInternetService.xml b/vcloud/terremark/src/main/resources/terremark/CreateInternetService.xml index 96a367108c..f4c8fd8d4b 100644 --- a/vcloud/terremark/src/main/resources/terremark/CreateInternetService.xml +++ b/vcloud/terremark/src/main/resources/terremark/CreateInternetService.xml @@ -1,7 +1,9 @@ - - {name} - {protocol} - {port} - {enabled}{description} - \ No newline at end of file + + {name} + {protocol} + {port} + {enabled} + {description} + diff --git a/vcloud/terremark/src/main/resources/terremark/CreateKey.xml b/vcloud/terremark/src/main/resources/terremark/CreateKey.xml new file mode 100644 index 0000000000..1046980e41 --- /dev/null +++ b/vcloud/terremark/src/main/resources/terremark/CreateKey.xml @@ -0,0 +1,5 @@ + + {name} + {isDefault} + \ No newline at end of file diff --git a/vcloud/terremark/src/main/resources/terremark/CreateNodeService.xml b/vcloud/terremark/src/main/resources/terremark/CreateNodeService.xml index a241d7dd31..d4084f76c0 100644 --- a/vcloud/terremark/src/main/resources/terremark/CreateNodeService.xml +++ b/vcloud/terremark/src/main/resources/terremark/CreateNodeService.xml @@ -1,7 +1,8 @@ - - {ipAddress} - {name} - {port} - {enabled}{description} - \ No newline at end of file + + {ipAddress} + {name} + {port} + {enabled} + {description} + \ No newline at end of file diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/InternetServiceLiveTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/InternetServiceLiveTest.java index 16052c35d9..5bb8de9b6f 100644 --- a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/InternetServiceLiveTest.java +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/InternetServiceLiveTest.java @@ -19,7 +19,6 @@ package org.jclouds.vcloud.terremark; import static com.google.common.base.Preconditions.checkNotNull; -import static org.testng.Assert.assertEquals; import java.util.Set; import java.util.SortedSet; @@ -29,9 +28,7 @@ import java.util.concurrent.TimeoutException; import org.jclouds.logging.log4j.config.Log4JLoggingModule; import org.jclouds.ssh.jsch.config.JschSshClientModule; import org.jclouds.vcloud.terremark.domain.InternetService; -import org.jclouds.vcloud.terremark.domain.InternetServiceConfiguration; import org.jclouds.vcloud.terremark.domain.Node; -import org.jclouds.vcloud.terremark.domain.Protocol; import org.jclouds.vcloud.terremark.domain.PublicIpAddress; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeGroups; @@ -58,21 +55,6 @@ public class InternetServiceLiveTest { tmClient.getAllInternetServicesInVDC(tmClient.getDefaultVDC().getId()); } - @Test - public void testAddAndConfigureInternetService() throws InterruptedException { - InternetService is = tmClient.addInternetServiceToVDC(tmClient.getDefaultVDC().getId(), - "test-" + 22, Protocol.TCP, 22); - is = tmClient.configureInternetService(is.getId(), new InternetServiceConfiguration() - .changeNameTo("test-33")); - assertEquals(is.getName(), "test-33"); - services.add(is); - PublicIpAddress ip = is.getPublicIpAddress(); - for (int port : new int[] { 80, 8080 }) { - services.add(tmClient.addInternetServiceToExistingIp(ip.getId(), "test-" + port, - Protocol.HTTP, port)); - } - } - private void delete(SortedSet set) { Set publicIps = Sets.newHashSet(); for (InternetService service : set) { diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/TerremarkVCloudAsyncClientTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/TerremarkVCloudAsyncClientTest.java index b2b654bb02..d79425e260 100644 --- a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/TerremarkVCloudAsyncClientTest.java +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/TerremarkVCloudAsyncClientTest.java @@ -42,7 +42,6 @@ import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404; import org.jclouds.rest.internal.GeneratedHttpRequest; import org.jclouds.rest.internal.RestAnnotationProcessor; -import com.google.inject.name.Names; import org.jclouds.util.Utils; import org.jclouds.vcloud.endpoints.Catalog; import org.jclouds.vcloud.endpoints.Network; @@ -52,18 +51,17 @@ import org.jclouds.vcloud.endpoints.internal.CatalogItemRoot; import org.jclouds.vcloud.endpoints.internal.VAppRoot; import org.jclouds.vcloud.filters.SetVCloudTokenCookie; import org.jclouds.vcloud.options.InstantiateVAppTemplateOptions; -import org.jclouds.vcloud.terremark.domain.InternetServiceConfiguration; import org.jclouds.vcloud.terremark.domain.NodeConfiguration; import org.jclouds.vcloud.terremark.domain.Protocol; +import org.jclouds.vcloud.terremark.endpoints.KeysList; import org.jclouds.vcloud.terremark.functions.ReturnEmptySetOnUnauthorized; import org.jclouds.vcloud.terremark.options.AddInternetServiceOptions; import org.jclouds.vcloud.terremark.options.AddNodeOptions; import org.jclouds.vcloud.terremark.options.TerremarkInstantiateVAppTemplateOptions; -import org.jclouds.vcloud.terremark.xml.ComputeOptionsHandler; import org.jclouds.vcloud.terremark.xml.CustomizationParametersHandler; import org.jclouds.vcloud.terremark.xml.InternetServiceHandler; import org.jclouds.vcloud.terremark.xml.InternetServicesHandler; -import org.jclouds.vcloud.terremark.xml.IpAddressesHandler; +import org.jclouds.vcloud.terremark.xml.KeyPairsHandler; import org.jclouds.vcloud.terremark.xml.NodeHandler; import org.jclouds.vcloud.terremark.xml.NodesHandler; import org.jclouds.vcloud.terremark.xml.TerremarkVDCHandler; @@ -75,6 +73,7 @@ import com.google.inject.AbstractModule; import com.google.inject.Module; import com.google.inject.Provides; import com.google.inject.TypeLiteral; +import com.google.inject.name.Names; /** * Tests behavior of {@code TerremarkVCloudAsyncClient} @@ -82,17 +81,21 @@ import com.google.inject.TypeLiteral; * @author Adrian Cole */ @Test(groups = "unit", sequential = true, testName = "vcloud.TerremarkVCloudAsyncClientTest") -public class TerremarkVCloudAsyncClientTest extends RestClientTest { +public class TerremarkVCloudAsyncClientTest extends + RestClientTest { /** * ignore parameter of catalog id since this doesn't work */ - public void testCatalog() throws SecurityException, NoSuchMethodException, IOException { - Method method = TerremarkVCloudAsyncClient.class.getMethod("getCatalog", String.class); - GeneratedHttpRequest httpMethod = processor.createRequest(method, - "1"); + public void testCatalog() throws SecurityException, NoSuchMethodException, + IOException { + Method method = TerremarkVCloudAsyncClient.class.getMethod("getCatalog", + String.class); + GeneratedHttpRequest httpMethod = processor + .createRequest(method, "1"); assertRequestLineEquals(httpMethod, "GET http://catalog HTTP/1.1"); - assertHeadersEqual(httpMethod, "Accept: application/vnd.vmware.vcloud.catalog+xml\n"); + assertHeadersEqual(httpMethod, + "Accept: application/vnd.vmware.vcloud.catalog+xml\n"); assertPayloadEquals(httpMethod, null); assertResponseParserClassEquals(method, httpMethod, ParseSax.class); @@ -102,30 +105,16 @@ public class TerremarkVCloudAsyncClientTest extends RestClientTest httpMethod = processor.createRequest(method, - "2"); - - assertRequestLineEquals(httpMethod, "GET http://vcloud/network/2/ipAddresses HTTP/1.1"); - assertHeadersEqual(httpMethod, "Accept: application/xml\n"); - assertPayloadEquals(httpMethod, null); - - assertResponseParserClassEquals(method, httpMethod, ParseSax.class); - assertSaxResponseParserClassEquals(method, IpAddressesHandler.class); - assertExceptionParserClassEquals(method, null); - - checkFilters(httpMethod); - } - - public void testGetDefaultVDC() throws SecurityException, NoSuchMethodException, IOException { - Method method = TerremarkVCloudAsyncClient.class.getMethod("getDefaultVDC"); - GeneratedHttpRequest httpMethod = processor.createRequest(method); + public void testGetDefaultVDC() throws SecurityException, + NoSuchMethodException, IOException { + Method method = TerremarkVCloudAsyncClient.class + .getMethod("getDefaultVDC"); + GeneratedHttpRequest httpMethod = processor + .createRequest(method); assertRequestLineEquals(httpMethod, "GET http://vdc HTTP/1.1"); - assertHeadersEqual(httpMethod, "Accept: application/vnd.vmware.vcloud.vdc+xml\n"); + assertHeadersEqual(httpMethod, + "Accept: application/vnd.vmware.vcloud.vdc+xml\n"); assertPayloadEquals(httpMethod, null); assertResponseParserClassEquals(method, httpMethod, ParseSax.class); @@ -135,13 +124,16 @@ public class TerremarkVCloudAsyncClientTest extends RestClientTest httpMethod = processor.createRequest(method, - "1"); + public void testGetVDC() throws SecurityException, NoSuchMethodException, + IOException { + Method method = TerremarkVCloudAsyncClient.class.getMethod("getVDC", + String.class); + GeneratedHttpRequest httpMethod = processor + .createRequest(method, "1"); assertRequestLineEquals(httpMethod, "GET http://vcloud/vdc/1 HTTP/1.1"); - assertHeadersEqual(httpMethod, "Accept: application/vnd.vmware.vcloud.vdc+xml\n"); + assertHeadersEqual(httpMethod, + "Accept: application/vnd.vmware.vcloud.vdc+xml\n"); assertPayloadEquals(httpMethod, null); assertResponseParserClassEquals(method, httpMethod, ParseSax.class); @@ -151,21 +143,23 @@ public class TerremarkVCloudAsyncClientTest extends RestClientTest httpMethod = processor.createRequest(method, - "1", "name", 3 + ""); + public void testInstantiateVAppTemplate() throws SecurityException, + NoSuchMethodException, IOException { + Method method = TerremarkVCloudAsyncClient.class.getMethod( + "instantiateVAppTemplateInVDC", String.class, String.class, + String.class, Array.newInstance( + InstantiateVAppTemplateOptions.class, 0).getClass()); + GeneratedHttpRequest httpMethod = processor + .createRequest(method, "1", "name", 3 + ""); assertRequestLineEquals(httpMethod, - "POST http://vcloud/vdc/1/action/instantiateVAppTemplate HTTP/1.1"); + "POST http://vcloud/vdc/1/action/instantiateVAppTemplate HTTP/1.1"); assertHeadersEqual( - httpMethod, - "Accept: application/vnd.vmware.vcloud.vApp+xml\nContent-Length: 1657\nContent-Type: application/vnd.vmware.vcloud.instantiateVAppTemplateParams+xml\n"); - assertPayloadEquals(httpMethod, Utils.toStringAndClose(getClass().getResourceAsStream( - "/terremark/InstantiateVAppTemplateParams-test.xml"))); + httpMethod, + "Accept: application/vnd.vmware.vcloud.vApp+xml\nContent-Length: 687\nContent-Type: application/vnd.vmware.vcloud.instantiateVAppTemplateParams+xml\n"); + assertPayloadEquals(httpMethod, Utils.toStringAndClose(getClass() + .getResourceAsStream( + "/terremark/InstantiateVAppTemplateParams-test.xml"))); assertResponseParserClassEquals(method, httpMethod, ParseSax.class); assertSaxResponseParserClassEquals(method, VAppHandler.class); @@ -175,22 +169,26 @@ public class TerremarkVCloudAsyncClientTest extends RestClientTest httpMethod = processor.createRequest(method, - "1", "name", 3 + "", TerremarkInstantiateVAppTemplateOptions.Builder.processorCount( - 2).memory(512).inRow("row").inGroup("group").withPassword("password") - .inNetwork(URI.create("http://network"))); + NoSuchMethodException, IOException { + Method method = TerremarkVCloudAsyncClient.class.getMethod( + "instantiateVAppTemplateInVDC", String.class, String.class, + String.class, Array.newInstance( + InstantiateVAppTemplateOptions.class, 0).getClass()); + GeneratedHttpRequest httpMethod = processor + .createRequest(method, "1", "name", 3 + "", + TerremarkInstantiateVAppTemplateOptions.Builder + .processorCount(2).memory(512).inRow("row").inGroup( + "group").withPassword("password").inNetwork( + URI.create("http://network"))); assertRequestLineEquals(httpMethod, - "POST http://vcloud/vdc/1/action/instantiateVAppTemplate HTTP/1.1"); + "POST http://vcloud/vdc/1/action/instantiateVAppTemplate HTTP/1.1"); assertHeadersEqual( - httpMethod, - "Accept: application/vnd.vmware.vcloud.vApp+xml\nContent-Length: 1920\nContent-Type: application/vnd.vmware.vcloud.instantiateVAppTemplateParams+xml\n"); - assertPayloadEquals(httpMethod, Utils.toStringAndClose(getClass().getResourceAsStream( - "/terremark/InstantiateVAppTemplateParams-options-test.xml"))); + httpMethod, + "Accept: application/vnd.vmware.vcloud.vApp+xml\nContent-Length: 1902\nContent-Type: application/vnd.vmware.vcloud.instantiateVAppTemplateParams+xml\n"); + assertPayloadEquals(httpMethod, Utils.toStringAndClose(getClass() + .getResourceAsStream( + "/terremark/InstantiateVAppTemplateParams-options-test.xml"))); assertResponseParserClassEquals(method, httpMethod, ParseSax.class); assertSaxResponseParserClassEquals(method, VAppHandler.class); @@ -199,19 +197,22 @@ public class TerremarkVCloudAsyncClientTest extends RestClientTest httpMethod = processor.createRequest(method, - "1", "name", Protocol.TCP, 22); + public void testAddInternetService() throws SecurityException, + NoSuchMethodException, IOException { + Method method = TerremarkVCloudAsyncClient.class.getMethod( + "addInternetServiceToVDC", String.class, String.class, + Protocol.class, int.class, Array.newInstance( + AddInternetServiceOptions.class, 0).getClass()); + GeneratedHttpRequest httpMethod = processor + .createRequest(method, "1", "name", Protocol.TCP, 22); - assertRequestLineEquals(httpMethod, "POST http://vcloud/vdc/1/internetServices HTTP/1.1"); - assertHeadersEqual(httpMethod, - "Accept: application/xml\nContent-Length: 303\nContent-Type: application/xml\n"); - assertPayloadEquals(httpMethod, Utils.toStringAndClose(getClass().getResourceAsStream( - "/terremark/CreateInternetService-test2.xml"))); + assertRequestLineEquals(httpMethod, + "POST http://vcloud/extensions/vdc/1/internetServices HTTP/1.1"); + assertHeadersEqual( + httpMethod, + "Accept: application/vnd.tmrk.vCloud.internetService+xml\nContent-Length: 298\nContent-Type: application/vnd.tmrk.vCloud.internetService+xml\n"); + assertPayloadEquals(httpMethod, Utils.toStringAndClose(getClass() + .getResourceAsStream("/terremark/CreateInternetService-test2.xml"))); assertResponseParserClassEquals(method, httpMethod, ParseSax.class); assertSaxResponseParserClassEquals(method, InternetServiceHandler.class); @@ -220,19 +221,24 @@ public class TerremarkVCloudAsyncClientTest extends RestClientTest httpMethod = processor.createRequest(method, - "1", "name", Protocol.TCP, 22, disabled().withDescription("yahoo")); + public void testAddInternetServiceOptions() throws SecurityException, + NoSuchMethodException, IOException { + Method method = TerremarkVCloudAsyncClient.class.getMethod( + "addInternetServiceToVDC", String.class, String.class, + Protocol.class, int.class, Array.newInstance( + AddInternetServiceOptions.class, 0).getClass()); + GeneratedHttpRequest httpMethod = processor + .createRequest(method, "1", "name", Protocol.TCP, 22, disabled() + .withDescription("yahoo")); - assertRequestLineEquals(httpMethod, "POST http://vcloud/vdc/1/internetServices HTTP/1.1"); - assertHeadersEqual(httpMethod, - "Accept: application/xml\nContent-Length: 341\nContent-Type: application/xml\n"); - assertPayloadEquals(httpMethod, Utils.toStringAndClose(getClass().getResourceAsStream( - "/terremark/CreateInternetService-options-test.xml"))); + assertRequestLineEquals(httpMethod, + "POST http://vcloud/extensions/vdc/1/internetServices HTTP/1.1"); + assertHeadersEqual( + httpMethod, + "Accept: application/vnd.tmrk.vCloud.internetService+xml\nContent-Length: 336\nContent-Type: application/vnd.tmrk.vCloud.internetService+xml\n"); + assertPayloadEquals(httpMethod, Utils.toStringAndClose(getClass() + .getResourceAsStream( + "/terremark/CreateInternetService-options-test.xml"))); assertResponseParserClassEquals(method, httpMethod, ParseSax.class); assertSaxResponseParserClassEquals(method, InternetServiceHandler.class); assertExceptionParserClassEquals(method, null); @@ -240,15 +246,17 @@ public class TerremarkVCloudAsyncClientTest extends RestClientTest httpMethod = processor.createRequest(method, - "1"); + public void testGetAllInternetServices() throws SecurityException, + NoSuchMethodException, IOException { + Method method = TerremarkVCloudAsyncClient.class.getMethod( + "getAllInternetServicesInVDC", String.class); + GeneratedHttpRequest httpMethod = processor + .createRequest(method, "1"); - assertRequestLineEquals(httpMethod, "GET http://vcloud/vdc/1/internetServices HTTP/1.1"); - assertHeadersEqual(httpMethod, "Accept: application/xml\n"); + assertRequestLineEquals(httpMethod, + "GET http://vcloud/extensions/vdc/1/internetServices HTTP/1.1"); + assertHeadersEqual(httpMethod, + "Accept: application/vnd.tmrk.vCloud.internetServicesList+xml\n"); assertPayloadEquals(httpMethod, null); assertResponseParserClassEquals(method, httpMethod, ParseSax.class); @@ -258,14 +266,17 @@ public class TerremarkVCloudAsyncClientTest extends RestClientTest httpMethod = processor.createRequest(method, - 12); + public void testGetInternetService() throws SecurityException, + NoSuchMethodException, IOException { + Method method = TerremarkVCloudAsyncClient.class.getMethod( + "getInternetService", int.class); + GeneratedHttpRequest httpMethod = processor + .createRequest(method, 12); - assertRequestLineEquals(httpMethod, "GET http://vcloud/internetServices/12 HTTP/1.1"); - assertHeadersEqual(httpMethod, "Accept: application/xml\n"); + assertRequestLineEquals(httpMethod, + "GET http://vcloud/extensions/internetService/12 HTTP/1.1"); + assertHeadersEqual(httpMethod, + "Accept: application/vnd.tmrk.vCloud.internetServicesList+xml\n"); assertPayloadEquals(httpMethod, null); assertResponseParserClassEquals(method, httpMethod, ParseSax.class); @@ -275,18 +286,20 @@ public class TerremarkVCloudAsyncClientTest extends RestClientTest httpMethod = processor.createRequest(method, - 12); + public void testDeleteInternetService() throws SecurityException, + NoSuchMethodException, IOException { + Method method = TerremarkVCloudAsyncClient.class.getMethod( + "deleteInternetService", int.class); + GeneratedHttpRequest httpMethod = processor + .createRequest(method, 12); - assertRequestLineEquals(httpMethod, "DELETE http://vcloud/internetServices/12 HTTP/1.1"); + assertRequestLineEquals(httpMethod, + "DELETE http://vcloud/extensions/internetService/12 HTTP/1.1"); assertHeadersEqual(httpMethod, ""); assertPayloadEquals(httpMethod, null); - assertResponseParserClassEquals(method, httpMethod, CloseContentAndReturn.class); + assertResponseParserClassEquals(method, httpMethod, + CloseContentAndReturn.class); assertSaxResponseParserClassEquals(method, null); assertExceptionParserClassEquals(method, ReturnVoidOnNotFoundOr404.class); @@ -294,19 +307,21 @@ public class TerremarkVCloudAsyncClientTest extends RestClientTest httpMethod = processor.createRequest(method, - 12, "name", Protocol.TCP, 22); + NoSuchMethodException, IOException { + Method method = TerremarkVCloudAsyncClient.class.getMethod( + "addInternetServiceToExistingIp", int.class, String.class, + Protocol.class, int.class, Array.newInstance( + AddInternetServiceOptions.class, 0).getClass()); + GeneratedHttpRequest httpMethod = processor + .createRequest(method, 12, "name", Protocol.TCP, 22); assertRequestLineEquals(httpMethod, - "POST http://vcloud/publicIps/12/InternetServices HTTP/1.1"); - assertHeadersEqual(httpMethod, - "Accept: application/xml\nContent-Length: 303\nContent-Type: application/xml\n"); - assertPayloadEquals(httpMethod, Utils.toStringAndClose(getClass().getResourceAsStream( - "/terremark/CreateInternetService-test2.xml"))); + "POST http://vcloud/extensions/publicIp/12/internetServices HTTP/1.1"); + assertHeadersEqual( + httpMethod, + "Accept: application/vnd.tmrk.vCloud.internetService+xml\nContent-Length: 298\nContent-Type: application/vnd.tmrk.vCloud.internetService+xml\n"); + assertPayloadEquals(httpMethod, Utils.toStringAndClose(getClass() + .getResourceAsStream("/terremark/CreateInternetService-test2.xml"))); assertResponseParserClassEquals(method, httpMethod, ParseSax.class); assertSaxResponseParserClassEquals(method, InternetServiceHandler.class); @@ -315,20 +330,24 @@ public class TerremarkVCloudAsyncClientTest extends RestClientTest httpMethod = processor.createRequest(method, - 12, "name", Protocol.TCP, 22, disabled().withDescription("yahoo")); + public void testAddInternetServiceToExistingIpOptions() + throws SecurityException, NoSuchMethodException, IOException { + Method method = TerremarkVCloudAsyncClient.class.getMethod( + "addInternetServiceToExistingIp", int.class, String.class, + Protocol.class, int.class, Array.newInstance( + AddInternetServiceOptions.class, 0).getClass()); + GeneratedHttpRequest httpMethod = processor + .createRequest(method, 12, "name", Protocol.TCP, 22, disabled() + .withDescription("yahoo")); assertRequestLineEquals(httpMethod, - "POST http://vcloud/publicIps/12/InternetServices HTTP/1.1"); - assertHeadersEqual(httpMethod, - "Accept: application/xml\nContent-Length: 341\nContent-Type: application/xml\n"); - assertPayloadEquals(httpMethod, Utils.toStringAndClose(getClass().getResourceAsStream( - "/terremark/CreateInternetService-options-test.xml"))); + "POST http://vcloud/extensions/publicIp/12/internetServices HTTP/1.1"); + assertHeadersEqual( + httpMethod, + "Accept: application/vnd.tmrk.vCloud.internetService+xml\nContent-Length: 336\nContent-Type: application/vnd.tmrk.vCloud.internetService+xml\n"); + assertPayloadEquals(httpMethod, Utils.toStringAndClose(getClass() + .getResourceAsStream( + "/terremark/CreateInternetService-options-test.xml"))); assertResponseParserClassEquals(method, httpMethod, ParseSax.class); assertSaxResponseParserClassEquals(method, InternetServiceHandler.class); assertExceptionParserClassEquals(method, null); @@ -336,18 +355,21 @@ public class TerremarkVCloudAsyncClientTest extends RestClientTest httpMethod = processor.createRequest(method, - 12, "10.2.2.2", "name", 22); + public void testAddNode() throws SecurityException, NoSuchMethodException, + IOException { + Method method = TerremarkVCloudAsyncClient.class.getMethod("addNode", + int.class, String.class, String.class, int.class, Array + .newInstance(AddNodeOptions.class, 0).getClass()); + GeneratedHttpRequest httpMethod = processor + .createRequest(method, 12, "10.2.2.2", "name", 22); - assertRequestLineEquals(httpMethod, "POST http://vcloud/internetServices/12/nodes HTTP/1.1"); - assertHeadersEqual(httpMethod, - "Accept: application/xml\nContent-Length: 298\nContent-Type: application/xml\n"); - assertPayloadEquals(httpMethod, Utils.toStringAndClose(getClass().getResourceAsStream( - "/terremark/CreateNodeService-test2.xml"))); + assertRequestLineEquals(httpMethod, + "POST http://vcloud/extensions/internetService/12/nodeServices HTTP/1.1"); + assertHeadersEqual( + httpMethod, + "Accept: application/vnd.tmrk.vCloud.nodeService+xml\nContent-Length: 295\nContent-Type: application/vnd.tmrk.vCloud.nodeService+xml\n"); + assertPayloadEquals(httpMethod, Utils.toStringAndClose(getClass() + .getResourceAsStream("/terremark/CreateNodeService-test2.xml"))); assertResponseParserClassEquals(method, httpMethod, ParseSax.class); assertSaxResponseParserClassEquals(method, NodeHandler.class); @@ -356,19 +378,24 @@ public class TerremarkVCloudAsyncClientTest extends RestClientTest httpMethod = processor.createRequest(method, - 12, "10.2.2.2", "name", 22, AddNodeOptions.Builder.disabled().withDescription( - "yahoo")); + public void testAddNodeOptions() throws SecurityException, + NoSuchMethodException, IOException { + Method method = TerremarkVCloudAsyncClient.class.getMethod("addNode", + int.class, String.class, String.class, int.class, Array + .newInstance(AddNodeOptions.class, 0).getClass()); + GeneratedHttpRequest httpMethod = processor + .createRequest(method, 12, "10.2.2.2", "name", 22, + AddNodeOptions.Builder.disabled().withDescription("yahoo")); - assertRequestLineEquals(httpMethod, "POST http://vcloud/internetServices/12/nodes HTTP/1.1"); - assertHeadersEqual(httpMethod, - "Accept: application/xml\nContent-Length: 336\nContent-Type: application/xml\n"); - assertPayloadEquals(httpMethod, Utils.toStringAndClose(getClass().getResourceAsStream( - "/terremark/CreateNodeService-options-test.xml"))); + assertRequestLineEquals(httpMethod, + "POST http://vcloud/extensions/internetService/12/nodeServices HTTP/1.1"); + assertHeadersEqual( + httpMethod, + "Accept: application/vnd.tmrk.vCloud.nodeService+xml\nContent-Length: 333\nContent-Type: application/vnd.tmrk.vCloud.nodeService+xml\n"); + + assertPayloadEquals(httpMethod, Utils.toStringAndClose(getClass() + .getResourceAsStream( + "/terremark/CreateNodeService-options-test.xml"))); assertResponseParserClassEquals(method, httpMethod, ParseSax.class); assertSaxResponseParserClassEquals(method, NodeHandler.class); assertExceptionParserClassEquals(method, null); @@ -376,13 +403,17 @@ public class TerremarkVCloudAsyncClientTest extends RestClientTest httpMethod = processor.createRequest(method, - 12); + public void testGetKeyPair() throws SecurityException, + NoSuchMethodException, IOException { + Method method = TerremarkVCloudAsyncClient.class.getMethod("getNode", + int.class); + GeneratedHttpRequest httpMethod = processor + .createRequest(method, 12); - assertRequestLineEquals(httpMethod, "GET http://vcloud/nodeServices/12 HTTP/1.1"); - assertHeadersEqual(httpMethod, "Accept: application/xml\n"); + assertRequestLineEquals(httpMethod, + "GET http://vcloud/extensions/nodeService/12 HTTP/1.1"); + assertHeadersEqual(httpMethod, + "Accept: application/vnd.tmrk.vCloud.nodeService+xml\n"); assertPayloadEquals(httpMethod, null); assertResponseParserClassEquals(method, httpMethod, ParseSax.class); @@ -392,19 +423,22 @@ public class TerremarkVCloudAsyncClientTest extends RestClientTest httpMethod = processor.createRequest(method, - 12, new NodeConfiguration().changeDescriptionTo("eggs")); + public void testConfigureNode() throws SecurityException, + NoSuchMethodException, IOException { + Method method = TerremarkVCloudAsyncClient.class.getMethod( + "configureNode", int.class, NodeConfiguration.class); + GeneratedHttpRequest httpMethod = processor + .createRequest(method, 12, new NodeConfiguration() + .changeDescriptionTo("eggs")); - assertRequestLineEquals(httpMethod, "PUT http://vcloud/nodeServices/12 HTTP/1.1"); - assertHeadersEqual(httpMethod, - "Accept: application/xml\nContent-Length: 145\nContent-Type: application/xml\n"); + assertRequestLineEquals(httpMethod, + "PUT http://vcloud/extensions/nodeService/12 HTTP/1.1"); + assertHeadersEqual( + httpMethod, + "Accept: application/vnd.tmrk.vCloud.nodeService+xml\nContent-Length: 155\nContent-Type: application/vnd.tmrk.vCloud.nodeService+xml\n"); assertPayloadEquals( - httpMethod, - "eggs"); - + httpMethod, + "eggs"); assertResponseParserClassEquals(method, httpMethod, ParseSax.class); assertSaxResponseParserClassEquals(method, NodeHandler.class); assertExceptionParserClassEquals(method, null); @@ -412,138 +446,177 @@ public class TerremarkVCloudAsyncClientTest extends RestClientTest httpMethod = processor.createRequest(method, - 12, new InternetServiceConfiguration().changeDescriptionTo("eggs")); + public void testGetNodes() throws SecurityException, NoSuchMethodException, + IOException { + Method method = TerremarkVCloudAsyncClient.class.getMethod("getNodes", + int.class); + GeneratedHttpRequest httpMethod = processor + .createRequest(method, 12); - assertRequestLineEquals(httpMethod, "PUT http://vcloud/internetServices/12 HTTP/1.1"); + assertRequestLineEquals(httpMethod, + "GET http://vcloud/extensions/internetService/12/nodeServices HTTP/1.1"); assertHeadersEqual(httpMethod, - "Accept: application/xml\nContent-Length: 153\nContent-Type: application/xml\n"); - assertPayloadEquals( - httpMethod, - "eggs"); - - assertResponseParserClassEquals(method, httpMethod, ParseSax.class); - assertSaxResponseParserClassEquals(method, InternetServiceHandler.class); - assertExceptionParserClassEquals(method, null); - - checkFilters(httpMethod); - } - - public void testGetNodes() throws SecurityException, NoSuchMethodException, IOException { - Method method = TerremarkVCloudAsyncClient.class.getMethod("getNodes", int.class); - GeneratedHttpRequest httpMethod = processor.createRequest(method, - 12); - - assertRequestLineEquals(httpMethod, "GET http://vcloud/internetServices/12/nodes HTTP/1.1"); - assertHeadersEqual(httpMethod, "Accept: application/xml\n"); + "Accept: application/vnd.tmrk.vCloud.nodeService+xml\n"); assertPayloadEquals(httpMethod, null); assertResponseParserClassEquals(method, httpMethod, ParseSax.class); assertSaxResponseParserClassEquals(method, NodesHandler.class); - assertExceptionParserClassEquals(method, ReturnEmptySetOnUnauthorized.class); + assertExceptionParserClassEquals(method, + ReturnEmptySetOnUnauthorized.class); checkFilters(httpMethod); } - public void testDeleteNode() throws SecurityException, NoSuchMethodException, IOException { - Method method = TerremarkVCloudAsyncClient.class.getMethod("deleteNode", int.class); - GeneratedHttpRequest httpMethod = processor.createRequest(method, - 12); + public void testDeleteNode() throws SecurityException, + NoSuchMethodException, IOException { + Method method = TerremarkVCloudAsyncClient.class.getMethod("deleteNode", + int.class); + GeneratedHttpRequest httpMethod = processor + .createRequest(method, 12); - assertRequestLineEquals(httpMethod, "DELETE http://vcloud/nodeServices/12 HTTP/1.1"); + assertRequestLineEquals(httpMethod, + "DELETE http://vcloud/extensions/nodeService/12 HTTP/1.1"); assertHeadersEqual(httpMethod, ""); assertPayloadEquals(httpMethod, null); - assertResponseParserClassEquals(method, httpMethod, CloseContentAndReturn.class); + assertResponseParserClassEquals(method, httpMethod, + CloseContentAndReturn.class); assertSaxResponseParserClassEquals(method, null); assertExceptionParserClassEquals(method, ReturnVoidOnNotFoundOr404.class); checkFilters(httpMethod); } - public void testGetComputeOptionsOfVApp() throws SecurityException, NoSuchMethodException, - IOException { - Method method = TerremarkVCloudAsyncClient.class.getMethod("getComputeOptionsOfVApp", - String.class); - GeneratedHttpRequest httpMethod = processor.createRequest(method, - 12); - - assertRequestLineEquals(httpMethod, "GET http://vcloud/vapp/12/options/compute HTTP/1.1"); - assertHeadersEqual(httpMethod, "Accept: application/xml\n"); - assertPayloadEquals(httpMethod, null); - - assertResponseParserClassEquals(method, httpMethod, ParseSax.class); - assertSaxResponseParserClassEquals(method, ComputeOptionsHandler.class); - assertExceptionParserClassEquals(method, null); - - checkFilters(httpMethod); - } - - public void testGetCustomizationOptionsOfVApp() throws SecurityException, NoSuchMethodException, - IOException { - Method method = TerremarkVCloudAsyncClient.class.getMethod("getCustomizationOptionsOfVApp", - String.class); - GeneratedHttpRequest httpMethod = processor.createRequest(method, - 12); - - assertRequestLineEquals(httpMethod, - "GET http://vcloud/vapp/12/options/customization HTTP/1.1"); - assertHeadersEqual(httpMethod, "Accept: application/xml\n"); - assertPayloadEquals(httpMethod, null); - - assertResponseParserClassEquals(method, httpMethod, ParseSax.class); - assertSaxResponseParserClassEquals(method, CustomizationParametersHandler.class); - assertExceptionParserClassEquals(method, null); - - checkFilters(httpMethod); - } - - public void testGetComputeOptionsOfCatalogItem() throws SecurityException, - NoSuchMethodException, IOException { - Method method = TerremarkVCloudAsyncClient.class.getMethod("getComputeOptionsOfCatalogItem", - String.class); - GeneratedHttpRequest httpMethod = processor.createRequest(method, - 12); - - assertRequestLineEquals(httpMethod, - "GET http://vcloud/catalogItem/12/options/compute HTTP/1.1"); - assertHeadersEqual(httpMethod, "Accept: application/xml\n"); - assertPayloadEquals(httpMethod, null); - - assertResponseParserClassEquals(method, httpMethod, ParseSax.class); - assertSaxResponseParserClassEquals(method, ComputeOptionsHandler.class); - assertExceptionParserClassEquals(method, null); - - checkFilters(httpMethod); - } - - public void testGetCustomizationOptionsOfCatalogItem() throws SecurityException, - NoSuchMethodException, IOException { + public void testGetCustomizationOptionsOfCatalogItem() + throws SecurityException, NoSuchMethodException, IOException { Method method = TerremarkVCloudAsyncClient.class.getMethod( - "getCustomizationOptionsOfCatalogItem", String.class); - GeneratedHttpRequest httpMethod = processor.createRequest(method, - 12); + "getCustomizationOptionsOfCatalogItem", String.class); + GeneratedHttpRequest httpMethod = processor + .createRequest(method, 12); assertRequestLineEquals(httpMethod, - "GET http://vcloud/catalogItem/12/options/customization HTTP/1.1"); - assertHeadersEqual(httpMethod, "Accept: application/xml\n"); + "GET http://vcloud/extensions/template/12/options/customization HTTP/1.1"); + assertHeadersEqual(httpMethod, + "Accept: application/vnd.tmrk.vCloud.catalogItemCustomizationParameters+xml\n"); assertPayloadEquals(httpMethod, null); assertResponseParserClassEquals(method, httpMethod, ParseSax.class); - assertSaxResponseParserClassEquals(method, CustomizationParametersHandler.class); + assertSaxResponseParserClassEquals(method, + CustomizationParametersHandler.class); assertExceptionParserClassEquals(method, null); checkFilters(httpMethod); } + public void testListKeyPairs() throws SecurityException, + NoSuchMethodException, IOException { + Method method = TerremarkVCloudAsyncClient.class + .getMethod("listKeyPairs"); + GeneratedHttpRequest httpMethod = processor + .createRequest(method); + + assertRequestLineEquals(httpMethod, "GET http://keysList HTTP/1.1"); + assertHeadersEqual(httpMethod, + "Accept: application/vnd.tmrk.vcloudExpress.keysList+xml\n"); + assertPayloadEquals(httpMethod, null); + + assertResponseParserClassEquals(method, httpMethod, ParseSax.class); + assertSaxResponseParserClassEquals(method, KeyPairsHandler.class); + assertExceptionParserClassEquals(method, null); + + checkFilters(httpMethod); + } + + public void testListKeyPairsInOrg() throws SecurityException, + NoSuchMethodException, IOException { + Method method = TerremarkVCloudAsyncClient.class.getMethod( + "listKeyPairsInOrg", String.class); + GeneratedHttpRequest httpMethod = processor + .createRequest(method, "org1"); + + assertRequestLineEquals(httpMethod, + "GET http://vcloud/extensions/org/org1/keys HTTP/1.1"); + assertHeadersEqual(httpMethod, + "Accept: application/vnd.tmrk.vcloudExpress.keysList+xml\n"); + assertPayloadEquals(httpMethod, null); + + assertResponseParserClassEquals(method, httpMethod, ParseSax.class); + assertSaxResponseParserClassEquals(method, KeyPairsHandler.class); + assertExceptionParserClassEquals(method, null); + + checkFilters(httpMethod); + } + + public void testGetNode() throws SecurityException, NoSuchMethodException, + IOException { + Method method = TerremarkVCloudAsyncClient.class.getMethod("getNode", + int.class); + GeneratedHttpRequest httpMethod = processor + .createRequest(method, 12); + + assertRequestLineEquals(httpMethod, + "GET http://vcloud/extensions/nodeService/12 HTTP/1.1"); + assertHeadersEqual(httpMethod, + "Accept: application/vnd.tmrk.vCloud.nodeService+xml\n"); + assertPayloadEquals(httpMethod, null); + + assertResponseParserClassEquals(method, httpMethod, ParseSax.class); + assertSaxResponseParserClassEquals(method, NodeHandler.class); + assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + + checkFilters(httpMethod); + } + + // TODO + // public void testConfigureKeyPair() throws SecurityException, + // NoSuchMethodException, IOException { + // Method method = TerremarkVCloudAsyncClient.class.getMethod( + // "configureKeyPair", int.class, KeyPairConfiguration.class); + // GeneratedHttpRequest httpMethod = processor + // .createRequest(method, 12, new KeyPairConfiguration() + // .changeDescriptionTo("eggs")); + // + // assertRequestLineEquals(httpMethod, + // "PUT http://vcloud/extensions/keyPairService/12 HTTP/1.1"); + // assertHeadersEqual( + // httpMethod, + // "Accept: application/vnd.tmrk.vCloud.keyPairService+xml\nContent-Length: 155\nContent-Type: application/vnd.tmrk.vCloud.keyPairService+xml\n"); + // assertPayloadEquals( + // httpMethod, + // "eggs"); + // assertResponseParserClassEquals(method, httpMethod, ParseSax.class); + // assertSaxResponseParserClassEquals(method, KeyPairHandler.class); + // assertExceptionParserClassEquals(method, null); + // + // checkFilters(httpMethod); + // } + + public void testDeleteKeyPair() throws SecurityException, + NoSuchMethodException, IOException { + Method method = TerremarkVCloudAsyncClient.class.getMethod( + "deleteKeyPair", int.class); + GeneratedHttpRequest httpMethod = processor + .createRequest(method, 12); + + assertRequestLineEquals(httpMethod, + "DELETE http://vcloud/extensions/key/12 HTTP/1.1"); + assertHeadersEqual(httpMethod, ""); + assertPayloadEquals(httpMethod, null); + + assertResponseParserClassEquals(method, httpMethod, + CloseContentAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnVoidOnNotFoundOr404.class); + + checkFilters(httpMethod); + } + @Override - protected void checkFilters(GeneratedHttpRequest httpMethod) { + protected void checkFilters( + GeneratedHttpRequest httpMethod) { assertEquals(httpMethod.getFilters().size(), 1); - assertEquals(httpMethod.getFilters().get(0).getClass(), SetVCloudTokenCookie.class); + assertEquals(httpMethod.getFilters().get(0).getClass(), + SetVCloudTokenCookie.class); } @Override @@ -559,24 +632,32 @@ public class TerremarkVCloudAsyncClientTest extends RestClientTest() { + new SetVCloudTokenCookie(new Provider() { - public String get() { - return "token"; - } + public String get() { + return "token"; + } - })); + })); bind(Logger.LoggerFactory.class).toInstance(new LoggerFactory() { public Logger getLogger(String category) { @@ -591,7 +672,7 @@ public class TerremarkVCloudAsyncClientTest extends RestClientTest addresses = tmClient.getIpAddressesForNetwork(resource.getId()); - assertNotNull(addresses); - } - } + public static final String PREFIX = System.getProperty("user.name") + + "-terremark"; + + // task list doesn't have a unique id like in regular vcloud + @Test(expectedExceptions = NullPointerException.class) + @Override + public void testDefaultTasksList() throws Exception { + super.testDefaultTasksList(); } @Test public void testGetAllInternetServices() throws Exception { - for (InternetService service : tmClient.getAllInternetServicesInVDC(tmClient.getDefaultVDC() - .getId())) { + for (InternetService service : tmClient + .getAllInternetServicesInVDC(tmClient.getDefaultVDC().getId())) { assertNotNull(tmClient.getNodes(service.getId())); } } @Test public void testGetPublicIpsAssociatedWithVDC() throws Exception { - for (PublicIpAddress ip : tmClient.getPublicIpsAssociatedWithVDC(tmClient.getDefaultVDC() - .getId())) { + for (PublicIpAddress ip : tmClient.getPublicIpsAssociatedWithVDC(tmClient + .getDefaultVDC().getId())) { assertNotNull(tmClient.getInternetServicesOnPublicIp(ip.getId())); assertNotNull(tmClient.getPublicIp(ip.getId())); } @@ -133,10 +129,6 @@ public class TerremarkVCloudClientLiveTest extends VCloudClientLiveTest { for (NamedResource resource : response.values()) { if (resource.getType().equals(VCloudMediaType.CATALOGITEM_XML)) { CatalogItem item = connection.getCatalogItem(resource.getId()); - SortedSet options = tmClient.getComputeOptionsOfCatalogItem(item - .getId()); - assert options.size() == 32 || options.size() == 20 : item.getId() + ": " - + options.size(); assert tmClient.getCustomizationOptionsOfCatalogItem(item.getId()) != null; } } @@ -153,8 +145,31 @@ public class TerremarkVCloudClientLiveTest extends VCloudClientLiveTest { } @Test - public void testInstantiateAndPowerOn() throws InterruptedException, ExecutionException, - TimeoutException, IOException { + public void testKeysList() throws Exception { + TerremarkOrganization org = tmClient.getDefaultOrganization(); + Set response = tmClient.listKeyPairs(); + assertNotNull(response); + System.err.println(response); + assertEquals(response, tmClient.listKeyPairsInOrg(org.getId())); + } + + @Test + public void testGenerateKeyPair() throws Exception { + TerremarkOrganization org = tmClient.getDefaultOrganization(); + key = tmClient.generateKeyPairInOrg(org.getId(), "livetest", false); + assertNotNull(key); + System.err.println(key); + assertEquals(key.getName(), "livetest"); + assertNotNull(key.getPrivateKey()); + assertNotNull(key.getFingerPrint()); + assertEquals(key.isDefault(), false); + assertEquals(key.getFingerPrint(), tmClient.getKeyPair(key.getId()) + .getFingerPrint()); + } + + @Test(enabled = true, dependsOnMethods = "testGenerateKeyPair") + public void testInstantiateAndPowerOn() throws InterruptedException, + ExecutionException, TimeoutException, IOException { StringBuffer name = new StringBuffer(); for (int i = 0; i < 15; i++) name.append("a"); @@ -174,38 +189,30 @@ public class TerremarkVCloudClientLiveTest extends VCloudClientLiveTest { Catalog catalog = tmClient.getDefaultCatalog(); String itemId = catalog.get("Ubuntu JeOS 9.10 (32-bit)").getId(); - // determine the cheapest configuration size - SortedSet sizeOptions = tmClient.getComputeOptionsOfCatalogItem(itemId); - - ComputeOptions cheapestOption = Iterables.find(sizeOptions, new Predicate() { - - @Override - public boolean apply(ComputeOptions arg0) { - return arg0.getProcessorCount() == 2; - } - - }); - // create an options object to collect the configuration we want. TerremarkInstantiateVAppTemplateOptions instantiateOptions = processorCount( - cheapestOption.getProcessorCount()).memory(cheapestOption.getMemory()); + 1).memory(512).sshKeyFingerprint(key.getFingerPrint()); - // if this template supports setting the root password, let's add it to our options + // if this template supports setting the root password, let's add it to + // our options CustomizationParameters customizationOptions = tmClient - .getCustomizationOptionsOfCatalogItem(itemId); + .getCustomizationOptionsOfCatalogItem(itemId); if (customizationOptions.canCustomizePassword()) instantiateOptions.withPassword("robotsarefun"); - // the vAppTemplateId tends to be the same as the itemId, but just in case, convert - String vAppTemplateId = tmClient.getCatalogItem(itemId).getEntity().getId(); + // the vAppTemplateId tends to be the same as the itemId, but just in + // case, convert + String vAppTemplateId = tmClient.getCatalogItem(itemId).getEntity() + .getId(); // instantiate, noting vApp returned has minimal details - vApp = tmClient.instantiateVAppTemplateInVDC(vDCId, serverName, vAppTemplateId, - instantiateOptions); + vApp = tmClient.instantiateVAppTemplateInVDC(vDCId, serverName, + vAppTemplateId, instantiateOptions); assertEquals(vApp.getStatus(), VAppStatus.RESOLVED); - // in terremark, this should be a no-op, as it should simply return the above task, which is + // in terremark, this should be a no-op, as it should simply return the + // above task, which is // already deploying Task deployTask = tmClient.deployVApp(vApp.getId()); @@ -224,48 +231,42 @@ public class TerremarkVCloudClientLiveTest extends VCloudClientLiveTest { } assert successTester.apply(deployTask.getId()); - System.out.printf("%d: done deploying vApp%n", System.currentTimeMillis()); + System.out + .printf("%d: done deploying vApp%n", System.currentTimeMillis()); vApp = tmClient.getVApp(vApp.getId()); - NamedResource vAppResource = tmClient.getDefaultVDC().getResourceEntities().get(serverName); + NamedResource vAppResource = tmClient.getDefaultVDC() + .getResourceEntities().get(serverName); assertEquals(vAppResource.getId(), vApp.getId()); - int processorCount = cheapestOption.getProcessorCount(); - long memory = cheapestOption.getMemory(); - verifyConfigurationOfVApp(vApp, serverName, expectedOs, processorCount, memory, hardDisk); + int processorCount = 1; + long memory = 512; + verifyConfigurationOfVApp(vApp, serverName, expectedOs, processorCount, + memory, hardDisk); assertEquals(vApp.getStatus(), VAppStatus.OFF); assert successTester.apply(tmClient.powerOnVApp(vApp.getId()).getId()); - System.out.printf("%d: done powering on vApp%n", System.currentTimeMillis()); + System.out.printf("%d: done powering on vApp%n", System + .currentTimeMillis()); vApp = tmClient.getVApp(vApp.getId()); assertEquals(vApp.getStatus(), VAppStatus.ON); - System.out.println(tmClient.getComputeOptionsOfVApp(vApp.getId())); - System.out.println(tmClient.getCustomizationOptionsOfVApp(vApp.getId())); } @Test - public void testAddInternetService() throws InterruptedException, ExecutionException, - TimeoutException, IOException { - is = tmClient.addInternetServiceToVDC(tmClient.getDefaultVDC().getId(), "SSH", Protocol.TCP, - 22); + public void testAddInternetService() throws InterruptedException, + ExecutionException, TimeoutException, IOException { + is = tmClient.addInternetServiceToVDC(tmClient.getDefaultVDC().getId(), + "SSH", Protocol.TCP, 22); publicIp = is.getPublicIpAddress().getAddress(); } - // 400 errors - @Test(dependsOnMethods = { "testAddInternetService" }, expectedExceptions = HttpResponseException.class) - public void testConfigureInternetService() throws InterruptedException, ExecutionException, - TimeoutException, IOException { - is = tmClient.configureInternetService(is.getId(), new InternetServiceConfiguration() - .changeDescriptionTo("holy cow")); - assertEquals(is.getDescription(), "holy cow"); - } - - @Test(dependsOnMethods = { "testInstantiateAndPowerOn" }) + @Test(enabled = true, dependsOnMethods = "testInstantiateAndPowerOn") public void testCloneVApp() throws IOException { assert successTester.apply(tmClient.powerOffVApp(vApp.getId()).getId()); - System.out.printf("%d: done powering off vApp%n", System.currentTimeMillis()); + System.out.printf("%d: done powering off vApp%n", System + .currentTimeMillis()); // lookup the id of the datacenter you are deploying into String vDCId = tmClient.getDefaultVDC().getId(); @@ -277,18 +278,20 @@ public class TerremarkVCloudClientLiveTest extends VCloudClientLiveTest { name.append("b"); String newName = name.toString(); - CloneVAppOptions options = deploy().powerOn() - .withDescription("The description of " + newName); + CloneVAppOptions options = deploy().powerOn().withDescription( + "The description of " + newName); System.out.printf("%d: cloning vApp%n", System.currentTimeMillis()); - Task task = tmClient.cloneVAppInVDC(vDCId, vAppIdToClone, newName, options); + Task task = tmClient.cloneVAppInVDC(vDCId, vAppIdToClone, newName, + options); // wait for the task to complete assert successTester.apply(task.getId()); System.out.printf("%d: done cloning vApp%n", System.currentTimeMillis()); assert successTester.apply(tmClient.powerOnVApp(vApp.getId()).getId()); - System.out.printf("%d: done powering on vApp%n", System.currentTimeMillis()); + System.out.printf("%d: done powering on vApp%n", System + .currentTimeMillis()); // refresh task to get the new vApp location task = tmClient.getTask(task.getId()); @@ -300,11 +303,12 @@ public class TerremarkVCloudClientLiveTest extends VCloudClientLiveTest { assertEquals(clone.getNetworkToAddresses().values().size(), 1); } - @Test(dependsOnMethods = { "testInstantiateAndPowerOn", "testAddInternetService" }) - public void testPublicIp() throws InterruptedException, ExecutionException, TimeoutException, - IOException { - node = tmClient.addNode(is.getId(), Iterables.getLast(vApp.getNetworkToAddresses().values()), - vApp.getName() + "-SSH", 22); + @Test(enabled = true, dependsOnMethods = { "testInstantiateAndPowerOn", + "testAddInternetService" }) + public void testPublicIp() throws InterruptedException, ExecutionException, + TimeoutException, IOException { + node = tmClient.addNode(is.getId(), Iterables.getLast(vApp + .getNetworkToAddresses().values()), vApp.getName() + "-SSH", 22); loopAndCheckPass(); } @@ -323,18 +327,18 @@ public class TerremarkVCloudClientLiveTest extends VCloudClientLiveTest { } } - // 400 errors - @Test(dependsOnMethods = { "testPublicIp" }, expectedExceptions = HttpResponseException.class) - public void testConfigureNode() throws InterruptedException, ExecutionException, - TimeoutException, IOException { + // TODO this fails + @Test(enabled = true, dependsOnMethods = "testPublicIp") + public void testConfigureNode() throws InterruptedException, + ExecutionException, TimeoutException, IOException { node = tmClient.configureNode(node.getId(), new NodeConfiguration() - .changeDescriptionTo("holy cow")); + .changeDescriptionTo("holy cow")); assertEquals(node.getDescription(), "holy cow"); } - @Test(dependsOnMethods = "testPublicIp") - public void testLifeCycle() throws InterruptedException, ExecutionException, TimeoutException, - IOException { + @Test(enabled = true, dependsOnMethods = "testPublicIp") + public void testLifeCycle() throws InterruptedException, ExecutionException, + TimeoutException, IOException { try {// per docs, this is not supported tmClient.undeployVApp(vApp.getId()); @@ -354,7 +358,8 @@ public class TerremarkVCloudClientLiveTest extends VCloudClientLiveTest { assertEquals(vApp.getStatus(), VAppStatus.ON); - // TODO we need to determine whether shutdown is supported before invoking it. + // TODO we need to determine whether shutdown is supported before invoking + // it. // tmClient.shutdownVApp(vApp.getId()); // vApp = tmClient.getVApp(vApp.getId()); // assertEquals(vApp.getStatus(), VAppStatus.ON); @@ -365,27 +370,28 @@ public class TerremarkVCloudClientLiveTest extends VCloudClientLiveTest { assertEquals(vApp.getStatus(), VAppStatus.OFF); } - @Test(dependsOnMethods = "testLifeCycle") - public void testConfigure() throws InterruptedException, ExecutionException, TimeoutException, - IOException { + @Test(enabled = true, dependsOnMethods = "testLifeCycle") + public void testConfigure() throws InterruptedException, ExecutionException, + TimeoutException, IOException { vApp = tmClient.getVApp(vApp.getId()); - Task task = tmClient.configureVApp(vApp, changeNameTo("eduardo").changeMemoryTo(1536) - .changeProcessorCountTo(1).addDisk(25 * 1048576).addDisk(25 * 1048576)); + Task task = tmClient.configureVApp(vApp, changeNameTo("eduardo") + .changeMemoryTo(1536).changeProcessorCountTo(1).addDisk( + 25 * 1048576).addDisk(25 * 1048576)); assert successTester.apply(task.getId()); vApp = tmClient.getVApp(vApp.getId()); assertEquals(vApp.getName(), "eduardo"); - assertEquals( - Iterables.getOnlyElement( - vApp.getResourceAllocationByType().get(ResourceType.PROCESSOR)) - .getVirtualQuantity(), 1); assertEquals(Iterables.getOnlyElement( - vApp.getResourceAllocationByType().get(ResourceType.MEMORY)).getVirtualQuantity(), - 1536); - assertEquals(vApp.getResourceAllocationByType().get(ResourceType.DISK_DRIVE).size(), 3); + vApp.getResourceAllocationByType().get(ResourceType.PROCESSOR)) + .getVirtualQuantity(), 1); + assertEquals(Iterables.getOnlyElement( + vApp.getResourceAllocationByType().get(ResourceType.MEMORY)) + .getVirtualQuantity(), 1536); + assertEquals(vApp.getResourceAllocationByType().get( + ResourceType.DISK_DRIVE).size(), 3); assert successTester.apply(tmClient.powerOnVApp(vApp.getId()).getId()); @@ -394,12 +400,12 @@ public class TerremarkVCloudClientLiveTest extends VCloudClientLiveTest { assert successTester.apply(tmClient.powerOffVApp(vApp.getId()).getId()); // extract the disks on the vApp sorted by addressOnParent - List disks = Lists.newArrayList(vApp.getResourceAllocationByType().get( - ResourceType.DISK_DRIVE)); + List disks = Lists.newArrayList(vApp + .getResourceAllocationByType().get(ResourceType.DISK_DRIVE)); // delete the second disk - task = tmClient.configureVApp(vApp, deleteDiskWithAddressOnParent(disks.get(1) - .getAddressOnParent())); + task = tmClient.configureVApp(vApp, deleteDiskWithAddressOnParent(disks + .get(1).getAddressOnParent())); assert successTester.apply(task.getId()); @@ -407,43 +413,46 @@ public class TerremarkVCloudClientLiveTest extends VCloudClientLiveTest { loopAndCheckPass(); } - private void verifyConfigurationOfVApp(VApp vApp, String serverName, String expectedOs, - int processorCount, long memory, long hardDisk) { + private void verifyConfigurationOfVApp(VApp vApp, String serverName, + String expectedOs, int processorCount, long memory, long hardDisk) { assertEquals(vApp.getName(), serverName); assertEquals(vApp.getOperatingSystemDescription(), expectedOs); - assertEquals( - Iterables.getOnlyElement( - vApp.getResourceAllocationByType().get(ResourceType.PROCESSOR)) - .getVirtualQuantity(), processorCount); assertEquals(Iterables.getOnlyElement( - vApp.getResourceAllocationByType().get(ResourceType.SCSI_CONTROLLER)) - .getVirtualQuantity(), 1); + vApp.getResourceAllocationByType().get(ResourceType.PROCESSOR)) + .getVirtualQuantity(), processorCount); assertEquals(Iterables.getOnlyElement( - vApp.getResourceAllocationByType().get(ResourceType.MEMORY)).getVirtualQuantity(), - memory); + vApp.getResourceAllocationByType() + .get(ResourceType.SCSI_CONTROLLER)).getVirtualQuantity(), 1); assertEquals(Iterables.getOnlyElement( - vApp.getResourceAllocationByType().get(ResourceType.DISK_DRIVE)) - .getVirtualQuantity(), hardDisk); + vApp.getResourceAllocationByType().get(ResourceType.MEMORY)) + .getVirtualQuantity(), memory); + assertEquals(Iterables.getOnlyElement( + vApp.getResourceAllocationByType().get(ResourceType.DISK_DRIVE)) + .getVirtualQuantity(), hardDisk); assertEquals(vApp.getSize().longValue(), Iterables.getOnlyElement( - vApp.getResourceAllocationByType().get(ResourceType.DISK_DRIVE)) - .getVirtualQuantity()); + vApp.getResourceAllocationByType().get(ResourceType.DISK_DRIVE)) + .getVirtualQuantity()); } private void doCheckPass(String address) throws IOException { IPSocket socket = new IPSocket(address, 22); - System.out.printf("%d: %s awaiting ssh service to start%n", System.currentTimeMillis(), - socket); + System.out.printf("%d: %s awaiting ssh service to start%n", System + .currentTimeMillis(), socket); assert socketTester.apply(socket); - System.out.printf("%d: %s ssh service started%n", System.currentTimeMillis(), socket); + System.out.printf("%d: %s ssh service started%n", System + .currentTimeMillis(), socket); - SshClient connection = sshFactory.create(socket, "vcloud", "$Ep455l0ud!2"); + SshClient connection = sshFactory.create(socket, "vcloud", key + .getPrivateKey().getBytes()); try { connection.connect(); - System.out.printf("%d: %s ssh connection made%n", System.currentTimeMillis(), socket); + System.out.printf("%d: %s ssh connection made%n", System + .currentTimeMillis(), socket); System.out.println(connection.exec("df -h")); System.out.println(connection.exec("ls -al /dev/sd*")); - System.out.println(connection.exec("echo '$Ep455l0ud!2'|sudo -S fdisk -l")); + System.out.println(connection + .exec("echo '$Ep455l0ud!2'|sudo -S fdisk -l")); } finally { if (connection != null) connection.disconnect(); @@ -451,7 +460,8 @@ public class TerremarkVCloudClientLiveTest extends VCloudClientLiveTest { } @AfterTest - void cleanup() throws InterruptedException, ExecutionException, TimeoutException { + void cleanup() throws InterruptedException, ExecutionException, + TimeoutException { if (node != null) tmClient.deleteNode(node.getId()); if (is != null) @@ -472,27 +482,35 @@ public class TerremarkVCloudClientLiveTest extends VCloudClientLiveTest { } tmClient.deleteVApp(clone.getId()); } + if (key != null) + tmClient.deleteKeyPair(key.getId()); } @BeforeGroups(groups = { "live" }) @Override public void setupClient() { - account = checkNotNull(System.getProperty("jclouds.test.user"), "jclouds.test.user"); - String key = checkNotNull(System.getProperty("jclouds.test.key"), "jclouds.test.key"); + account = checkNotNull(System.getProperty("jclouds.test.user"), + "jclouds.test.user"); + String key = checkNotNull(System.getProperty("jclouds.test.key"), + "jclouds.test.key"); Injector injector = new TerremarkVCloudContextBuilder("terremark", - new TerremarkVCloudPropertiesBuilder(account, key).build()).withModules( - new Log4JLoggingModule(), new JschSshClientModule()).buildInjector(); + new TerremarkVCloudPropertiesBuilder(account, key).build()) + .withModules(new Log4JLoggingModule(), new JschSshClientModule()) + .buildInjector(); connection = tmClient = injector.getInstance(TerremarkVCloudClient.class); sshFactory = injector.getInstance(SshClient.Factory.class); - socketTester = new RetryablePredicate(injector.getInstance(SocketOpen.class), 130, - 10, TimeUnit.SECONDS);// make it longer then + socketTester = new RetryablePredicate(injector + .getInstance(SocketOpen.class), 130, 10, TimeUnit.SECONDS);// make + // it + // longer + // then // default internet // service timeout - successTester = new RetryablePredicate(injector.getInstance(TaskSuccess.class), 650, - 10, TimeUnit.SECONDS); + successTester = new RetryablePredicate(injector + .getInstance(TaskSuccess.class), 650, 10, TimeUnit.SECONDS); } } diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/binders/BindAddInternetServiceToXmlPayloadTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/binders/BindAddInternetServiceToXmlPayloadTest.java index 50d1d2df50..40da75705a 100644 --- a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/binders/BindAddInternetServiceToXmlPayloadTest.java +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/binders/BindAddInternetServiceToXmlPayloadTest.java @@ -77,7 +77,7 @@ public class BindAddInternetServiceToXmlPayloadTest { map.put("description", "name TCP 22"); binder.bindToRequest(request, map); assertEquals(request.getFirstHeaderOrNull(HttpHeaders.CONTENT_TYPE), "application/unknown"); - assertEquals(request.getFirstHeaderOrNull(HttpHeaders.CONTENT_LENGTH), "346"); + assertEquals(request.getFirstHeaderOrNull(HttpHeaders.CONTENT_LENGTH), "341"); assertEquals(request.getPayload().getRawContent(), expected); } diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/binders/BindAddNodeServiceToXmlPayloadTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/binders/BindAddNodeServiceToXmlPayloadTest.java index aa4e870602..08cbdd8b39 100644 --- a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/binders/BindAddNodeServiceToXmlPayloadTest.java +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/binders/BindAddNodeServiceToXmlPayloadTest.java @@ -77,7 +77,7 @@ public class BindAddNodeServiceToXmlPayloadTest { map.put("description", "Some test node"); binder.bindToRequest(request, map); assertEquals(request.getFirstHeaderOrNull(HttpHeaders.CONTENT_TYPE), "application/unknown"); - assertEquals(request.getFirstHeaderOrNull(HttpHeaders.CONTENT_LENGTH), "356"); + assertEquals(request.getFirstHeaderOrNull(HttpHeaders.CONTENT_LENGTH), "353"); assertEquals(request.getPayload().getRawContent(), expected); } diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/binders/BindInternetServiceConfigurationToXmlPayloadTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/binders/BindInternetServiceConfigurationToXmlPayloadTest.java deleted file mode 100644 index 86df93900e..0000000000 --- a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/binders/BindInternetServiceConfigurationToXmlPayloadTest.java +++ /dev/null @@ -1,123 +0,0 @@ -/** - * - * Copyright (C) 2009 Cloud Conscious, LLC. - * - * ==================================================================== - * 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.vcloud.terremark.binders; - -import static com.google.common.base.Preconditions.checkNotNull; -import static org.easymock.EasyMock.expect; -import static org.easymock.classextension.EasyMock.createMock; -import static org.easymock.classextension.EasyMock.replay; -import static org.easymock.classextension.EasyMock.verify; - -import java.io.IOException; -import java.net.URI; -import java.util.Properties; - -import org.jclouds.rest.internal.GeneratedHttpRequest; -import com.google.inject.name.Names; -import org.jclouds.vcloud.VCloudPropertiesBuilder; -import org.jclouds.vcloud.terremark.domain.InternetServiceConfiguration; -import org.testng.annotations.Test; - -import com.google.common.collect.HashMultimap; -import com.google.common.collect.Multimap; -import com.google.common.collect.Multimaps; -import com.google.inject.AbstractModule; -import com.google.inject.Guice; -import com.google.inject.Injector; - -/** - * Tests behavior of {@code BindInternetServiceConfigurationToXmlPayload} - * - * @author Adrian Cole - */ -@Test(groups = "unit", testName = "vcloud.BindInternetServiceConfigurationToXmlPayloadTest") -public class BindInternetServiceConfigurationToXmlPayloadTest { - Injector injector = Guice.createInjector(new AbstractModule() { - - @Override - protected void configure() { - Properties props = new Properties(); - Names.bindProperties(binder(), checkNotNull(new VCloudPropertiesBuilder(props).build(), - "properties")); - } - }); - - public void testChangeName() throws IOException { - InternetServiceConfiguration config = new InternetServiceConfiguration() - .changeNameTo("willie"); - String expectedPayload = "willie"; - assertConfigMakesPayload(config, expectedPayload); - } - - public void testChangeDescription() throws IOException { - InternetServiceConfiguration config = new InternetServiceConfiguration() - .changeDescriptionTo("description"); - String expectedPayload = "description"; - assertConfigMakesPayload(config, expectedPayload); - } - - public void testChangeTimeout() throws IOException { - InternetServiceConfiguration config = new InternetServiceConfiguration().changeTimeoutTo(3); - String expectedPayload = "3"; - assertConfigMakesPayload(config, expectedPayload); - } - - public void testEnableTraffic() throws IOException { - InternetServiceConfiguration config = new InternetServiceConfiguration().enableTraffic(); - String expectedPayload = "true"; - assertConfigMakesPayload(config, expectedPayload); - } - - public void testDisableTraffic() throws IOException { - InternetServiceConfiguration config = new InternetServiceConfiguration().disableTraffic(); - String expectedPayload = "false"; - assertConfigMakesPayload(config, expectedPayload); - } - - public void testTwoOptions() throws IOException { - InternetServiceConfiguration config = new InternetServiceConfiguration().disableTraffic() - .changeNameTo("willie"); - String expectedPayload = "williefalse"; - assertConfigMakesPayload(config, expectedPayload); - } - - @Test(expectedExceptions = IllegalArgumentException.class) - public void testNoOptions() throws IOException { - InternetServiceConfiguration config = new InternetServiceConfiguration(); - String expectedPayload = "williefalse"; - assertConfigMakesPayload(config, expectedPayload); - } - - private void assertConfigMakesPayload(InternetServiceConfiguration config, String expectedPayload) { - BindInternetServiceConfigurationToXmlPayload binder = injector - .getInstance(BindInternetServiceConfigurationToXmlPayload.class); - Multimap headers = Multimaps.synchronizedMultimap(HashMultimap - . create()); - GeneratedHttpRequest request = createMock(GeneratedHttpRequest.class); - expect(request.getArgs()).andReturn(new Object[] { config }).atLeastOnce(); - expect(request.getEndpoint()).andReturn(URI.create("http://localhost/key")).anyTimes(); - expect(request.getFirstHeaderOrNull("Content-Type")).andReturn(null).atLeastOnce(); - expect(request.getHeaders()).andReturn(headers).atLeastOnce(); - request.setPayload(expectedPayload); - replay(request); - binder.bindToRequest(request, config); - verify(request); - } - -} diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/binders/BindNodeConfigurationToXmlPayloadTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/binders/BindNodeConfigurationToXmlPayloadTest.java index c579a194ad..6434fd2cf1 100644 --- a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/binders/BindNodeConfigurationToXmlPayloadTest.java +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/binders/BindNodeConfigurationToXmlPayloadTest.java @@ -60,38 +60,38 @@ public class BindNodeConfigurationToXmlPayloadTest { public void testChangeName() throws IOException { NodeConfiguration config = new NodeConfiguration().changeNameTo("willie"); - String expectedPayload = "willie"; + String expectedPayload = "willie"; assertConfigMakesPayload(config, expectedPayload); } public void testChangeDescription() throws IOException { NodeConfiguration config = new NodeConfiguration().changeDescriptionTo("description"); - String expectedPayload = "description"; + String expectedPayload = "description"; assertConfigMakesPayload(config, expectedPayload); } public void testEnableTraffic() throws IOException { NodeConfiguration config = new NodeConfiguration().enableTraffic(); - String expectedPayload = "true"; + String expectedPayload = "true"; assertConfigMakesPayload(config, expectedPayload); } public void testDisableTraffic() throws IOException { NodeConfiguration config = new NodeConfiguration().disableTraffic(); - String expectedPayload = "false"; + String expectedPayload = "false"; assertConfigMakesPayload(config, expectedPayload); } public void testTwoOptions() throws IOException { NodeConfiguration config = new NodeConfiguration().disableTraffic().changeNameTo("willie"); - String expectedPayload = "williefalse"; + String expectedPayload = "williefalse"; assertConfigMakesPayload(config, expectedPayload); } @Test(expectedExceptions = IllegalArgumentException.class) public void testNoOptions() throws IOException { NodeConfiguration config = new NodeConfiguration(); - String expectedPayload = "williefalse"; + String expectedPayload = "williefalse"; assertConfigMakesPayload(config, expectedPayload); } diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/TerremarkVCloudTemplateOptionsTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/TerremarkVCloudTemplateOptionsTest.java new file mode 100644 index 0000000000..60e99f1b83 --- /dev/null +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/TerremarkVCloudTemplateOptionsTest.java @@ -0,0 +1,211 @@ +package org.jclouds.vcloud.terremark.compute; + +import static org.jclouds.vcloud.terremark.compute.options.TerremarkVCloudTemplateOptions.Builder.authorizePublicKey; +import static org.jclouds.vcloud.terremark.compute.options.TerremarkVCloudTemplateOptions.Builder.blockOnPort; +import static org.jclouds.vcloud.terremark.compute.options.TerremarkVCloudTemplateOptions.Builder.inboundPorts; +import static org.jclouds.vcloud.terremark.compute.options.TerremarkVCloudTemplateOptions.Builder.installPrivateKey; +import static org.jclouds.vcloud.terremark.compute.options.TerremarkVCloudTemplateOptions.Builder.noKeyPair; +import static org.jclouds.vcloud.terremark.compute.options.TerremarkVCloudTemplateOptions.Builder.sshKeyFingerprint; +import static org.testng.Assert.assertEquals; + +import org.jclouds.compute.options.TemplateOptions; +import org.jclouds.vcloud.terremark.compute.options.TerremarkVCloudTemplateOptions; +import org.testng.annotations.Test; + +/** + * Tests possible uses of TerremarkVCloudTemplateOptions and + * TerremarkVCloudTemplateOptions.Builder.* + * + * @author Adrian Cole + */ +public class TerremarkVCloudTemplateOptionsTest { + + public void testAs() { + TemplateOptions options = new TerremarkVCloudTemplateOptions(); + assertEquals(options.as(TerremarkVCloudTemplateOptions.class), options); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testkeyPairBadFormat() { + TerremarkVCloudTemplateOptions options = new TerremarkVCloudTemplateOptions(); + options.sshKeyFingerprint(""); + } + + @Test(expectedExceptions = IllegalStateException.class) + public void testkeyPairAndNoKeyPair() { + TerremarkVCloudTemplateOptions options = new TerremarkVCloudTemplateOptions(); + options.sshKeyFingerprint("mykeypair"); + options.noKeyPair(); + } + + @Test(expectedExceptions = IllegalStateException.class) + public void testNoKeyPairAndKeyPair() { + TerremarkVCloudTemplateOptions options = new TerremarkVCloudTemplateOptions(); + options.noKeyPair(); + options.sshKeyFingerprint("mykeypair"); + } + + @Test + public void testkeyPair() { + TerremarkVCloudTemplateOptions options = new TerremarkVCloudTemplateOptions(); + options.sshKeyFingerprint("mykeypair"); + assertEquals(options.getSshKeyFingerprint(), "mykeypair"); + } + + @Test + public void testNullkeyPair() { + TerremarkVCloudTemplateOptions options = new TerremarkVCloudTemplateOptions(); + assertEquals(options.getSshKeyFingerprint(), null); + } + + @Test + public void testkeyPairStatic() { + TerremarkVCloudTemplateOptions options = sshKeyFingerprint("mykeypair"); + assertEquals(options.getSshKeyFingerprint(), "mykeypair"); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testkeyPairNPE() { + sshKeyFingerprint(null); + } + + @Test + public void testnoKeyPair() { + TerremarkVCloudTemplateOptions options = new TerremarkVCloudTemplateOptions(); + options.noKeyPair(); + assertEquals(options.getSshKeyFingerprint(), null); + assert !options.shouldAutomaticallyCreateKeyPair(); + } + + @Test + public void testFalsenoKeyPair() { + TerremarkVCloudTemplateOptions options = new TerremarkVCloudTemplateOptions(); + assertEquals(options.getSshKeyFingerprint(), null); + assert options.shouldAutomaticallyCreateKeyPair(); + } + + @Test + public void testnoKeyPairStatic() { + TerremarkVCloudTemplateOptions options = noKeyPair(); + assertEquals(options.getSshKeyFingerprint(), null); + assert !options.shouldAutomaticallyCreateKeyPair(); + } + + // superclass tests + @Test(expectedExceptions = IllegalArgumentException.class) + public void testinstallPrivateKeyBadFormat() { + TerremarkVCloudTemplateOptions options = new TerremarkVCloudTemplateOptions(); + options.installPrivateKey("whompy"); + } + + @Test + public void testinstallPrivateKey() { + TerremarkVCloudTemplateOptions options = new TerremarkVCloudTemplateOptions(); + options.installPrivateKey("-----BEGIN RSA PRIVATE KEY-----"); + assertEquals(options.getPrivateKey(), "-----BEGIN RSA PRIVATE KEY-----"); + } + + @Test + public void testNullinstallPrivateKey() { + TerremarkVCloudTemplateOptions options = new TerremarkVCloudTemplateOptions(); + assertEquals(options.getPrivateKey(), null); + } + + @Test + public void testinstallPrivateKeyStatic() { + TerremarkVCloudTemplateOptions options = installPrivateKey("-----BEGIN RSA PRIVATE KEY-----"); + assertEquals(options.getPrivateKey(), "-----BEGIN RSA PRIVATE KEY-----"); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testinstallPrivateKeyNPE() { + installPrivateKey(null); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testauthorizePublicKeyBadFormat() { + TerremarkVCloudTemplateOptions options = new TerremarkVCloudTemplateOptions(); + options.authorizePublicKey("whompy"); + } + + @Test + public void testauthorizePublicKey() { + TerremarkVCloudTemplateOptions options = new TerremarkVCloudTemplateOptions(); + options.authorizePublicKey("ssh-rsa"); + assertEquals(options.getPublicKey(), "ssh-rsa"); + } + + @Test + public void testNullauthorizePublicKey() { + TerremarkVCloudTemplateOptions options = new TerremarkVCloudTemplateOptions(); + assertEquals(options.getPublicKey(), null); + } + + @Test + public void testauthorizePublicKeyStatic() { + TerremarkVCloudTemplateOptions options = authorizePublicKey("ssh-rsa"); + assertEquals(options.getPublicKey(), "ssh-rsa"); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testauthorizePublicKeyNPE() { + authorizePublicKey(null); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testblockOnPortBadFormat() { + TerremarkVCloudTemplateOptions options = new TerremarkVCloudTemplateOptions(); + options.blockOnPort(-1, -1); + } + + @Test + public void testblockOnPort() { + TerremarkVCloudTemplateOptions options = new TerremarkVCloudTemplateOptions(); + options.blockOnPort(22, 30); + assertEquals(options.getPort(), 22); + assertEquals(options.getSeconds(), 30); + + } + + @Test + public void testNullblockOnPort() { + TerremarkVCloudTemplateOptions options = new TerremarkVCloudTemplateOptions(); + assertEquals(options.getPort(), -1); + assertEquals(options.getSeconds(), -1); + } + + @Test + public void testblockOnPortStatic() { + TerremarkVCloudTemplateOptions options = blockOnPort(22, 30); + assertEquals(options.getPort(), 22); + assertEquals(options.getSeconds(), 30); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testinboundPortsBadFormat() { + TerremarkVCloudTemplateOptions options = new TerremarkVCloudTemplateOptions(); + options.inboundPorts(-1, -1); + } + + @Test + public void testinboundPorts() { + TerremarkVCloudTemplateOptions options = new TerremarkVCloudTemplateOptions(); + options.inboundPorts(22, 30); + assertEquals(options.getInboundPorts()[0], 22); + assertEquals(options.getInboundPorts()[1], 30); + + } + + @Test + public void testDefaultOpen22() { + TerremarkVCloudTemplateOptions options = new TerremarkVCloudTemplateOptions(); + assertEquals(options.getInboundPorts()[0], 22); + } + + @Test + public void testinboundPortsStatic() { + TerremarkVCloudTemplateOptions options = inboundPorts(22, 30); + assertEquals(options.getInboundPorts()[0], 22); + assertEquals(options.getInboundPorts()[1], 30); + } +} diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/strategy/CleanupOrphanKeysTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/strategy/CleanupOrphanKeysTest.java new file mode 100644 index 0000000000..804e3ad1b2 --- /dev/null +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/strategy/CleanupOrphanKeysTest.java @@ -0,0 +1,195 @@ +/** + * + * Copyright (C) 2009 Cloud Conscious, LLC. + * + * ==================================================================== + * 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.vcloud.terremark.compute.strategy; + +import static org.easymock.EasyMock.expect; +import static org.easymock.classextension.EasyMock.createMock; +import static org.easymock.classextension.EasyMock.replay; +import static org.easymock.classextension.EasyMock.verify; +import static org.jclouds.compute.predicates.NodePredicates.parentLocationId; + +import org.jclouds.compute.domain.NodeMetadata; +import org.jclouds.compute.domain.NodeState; +import org.jclouds.compute.strategy.ListNodesStrategy; +import org.jclouds.vcloud.terremark.compute.domain.OrgAndName; +import org.jclouds.vcloud.terremark.compute.functions.NodeMetadataToOrgAndName; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableSet; + +/** + * @author Adrian Cole + */ +@Test(groups = "unit", testName = "terremark.CleanupOrphanKeysTest") +public class CleanupOrphanKeysTest { + + public void testWhenNoDeletedNodes() { + Iterable deadOnes = ImmutableSet + . of(); + // create mocks + CleanupOrphanKeys strategy = setupStrategy(); + + // setup expectations + + // replay mocks + replayStrategy(strategy); + + // run + strategy.execute(deadOnes); + + // verify mocks + verifyStrategy(strategy); + } + + public void testWhenDeletedNodesHaveNoTag() { + // create mocks + CleanupOrphanKeys strategy = setupStrategy(); + NodeMetadata nodeMetadata = createMock(NodeMetadata.class); + Iterable deadOnes = ImmutableSet + . of(nodeMetadata); + + // setup expectations + expect(strategy.nodeToOrgAndName.apply(nodeMetadata)).andReturn(null) + .atLeastOnce(); + + // replay mocks + replay(nodeMetadata); + replayStrategy(strategy); + + // run + strategy.execute(deadOnes); + + // verify mocks + verify(nodeMetadata); + verifyStrategy(strategy); + } + + public void testWhenStillRunningWithTag() { + // create mocks + CleanupOrphanKeys strategy = setupStrategy(); + NodeMetadata nodeMetadata = createMock(NodeMetadata.class); + Iterable deadOnes = ImmutableSet + . of(nodeMetadata); + OrgAndName orgTag = new OrgAndName("location", "tag"); + + // setup expectations + expect(strategy.nodeToOrgAndName.apply(nodeMetadata)).andReturn(orgTag) + .atLeastOnce(); + expect( + (Object) strategy.listNodes + .listDetailsOnNodesMatching(parentLocationId(orgTag.getOrg()))) + .andReturn(ImmutableSet.of(nodeMetadata)); + expect(nodeMetadata.getTag()).andReturn(orgTag.getName()).atLeastOnce(); + expect(nodeMetadata.getState()).andReturn(NodeState.RUNNING) + .atLeastOnce(); + + // replay mocks + replay(nodeMetadata); + replayStrategy(strategy); + + // run + strategy.execute(deadOnes); + + // verify mocks + verify(nodeMetadata); + verifyStrategy(strategy); + } + + public void testWhenTerminatedWithTag() { + // create mocks + CleanupOrphanKeys strategy = setupStrategy(); + NodeMetadata nodeMetadata = createMock(NodeMetadata.class); + Iterable deadOnes = ImmutableSet + . of(nodeMetadata); + OrgAndName orgTag = new OrgAndName("location", "tag"); + + // setup expectations + expect(strategy.nodeToOrgAndName.apply(nodeMetadata)).andReturn(orgTag) + .atLeastOnce(); + expect( + (Object) strategy.listNodes + .listDetailsOnNodesMatching(parentLocationId(orgTag.getOrg()))) + .andReturn(ImmutableSet.of(nodeMetadata)); + expect(nodeMetadata.getTag()).andReturn(orgTag.getName()).atLeastOnce(); + expect(nodeMetadata.getState()).andReturn(NodeState.TERMINATED) + .atLeastOnce(); + strategy.deleteKeyPair.execute(orgTag); + + // replay mocks + replay(nodeMetadata); + replayStrategy(strategy); + + // run + strategy.execute(deadOnes); + + // verify mocks + verify(nodeMetadata); + verifyStrategy(strategy); + } + + public void testWhenNoneLeftWithTag() { + // create mocks + CleanupOrphanKeys strategy = setupStrategy(); + NodeMetadata nodeMetadata = createMock(NodeMetadata.class); + Iterable deadOnes = ImmutableSet + . of(nodeMetadata); + OrgAndName orgTag = new OrgAndName("location", "tag"); + + // setup expectations + expect(strategy.nodeToOrgAndName.apply(nodeMetadata)).andReturn(orgTag) + .atLeastOnce(); + expect( + (Object) strategy.listNodes + .listDetailsOnNodesMatching(parentLocationId(orgTag.getOrg()))) + .andReturn(ImmutableSet.of()); + strategy.deleteKeyPair.execute(orgTag); + + // replay mocks + replay(nodeMetadata); + replayStrategy(strategy); + + // run + strategy.execute(deadOnes); + + // verify mocks + verify(nodeMetadata); + verifyStrategy(strategy); + } + + private void verifyStrategy(CleanupOrphanKeys strategy) { + verify(strategy.nodeToOrgAndName); + verify(strategy.deleteKeyPair); + verify(strategy.listNodes); + + } + + private CleanupOrphanKeys setupStrategy() { + NodeMetadataToOrgAndName nodeToOrgAndName = createMock(NodeMetadataToOrgAndName.class); + DeleteKeyPair deleteKeyPair = createMock(DeleteKeyPair.class); + ListNodesStrategy listNodes = createMock(ListNodesStrategy.class); + return new CleanupOrphanKeys(nodeToOrgAndName, deleteKeyPair, listNodes); + } + + private void replayStrategy(CleanupOrphanKeys strategy) { + replay(strategy.nodeToOrgAndName); + replay(strategy.deleteKeyPair); + replay(strategy.listNodes); + } + +} diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/strategy/CreateNewKeyPairUnlessUserSpecifiedOtherwiseTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/strategy/CreateNewKeyPairUnlessUserSpecifiedOtherwiseTest.java new file mode 100644 index 0000000000..e2207f6bc1 --- /dev/null +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/strategy/CreateNewKeyPairUnlessUserSpecifiedOtherwiseTest.java @@ -0,0 +1,179 @@ +/** + * + * Copyright (C) 2009 Cloud Conscious, LLC. + * + * ==================================================================== + * 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.vcloud.terremark.compute.strategy; + +import static org.easymock.EasyMock.expect; +import static org.easymock.classextension.EasyMock.createMock; +import static org.easymock.classextension.EasyMock.replay; +import static org.easymock.classextension.EasyMock.verify; +import static org.jclouds.vcloud.terremark.compute.options.TerremarkVCloudTemplateOptions.Builder.noKeyPair; +import static org.jclouds.vcloud.terremark.compute.options.TerremarkVCloudTemplateOptions.Builder.sshKeyFingerprint; +import static org.testng.Assert.assertEquals; + +import java.util.concurrent.ConcurrentMap; + +import org.jclouds.vcloud.terremark.compute.domain.OrgAndName; +import org.jclouds.vcloud.terremark.compute.functions.CreateUniqueKeyPair; +import org.jclouds.vcloud.terremark.compute.options.TerremarkVCloudTemplateOptions; +import org.jclouds.vcloud.terremark.domain.KeyPair; +import org.testng.annotations.Test; + +/** + * @author Adrian Cole + */ +@Test(groups = "unit", testName = "terremark.CreateNewKeyPairUnlessUserSpecifiedOtherwiseTest") +public class CreateNewKeyPairUnlessUserSpecifiedOtherwiseTest { + + public void testExecuteWithDefaultOptionsAlreadyHasKey() + throws SecurityException, NoSuchMethodException { + // setup constants + String org = "org1"; + String tag = "tag"; + OrgAndName orgAndName = new OrgAndName("org1", "tag"); + String systemGeneratedFingerprint = "systemGeneratedKeyPairfinger"; + TerremarkVCloudTemplateOptions options = new TerremarkVCloudTemplateOptions(); + + // create mocks + CreateNewKeyPairUnlessUserSpecifiedOtherwise strategy = setupStrategy(); + KeyPair keyPair = createMock(KeyPair.class); + + // setup expectations + expect(strategy.credentialsMap.containsKey(orgAndName)).andReturn(true); + expect(strategy.credentialsMap.get(orgAndName)).andReturn(keyPair); + expect(keyPair.getFingerPrint()).andReturn(systemGeneratedFingerprint) + .atLeastOnce(); + + // replay mocks + replay(keyPair); + replayStrategy(strategy); + + // run + strategy.execute(org, tag, options); + assertEquals(options.getSshKeyFingerprint(), + "systemGeneratedKeyPairfinger"); + + // verify mocks + verify(keyPair); + verifyStrategy(strategy); + } + + public void testCreateNewKeyPairUnlessUserSpecifiedOtherwise_reusesKeyWhenToldTo() { + // setup constants + String org = "org1"; + String tag = "tag"; + TerremarkVCloudTemplateOptions options = sshKeyFingerprint("fingerprintFromUser"); + + // create mocks + CreateNewKeyPairUnlessUserSpecifiedOtherwise strategy = setupStrategy(); + KeyPair keyPair = createMock(KeyPair.class); + + // setup expectations + + // replay mocks + replay(keyPair); + replayStrategy(strategy); + + // run + strategy.execute(org, tag, options); + assertEquals(options.getSshKeyFingerprint(), "fingerprintFromUser"); + + // verify mocks + verify(keyPair); + verifyStrategy(strategy); + } + + public void testCreateNewKeyPairUnlessUserSpecifiedOtherwise_createsNewKeyPairAndReturnsItsNameByDefault() { + // setup constants + String org = "org1"; + String tag = "tag"; + String systemGeneratedFingerprint = "systemGeneratedKeyPairfinger"; + TerremarkVCloudTemplateOptions options = new TerremarkVCloudTemplateOptions(); + OrgAndName orgAndName = new OrgAndName("org1", "tag"); + + // create mocks + CreateNewKeyPairUnlessUserSpecifiedOtherwise strategy = setupStrategy(); + KeyPair keyPair = createMock(KeyPair.class); + + // setup expectations + expect(strategy.credentialsMap.containsKey(orgAndName)).andReturn(false); + expect(strategy.createUniqueKeyPair.apply(orgAndName)).andReturn(keyPair); + expect(keyPair.getFingerPrint()).andReturn(systemGeneratedFingerprint) + .atLeastOnce(); + expect(strategy.credentialsMap.put(orgAndName, keyPair)).andReturn(null); + + // replay mocks + replay(keyPair); + replayStrategy(strategy); + + // run + strategy.execute(org, tag, options); + assertEquals(options.getSshKeyFingerprint(), systemGeneratedFingerprint); + + // verify mocks + verify(keyPair); + verifyStrategy(strategy); + } + + public void testCreateNewKeyPairUnlessUserSpecifiedOtherwise_doesntCreateAKeyPairAndReturnsNullWhenToldNotTo() { + // setup constants + String org = "org1"; + String tag = "tag"; + TerremarkVCloudTemplateOptions options = noKeyPair(); + + // create mocks + CreateNewKeyPairUnlessUserSpecifiedOtherwise strategy = setupStrategy(); + KeyPair keyPair = createMock(KeyPair.class); + + // setup expectations + + // replay mocks + replay(keyPair); + replayStrategy(strategy); + + // run + strategy.execute(org, tag, options); + assertEquals(options.getSshKeyFingerprint(), null); + + // verify mocks + verify(keyPair); + verifyStrategy(strategy); + } + + private void verifyStrategy( + CreateNewKeyPairUnlessUserSpecifiedOtherwise strategy) { + verify(strategy.credentialsMap); + verify(strategy.createUniqueKeyPair); + } + + @SuppressWarnings("unchecked") + private CreateNewKeyPairUnlessUserSpecifiedOtherwise setupStrategy() { + ConcurrentMap credentialsMap = createMock(ConcurrentMap.class); + CreateUniqueKeyPair createUniqueKeyPair = createMock(CreateUniqueKeyPair.class); + + return new CreateNewKeyPairUnlessUserSpecifiedOtherwise(credentialsMap, + createUniqueKeyPair); + } + + private void replayStrategy( + CreateNewKeyPairUnlessUserSpecifiedOtherwise strategy) { + replay(strategy.credentialsMap); + replay(strategy.createUniqueKeyPair); + } + +} diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/strategy/DeleteKeyPairTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/strategy/DeleteKeyPairTest.java new file mode 100644 index 0000000000..e8b07300f2 --- /dev/null +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/strategy/DeleteKeyPairTest.java @@ -0,0 +1,135 @@ +/** + * + * Copyright (C) 2009 Cloud Conscious, LLC. + * + * ==================================================================== + * 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.vcloud.terremark.compute.strategy; + +import static org.easymock.EasyMock.expect; +import static org.easymock.classextension.EasyMock.createMock; +import static org.easymock.classextension.EasyMock.replay; +import static org.easymock.classextension.EasyMock.verify; + +import java.util.concurrent.ConcurrentMap; + +import org.jclouds.vcloud.terremark.TerremarkVCloudClient; +import org.jclouds.vcloud.terremark.compute.domain.OrgAndName; +import org.jclouds.vcloud.terremark.domain.KeyPair; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableSet; + +/** + * @author Adrian Cole + */ +@Test(groups = "unit", testName = "terremark.DeleteKeyPairTest") +public class DeleteKeyPairTest { + + public void testWhenNoKeyPairsInOrg() { + // setup constants + OrgAndName orgTag = new OrgAndName("org1", "tag"); + + // create mocks + DeleteKeyPair strategy = setupStrategy(); + + // setup expectations + expect(strategy.terremarkClient.listKeyPairsInOrg(orgTag.getOrg())) + .andReturn(ImmutableSet. of()); + + // replay mocks + replayStrategy(strategy); + + // run + strategy.execute(orgTag); + + // verify mocks + verifyStrategy(strategy); + } + + public void testWhenKeyPairMatches() { + // setup constants + OrgAndName orgTag = new OrgAndName("org1", "tag"); + + // create mocks + DeleteKeyPair strategy = setupStrategy(); + KeyPair keyPair = createMock(KeyPair.class); + + // setup expectations + expect(strategy.terremarkClient.listKeyPairsInOrg(orgTag.getOrg())) + .andReturn(ImmutableSet. of(keyPair)); + expect(keyPair.getName()).andReturn( + "jclouds#" + orgTag.getName() + "-123").atLeastOnce(); + expect(keyPair.getId()).andReturn(1234); + strategy.terremarkClient.deleteKeyPair(1234); + expect(strategy.credentialsMap.remove(orgTag)).andReturn(null); + + // replay mocks + replay(keyPair); + replayStrategy(strategy); + + // run + strategy.execute(orgTag); + + // verify mocks + verify(keyPair); + verifyStrategy(strategy); + } + + public void testWhenKeyPairDoesntMatch() { + // setup constants + OrgAndName orgTag = new OrgAndName("org1", "tag"); + + // create mocks + DeleteKeyPair strategy = setupStrategy(); + KeyPair keyPair = createMock(KeyPair.class); + + // setup expectations + expect(strategy.terremarkClient.listKeyPairsInOrg(orgTag.getOrg())) + .andReturn(ImmutableSet. of(keyPair)); + expect(keyPair.getName()).andReturn( + "kclouds#" + orgTag.getName() + "-123"); + + // replay mocks + replay(keyPair); + replayStrategy(strategy); + + // run + strategy.execute(orgTag); + + // verify mocks + verify(keyPair); + verifyStrategy(strategy); + } + + private void verifyStrategy(DeleteKeyPair strategy) { + verify(strategy.credentialsMap); + verify(strategy.terremarkClient); + } + + @SuppressWarnings("unchecked") + private DeleteKeyPair setupStrategy() { + ConcurrentMap credentialsMap = createMock(ConcurrentMap.class); + TerremarkVCloudClient terremarkClient = createMock(TerremarkVCloudClient.class); + + return new DeleteKeyPair(terremarkClient, credentialsMap); + } + + private void replayStrategy(DeleteKeyPair strategy) { + replay(strategy.credentialsMap); + replay(strategy.terremarkClient); + } + +} diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/CustomizationParametersHandlerTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/CustomizationParametersHandlerTest.java index e7603826cc..13d3161baa 100644 --- a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/CustomizationParametersHandlerTest.java +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/CustomizationParametersHandlerTest.java @@ -36,10 +36,12 @@ import org.testng.annotations.Test; public class CustomizationParametersHandlerTest extends BaseHandlerTest { public void test1() throws UnknownHostException { - InputStream is = getClass().getResourceAsStream("/terremark/CustomizationParameters.xml"); + InputStream is = getClass().getResourceAsStream( + "/terremark/CustomizationParameters.xml"); - CustomizationParameters result = (CustomizationParameters) factory.create( - injector.getInstance(CustomizationParametersHandler.class)).parse(is); - assertEquals(result, new CustomizationParameters(true, false)); + CustomizationParameters result = (CustomizationParameters) factory + .create(injector.getInstance(CustomizationParametersHandler.class)) + .parse(is); + assertEquals(result, new CustomizationParameters(true, false, false)); } } diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/ComputeOptionHandlerTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/KeyHandlerTest.java similarity index 63% rename from vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/ComputeOptionHandlerTest.java rename to vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/KeyHandlerTest.java index 1aef5b221c..d6adcae0f8 100644 --- a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/ComputeOptionHandlerTest.java +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/KeyHandlerTest.java @@ -18,28 +18,27 @@ */ package org.jclouds.vcloud.terremark.xml; -import static org.testng.Assert.assertEquals; - -import java.io.InputStream; import java.net.UnknownHostException; import org.jclouds.http.functions.BaseHandlerTest; -import org.jclouds.vcloud.terremark.domain.ComputeOptions; import org.testng.annotations.Test; /** - * Tests behavior of {@code ComputeOptionServiceHandler} + * Tests behavior of {@code KeyHandler} * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.ComputeOptionHandlerTest") -public class ComputeOptionHandlerTest extends BaseHandlerTest { +@Test(groups = "unit", testName = "vcloud.KeyHandlerTest") +public class KeyHandlerTest extends BaseHandlerTest { public void test1() throws UnknownHostException { - InputStream is = getClass().getResourceAsStream("/terremark/ComputeOption.xml"); - ComputeOptions result = (ComputeOptions) factory.create( - injector.getInstance(ComputeOptionHandler.class)).parse(is); - assertEquals(result, new ComputeOptions(1, 512, 0.039f)); + // TODO + // InputStream is = getClass().getResourceAsStream("/terremark/key.xml"); + // Key result = (Key) + // factory.create(injector.getInstance(KeyHandler.class)).parse(is); + // assertEquals(result, new Key(242, "Key for Jim", URI + // .create("https://services.vcloudexpress.terremark.com/api/v0.8/Keys/242"), + // "172.16.20.3", 80, false, "Some test node")); } } diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/ComputeOptionsHandlerTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/KeysHandlerTest.java similarity index 55% rename from vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/ComputeOptionsHandlerTest.java rename to vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/KeysHandlerTest.java index 24e135af14..7fb1c3c124 100644 --- a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/ComputeOptionsHandlerTest.java +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/KeysHandlerTest.java @@ -21,29 +21,39 @@ package org.jclouds.vcloud.terremark.xml; import static org.testng.Assert.assertEquals; import java.io.InputStream; +import java.net.URI; import java.net.UnknownHostException; -import java.util.SortedSet; +import java.util.Set; import org.jclouds.http.functions.BaseHandlerTest; -import org.jclouds.vcloud.terremark.domain.ComputeOptions; +import org.jclouds.vcloud.terremark.domain.KeyPair; import org.testng.annotations.Test; -import com.google.common.collect.ImmutableSortedSet; +import com.google.common.collect.ImmutableSet; /** - * Tests behavior of {@code ComputeOptionsHandler} + * Tests behavior of {@code KeysHandler} * * @author Adrian Cole */ -@Test(groups = "unit", testName = "vcloud.ComputeOptionsHandlerTest") -public class ComputeOptionsHandlerTest extends BaseHandlerTest { +@Test(groups = "unit", testName = "vcloud.KeysHandlerTest") +public class KeysHandlerTest extends BaseHandlerTest { public void test1() throws UnknownHostException { - InputStream is = getClass().getResourceAsStream("/terremark/ComputeOptions.xml"); + InputStream is = getClass() + .getResourceAsStream("/terremark/keysList.xml"); + + Set result = factory.create(injector.getInstance(KeyPairsHandler.class)) + .parse(is); + assertEquals( + result, + ImmutableSet + .of(new KeyPair( + 9, + URI + .create("https://services.vcloudexpress.terremark.com/api/v0.8a-ext1.6/extensions/key/9"), + "default", true, null, + "4e:af:8a:9f:e9:d2:72:d7:4b:a0:da:98:72:98:4d:7d"))); - SortedSet result = factory.create( - injector.getInstance(ComputeOptionsHandler.class)).parse(is); - assertEquals(result, ImmutableSortedSet.of(new ComputeOptions(1, 512, 0.039f), - new ComputeOptions(8, 16384, 1.61f))); } } diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/TerremarkOrgHandlerTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/TerremarkOrgHandlerTest.java new file mode 100644 index 0000000000..5db4ac683e --- /dev/null +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/xml/TerremarkOrgHandlerTest.java @@ -0,0 +1,107 @@ +package org.jclouds.vcloud.terremark.xml; + +import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.vcloud.VCloudMediaType.CATALOG_XML; +import static org.jclouds.vcloud.VCloudMediaType.TASKSLIST_XML; +import static org.testng.Assert.assertEquals; + +import java.io.InputStream; +import java.net.URI; +import java.util.Properties; + +import org.jclouds.http.functions.BaseHandlerTest; +import org.jclouds.http.functions.ParseSax; +import org.jclouds.http.functions.config.ParserModule; +import org.jclouds.vcloud.VCloudMediaType; +import org.jclouds.vcloud.domain.internal.NamedResourceImpl; +import org.jclouds.vcloud.terremark.TerremarkVCloudMediaType; +import org.jclouds.vcloud.terremark.TerremarkVCloudPropertiesBuilder; +import org.jclouds.vcloud.terremark.domain.TerremarkOrganization; +import org.testng.annotations.BeforeTest; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableMap; +import com.google.inject.Guice; +import com.google.inject.name.Names; + +/** + * Tests behavior of {@code TerremarkOrgHandler} + * + * @author Adrian Cole + */ +@Test(groups = "unit", testName = "vcloud.TerremarkOrgHandlerTest") +public class TerremarkOrgHandlerTest extends BaseHandlerTest { + @Override + @BeforeTest + protected void setUpInjector() { + injector = Guice.createInjector(new ParserModule() { + @Override + public void configure() { + super.configure(); + Properties props = new Properties(); + Names.bindProperties(binder(), checkNotNull( + new TerremarkVCloudPropertiesBuilder(props).build(), + "properties")); + } + }); + factory = injector.getInstance(ParseSax.Factory.class); + assert factory != null; + } + + public void testApplyInputStream() { + + InputStream is = getClass().getResourceAsStream("/terremark/org.xml"); + + TerremarkOrganization result = (TerremarkOrganization) factory.create( + injector.getInstance(TerremarkOrgHandler.class)).parse(is); + assertEquals(result.getName(), "adrian@jclouds.org"); + assertEquals(result.getId(), 48 + ""); + assertEquals( + result.getLocation(), + URI + .create("https://services.vcloudexpress.terremark.com/api/v0.8a-ext1.6/org/48")); + assertEquals( + result.getCatalogs(), + ImmutableMap + .of( + "Miami Environment 1 Catalog", + new NamedResourceImpl( + "catalog", + "Miami Environment 1 Catalog", + CATALOG_XML, + URI + .create("https://services.vcloudexpress.terremark.com/api/v0.8a-ext1.6/vdc/32/catalog")))); + + assertEquals( + result.getVDCs(), + ImmutableMap + .of( + "Miami Environment 1", + new NamedResourceImpl( + "32", + "Miami Environment 1", + VCloudMediaType.VDC_XML, + URI + .create("https://services.vcloudexpress.terremark.com/api/v0.8a-ext1.6/vdc/32")))); + assertEquals( + result.getTasksLists(), + ImmutableMap + .of( + "Miami Environment 1 Tasks List", + new NamedResourceImpl( + "tasksList", + "Miami Environment 1 Tasks List", + TASKSLIST_XML, + URI + .create("https://services.vcloudexpress.terremark.com/api/v0.8a-ext1.6/vdc/32/tasksList")))); + assertEquals( + result.getKeysList(), + new NamedResourceImpl( + "keys", + "Keys", + TerremarkVCloudMediaType.KEYSLIST_XML, + URI + .create("https://services.vcloudexpress.terremark.com/api/v0.8a-ext1.6/extensions/org/48/keys"))); + + } +} diff --git a/vcloud/terremark/src/test/resources/terremark/CreateInternetService-options-test.xml b/vcloud/terremark/src/test/resources/terremark/CreateInternetService-options-test.xml index 0bd090aafa..82730c8dfe 100644 --- a/vcloud/terremark/src/test/resources/terremark/CreateInternetService-options-test.xml +++ b/vcloud/terremark/src/test/resources/terremark/CreateInternetService-options-test.xml @@ -1,8 +1,10 @@ - - name - TCP - 22 - false + + name + TCP + 22 + false + yahoo - \ No newline at end of file + diff --git a/vcloud/terremark/src/test/resources/terremark/CreateInternetService-test.xml b/vcloud/terremark/src/test/resources/terremark/CreateInternetService-test.xml index 74e1419733..6207dd6dd8 100644 --- a/vcloud/terremark/src/test/resources/terremark/CreateInternetService-test.xml +++ b/vcloud/terremark/src/test/resources/terremark/CreateInternetService-test.xml @@ -1,8 +1,10 @@ - - name - TCP - 22 - true + + name + TCP + 22 + true + name TCP 22 - \ No newline at end of file + diff --git a/vcloud/terremark/src/test/resources/terremark/CreateInternetService-test2.xml b/vcloud/terremark/src/test/resources/terremark/CreateInternetService-test2.xml index e97a9d2e7f..301c21589d 100644 --- a/vcloud/terremark/src/test/resources/terremark/CreateInternetService-test2.xml +++ b/vcloud/terremark/src/test/resources/terremark/CreateInternetService-test2.xml @@ -1,7 +1,9 @@ - - name - TCP - 22 - true - \ No newline at end of file + + name + TCP + 22 + true + + diff --git a/vcloud/terremark/src/test/resources/terremark/CreateNodeService-options-test.xml b/vcloud/terremark/src/test/resources/terremark/CreateNodeService-options-test.xml index 038a07d59b..e36e23b8b8 100644 --- a/vcloud/terremark/src/test/resources/terremark/CreateNodeService-options-test.xml +++ b/vcloud/terremark/src/test/resources/terremark/CreateNodeService-options-test.xml @@ -1,8 +1,9 @@ - - 10.2.2.2 - name - 22 - false + + 10.2.2.2 + name + 22 + false + yahoo - \ No newline at end of file + \ No newline at end of file diff --git a/vcloud/terremark/src/test/resources/terremark/CreateNodeService-test.xml b/vcloud/terremark/src/test/resources/terremark/CreateNodeService-test.xml index 71eb80ce56..89ad6db72a 100644 --- a/vcloud/terremark/src/test/resources/terremark/CreateNodeService-test.xml +++ b/vcloud/terremark/src/test/resources/terremark/CreateNodeService-test.xml @@ -1,8 +1,9 @@ - - 172.16.20.3 - Node for Jim - 80 - false + + 172.16.20.3 + Node for Jim + 80 + false + Some test node - \ No newline at end of file + \ No newline at end of file diff --git a/vcloud/terremark/src/test/resources/terremark/CreateNodeService-test2.xml b/vcloud/terremark/src/test/resources/terremark/CreateNodeService-test2.xml index 4c4eead99c..4561e2a757 100644 --- a/vcloud/terremark/src/test/resources/terremark/CreateNodeService-test2.xml +++ b/vcloud/terremark/src/test/resources/terremark/CreateNodeService-test2.xml @@ -1,7 +1,8 @@ - - 10.2.2.2 - name - 22 - true - \ No newline at end of file + + 10.2.2.2 + name + 22 + true + + \ No newline at end of file diff --git a/vcloud/terremark/src/test/resources/terremark/CustomizationParameters.xml b/vcloud/terremark/src/test/resources/terremark/CustomizationParameters.xml index 2cabbe7570..bfc2e775f4 100644 --- a/vcloud/terremark/src/test/resources/terremark/CustomizationParameters.xml +++ b/vcloud/terremark/src/test/resources/terremark/CustomizationParameters.xml @@ -1,5 +1,6 @@ - true - false + xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> + true + false + false \ No newline at end of file diff --git a/vcloud/terremark/src/test/resources/terremark/InstantiateVAppTemplateParams-options-test.xml b/vcloud/terremark/src/test/resources/terremark/InstantiateVAppTemplateParams-options-test.xml index b445cd77d8..64516ec5ff 100644 --- a/vcloud/terremark/src/test/resources/terremark/InstantiateVAppTemplateParams-options-test.xml +++ b/vcloud/terremark/src/test/resources/terremark/InstantiateVAppTemplateParams-options-test.xml @@ -1 +1 @@ -13224512allowInOutfalse \ No newline at end of file +13224512allowInOut \ No newline at end of file diff --git a/vcloud/terremark/src/test/resources/terremark/InstantiateVAppTemplateParams-test.xml b/vcloud/terremark/src/test/resources/terremark/InstantiateVAppTemplateParams-test.xml index abe9905675..be6a95335d 100644 --- a/vcloud/terremark/src/test/resources/terremark/InstantiateVAppTemplateParams-test.xml +++ b/vcloud/terremark/src/test/resources/terremark/InstantiateVAppTemplateParams-test.xml @@ -1 +1 @@ -13124512allowInOutfalse \ No newline at end of file +allowInOut \ No newline at end of file diff --git a/vcloud/terremark/src/test/resources/terremark/key.xml b/vcloud/terremark/src/test/resources/terremark/key.xml new file mode 100644 index 0000000000..d202c63010 --- /dev/null +++ b/vcloud/terremark/src/test/resources/terremark/key.xml @@ -0,0 +1,9 @@ + + + 9 + https://services.vcloudexpress.terremark.com/api/v0.8a-ext1.6/extensions/key/9 + default + true + 4e:af:8a:9f:e9:d2:72:d7:4b:a0:da:98:72:98:4d:7d + + \ No newline at end of file diff --git a/vcloud/terremark/src/test/resources/terremark/keysList.xml b/vcloud/terremark/src/test/resources/terremark/keysList.xml new file mode 100644 index 0000000000..d202c63010 --- /dev/null +++ b/vcloud/terremark/src/test/resources/terremark/keysList.xml @@ -0,0 +1,9 @@ + + + 9 + https://services.vcloudexpress.terremark.com/api/v0.8a-ext1.6/extensions/key/9 + default + true + 4e:af:8a:9f:e9:d2:72:d7:4b:a0:da:98:72:98:4d:7d + + \ No newline at end of file diff --git a/vcloud/terremark/src/test/resources/terremark/org.xml b/vcloud/terremark/src/test/resources/terremark/org.xml new file mode 100644 index 0000000000..978440c913 --- /dev/null +++ b/vcloud/terremark/src/test/resources/terremark/org.xml @@ -0,0 +1,17 @@ + + + + + +