Skip to main content

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. Select information in your profile (name, country/region, and company) is displayed to the public and will accompany any content you post. You may update your IBM account at any time.

All information submitted is secure.

  • Close [x]

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

  • Close [x]

Convert IBM Cloud image parameters into Java using JAXB

JAXB and Plain Old Java Objects morph XML cloud image parameters in usable Java code

Dominique Vernier, IT Architect, IBM
Dominique Vernier photo
In recent years, Dominique Vernier focused on Java technologies and cloud architecture. He also has been working in Information Technology for quite a while where he earned a broad knowledge in such technologies and products as messaging, database, SOA, EAI, client/server, C/C++, and existing frameworks. Dominique also has extensive knowledge in industry areas such as telecom, CRM, logistics, and insurance. He is the author/co-author of four patents having to do with state engines and resource management. At present, Dominique is in charge of the Smart Business Development and Test on IBM Cloud solutions on the IBM GTS Global Team.

Summary:  The image parameters of an IBM® Cloud image can be retrieved via a URL called manifest which is provided by the image description. The URL returns an XML response. In this article, the author explains how to transform that XML response into a Java™-usable response by creating Plain Old Java Objects (POJOs) and calling JAXB's unmarshal method — once you have this response, it will be easy for you to send requests to create new instances based on images that request parameters from Java classes.

Date:  14 Feb 2011
Level:  Intermediate PDF:  A4 and Letter (55KB | 7 pages)Get Adobe® Reader®
Also available in:   Japanese  Portuguese

Activity:  16725 views
Comments:  

The IBM® Cloud parameters are passed from an image to an instance using an XML file called parameters.xml. That file is located in the RAM content for the image and then copied under the directory /etc/cloud (for Linux®) in your instance with the actual parameters.

Define custom parameters to create your instance in the parameters.xml. For example, you can have a custom image that sets up Virtual Network Computing (VNC) at the instance creation time. The image requests the parameters: user id, password, and VNC password (see Figure 1).


Figure 1. Defining parameters to create your instance
Defining parameters to create your instance

Now if, for example, you want to create a Java™ program that extracts the parameters from your XML file either from the image or instance, you need to read this parameter file from your Java program. For example, if you want to create your own portal that provides the ability to request instances from images. You need to know which parameters are requested by the image to dynamically build your screen request. And, you need to get that information dynamically, not as a static result; by doing that, you avoid creating specific screens from each type of image and then posting the values in the parameters file again.

You can retrieve parameters.xml using the IBM Cloud Java API and the Image.getManifest() method. This article provides a set of APIs that delivers all necessary methods to access parameters.xml. Multiple methods exist to parse XML files, but in this article, the example uses JAXB that lets you marshal and unmarshal XML files.

But first, some concepts

JAXB can create a Java package based on an XSD file. Find the parameters.xsd file in the "Creating and customizing images" document (see Resources).

From this XSD file, use the tool xjc provided by Java to generate the Java package that will contain the classes that represent the parameters model plus a factory class. These generated classes are used to access parameters.xml.

That's all the concept you need. Let's create the Java package.


Create the Java package

As mentioned, use the xjc tool provided by Java, but first you need the parameters.xsd file. For the time being, the best way to create the parameters.xsd file is to copy and paste it from the "Creating and customizing images" document available from the IBM Cloud support tab (see Resources).

Once you have the parameters.xsd file, just enter the following command to generate your package:

xjc -p <packageName> parameters.xsd

A package is created in your current directory similar to the following:

C:\Documents and Settings\Dominique\workspaceCloud\com.ibm.cloud.parameters\src>xjc 
   -p com.ibm.cloud.parameters ../resource/parameters.xsd
parsing a schema...
compiling a schema...
com\ibm\cloud\parameters\DataType.java
com\ibm\cloud\parameters\Field.java
com\ibm\cloud\parameters\ObjectFactory.java
com\ibm\cloud\parameters\OptionType.java
com\ibm\cloud\parameters\Options.java
com\ibm\cloud\parameters\Parameters.java
com\ibm\cloud\parameters\Values.java

Import this package in your Java project (Figure 2):


Figure 2. Import the parameters package into the Java project
Import the parameters package into the Java project

In this package, you can see Plain Old Java Objects (POJOs) representing each object defined in the XSD file and a factory class.


Testing the parameters package

Run a small program to test your Java parameters package:

String cloudPasswordFile = args[0];
cloudUserId = args[1];
String cloudPassPhrase = args[2];

// Retrieve cloud access information.
cloudPassword = PasswordFileProcessor.getRealPassword(
        cloudPassPhrase, cloudPasswordFile, cloudUserId);
Properties props = new Properties();
props.load(new FileInputStream("cloud.properties"));
address = props.getProperty("address",
        "https://www-147.ibm.com/cloud/enterprise/");

// Set Credential and address.
client.setRemoteCredentials(cloudUserId, cloudPassword);
client.setEndpointAddress(address);

//Search for an image description
Image image = client.describeImage("20004761");

Security.setProperty("ssl.SocketFactory.provider", 
  "com.ibm.jsse2.SSLSocketFactoryImpl");
Security.setProperty("ssl.ServerSocketFactory.provider", 
  "com.ibm.jsse2.SSLServerSocketFactoryImpl");

//Create an http client
HttpClient httpclient = new HttpClient();
Credentials defaultcreds = 
   new UsernamePasswordCredentials(cloudUserId, cloudPassword);
httpclient.getState().setCredentials(AuthScope.ANY, defaultcreds);

//Create the method, it is important to use the escape 
//because the url contains '{' and '}'.
GetMethod httpget = new GetMethod(new HttpsURL(image.getManifest()).getEscapedURI());

//Execute the request
httpclient.executeMethod(httpget);

//Get the result
String result = httpget.getResponseBodyAsString();

//Prepare JAXB
JAXBContext jc;
jc = JAXBContext.newInstance("com.ibm.cloud.parameters");
Unmarshaller u = jc.createUnmarshaller();

//Unmarshal the result
Parameters parameters = (Parameters) u.unmarshal(new StringReader(result));

//Display the parameters
for (Field field : parameters.getField()) {
     System.out.println("Field Name=" + field.getName());
}

In the example, we used a customized image with imageID=20004761. You can find the image ID by browsing the Asset Catalog. (Control Panel > View Asset Catalog. Select an image either from My Dashboard or from Assets and the ID is specified in the image ID field.)

This parameters.xml file looks like:

<parameters xsi:noNamespaceSchemaLocation=
  "platform:/resource/com.ibm.ccl.devcloud.client/schema/parameters.xsd">
  <field name="userID" label="User ID" type="string"/>
  <field name="userPassword" label="User Password" type="password" 
               pattern="^\w*(?=\w*\d)(?=\w*[a-z])(?=\w*[A-Z])\w*$" 
               patternErrorMessage="Invalid Password. Must contain at least 1 number, 
               at least 1 lower case letter, and at least 1 upper case letter.">
  </field>
  <field name="vncPassword" label="VNC Password" type="password" 
               pattern="^\w*(?=\w*\d)(?=\w*[a-z])(?=\w*[A-Z])\w*$" 
               patternErrorMessage="Invalid Password. Must contain at least 1 number, 
               at least 1 lower case letter, and at least 1 upper case letter.">
  </field>
</parameters>

And the results are:

Field Name=userID
Field Name=userPassword
Field Name=vncPassword


In conclusion

There are multiple techniques to convert XML into Java models using such technologies as XMLBeans and XStreams, but JAXB is one of the simplest. Hopefully this article has inspired you to enjoy using the Java IBM Cloud API to fulfill your requirements around the IBM Cloud and perhaps develop your own "create instance" method.


Resources

Learn

Get products and technologies

  • See the product images available on the IBM Smart Business Development and Test on the IBM Cloud.

Discuss

About the author

Dominique Vernier photo

In recent years, Dominique Vernier focused on Java technologies and cloud architecture. He also has been working in Information Technology for quite a while where he earned a broad knowledge in such technologies and products as messaging, database, SOA, EAI, client/server, C/C++, and existing frameworks. Dominique also has extensive knowledge in industry areas such as telecom, CRM, logistics, and insurance. He is the author/co-author of four patents having to do with state engines and resource management. At present, Dominique is in charge of the Smart Business Development and Test on IBM Cloud solutions on the IBM GTS Global Team.

Report abuse help

Report abuse

Thank you. This entry has been flagged for moderator attention.


Report abuse help

Report abuse

Report abuse submission failed. Please try again later.


developerWorks: Sign in


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Select information in your profile (name, country/region, and company) is displayed to the public and will accompany any content you post. You may update your IBM account at any time.

Choose your display name

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


Rate this article

Comments

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=, Java technology, XML
ArticleID=626952
ArticleTitle=Convert IBM Cloud image parameters into Java using JAXB
publish-date=02142011
author1-email=dominique_vernier@be.ibm.com
author1-email-cc=aimeed@us.ibm.com