Automating configuration changes using Java


The code example presented below, shows how to automate the following functions:

  • Initiate a stateful transaction (openTx method)
  • Retrieve a list of all Watchpoints (getWPs method)
  • Create a new custom field (createCF method)
  • Add a Watchpoint based on this custom field (createWP method)
  • Commit the operations using Java (commitTx method)

To run the example, modify the HOST, USERNAME, and PASSWORD constants so that they correspond with your application settings.

Before you begin

Before you start automating the configuration changes using Java, you must address the following environmental prerequisites. You must know your user name, password, and the IP address of your BMC Real End User Experience Monitoring Software Edition component to use them in the sample code.

Environmental prerequisites:

  • Download the following open-source libraries to the application Classpath:
    • commons-http-client-3.1.jar
    • commons-codec-1.3.jar
    • commons-logging-1.0.4.jar
  • Because the system requires a secure (HTTPS) connection, you must import the BMC Real End User Experience Monitoring Software Edition self-signed certificate into your JVM keystore:
    • Using Internet Explorer
      1. Log on to your BMC Real End User Experience Monitoring Software Edition device via the web interface to save the certificate form.
      2. Use the right mouse button (right-click) to navigate to Properties > Certificates > Details > Copy to file.
      3. Select the default DER encoded binary X.509 and select a DESTINATION (to use later).
      4. Using the keytool command, import the certificate into your JVM keystore as shown in the following example:

        keytool -import -alias bmc -file DESTINATION/certificate.cer - keystore JAVA_HOME/jre/lib/security/cacerts -storepasschangeit
    • Using Firefox 3
      1. Log on to your BMC Real End User Experience Monitoring Software Edition device via the web interface and right-click the page.
      2. Navigate to View Page Info and click the Security tab.
      3. Click View Certificate.
      4. Click the Details tab.
      5. Click Export and enter a file name.
      6. In the drop-down list select X.509 Certificate (DER).
      7. Using the keytool command, import the certificate into your JVM keystore as shown in the following example:

        keytool -import -alias bmc -file DESTINATION/certificate.cer - keystore JAVA_HOME/jre/lib/security/cacerts -storepasschangeit
    • Using Safari 3
      1. Log on to your BMC Real End User Experience Monitoring Software Edition device via the web interface.
      2. Click the Lock icon in the upper right of the page.
      3. Click the Details tab.
      4. Click Copy to file.
      5. Select DER encoded binary X.509 and click Next.
      6. Type a file name for the certificate and click Next.
      7. Click Finish.
      8. Using the keytool command, import the certificate into your JVM keystore as shown in the following example:

        keytool -import -alias bmc -file DESTINATION/certificate.cer - keystore JAVA_HOME/jre/lib/security/cacerts -storepasschangeit

Note

 You can find the sample scripts on this page in the API toolkit, which is available on the PDFs-and-videos page. 

Example code

import java.io.StringReader;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
/**
* (c) 2009-2013 BMC, Inc.
* Created on 2009-02-10.
*
* This sample application demonstrates the basic capabilities of the
* product Configuration API by creating a transaction, getting all
* Watchpoints, creating a custom field, creating a Watchpoint based on that
* custom field, and committing the transaction.
*
*/
public class ConfigApiClient {
private static final String HOSTNAME = "<HOST>";
private static final String USERNAME = "<USERNAME>";
private static final String PASSWORD = "<PASSWORD>";
private static final String lineSeparator = System.getProperty(
"line.separator", "\n");
private HttpClient httpClient = new HttpClient();
public long openTx() {
// URI to create a transaction with a timeout of 300 seconds that will
// automatically terminate after a successful commit
final String resourceUri = "https://" + <HOST>
+ "/rest/configurationapi/transactionapi/1.0/transaction?usr="
+ <USERNAME> + "&pwd=" + <PASSWORD> + "&tto=300&autoterminate=true";
long tid = 0;
PostMethod post = new PostMethod(resourceUri);
try {
printOperationStart(post, null);
// Execute request
int httpStatusCode = httpClient.executeMethod(post);
String xmlResponse = post.getResponseBodyAsString();
printResponse(httpStatusCode, xmlResponse);
// Get the Transaction ID (TID) from the XML response using XPath
if (httpStatusCode == HttpStatus.SC_CREATED) {
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xPath = xPathFactory.newXPath();
InputSource inputSource = new InputSource(new StringReader(xmlResponse));
try {
Element tidElement = (Element) (xPath.evaluate(
"/response/result/tid", inputSource, XPathConstants.NODE));
String tidStr = tidElement.getTextContent();
if (tidStr != null) {
tid = Long.parseLong(tidStr);
}
} catch (XPathExpressionException e) {
System.out
.println("Error trying to get the TID from the XML response.");
e.printStackTrace();
}
} else {
System.out.println("Error creating transaction.");
}
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
} finally {
post.releaseConnection();
}
return tid;
}
public void commitTx(long tid) {
// URI to commit a transaction matching the TID
final String resourceUri = "https://" + <HOST>
+ "/rest/configurationapi/transactionapi/1.0/transaction/" + tid
+ "?usr=" + <USERNAME> + "&pwd=" + <PASSWORD>;
PutMethod put = new PutMethod(resourceUri);
try {
// We need to provide a request body for PUT operations
put.setRequestEntity(new StringRequestEntity(" ", "text/xml", null));
printOperationStart(put, null);
// Execute request
int httpStatusCode = httpClient.executeMethod(put);
printResponse(httpStatusCode, put.getResponseBodyAsString());
if (httpStatusCode != HttpStatus.SC_OK) {
System.out.println("Error commiting transaction.");
}
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
} finally {
put.releaseConnection();
}
}
public void getWPs(long tid) {
// URI to get all Watchpoints for the transaction matching the TID
final String resourceUri = "https://" + <HOST>
+ "/rest/configurationapi/watchpointapi/1.0/watchpoints?usr="
+ <USERNAME> + "&pwd=" + <PASSWORD> + "&tid=" + tid;
GetMethod get = new GetMethod(resourceUri);
try {
printOperationStart(get, null);
// Execute request
int httpStatusCode = httpClient.executeMethod(get);
printResponse(httpStatusCode, get.getResponseBodyAsString());
if (httpStatusCode != HttpStatus.SC_OK) {
System.out.println("Error getting all Custom fields.");
}
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
} finally {
get.releaseConnection();
}
}
public void createCF(long tid) {
// URI to create a custom field in the transaction matching the TID
final String resourceUri = "https://" + <HOST>
+ "/rest/configurationapi/customfieldapi/1.0/customfield?usr="
+ <USERNAME> + "&pwd=" + <PASSWORD> + "&tid=" + tid;
PostMethod post = new PostMethod(resourceUri);
try {
post.setRequestEntity(new StringRequestEntity(getCfXml(), "text/xml", null));
printOperationStart(post, getCfXml());
// Execute request
int httpStatusCode = httpClient.executeMethod(post);
printResponse(httpStatusCode, post.getResponseBodyAsString());
if (httpStatusCode != HttpStatus.SC_CREATED) {
System.out.println("Error creating Custom field.");
}
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
} finally {
post.releaseConnection();
}
}
private String getCfXml() {
String xml = " <customField id='100' active='true' entity='object' "
+ "srcEntity='object' type='string' policy='first-non-null' "
+ "grammar='custom_test' export='x-custom-test' size='255'>"
+ lineSeparator + " <name><![CDATA[Test CF]]></name>"
+ lineSeparator
+ " <description><![CDATA[Description for Test CF]]></description>"
+ lineSeparator + " <extractions>" + lineSeparator
+ " <defaultExtraction>" + lineSeparator + " <source>"
+ lineSeparator + " <sourceHost/>" + lineSeparator
+ " </source>" + lineSeparator + " </defaultExtraction>"
+ lineSeparator + " </extractions>" + lineSeparator
+ " </customField>";
return xml;
}
public void createWP(long tid) {
// URI to create a Watchpoint in the transaction matching the TID
final String resourceUri = "https://" + <HOST>
+ "/rest/configurationapi/watchpointapi/1.0/watchpoint?usr=" + <USERNAME>
+ "&pwd=" + <PASSWORD> + "&tid=" + tid;
PostMethod post = new PostMethod(resourceUri);
try {
post.setRequestEntity(new StringRequestEntity(getWpXml(), "text/xml", null));
printOperationStart(post, getWpXml());
// Execute request
int httpStatusCode = httpClient.executeMethod(post);
printResponse(httpStatusCode, post.getResponseBodyAsString());
if (httpStatusCode != HttpStatus.SC_CREATED) {
System.out.println("Error creating WatchPoint");
}
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
} finally {
post.releaseConnection();
}
}

private String getWpXml() {
String xml = " <watchpoint id='100' type='object' active='true' "
+ "active-alarm='false' active-mib='false' filter-selection='all'>"
+ lineSeparator + " <name><![CDATA[Test Wp]]></name>"
+ lineSeparator
+ " <description><![CDATA[Description for Test Wp]]></description>"
+ lineSeparator + " <filter active='true'>" + lineSeparator
+ " <name><![CDATA[Test Wp filter]]></name>" + lineSeparator
+ " <expression><![CDATA[(custom_test is \"test\" ignorecase)]]>"
+ "</expression>" + lineSeparator + " </filter>" + lineSeparator
+ " </watchpoint>";
return xml;
}
private void printOperationStart(HttpMethod method, String body) {
try {
System.out.println("");
System.out.println("Config API operation: " + method.getName() + " "
+ method.getURI());
if (body != null) {
System.out.println("Request body: ");
System.out.println(body);
}
} catch (URIException e) {
e.printStackTrace();
}
}
private void printResponse(int httpStatusCode, String xmlResponse) {
System.out.println("");
System.out.println("Response status code: " + httpStatusCode + " ("
+ HttpStatus.getStatusText(httpStatusCode) + ")");
System.out.println("Response body: ");
System.out.println(xmlResponse);
}
// -------------------------------------------------------------------
/**
* Execute the main to run the application.
*/
public static void main(String[] args) {
ConfigApiClient client = new ConfigApiClient();
long tid = client.openTx();
client.getWPs(tid);
client.createCF(tid);
client.createWP(tid);
client.commitTx(tid);
}
}

back to top

 

Tip: For faster searching, add an asterisk to the end of your partial query. Example: cert*