Вы находитесь на странице: 1из 22

vCloud SDK for Java Developers Guide

vCloud SDK for Java 1.0

This document supports the version of each product listed and supports all subsequent versions until the document is replaced by a new edition. To check for more recent editions of this document, see http://www.vmware.com/support/pubs.

EN-000362-00

vCloud SDK for Java Developers Guide

You can find the most up-to-date technical documentation on the VMware Web site at: http://www.vmware.com/support/ The VMware Web site also provides the latest product updates. If you have comments about this documentation, submit your feedback to: docfeedback@vmware.com

Copyright 2010 VMware, Inc. All rights reserved. This product is protected by U.S. and international copyright and intellectual property laws. VMware products are covered by one or more patents listed at http://www.vmware.com/go/patents. VMware is a registered trademark or trademark of VMware, Inc. in the United States and/or other jurisdictions. All other marks and names mentioned herein may be trademarks of their respective companies.

VMware, Inc. 3401 Hillview Ave. Palo Alto, CA 94304 www.vmware.com

VMware, Inc.

Contents

AboutThisBook

1 AboutthevCloudSDKforJava 7
vCloudSDKforJavaDesign 7 vCloudObjectTaxonomy 7 vCloudOrganizations 8 vCloudUsersandGroups 8 vCloudNetworks 8 vCloudVirtualDatacenters 8 vCloudCatalogs 9 vCloudTasks 9 VirtualSystemsandMediaImagesinavCloud 9

2 SettingUpforJavaDevelopment 11
Prerequisites 11 DownloadthevCloudSDKforJavaPackage 11 ImporttheSDKIntoYourJavaIDE 12 AboutSSLAccess 12

3 HellovCloud:AStructuredJavaWorkflowExample 13
RunningtheHellovCloudSample 13 LoggingInandGettinganOrganizationList 14 GettingReferencestothevDCandCatalog 14 UploadanOVFPackagetoCreateavAppTemplate 15 AddthevAppTemplatetoaCatalog 16 InstantiatethevAppTemplate 16 OperatethevApp 17

4 OverviewofPackagesandSamples 19
Packages 19 Samples 19

Index 21

VMware, Inc.

vCloud SDK for Java Developers Guide

VMware, Inc.

About This Book

Thisbook,thevCloudSDKforJavaDevelopersGuide,providesinformationaboutusingtheVMwarevCloud SDKforJava. VMwareprovidesseveraldifferentAPIsandSDKsforvariousapplicationsandgoals.Thisbookprovides informationaboutusingthevCloudSDKforJavafordevelopersthatareinterestedincreatingclient applicationsformanagingVMwarevCloudcomponentsavailableonVMwareESX,VMwareESXi,and VMwarevCenterServersystems. ToviewthecurrentversionofthisbookaswellasallVMwareAPIandSDKdocumentation,goto http://www.vmware.com/support/pubs/sdk_pubs.html.

Revision History
Thisguideisrevisedwitheachreleaseoftheproductorwhennecessary.Arevisedversioncancontainminor ormajorchanges.Table 1summarizesthesignificantchangesineachversionofthisguide. Table 1. Revision History
Revision 30AUG10 Description Version1.0

Intended Audience
ThisguideisintendedforsoftwaredeveloperswhoarebuildingvCloudAPIapplications,including interactiveclientsofVMwareCloudDirector.ThisguideassumesyouarefamiliarwiththeJavaprogramming language,RepresentationalStateTransfer(REST)andRESTfulprogrammingconventions,theOpen VirtualizationFormatSpecification,andVMwareVirtualmachinetechnology.Familiaritywithother widelydeployedtechnologiessuchasXML,HTTP,andtheWindowsorLinuxoperatingsystemsisalso assumed.

VMware Technical Publications Glossary


VMwareTechnicalPublicationsprovidesaglossaryoftermsthatmightbeunfamiliartoyou.Fordefinitions oftermsastheyareusedinVMwaretechnicaldocumentationgotohttp://www.vmware.com/support/pubs.

Document Feedback
VMwarewelcomesyoursuggestionsforimprovingourdocumentation.Sendyourfeedbackto docfeedback@vmware.com.

Technical Support and Education Resources


Thefollowingsectionsdescribethetechnicalsupportresourcesavailabletoyou.Toaccessthecurrentversions ofotherVMwarebooks,gotohttp://www.vmware.com/support/pubs.
VMware, Inc. 5

vCloud SDK for Java Developers Guide

Online and Telephone Support


Touseonlinesupporttosubmittechnicalsupportrequests,viewyourproductandcontractinformation,and registeryourproducts,gotohttp://communities.vmware.com/community/developer.

Support Offerings
TofindouthowVMwaresupportofferingscanhelpmeetyourbusinessneeds,goto http://www.vmware.com/support/services.

VMware Professional Services


VMwareEducationServicescoursesofferextensivehandsonlabs,casestudyexamples,andcoursematerials designedtobeusedasonthejobreferencetools.Coursesareavailableonsite,intheclassroom,andlive online.Foronsitepilotprograms andimplementationbestpractices,VMwareConsultingServicesprovides offeringsto helpyouassess,plan,build,andmanageyourvirtualenvironment.Toaccessinformationabout educationclasses,certificationprograms,andconsultingservices,gotohttp://www.vmware.com/services.

VMware, Inc.

About the vCloud SDK for Java

TheVMwarevCloudAPIprovidessupportfordeveloperswhoarebuildinginteractiveclientsofVMware CloudDirectorusingaRESTfulapplicationdevelopmentstyle.vCloudAPIclientsandserverscommunicate overHTTP,exchangingrepresentationsofvCloudobjects.TheserepresentationstaketheformofXML elements.HTTPGETrequestsareusedtoretrievethecurrentrepresentationofanobject,HTTPPOSTand PUTrequestsareusedtocreateormodifyanobject,andHTTPDELETErequestsaretypicallyusedtodelete anobject. ThevCloudSDKforJavaisaJavalanguagebindingforthevCloudAPI.ItusestheJAXBframeworktocreate JavaclassesfortheresourcesdefinedinthevCloudAPIXMLschemas.ThevCloudSDKforJavaprovides classesandmethodsthatencapsulatetheinterfaces,objects,andoperationssupportedbythevCloudAPI whilepreservingitsRESTfulprogrammingstyleandcompatibilitywiththeHTTPprotocolfamily. ThisvCloudSDKforJavaDevelopersGuideprovidesinformationaboutsettinguptheSDKinadevelopment environment,andinformationaboutrunningthesampleapplicationsincludedintheSDK. Thischapterincludesthesetopics:

vCloudSDKforJavaDesignonpage 7 vCloudObjectTaxonomyonpage 7

vCloud SDK for Java Design


ThevCloudSDKforJavaprovidesobjectspecificmethodsforcreating,updating,retrieving,anddeleting objectsdefinedbythevCloudAPI.Italsoincludeswrapperclassesthatprovide:

HelpersforRESTcommunicationandJavaobjectrepresentationoftheXMLresourcesdefinedbythe vCloudAPI. Helpermethodsthatcanassistinclientdevelopment

EverywrapperclasshasmethodsthataccessvCloudAPIresourcesusingareference.Areferenceobject containsthehref,resourcetype,andnameproperties.Staticmethodsgetresourcesdirectlybypassingthe reference,andactasconstructorsorfactoriesforSDKwrapperobjects. NOTEThevCloudSDKforJavadoesnotprovideobjectlifecyclemanagement.Everywrapperobject representstheresourceatthetimeoftheGEToperation.IfaclientmakesmultipleGETrequestsforthesame resource,theclientreceivesmultiplerepresentationsoftheresourcewrappedinthehelperobject.Thereisno automaticrefreshoftheclientsiderepresentation.Itistheclientsresponsibilitytomakenewrequeststoget thelatestvalues.Toavoidmemoryleaks,theclientmustdisposeofobjectsthatarenotinuse.

vCloud Object Taxonomy


ThevCloudSDKforJavadefinesasetofobjectscommontocloudcomputingenvironments.Figure 11 illustratestheprincipalobjecttypes.

VMware, Inc.

vCloud SDK for Java Developers Guide

Figure 1-1. vCloud Object Taxonomy

Organization vDC1
vApp Media Media vApp template

Catalog 3
Catalogitem em Catalog 2 em em Catalogitem em Catalog 1 em em Catalogitem Catalogitem Catalogitem Catalogitem

vDC2
vApp Media Media vApp template

Network Network

users

groups

TasksList

vCloud Organizations
AvCloudcontainsoneormoreorganizations.AvCloudorganizationisaunitofadministrationfora collectionofusers,groups,andcomputingresources.Usersauthenticateattheorganizationlevel,supplying credentialsestablishedbyanorganizationadministratorwhentheuserwascreatedorimported.

vCloud Users and Groups


Anorganizationcancontainanarbitrarynumberofusersandgroups.Userscanbecreatedbythe organizationadministratororimportedfromadirectoryservicesuchasLDAP.Groupsmustbeimported fromthedirectoryservice.Permissionswithinanorganizationarecontrolledthroughtheassignmentofrights androlestousersandgroups.

vCloud Networks
Anorganizationcanbeprovisionedwithoneormorenetworks.Theseorganizationnetworkscanbe configuredtoprovideservicessuchasDHCP,NAT,andfirewalls.

vCloud Virtual Datacenters


AvCloudvirtualdatacenter(vDC)isanallocationmechanismforresourcessuchasnetworks,storage,CPU, andmemory.InavDC,computingresourcesarefullyvirtualized,andcanbeallocatedbasedondemand, servicelevelrequirements,oracombinationofthetwo. TherearetwokindsofvDCs:

ProvidervDCs.ThesevDCscontainalltheresourcesavailablefromthevCloudserviceprovider. ProvidervDCsarecreatedandmanagedbyvCloudsystemadministrators. OrganizationvDCs.ThesevDCsprovideanenvironmentwherevirtualsystemscanbestored,deployed, andoperated.Theyalsoprovidestorageforvirtualmedia,suchasfloppydisksandCDROMs.

AnorganizationadministratorspecifieshowresourcesfromaprovidervDCaredistributedtothevDCsinan organization.

VMware, Inc.

Chapter 1 About the vCloud SDK for Java

vCloud Catalogs
Catalogscontainreferencestovirtualsystemsandmediaimages.Acatalogcanbesharedtomakeitvisibleto othermembersofanorganization,andcanbepublishedtomakeitvisibletootherorganizations.AvCloud systemadministratorspecifieswhichorganizationscanpublishcatalogs,andanorganizationadministrator controlsaccesstocatalogsbyorganizationmembers.

vCloud Tasks
Longrunningoperationsinitiatedbymembersofanorganizationcreatetasks,whicharekeptonthe organizationstaskslist.

Virtual Systems and Media Images in a vCloud


VirtualsystemsandmediaimagesarestoredinavDCandcanbeincludedinacatalog.Mediaimagesare storedintheirnativerepresentation(ISOorfloppy).Virtualsystemsarestoredastemplates,usinganopen standardformat(OVF1.0).Thesetemplatescanberetrievedfromcatalogsandtransformedintovirtual systems,calledvApps,throughaprocesscalledinstantiation,whichbindsatemplatesabstractresource requirementstoresourcesavailableinavDC.AvAppcontainsoneormoreindividualvirtualmachines(Vm elements),alongwithparametersthatdefineoperationaldetailssuchas:

Howthecontainedvirtualmachinesareconnectedtoeachotherandtoexternalnetworks. Theorderinwhichindividualvirtualmachinesarepoweredonoroff. Enduserlicenseagreementtermsforeachvirtualmachine. Deploymentleaseterms(typicallyinheritedfromthecontainingorganization)thatconstrainthevApps consumptionofvDCresources Accesscontrolinformationspecifyingwhichusersandgroupscanperformoperationssuchasdeploy, poweron,modify,andsuspendonthevAppandthevirtualmachinesitcontains.

VMware, Inc.

vCloud SDK for Java Developers Guide

10

VMware, Inc.

Setting Up for Java Development

Thischapterincludesthesetopics:

Prerequisitesonpage 11 DownloadthevCloudSDKforJavaPackageonpage 11

Prerequisites
ThevCloudSDKforJavarequiresJDK6orlater(theSDKandsamplesweredevelopedusingJDK 1.6.0_14b08).ThisdocumentandtheSDKreferencedocumentationassumethatyouarefamiliarwiththeJava programminglanguageandhaveaccesstoaninstallationofVMwareCloudDirector. Inaddition,youshouldconsiderthefollowing:

AlthoughthevCloudSDKforJavajavadocprovidesinformationaboutthevCloudAPIXMLschemas, whichdefinetheobjectsandoperationsthattheSDKsupports,familiaritywiththedetailsofthe underlyingobjectsandoperations,asdescribedinthevCloudAPIProgrammingGuide,canhelpyou understandthestructureofvCloudAPIobjects,andhowthemethodsinthisSDKoperateonthose objects. Beforeyoucanrunthesamples,youmustusetheCloudDirectorwebconsoleorthevCloudAPItocreate anorganization,catalog,andvDCthatthesamplescanuse.Theorganizationmusthaveauseraccount withrightstorunthesamples.ThepredefinedroleCatalogAuthorshouldprovideallthenecessary rights.Formoreinformationaboutrolesandrights,seetheVMwareCloudDirectorAdministratorsGuide. Severalofthesampleprograms,includingHellovCloud.java,requireyoutohaveanOVFpackage availableontheclienthost.Thispackagemustbeuncompressed,andmustspecifyasinglevmdkfile.For moreinformationaboutOVF,seethevCloudAPIProgrammingGuide.

Download the vCloud SDK for Java Package


ThevCloudSDKforJavaisdistributedasazippedarchive.Unzipped,itrequiresabout14.1MBofdiskspace. Thepackageincludesthefollowingfiles:

TheSDKpackageincludesprecompiledclientsidelibraries(vcloud-java-sdk-1.0.jar, rest-api-schemas-1.0.0.jar).Thevcloud-java-sdk-1.0.jar filecontainsthevCloudJavaSDK classesandmethods.Therest-api-schemas-1.0.0.jarfilecontainsJAXBbasedJavaclassesforthe resourcesdefinedinthevCloudAPI. Samplecode(vcloud-java-sdk-samples-1.0-sources.jar)demonstratingcommonusecases associatedwithprogrammaticallymanagingvirtualinfrastructure.ThesamplesincludeJavasourcecode, compiledJavaclassfiles,andtextexamplesofprograminputsandoutputs.

VMware, Inc.

11

vCloud SDK for Java Developers Guide

SDKreferencedocumentationinjavadocform(intheapidocsfolder)thatprovidesobjecttype definitions,properties,methodsignatures,andsimilarinformationaboutthevCloudSDKforJava. Accesstotechnicalpublications,includingthevCloudSDKforJavaDevelopersGuide(thisbook),which helpsyousetupyourdevelopmentenvironmentandrunsampleapplicationsusingJava.

Import the SDK Into Your Java IDE


YoucanimportthevCloudSDKforJavaintoaJavaIDE. 1 2 3 Unzipthepackage(usegziporasimilarprogram). Intheunzippedpackage,openthevcloud-java-sdk-allfolderandunzipthesamplesjar vcloud-java-sdk-samples-1.0-sources.jar. Importthecontentsofthevcloud-java-sdk-allfolderintoyourJavaIDE.

About SSL Access


Inthedefaultconfiguration,VMwareCloudDirectorrequiresvCloudAPIclientstouseSSL.Tosimplify accesstoCloudDirector,allSDKsamplesuseaFakeSSLSocketFactoryclassthatallowsthesample programstoacceptallSSLcertificates.BecauseclientsthatusetheFakeSSLSocketFactoryclassare inherentlyinsecure,youshouldrestrictuseofthismethodtosampleapplications,andonlyintrusted environments.AllofthesampleapplicationsusetheFakeSSLSocketFactoryclass. ClientapplicationsbuiltwiththisSDKcanenabletheuseofSSLcertificatesbyeitherimportingcertificates intoakeystoreorimplementingacustomsocketfactorythatacceptscertificatesfromtheserver.Client applicationsshouldnotusetheFakeSSLSocketFactoryclass.

12

VMware, Inc.

Hello vCloud: A Structured Java Workflow Example

ThischapterpresentsanexampleofusingthevCloudSDKforJavatoimplementastructuredworkflow throughthelifecycleofavApp.Itcontainsthefollowingtopics.

RunningtheHellovCloudSampleonpage 13 LoggingInandGettinganOrganizationListonpage 14 GettingReferencestothevDCandCatalogonpage 14 UploadanOVFPackagetoCreateavAppTemplateonpage 15 AddthevAppTemplatetoaCatalogonpage 16 InstantiatethevAppTemplateonpage 16 OperatethevApponpage 17

Running the HellovCloud Sample


TheHellovCloud.javasample,includedinthesamplesfolderof vcloud-java-sdk-samples-1.0-sources.jar,demonstratesanumberoftheoperationssupportedbythe vCloudSDKforJava:

LoggingintothevCloud UploadinganOVFpackagetocreateavApptemplate AddingthevApptemplatetoacatalog InstantiatingthevApptemplatetocreateavApp OperatingthevApp

ThefileHellovCloud.txtinthatfolderincludessampleinputandoutput. TheexamplesshowninthissectionareextractedfromtheHellovCloud.javasample. ToruntheHellovCloud.javasample,usethefollowingcommandline.


java HellovCloud vCloudApiVersionsURL versionId user@vcloud-organization password orgName vdcName ovfFileLocation vmdkFileLocation vmdkFileName catalogName

where:

vCloudApiVersionsURListhebaseAPIURLofthevCloud. versionIdistheversionoftheAPItouse(always1.0forthisrelease). usernameisthenameofaCloudDirectoruser,intheformuser@vcloudorganization,whohasrightsto uploadOVF,createvApptemplates,createvApps,andoperatevApps. passwordistheuserspassword.

VMware, Inc.

13

vCloud SDK for Java Developers Guide

orgNameisthenameoftheorganizationtowhichtheuserisauthenticating. vdcNameisthenameofavDCinthatorganizationwheretheusercanuploadtheOVFanddeploythe vApp. ovfFileLocationisthefullpathnametotheOVFdescriptoronthelocaldisk. vmdkFileLocationisthefullpathnametothevmdkfilereferencedintheOVFdescriptor. vmdkFileNameisthefilenameofthevmdkfile. catalogNameisthenameofthecataloginwhichthevApptemplatewillbecatalogued.

Forexample:
java HellovCloud https://vcloud/api/versions 1.0 user@SampleOrg Pa55w0rd SampleOrg SampleVdc C:\descriptor.ovf C:\disk.vmdk disk.vmdk SampleCatalog

Logging In and Getting an Organization List


MostvCloudAPIrequestsmustbeauthenticatedbyaloginrequestthatsuppliesusercredentialsintheform requiredbyBasicHTTPauthentication(MIMEBase64encodingofastringhavingtheform user@vcloudorganization:password).TheVcloudClientclassimplementsaloginmethodthattakestwo parameters:

userName:suppliedintheformuser@vcloudorganization password:theuserspassword

AsshownintheexcerptinExample 31,HellovCloud.javausesthismethodtoauthenticatetothecloud. ThevCloudAPIreturnsalistoftheorganizationstowhichtheuserhasaccess,andtheloginmethodin HellovCloud.javaprintsthislist.Inthetypicalcase,thislisthasasinglemember,theorganizationthatwas suppliedintheuserNameparameter. Example 3-1. Logging In and Getting an Organization List
public static void login(String vCloudVersionsURL, String versionId,String username, String password) ... { ... System.out.println("Organizations:"); System.out.println("-------------"); for (String organizationName : organizationsMap.keySet()) System.out.println("" + organizationName); } else { System.out.println(Try Logging in with valid details"); System.exit(0); }

Getting References to the vDC and Catalog


ToinstantiateavApptemplateandoperatetheresultingvApp,youneedtheobjectreferences(hrefvalues) forthecataloginwhichthevApptemplatewillbeenteredandthevDCinwhichthevAppwillbedeployed. TheOrganizationclassimplementsseveralmethodsthatreturnreferencestovDCsandcatalogs. HellovCloud.javausesthesemethodsasshowninExample 32. Example 3-2. Getting References to the vDC and Catalog
public static Vdc findVdc(String orgName, String vdcName) throws VCloudException { ReferenceType orgRef = vcloudClient.getOrgRefByName(orgName); Organization org = Organization.getOrganizationByReference(vcloudClient, orgRef); ReferenceType vdcRef = org.getVdcRefByName(vdcName); return Vdc.getVdcByReference(vcloudClient, vdcRef); } ...

14

VMware, Inc.

Chapter 3 Hello vCloud: A Structured Java Workflow Example

public static ReferenceType findCatalogRef(String orgName,String catalogName) throws VCloudException { ReferenceType orgRef = vcloudClient.getOrgRefByName(orgName); Organization org = Organization.getOrganizationByReference(vcloudClient, orgRef); return org.getCatalogRefByName(catalogName); }

Upload an OVF Package to Create a vApp Template


TheHellovCloud.javacommandlinerequiresyoutosupplythenameofanOVFdescriptorfileandthe vmdkfilethatitreferences.ThisinformationisusedinthecreateUploadvAppTemplatemethodtoupload theOVFdescriptorandvmdkfile,createavApptemplate,andreturnareferencetothetemplatethatcanbe usedbyothermethodsintheprogram. ThecreateUploadvAppTemplatemethodandthemethodsitcallsfromthevCloudSDKforJavaimplement thefollowingworkflowtouploadtheOVFpackageandcreateavApptemplate. 1 2 3 4 TheclientPOSTsaninitialrequestthatspecifiesanameforthetemplate,atransferformatforthedata, andanoptionaldescription. Theserverreturnsanunresolved(status="0")vAppTemplatedocumentthatincludesanuploadURL fortheOVFpackage. TheclientusesanHTTPPUTrequesttouploadtheOVFpackagedescriptor(the .ovffile)totheupload URL. TheserverreadsthedescriptorandconstructsavAppTemplateobjectthatincludesanuploadURLfor eachfilelistedintheReferencessectionofthedescriptor).Whiletheserverisconstructingthis document,theclientmakesperiodicrequestsforitandexaminestheresponseforadditionalupload URLs.WhentheresponsecontainsanyuploadURLsbeyondtheonereturnedinStep2,templateis complete. TheclientusesHTTPPUTrequeststouploadeachofthefiles. IftheOVFpackageincludesamanifestfile,theentireuploadisvalidatedagainstthecontentsofthe manifestfile.

5 6

Afterallthefilesareuploaded(andvalidatedifamanifestispresent),theserverprocessestheuploads.When processingiscomplete,theserversetsthevalueofthetemplatesstatusattributeto8,indicatingthatthe templateisreadyforuse.(Thisstatusvalueindicatesthatallofthevirtualmachinesinthetemplateare poweredoff.Formoreinformation,seethevCloudAPIProgrammingGuide.) Example 3-3. Upload an OVF Package to Create a vApp Template
public static ReferenceType createUploadvAppTemplate(Vdc vdc, String ovfFileLocation, String vmdkFileLocation, String vmdkfileName) throws VCloudException, FileNotFoundException, InterruptedException { ... //fill in the upload params with name and Description UploadVAppTemplateParamsType vappTemplParams = new UploadVAppTemplateParamsType(); vappTemplParams.setDescription("HellovCloudvAppTemplate Description"); vappTemplParams.setName("HellovCloudvAppTemplate"); ... //get the action/uploadVappTemplate link VappTemplate vappTemplate = vdc.createVappTemplate(vappTemplParams); ... //upload the OVF descriptor vappTemplate.uploadOVFFile(ovfFileInputStream, ovfFile.length()); ... //using the href of the new vAppTemplate, check to see if the descriptor // upload is complete (ovfDescriptorUploaded=true) vappTemplate = VappTemplate.getVappTemplateByReference(vcloudClient, vappTemplate.getReference()); while (!vappTemplate.getResource().isOvfDescriptorUploaded()) { Thread.sleep(5000);

VMware, Inc.

15

vCloud SDK for Java Developers Guide

... //get the upload:default URI for the vmdk file and PUT the serialized bits vappTemplate.uploadFile(vmdkfileName, vmdkFileInputStream, vmdkFile .length()); ... //check the status. when status=8, template is complete while (vappTemplate.getResource().getStatus() != 8) { Thread.sleep(5000); vappTemplate = VappTemplate.getVappTemplateByReference(vcloudClient, vappTemplate.getReference()); } ... //return the href of the vAppTemplate return vappTemplate.getReference(); }

Add the vApp Template to a Catalog


AfterthevAppTemplatehasbeenuploaded,HellovCloud.javausesitscreateNewCatalogItemmethodto createaCatalogItemobjectinthecatalogwhosenamewasprovidedonthecommandline.TheCatalogItem containsthereferencetothetemplatethatwasreturnedinExample 33.

Instantiate the vApp Template


Nowthatwehavethetemplateinthecatalog,wecaninstantiateittocreateavApp.HellovCloud.java implementsanewvAppFromTemplatemethodthathastwoparameters:

vAppTemplateReference:areferencetothetemplate(obtainedfromthecatalog). Vdc:areferencetothevDCinwhichtoinstantiatethetemplate.

Withtheseinputs,newvAppFromTemplateconstructsasimpleInstantiateVAppTemplateParamsrequest body,makestherequesttotheaction/instantiateVAppTemplateURLofthevDC,andreturnsaVapp helperobjectthatcontains(amongotherthings)areferencetothevApp. Example 3-4. Instantiating the vApp Template


public static Vapp newvAppFromTemplate(ReferenceType vAppTemplateReference,Vdc vdc) throws VCloudException { ... //get the href of the OrgNetwork to which we can connect the vApp network NetworkConfigurationType networkConfigurationType = new NetworkConfigurationType(); if (vdc.getAvailableNetworkRefs().size() == 0) { System.out.println("No Networks in vdc to instantiate the vapp"); System.exit(0); } //specify the NetworkConfiguration for the vApp network networkConfigurationType.setParentNetwork(vdc.getAvailableNetworkRefs() .iterator().next()); networkConfigurationType.setFenceMode(FenceModeValuesType.BRIDGED); VAppNetworkConfigurationType vAppNetworkConfigurationType = new VAppNetworkConfigurationType(); vAppNetworkConfigurationType.setConfiguration(networkConfigurationType); vAppNetworkConfigurationType.setNetworkName("new network"); //fill in the NetworkConfigSection NetworkConfigSectionType networkConfigSectionType = new NetworkConfigSectionType(); MsgType networkInfo = new MsgType(); networkInfo.setMsgid("1"); networkInfo.setValue("network info"); networkConfigSectionType.setInfo(networkInfo); List<VAppNetworkConfigurationType> vAppNetworkConfigs = networkConfigSectionType .getNetworkConfig(); vAppNetworkConfigs.add(vAppNetworkConfigurationType); //fill in remaining InstatiationParams InstantiationParamsType instantiationParamsType = new InstantiationParamsType();

16

VMware, Inc.

Chapter 3 Hello vCloud: A Structured Java Workflow Example

List<JAXBElement<? extends SectionType>> sections = instantiationParamsType .getSection(); sections.add(new ObjectFactory() .createNetworkConfigSection(networkConfigSectionType)); //create the request body (InstantiateVAppTemplateParams) InstantiateVAppTemplateParamsType instVappTemplParamsType = new InstantiateVAppTemplateParamsType(); instVappTemplParamsType.setName("HellovCloudvAppp"); instVappTemplParamsType.setSource(vAppTemplateReference); instVappTemplParamsType.setInstantiationParams(instantiationParamsType); //make the request, and get an href to the vApp in return Vapp vapp = vdc.instantiateVappTemplate(instVappTemplParamsType); return vapp;

Operate the vApp


TheVappclassincludesmethodsthatperformoperationsonthevApp.Themajorityoftheseoperationsreturn aTaskobjectthattrackstheprogressoftheoperation.HellovCloud.javausesanumberofthesemethodsto cyclethevAppthroughthefollowingstates: 1 2 3 4 5 6 deploy:deploy() poweron:powerOn() suspend:suspend() poweroff:powerOff() undeploy:undeploy() delete:delete()

VMware, Inc.

17

vCloud SDK for Java Developers Guide

18

VMware, Inc.

Overview of Packages and Samples

ThevCloudSDKforJavaincludessampleapplicationcodeandcompletereferencedocumentationonall packages,classes,andmethodsintheSDK.Thischapterisanintroductorytourofthoseitems.

Packages
TheSDKincludesfourpackagesthatsupporttheJAXBbindingstothevCloudAPIXMLschemasandthree packagesthatimplementcreate,retrieve,update,anddelete(CRUD)operationsontheobjectsrepresentedby thoseschemas. Table 4-1. Packages in the vCloud SDK for Java
Package Name com.vmware.vcloud.sdk Description DefinestheclassesthatimplementtheuserAPI.Objectsaccessedby theseclassesaretypicallyreadablebyallusers,andcanbemodified byuserswithappropriaterights. DefinestheclassesthatimplementtheadministrativeAPI.Objects accessedbytheseclassesaretypicallyreadablebyallusers,butcan becreatedandmodifiedonlybyasystemadministrator,organization administratororotherprivilegeduser.Manyoftheseobjectsextend typesthataredefinedintheuserAPI. Definestheclassesthatimplementextensionsthatsupport operationsonthevSpherePlatform.AllvSphereplatformoperations arerestrictedtothesystemadministrator. XMLschemasusedbyJAXBbinding

com.vmware.vcloud.sdk.admin

com.vmware.vcloud.sdk.admin.extension

com.vmware.vcloud.api.rest.schema, com.vmware.vcloud.api.rest.schema.extension com.vmware.vcloud.api.rest.schema.ovf com.vmware.vcloud.api.rest.schema.versioning org.w3._2001.xmlschema

Samples
InadditiontoHellovCloud.java(seeHellovCloud:AStructuredJavaWorkflowExampleonpage 13),the SDKsamplesdirectory(vcloud-java-sdk-samples-1.0-sources\com\vmware\vcloud\sdk\samples) includesseveralsamplesthatdemonstratehowyoucanusethevCloudSDKforJavatodevelopclient applications.SampleslistedTable 42canberunbyanyuserwithrightstocreateandmodifycatalogitems andvApps.SampleslistedTable 43requireorganizationadministratorprivileges. Table 4-2. User API Samples
Sample Name CatalogInventorySample.java CatalogItemCRUD.java DiskCRUD.java Description Listsnameandhrefforallitemsinallcatalogsintheorganization. Create,retrieve,update,ordeleteacatalogitem. Create,retrieve,update,ordeleteavirtualharddiskinaVmobject.

VMware, Inc.

19

vCloud SDK for Java Developers Guide

Table 4-2. User API Samples (Continued)


Sample Name ListAllvApps.java ThreadSample.java VdcInventorySample.java Description ListallvAppsinavDCbynameandhref Examplesofhowtoimplementmultithreadedclientapplications thatexecutemultiplerequestsinparallel. ListnameandhrefforallvApps,vApptemplates,andmedia imagesinallvDCsintheorganization

Table 4-3. Administrative API Samples


Sample Name CatalogCRUD.java OrganizationCRUD.java OrgNetworkCRUD.java RoleCRUD.java UserCRUD.java VdcCRUD.java Description Create,retrieve,update,ordeleteacatalog. Create,retrieve,update,ordeleteanorganization.(Requiressystem administratorprivileges.) Create,retrieve,update,ordeleteanorganizationnetwork Create,retrieve,update,ordeletearole. Create,retrieve,update,ordeletealocaluser. Create,retrieve,update,ordeleteavDC

20

VMware, Inc.

Index

C
Catalogs, about 9

G
groups, about 8

H
helper object not garbage collected 7 to use 7

to create from template 16 to delete 17 vApp template about 9 OVF upload workflow 15 to create 13, 15 to instantiate 16 vDC, about 8

L
login 13

N
networks, about 8

O
organizations about 8 list of 14 OVF to upload 13 OVF package to upload 15

P
packages, overview of 19

S
samples HellovCloud sample 13 overview of 19 rights required to run 11 txt file output 11

T
Tasks, about 9 technical support resources 5

U
users, about 8

V
vApp about 9 power state changes 17

VMware, Inc.

21

vCloud SDK for Java Developers Guide

22

VMware, Inc.

Вам также может понравиться