Blueworks Live

 View Only

Do more with the IBM Blueworks Live REST API, Part 4: Write Java applications with the Blueworks Live REST API

By Stephanie Wilkerson posted Wed December 16, 2020 10:33 PM

  


Part 2 of this series explored the Representational State Transfer (REST) application programming interface (API) for IBM® Blueworks Live with a test tool. Part 3 showed how to use shell commands to quickly get information about the Blueworks Live data that you retrieve through the REST API. Although shell commands are very flexible and powerful, the approach is technical and can be very complex to use.

Part 4 shows how to write Java™ applications that are easy to use but can handle complex processing of the data that you retrieve through the REST API.

Prepare your environment

The Blueworks Live REST API documentation includes Java code templates that you can use as a basis for your own projects. Under Example you can download the following three sample Java programs:

The example also provides the following Java archive (JAR) file, which is a library to work with JavaScript Object Notation (JSON) objects:

In the Blueworks Live REST API documentation, you can read information about compiling the source code and running it. A prerequisite is a Java installation on your operating system (a Java development kit to compile code and a Java runtime environment to run code).

With an integrated development environment (IDE) like Eclipse, you can modify the Java code or comfortably write your own code. See the Eclipse downloads website.

The following sections describe how to create a Java program that you can run directly as a desktop application. Also, you can extend it to a servlet that runs on a server and that is called from a browser.

For the desktop application development, you need Eclipse IDE for Java Developers. To extend the example to a servlet, use Eclipse IDE for Java EE Developers.

This tutorial does not delve into details of using Java and Eclipse. It assumes a basic Java programming knowledge.

Sample Java programs

With the example Java template available in the Blueworks Live REST API documentation, you can work with three Java files:

RestApiClientAuthTemplate.java

Like in Part 2 and Part 3 examples, you first use the /api/Auth resource. The RestApiClientAuthTemplate.java sample shows you how to use the /api/Auth resource in Java. A closer look into the Java code reveals that besides the Blueworks Live URL, the API resource, the version, and the login information is set.

Modify the login data (REST_API_USERNAME and REST_API_PASSWORD) to match your Blueworks Live account, as shown in the following example:

1
2
3
4
5
private final static String REST_API_SERVER = "https://www.blueworkslive.com";
private final static String REST_API_CALL_AUTH = "/api/Auth";
private final static String REST_API_AUTH_VERSION = "20110917";
private final static String REST_API_USERNAME = "westphal@de.ibm.com";
private final static String REST_API_PASSWORD = "***";

Below those settings, in the main method, you see how a string is built for the API request and how a connection is established, as shown in the following example:

1
2
3
4
5
StringBuilder authUrlBuilder = new StringBuilder(REST_API_SERVER);
authUrlBuilder.append(REST_API_CALL_AUTH);
authUrlBuilder.append("?version=").append(REST_API_AUTH_VERSION);
 
HttpURLConnection restApiURLConnection = getRestApiConnection(authUrlBuilder.toString(), "GET");

The remainder of the code deals mainly with catching potential error cases. The following command prompts get and print the the API call results:

1
2
3
4
5
6
7
8
9
10
InputStream restApiStream = restApiURLConnection.getInputStream();
try {
JSONObject authenticateResult = new JSONObject(restApiStream);
String userStatus = (String) authenticateResult.get("result");
JSONArray accounts = (JSONArray) authenticateResult.get("accounts");
for (Object account : accounts) {
System.out.println("\t" + ((JSONObject) account).get("name"));
}

Remember from Part 2 and Part 3 that the JSON result, which is stored in authenticateResult, looks like the following example:{"result":"multiaccount","accounts":[{"id":"163a15e19f","name":"IBM70"},{"id":"3a480000","name":"IBMTechSales"},…

Use the get() method, for example, get("accounts"), to extract all corresponding account objects. With get("name"), the name is read for each account entry. So the output of the program looks like the following example:

1
2
3
IBM70
IBMTechSales

RestApiClientTemplate.java

The structure of the RestApiClientTemplate.java sample program is similar to the RestApiClientAuthTemplate.java sample program, and prints a list of user names.

In addition to the login data, you also must define a valid account name, like the following example:

1
private final static String REST_API_ACCOUNT_NAME = "YYY";

This account name is used as an extra parameter in the request, in addition to the version, as shown in the following example:

1
2
3
StringBuilder appListUrlBuilder = new StringBuilder(REST_API_CALL_USERLIST);
appListUrlBuilder.append("?version=").append(REST_API_USERLIST_VERSION);
appListUrlBuilder.append("&account=").append(REST_API_ACCOUNT_NAME);

You can extend the output to get further information, as shown in the following example:

1
2
3
4
System..print("User name=" + user.get("name"));
System..print(" email=" + user.get("email"));
System..print(" license=" + user.get("license"));
System..println("");

RestApiClientPostTemplate.java: forwarding and encoding

As discussed in Part 2 and Part 3, the www.blueworkslive.com server is not the service endpoint. Any request other than /api/Auth is forwarded to a server that hosts your account (for example, a Blueworks Live server in Amsterdam). The last sample, RestApiClientPostTemplate.java, handles this forwarding from www.blueworkslive.com to the local data center server of your account. Ideally you determine this server once and use it directly in the settings. However, the way it is implemented in this Java sample makes the program more generic.

With the following command, the program first calls the /api/Auth resource to determine the service provider address (the service endpoint) from the REST API call result:

1
String serviceProviderAddress = getServiceProviderAddress();

The determined address is then used instead of www.blueworkslive.com for any consecutive REST API calls.

The sample Java application uses the /scr/api/Search resource to send a search request. It hands over parameters, which are simplified as shown in the following example:

1
2
3
4
5
6
7
StringBuilder appSearchUrlBuilder = new StringBuilder(serviceProviderAddress);
appSearchUrlBuilder.append(REST_API_CALL_SEARCH);
appSearchUrlBuilder.append("?version=").append(REST_API_SEARCH_VERSION);
appSearchUrlBuilder.append("&account=").append(REST_API_ACCOUNT_NAME);
appSearchUrlBuilder.append("&searchFieldName=").append("process_name");
appSearchUrlBuilder.append("&searchValue=").append("Hiring%20-%20Onboarding");
appSearchUrlBuilder.append("&returnFields=*");

Because the search term is part of the resource request, certain characters must be protected: they must be passed with a specific URL encoding, which is a mechanism for encoding information in a Uniform Resource Identifier. Characters that require this URL encoding include the space character of Hiring Onboarding in the previous code sample. The space must be represented as %20 or alternatively as +. Otherwise, you receive the following error message as a response: Error calling the Blueworks Live REST API: Bad Request

If you want to enter search queries manually, the following table shows examples of the URL encoding for some characters. In general, the encoding starts with % followed by the hexadecimal presentation of the UTF-8 coding of the character, which is why this type of URL encoding is also called percent encoding.

Table 1. URL encoding

This encoding also applies for the % wildcard symbol. For example, if you want to find processes that end with Onboarding, you take %Onboarding as a search term and with encoding you must write it like the following example:

1
appSearchUrlBuilder.append("&searchValue=").append("%25Onboarding");

Instead of doing the encoding manually, you can let Java do it automatically. You need the URLEncoder.encode() method with the "UTF-8" encoding, as shown in the following example:

1
2
3
import java.net.URLEncoder;
appSearchUrlBuilder.append("&searchValue=").append(URLEncoder.encode("% Prozessübersicht", "UTF-8"));

This sample search query finds all processes that end with Prozessübersicht (German for process overview). The query is automatically converted into the following code:… &searchValue=%25+Prozess%C3%BCbersicht …

Use case examples

A sample implementation in Java including documentation for the use case scenarios is provided as code samples at github.com/BwlSamples:

Download each code sample. Study the code, compile it, and then run or modify to fit your needs. The following sections highlight some implementation details and give an example of a further analysis of the application output.

All programs require three mandatory command-line arguments: user, password, and account name. There are also optional arguments, specific to each program.

Use Case 1: Attached documents

For the first use case, you want to get all attached documents from a specific Blueworks Live account and download them to a local file system. Then, you want to get only the files that were added to the Blueworks Live repository since your last call.

The BwlFileDownloader program implements the first use case. From the Downloads section, download the Use case 1 code sample: github.com/BwlSamples/BwlFileDownloader. You can add -f timestamp.txt to the program call to hand over a file that contains a from date such as 2015-07-01.

The program then uses the REST API to get a list of all attached documents from your Blueworks Live account since that date. It downloads each file into a local directory that you can specify with the following optional command-line flag: -d mydownloaddirectory.

The default directory is ./downloads. The files are downloaded through the REST API, and the retrieved binary data is directly written to a corresponding file. Pay attention to documents with the same name, which will overwrite each other.

In a first call, you can skip the -f option, which means that you do not set any from date and you get all attachments from your Blueworks Live account until today. The program also writes the current date to a file (default timestamp.txt).

In consecutive calls, use -f timestamp.txt to pick up the last download date, download only the documents since that date, and then overwrite the timestamp.txt file with the new date. Then, you are ready for the next incremental download a few days later.

For more information, see the documentation that is included in the compressed file with the code sample.

Use Case 2: User activities

In the second use case, you want to determine the last time that a user logged in during a specific time period.

The BwlUserStats program implements the second use case scenario. From the Downloads section, download the Use case 2 code sample: github.com/BwlSamples/BwlUserStats.

The BwlUserStats program implements the second use case scenario in a different way than the sample implementation that you used in Part 3. This time, you want to request both the login data and information about updates made by the users.

The program can create up to four files with information corresponding to LOGINS, COMMENTS, ITEMS_CHANGED, and ITEMS_VIEWED.

To get a full list of activity information types, see Part 2 for the discussion of the second use case scenario. Each login or update type is stored as a single-line comma-separated value (CSV) file in one of the output files. For more information, see the documentation that is included in the compressed file with the code sample.

Implementation details worth considering are the period computation and the date conversion:

  • Because the /scr/api/activity REST API resource allows a maximum of only 31 days, the program creates consecutive time periods between the wanted start and end date and sends as many corresponding calls as needed to cover longer periods.
  • To simplify, the program takes a simple date format such as 2015-07-01 and converts it into the longer ISO8601 date-time format that is needed for the API call. Also, for the logging and CSV file output, the dates are converted to more readable date-time formats.

The CSV output files might contain a lot of data and can be further analyzed, for example with Microsoft Excel. The screen capture in Figure 1 shows an example of the ITEMS_CHANGED output that displays the number of changes by users during 6 months. For more information, including hints for creating charts, see the documentation that is included in the compressed file with the code sample.

Figure 1. Excel chart that shows changes per month and users

Screen  capture of example Microsoft Excel bar chart

Use Case 3: Tagged artifacts list

In the third use case, you want to produce a report that lists all artifacts that are tagged with a specific keyword and that contains detailed information like artifact type, name, and ID.

The BwlTaggedArtifacts program implements the third use case scenario. From the Downloads section, download the Use case 3 code sample: github.com/BwlSamples/BwlTaggedArtifact.

In Part 3, you found that it was quite difficult to get the wanted output with Client for URLs (cURL) and shell commands because of the complexity of the returned search response. However, in Java, with the capability to directly access the JSON object, it is quite simple.

The program goes through the list of returned spaces and checks for the required tag. If artifacts such as processes or decisions are given for a space, it does the same for these artifacts and prints the result.

Review the following example command for a Windows command (cmd) shell and output.

1
2
java -cp .;commons-io-2.4.jar;wink-json4j-1.3.0.jar BwlTaggedArtifacts
                westphal@de.ibm.com *** IBM70 demo

The example command returns the following output:

1
2
3
4
5
6
space,Prozessbearbeitung,400006dea8b3989
space,Mediteran Autoteile,3ea6e050b
space,2.3.6 Garantiemanagement,30000d5ea8b30c7
process,Garantieabwicklung,c83e8fdd25
process,Garantieabwicklung mit Regelservice,100003bea79d1aa
decision,Gutachtenbedarf ermitteln,8b3fb24eba

For more information, see the documentation that is included in the compressed file with the code sample.

The result can be further processed, for example, with Microsoft Excel or with shell commands as shown in Part 3. By adding the following pipe in a UNIX or Linux shell or with Cygwin on Windows, you extract all spaces and sort the names alphabetically.

The following example command uses Cygwin (a collection of open source tools that provide similar capabilities as a Linux distribution):

1
2
java -cp ".;commons-io-2.4.jar;wink-json4j-1.3.0.jar" BwlTaggedArtifacts
    westphal@de.ibm.com *** IBM70 demo | grep "^space" | sort

The example command returns the following output:

1
2
3
space,2.3.6 Garantiemanagement,30000d5ea8b30c7
space,Mediteran Autoteile,3ea6e050b
space,Prozessbearbeitung,400006dea8b3989

Conclusion

Now you completed the fourth part of the Do more with the IBM Blueworks Live REST API series. Use the insight into the API and necessary tools and examples as a starting point. Now you can implement your own tools to be more productive with the Blueworks REST API.

The Java approach is fine for stand-alone applications that run on one computer that is either started manually by a person or is automated (on demand or according to a preset schedule). If you require an application that multiple users can access from their browsers, just as they use Blueworks Live itself, then you a need different approach. Part 5 explains how you to set up a light-weight web server and build your application in Javascript and HTML.

Acknowledgments

The author would like to thank Margaret Thorpe from the Blueworks Live management team for help with the tutorial concept and Daniel Treiber from the development team and Sean Roe from the technical sales team for their review and comments.

Downloadable resources

Related topics


#BlueworksLive
0 comments
15 views

Permalink