TIBCO Spotfire® Server Web Services API · 4 TIBCO® Spotfire® Server Web Service s API Samples...
Transcript of TIBCO Spotfire® Server Web Services API · 4 TIBCO® Spotfire® Server Web Service s API Samples...
TIBCO® Spotfire® Server Web Services API Samples
TIBCO Spotfire® Server Web Services API
API Samples 7.13 and Above
Software Release 7.13
August 2018
2
TIBCO® Spotfire® Server Web Services API Samples
Table of Contents Preface............................................................................................................... 3
Typographical Conventions ................................................................................ 4
Connecting with TIBCO Resources ...................................................................... 5
Introduction ........................................................................................................ 6
Understanding the Sample Code ............................................................................ 7
Configuring the Environment................................................................................. 8
Register the API Client ...................................................................................... 8
Granting Client User Required Permissions........................................................... 9
Compiling the .NET Sample Code ......................................................................... 11
Create a Visual Studio Project .......................................................................... 11
Add the Sample Source Code ........................................................................... 12
Creating the Service References ....................................................................... 14
Executing the .NET Sample Code ......................................................................... 16
Examining the .NET Sample Code ........................................................................ 17
Locating a User .............................................................................................. 17
Use of Domain Name ...................................................................................... 17
Use of Arrays ................................................................................................. 18
Authentication ................................................................................................ 18
Transport Message Size ................................................................................... 20
Compiling the Java Sample Code ......................................................................... 21
Create an Eclipse Project ................................................................................. 21
Add the Sample Source Code ........................................................................... 22
Creating the Service Proxies ............................................................................ 24
Executing the Java Sample Code ......................................................................... 26
Examining the Java Sample Code ........................................................................ 27
Locating a User .............................................................................................. 27
Use of Domain Name ...................................................................................... 27
Use of Generic List Class ................................................................................. 28
Authentication ................................................................................................ 28
Overriding the WSDL Binding ........................................................................... 29
Known Issues ................................................................................................ 31
3
TIBCO® Spotfire® Server Web Services API Samples
Preface
Topics
Typographical Conventions, page 4
Connecting with TIBCO Resources, page 5
4
TIBCO® Spotfire® Server Web Services API Samples
Typographical Conventions
The following typographical conventions are used in this manual.
General Typographical Conventions
Convention Use
code font Code font identifies commands, code examples, filenames,
pathnames, and output displayed in a command window. For
example:
Use MyCommand to start the foo process.
bold code font
Bold code font is used in the following ways:
In procedures, to indicate what a user types. For example:
Type admin.
In large code samples, to indicate the parts of the sample
that is of particular interest.
In command syntax, to indicate the default parameter for
a command. For example, if no parameter is specified,
MyCommand is enabled:
MyCommand [ enable | disable]
italic font Italic font is used in the following ways:
To indicate a document title. For example: See Concepts.
To introduce new terms For example: A portal page may
contain several portlets. Portlets are mini-applications that
run in a portal.
To indicate a variable in a command or code syntax that
you must replace. For example: MyCommand PathName
Key combinations
Key name separated by a plus sign indicate keys pressed
simultaneously. For example: Ctrl+C.
Key names separated by a comma and space indicate keys
pressed one after the other. For example: Esc , Ctrl+Q.
The note icon indicates information that is of special interest
or importance, for example, an additional action required only
in certain circumstances.
The tip icon indicates an idea that could be useful, for
example, a way to apply the information provided in the
current section to achieve a specific result.
The warning icon indicates the potential for a damaging
situation, for example, data loss or corruption if certain steps
are taken or not taken.
5
TIBCO® Spotfire® Server Web Services API Samples
Connecting with TIBCO Resources
How to Join TIBCO Community
TIBCO Community is an online destination for TIBCO customers, partners, and
resident experts, a place to share and access the collective experience of the
TIBCO community. TIBCO Community offers forums, blogs, and access to a
variety of resources. To register, go to https://community.tibco.com/.
How to Access All TIBCO Documentation
After you join TIBCO Community, you can access the documentation for all
supported product versions here:
http://docs.tibco.com/
How to Contact TIBCO Spotfire Support
For comments or problems with this manual or the software it addresses, please
contact TIBCO Spotfire Support as follows.
For an overview of TIBCO Support, and information about getting started with
TIBCO Support, visit this site:
http://www.tibco.com/services/support
If you already have a valid maintenance or support contract, visit this site:
https://support.tibco.com
Entry to this site requires a user name and password. If you do not have a
user name, you can request one.
If you have ideas for improvements and enhancements to the software, you
can visit the TIBCO Ideas Portal:
https://ideas.tibco.com/?project=TS
6
TIBCO® Spotfire® Server Web Services API Samples
Introduction
Spotfire Server 5.5 introduced a set of public Web Service APIs that allow
programmatic access to the Spotfire Server rather than having to use either the
Administration Console or Spotfire Analyst. In Spotfire Server 7.13, the URL and
authentication method for accessing the supported Web Services changed. The
Web Services API for 7.12 and previous versions was deprecated, but still
available by enabling the legacy SOAP API.
As of Spotfire Server 7.13, the current set of Spotfire Server Web Service APIs
contains the following services:
Information Model Service
Library Service
License Service
Security Service
Update Analysis Service
User Directory Service
The URL and authentication method for the Spotfire Server Web Services
API changed in Spotfire Server 7.13. This document discusses the 7.13
and above method for using the Spotfire Server Web Services API.
Please refer to the previous documentation for how to connect to earlier
versions of Spotfire Server.
Starting with Spotfire Server 7.13, the Web Services API uses the OAuth 2.0
protocol for authentication and authorization.
For the Library Service and User Directory Service, sample code is provided
showing how to perform a subset of the available operations in both Java and
.NET code. This document is a companion to that sample code and explains:
How to understand the sample code
How to compile the sample code
How to run the compiled samples
The full Web Services API documentation can be found on the TIBCO
Documentation website in the Spotfire Server section.
7
TIBCO® Spotfire® Server Web Services API Samples
Understanding the Sample Code
The sample code is divided into 3 major functional areas:
1. User and Group management tasks
- User and Group creation and deletion and Group membership
2. Library management tasks
- Folder creation and deletion and assignment of access rights
3. Library traversal operations
- Recursive traversal of the library and retrieval of item and folder
metadata
When run, the sample code presents a list of these three areas:
Please choose from the following samples...
1 - User creation / deletion and rights assignment
2 - Spotfire Library search / creation / deletion operations
3 - Spotfire Library traversal and item details
Press q to quit
The user chooses one and the sample code for that area executes:
Please choose from the following samples...
1 - User creation / deletion and rights assignment
2 - Spotfire Library search / creation / deletion operations
3 - Spotfire Library traversal and item details
Press q to quit
Option 1 - User creation / deletion and rights assignment
=========================================================
Searching for user 'myAdminUser'
...
Once completed, the user is returned to the list.
8
TIBCO® Spotfire® Server Web Services API Samples
Configuring the Environment
There is some additional configuration in the environment required with a default
Spotfire Server installation before the Web Services API can be used. Starting
with Spotfire Server 7.13, the Web Services are enabled by default and the CSRF
protection is not applicable anymore.
The activities consist of:
Register the API Client
Granting a User the required permissions
Register the API Client
In order to use the Spotfire Server Web Services API, one needs to register the
client with Spotfire Server and obtain a client ID and client secret that will be used
when calling the Web Services API.
The register-api-client Spotfire Server command-line command is used to do
this. One uses the config Spotfire Server command so this will need to be run
from a command-line on a Spotfire Server.
Here is an example with output: config register-api-client -n TestAPIClient -Sapi.soap.library-service -Sapi.soap.user-directory-service Tool password: Successfully registered a new API client with the display name 'TestAPIClient': Client ID: <GUID.oauth-clients.spotfire.tibco.com> Client secret: <CLIENT_SECRET_FROM_SERVER_TO_USE_IN_CODE> To view the full client configuration, please use the 'show-oauth2-client' command.
The command needs to be run from the Spotfire Server tomcat/bin directory, e.g.
C:\tibco\tss\7.13.0\tomcat\bin. The Client ID and Client Secret obtained
using the register-api-client command can be passed on the command line to the
example programs. Please see the sections regarding Executing the Sample
Code below for details.
The OAuth 2.0 protocol requires one to register the scopes that the API client will
access and then request access to those scopes when the client makes the calls to
the Web Services. The available scopes are listed in the documentation for each
of the Web Services. The currently available scopes are:
api.soap.library-service
api.soap.update-analysis-service
api.soap.information-model-service
api.soap.license-service
api.soap.user-directory-service
api.soap.impersonate
9
TIBCO® Spotfire® Server Web Services API Samples
Most of these scopes are self-explanatory. The last one – api.soap.impersonate –
is needed by some Library Service calls when one needs to impersonate another user, e.g. when calling searchItemsAsUser.
This example registers the scopes api.soap.library-service and the api.soap.user-
directory-service scopes since it will be accessing the Library and User Directory
Services. The Client ID and Client Secret will be used in the code when calling the Spotfire Server. The register-api-client stores information in the Spotfire
database and creates a user with the name given in the ‘-n’ parameter, in this
example “TestAPIClient”. The TestAPIClient user will need to be given access to
the Library and User Directory.
Granting Client User Required Permissions
Once the API Client has been registered in the previous step, the API Client may
need additional authorization depending on which APIs are getting called. If the
API Client is going to manipulate the Library, then the Library Manager group or
License is required. If the API Client is going to manipulate the User Directory,
then the API Client has to be a member of the Administrator group.
In this example with the Library and User Directory Services, the TestAPIClient
(the name specified during the register API Client step) had to be given
Administrator access.
These steps can be done using the “Administration Manager” tool in Spotfire
Analyst or using the Spotfire Administration Web Console. These instructions use
the Spotfire Administration Web Console.
1. Open a Web Browser and open the Spotfire Server URL. Login as a Spotfire
administrator and click on “Users & Groups”
2. Locate the “TestAPIClient” user and click “Add” to edit the group memberships
10
TIBCO® Spotfire® Server Web Services API Samples
Note that the username was created is the Client Id and the Domain is the
SPOTFIREOAUTH2 domain.
3. In general, the least privileged group membership should be granted that will
allow the client API user to complete the API calls. For the example code,
Administrator access is required because the sample manipulates the Sptofire
User Directory, adding and deleting a user.
Select the “Administrator” group and click Save. This gives the selected client
user access to create and delete users in the User Directory and create and
delete Library folders.
As mentioned above, the specific privileges that your API client user needs will
depend on which Web Services are called. If the API client is only querying the
Library and User Directory, then Administrator privileges are likely not needed. If
one needs to manipulate the Library, then the Library Administrator Group or
License will need to be granted. You will want to test what privileges are needed
for your use case and make sure to grant only those that required.
11
TIBCO® Spotfire® Server Web Services API Samples
Compiling the .NET Sample Code
This consists of the following steps:
Creating a Visual Studio Project
Adding the sample source code
Creating the Service References from the Spotfire Server WSDLs
Create a Visual Studio Project
The first step is to create a project in Visual Studio. This example was done using
Visual Studio 2013.
1. Create a new Console Application called “TSSAPISampleCode” as shown
below:
12
TIBCO® Spotfire® Server Web Services API Samples
Add the Sample Source Code
The next step is to add the source code for the Web Services API samples to the
project.
2. Right click the “Program.cs” entry in the Project Explorer window, and rename
it to “TSSAPISampleCode.cs”.
3. Paste the contents of the downloaded “TSSAPISampleCode.cs” sample code file
into the “TSSAPISampleCode.cs” file in the Visual Studio project.
Ignore any compilation errors at this point
4. To support the OAuth2 protocol, some other code is needed to manage the
authentication token. With Spotfire Server 7.13 and above, all the calls are
stateless to the Web Services API so no session cookies need to be
maintained, but the OAuth2 authentication token has to be passed with each
request. Right-click on the TSSAPISampleCode project in the Solution
Explorer and select Add -> Existing Item. Browse to where you have
downloaded the code and select the CookieManagerBehaviorExtension.cs,
CookieManagerEndpointBehavior.cs, and CookieManagerMessageInspector.cs
files. Click Add button. (Note this code is based on a blog post titled
"Managing shared cookies in WCF" by Enrico Campidoglio -
http://megakemp.com/2009/02/06/managing-shared-cookies-in-wcf/)
13
TIBCO® Spotfire® Server Web Services API Samples
5. The parsing of the OAuth2 authentication response uses the
JavaScriptSerializer which is in the System.Web.Extensions assembly so a
reference to the System.Web.Extensions assembly needs to be added:
6. The CookieManagerBehaviorExtension.cs file requires another assembly
reference. In the Solution Explorer, right-click the “References” and select
Add Reference. In the Framework Assemblies list, scroll down and select
“System.Configuration” making sure to check the box, then click OK.
14
TIBCO® Spotfire® Server Web Services API Samples
Creating the Service References
The last step is to read the Spotfire Server WSDLs and create the Service
References.
7. Within the Solution Explorer, right click on the “TSSAPISampleCode” Project
and select Add -> “Service Reference”
The path to the User Directory Service WSDL file is of the form:
http://<server>:<port>/spotfire/api/soap/UserDirectoryService/wsdl
Enter the correct path for your server and click “Go”. You will be prompted
multiple times to authenticate as Visual Studio retrieves the non-existent
metadata. One only needs to authenticate the first time and then click cancel.
Eventually the dialog will update to show the retrieved service.
One can also download the WSDL file and put the file location into the Add
Service Reference Address:
15
TIBCO® Spotfire® Server Web Services API Samples
8. Enter the Namespace as “UserDirectoryService” and click OK.
9. Repeat steps 7 and 8 above to create a Service Reference for the Library
Service called “LibraryService”.
The path to the Library Service WSDL file is of the form:
http://<server>:<port>/spotfire/api/soap/LibraryService/wsdl
10. The files generated by Visual Studio have extra namespace information that
we don’t want. We need to edit these generated files before we can use them
in our project.
In the Solution Explorer window, click on the “Show all Files” toolbar button
and expand the tree under the UserDirectoryService Service Reference until
you locate the “Reference.cs” file.
Open the Reference.cs file in the editor and remove all occurrences of the
string “TSSAPISampleCode.UserDirectoryService.” (note the trailing period).
Save and close the file.
Expand the tree under the LibraryService Service Reference until you locate
the “Reference.cs” file.
Open the Reference.cs file in the editor and remove all occurrences of the
string “TSSAPISampleCode.LibraryService.” (note the trailing period). Save
and close the file.
At this point the project should compile successfully.
16
TIBCO® Spotfire® Server Web Services API Samples
Executing the .NET Sample Code
The sample code is written to accept parameters on the command line as follows:
Usage: TSSAPISampleCode [options]
where options are:
-server <server> - Spotfire Server Address
-port <port> - Spotfire Server Port
-clientid <client ID> - API Client ID from registering client
-clientsecret <clientsecret> - API Client Secret from registering client
-debug <debug> - Set to true to enable debug output
For example:
TSSAPISampleCode -server localhost -port 8713 -clientid d07d2dea2a29ae0b9c79fa08218d15fb.oauth-clients.spotfire.tibco.com -clientsecret 6a27afefdb2a6c11c0a1acf808cc46c3012451346e0eefe5fef699b316ff78df –debug true
As a reminder, the client ID and client secret are from the register-api-client call.
17
TIBCO® Spotfire® Server Web Services API Samples
Examining the .NET Sample Code
The following sections look inside the sample code to point out areas of interest
for programmers using the samples as a basis for their own code.
Locating a User
There are two ways of locating a User using the Web Services API:
getUserByName() – takes an actual User Name and returns at most 1 result
searchUsers() – take a search expression and returns null, 1 or many
results
Within the doUserSample() function, the sample code demonstrates using one or
the other of these methods. Which method is used is determined by the value of the Boolean variable bDoUserSearch in the doUserSample() function.
To use the searchUsers() method, set the bDoUserSearch variable to true:
static void doUserSample () { Boolean bDoUserSearch = true; ...
To use the getUserByName() method, set the bDoUserSearch variable to false.
Use of Domain Name
When working with Users and Groups, these objects have two members:
name – the name of the User or Group
domainName – the Spotfire Domain that the item belongs to
In the sample code the Domain Name is defaulted to “SPOTFIRE”. This is the
default internal Domain created at installation.
For further information on the use of Domains, see the Spotfire Server Installation
and Configuration Manual.
18
TIBCO® Spotfire® Server Web Services API Samples
Use of Arrays
Wherever the Web Services API takes as input or returns as output data that
describes multiple objects, arrays are used.
So for example, the call to delete a User can delete multiple users in one go. To
call it, an array is created containing the User to be deleted and this is passed to
the actual API call.
UserDirectoryService.PrincipalName[] arUserNamesToDelete = new UserDirectoryService.PrincipalName[] { myAdminUser.principalName }; myUserDirectoryServiceClient.removePrincipals ( arUserNamesToDelete );
Similarly, when retrieving the child items of a Library Folder, the result is an array
of items.
LibraryItem[] arChildItems = null; arChildItems = myLibraryServiceClient.getChildItems ( thisLibraryItem.id );
The returned array should never be null, but it may be empty if no items were
returned.
Authentication
The sample code works with the OAuth 2.0 protocol that is used with Spotfire
Server 7.13 and above for accessing the Web Services API. The OAuth 2.0 endpoint will be called so no credentials need to be passed via the HTTPBinding:
BasicHttpBinding HTTPBinding = new BasicHttpBinding (); HTTPBinding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly; HTTPBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
The OAuth access token needs to be obtained from the Spotfire Server. The
token is retrieved by calling the token endpoint:
http://<server>:<port>/spotfire/oauth2/token
In the code, this is done in the getOAuthToken method. The entire code will not be
displayed here. Basically, the code does the following:
19
TIBCO® Spotfire® Server Web Services API Samples
- Creates a basic authentication header with clientid:clientsecret to be passed,
base64 encodes it and adds as the Basic authentication HTTP header.
- Creates the post data to be sent which contains the access request to the
scopes. Multiple scopes are separated by spaces:
byte[] postBytes = Encoding.UTF8.GetBytes("grant_type=client_credentials&scope=" + WebUtility.UrlEncode("api.soap.library-service api.soap.user-directory-service"));
- Calls the URL to get the response
- The response is a JSON string that is parsed in order to pull out the
access_token which is used as the Bearer authentication token in all future
requests to the API.
As mentioned earlier, the other code files, CookieManagerBehaviorExtension.cs,
CookieManagerEndpointBehavior.cs, and CookieManagerMessageInspector.cs, are
needed in order to support passing the access token with each request. Most of this work is done in the CookieManagerMessageInspector.cs.
In the sample code itself, the CookieManagerEndpointBehavior is added to the
behaviors for the service client and then the getOAuthToken method is called:
myUserDirectoryServiceClient.Endpoint.Behaviors.Add(_wcfCookieBehavior); getOAuthToken("http://" + _server + ":" + _port + strSpotfireServerBase);
The getOAuthToken method sets the access token variable in the
_wcfCookieBehavior object so it can be inserted later into the header when call the
services.
The authorization header is set with the access token, OAuth Bearer token, by the CookieManagerMessateInspector.BeforeSendRequest method:
httpRequest.Headers.Add("Authorization", "Bearer " + OAuthBearerToken);
20
TIBCO® Spotfire® Server Web Services API Samples
Transport Message Size
By default, the BasicHTTPBinding object used in the creation of the Web Services
clients has a default maximum received message size of 64K bytes, a Send
Timeout of 1 minute and a receive Timeout of 10 minutes.
When using the LibraryService API methods, the response messages can become
quite large and may exceed the default buffer size allocated by Visual Studio for
Web Services messages.
In addition, the API methods may take longer to execute due to the amount of
information being retrieved and encoded for return to the caller. In such cases,
the default send and receive timeouts may be exceeded.
In order to prevent this, the doLibrarySample2 () function uses the alternate
BasicHTTPBinding constructor in the .NET API to increase the default buffer size
and override the send and receive message timeouts.
TimeSpan Timeout = new TimeSpan ( 0, 10, 0 ); BasicHttpBinding HTTPBinding = new BasicHttpBinding () { MaxReceivedMessageSize = 131072000, ReceiveTimeout=Timeout, SendTimeout=Timeout };
The exact values may have to be adjusted through experience.
21
TIBCO® Spotfire® Server Web Services API Samples
Compiling the Java Sample Code
This consists of the following steps:
Creating an Eclipse Project
Adding the sample source code
Creating the Service Proxies from the Spotfire Server WSDLs
Create an Eclipse Project
The first step is to create a project in Eclipse.
1. Create a new Eclipse Java Project called “TSSAPISampleCode” as shown
below:
Make sure to use an appropriate JRE version. In this example, I linked to the
JDK that comes with Spotfire Server 7.13 which is Java version 1.8.0_171.
The recent Spotfire Servers all use a version of Java 1.8.
Select “Finish” to create the Project.
22
TIBCO® Spotfire® Server Web Services API Samples
Add the Sample Source Code
The next step is to add the source code for the Web Services API samples to the
project.
2. Expand the Project node, right click the “src” node and select New ->
Package. Create a package called “com.tibco.spotfire.TSSAPISamples” as
shown:
Repeat the above steps to create two more packages called “com.tibco.spotfire.TSSUserDirectoryService” and
“com.tibco.spotfire.TSSLibraryService”.
3. Right click on the “com.tibco.spotfire.TSSAPISamples” package and select
New -> Class. Enter the class name as “TSSAPISampleCode” and click “Finish”.
Open the newly created “TSSAPISampleCode.java” file in the Eclipse project and
delete the entire contents.
Paste the contents of the downloaded “TSSAPISampleCode.java” sample code
file into the “TSSAPISampleCode.java” file in the Eclipse project. Save the file.
Ignore any compilation errors at this point
4. To support the OAuth 2.0 authentication protocol, some other code is needed
to manage the authentication header. Right-click on the “com.tibco.spotfire.TSSAPISamples” package and select Import. For the
import source, select General -> File System and click “Next”.
23
TIBCO® Spotfire® Server Web Services API Samples
Browse to the downloaded code and select the “TSSWSAPIHandler.java” file as
seen below and click “Finish”.
This file contains extra handling of the underlying Web Services messages in
order to insert the OAuth 2.0 Bearer authentication token into the HTTP
headers.
24
TIBCO® Spotfire® Server Web Services API Samples
Creating the Service Proxies
The last step is to read the Spotfire Server WSDLs and create the Service Proxies.
5. The WSDL is not protected with authentication so one can directly parse it using the Java wsimport command. If needed, one can download the WSDL by
opening the URL in a browser and saving the contents to a file on the hard
drive. The path to the User Directory Service WSDL file is of the form:
http://<server>:<port>/spotfire/api/soap/UserDirectoryService/wsdl
Use the Java wsimport utility to create Java Proxy classes from the WSDL file.
wsimport -s <path to java project src folder> -p com.tibco.spotfire.TSSUserDirectoryService <URL to the Directory Service WSDL>
For Example,
C:\tibco\tss\7.13.0\jdk\bin\wsimport -s E:\Workspace\TSSAPISampleCode\src -p com.tibco.spotfire.TSSUserDirectoryService http://localhost:8713/spotfire/api/soap/UserDirectoryService/wsdl
The wsimport utility is located in the “bin” folder of a Java JDK
installation.
6. Now we will do the same for the Library Service. The path to the Library
Service WSDL file is of the form:
http://<server>:<port>/spotfire/api/soap/LibraryService/wsdl
Use the Java wsimport utility to create Java Proxy classes from the WSDL file.
wsimport -s <path to Eclipse project src folder> -p com.tibco.spotfire.TSSLibraryService <URL to the Library Service WSDL>
For Example,
C:\tibco\tss\7.7.0\jdk\bin\wsimport -s E:\Workspace\TSSAPISampleCode\src -p com.tibco.spotfire.TSSLibraryService http://localhost:8713/spotfire/api/soap/LibraryService/wsdl
This will create the Java Proxy classes under the Java Packages created in
Step 2. For the Library Service, one will receive warnings that can be ignored.
7. In the Eclipse IDE, refresh the contents of the “com.tibco.spotfire.TSSUserDirectoryService” and
“com.tibco.spotfire.TSSLibraryService” Java Packages. One can refresh the
source tree by right-clicking packages and selecting “Refresh” from the menu.
8. The OAuth 2.0 protocol uses JSON messages to send back the access token
information after the code calls the Spotfire Server token endpoint. In order
25
TIBCO® Spotfire® Server Web Services API Samples
to parse the JSON, the sample code use the Jackson JSON packages since
they are included with the Spotfire Server. Other JSON parsing packages can
be used. One needs to include the jackson-annotations.jar, jackson-core.jar,
and jackson-databind.jar files as Referenced Libraries for the project.
The jar files can be added to the projects Java Build Path using the “Add
External Jars…” button:
Click “Apply and Close” to add the Jackson libraries. After adding these jar
files, the Project should now compile successfully.
26
TIBCO® Spotfire® Server Web Services API Samples
Executing the Java Sample Code
The sample code is written to accept parameters on the command line as follows:
Usage: TSSAPISampleCode [options]
where options are:
-server <server> - Spotfire Server Address
-port <port> - Spotfire Server Port
-clientid <client ID> - API Client ID from registering client
-clientsecret <clientsecret> - API Client Secret from registering client
-debug <debug> - Set to true to enable debug output
For example:
java –cp ... com.tibco.spotfire.TSSAPISamples.TSSAPISampleCode -server localhost -port 8713 -clientid d07d2dea2a29ae0b9c79fa08218d15fb.oauth-clients.spotfire.tibco.com -clientsecret 6a27afefdb2a6c11c0a1acf808cc46c3012451346e0eefe5fef699b316ff78df -debug true
The actual classpath will depend on the setup of the system running the sample
code. However at least the following must be present on the classpath:
The path to the location of the compiled sample code or a jar file containing
the compiled sample code
The jackson jar files – jackson-annotations.jar, jackson-core.jar and jackson-
databind.jar
As a reminder, the client ID and client secret are from the register-api-client call.
27
TIBCO® Spotfire® Server Web Services API Samples
Examining the Java Sample Code
The following sections look inside the sample code to point out areas of interest
for programmers using the samples as a basis for their own code.
Locating a User
There are two ways of locating a User using the Web Services API:
getUserByName() – takes an actual User Name and returns at most 1 result
searchUsers() – take a search expression and returns 0, 1 or many results
Within the doUserSample() function, the sample code demonstrates using one or
the other of these methods. Which method is used is determined by the value of the boolean variable bDoUserSearch in the doUserSample() function.
To use the searchUsers() method, set the bDoUserSearch variable to true:
static void doUserSample () { boolean bDoUserSearch = true; ...
To use the getUserByName() method, set the bDoUserSearch variable to false.
Use of Domain Name
When working with Users and Groups, these objects have two members:
name – the name of the User or Group
domainName – the Spotfire Domain that the item belongs to
In the sample code the Domain Name is defaulted to “SPOTFIRE”. This is the
default internal Domain created at installation.
For further information on the use of Domains, see the Spotfire Server Installation
and Configuration Manual.
28
TIBCO® Spotfire® Server Web Services API Samples
Use of Generic List Class
Wherever the Web Services API takes as input or returns as output data that
describes multiple objects, Java Generic List objects are used.
However, as the List class is an interface, a class that implements this interface
must be used. In the sample code, the ArrayList class is used.
So for example, the call to delete a User can delete multiple users in one go. To
call it, an ArrayList is created containing the User to be deleted and this is passed
to the actual API call.
ArrayList<com.tibco.spotfire.TSSUserDirectoryService.PrincipalName> lstPrincipalNames = new ArrayList<com.tibco.spotfire.TSSUserDirectoryService.PrincipalName> (); lstPrincipalNames.add( thisUser.getPrincipalName () ); myUserDirectoryServiceClient.removePrincipals ( lstPrincipalNames );
However when API functions return collections, they simply return the List
interface. So when retrieving the child items of a Library Folder, the result is as
follows:
List<LibraryItem> lstChildItems = null; lstChildItems = myLibraryServiceClient.getChildItems ( thisLibraryItem.getId () );
The returned List object should never be null, but it may be empty if no items
were returned.
Authentication
The sample code works with the OAuth 2.0 protocol that is used with Spotfire
Server 7.13 and above for accessing the Web Services API. The OAuth 2.0
endpoint will be called so no credentials need to be passed, and, therefore, no
Authenticator is needed.
The OAuth access token needs to be obtained from the Spotfire Server. The
token is retrieved by calling the token endpoint:
http://<server>:<port>/spotfire/oauth2/token
In the code, this is done in the getOAuthToken method which is called by
configureServiceSession. The entire code will not be displayed here. Basically,
the code does the following:
- Creates a basic authentication header with clientid:clientsecret to be passed,
base64 encodes it and adds as the Basic authentication HTTP header.
29
TIBCO® Spotfire® Server Web Services API Samples
- Creates the post data to be sent which contains the access request to the
scopes. Multiple scopes are separated by spaces: String strScopeInfo = "grant_type=client_credentials&scope=" + URLEncoder.encode("api.soap.library-service api.soap.user-directory-service", "UTF-8"); byte[] postBytes = strScopeInfo.getBytes("UTF-8");
- Calls the URL to get the response
- The response is a JSON string that is parsed in order to pull out the
“access_token” which is used as the Bearer authentication token in all future
requests to the API.
As mentioned earlier, the other code file, TSSWSAPIHandler.cs, is needed in order
to support passing the access token with each request.
In the sample code itself, a TSSWSAPIHandler object is added to the handlerChain
for the WSDL Binding object: TSSWSAPIHandler tssWSAPIHandler = new TSSWSAPIHandler(); tssWSAPIHandler.setOAuthBearerToken(getOAuthToken("http://" + server + ":" + port + strSpotfireServerBase)); List<Handler> handlerChain = new ArrayList<Handler>(); handlerChain.add(tssWSAPIHandler); Binding bindObj = wsdlProvider.getBinding(); bindObj.setHandlerChain(handlerChain);
The getOAuthToken method sets the access token variable in the tssWSAPIHandler
object so it can be inserted later into the header when call the services.
The authorization header is set with the access token, OAuth Bearer token, by the TSSWSAPIHandler.processMessage method:
httpRequestHeaders.put("Authorization", oauthBearerToken);
Overriding the WSDL Binding
The classes generated by the Web Services Client wizard have the binding path
from the original WSDL hard coded into them.
public class UserDirectoryService_Service extends Service { private final static URL USERDIRECTORYSERVICE_WSDL_LOCATION; private final static WebServiceException USERDIRECTORYSERVICE_EXCEPTION; ....... static { URL url = null; WebServiceException e = null;
30
TIBCO® Spotfire® Server Web Services API Samples
try { url = new URL("http://localhost:8713/spotfire/api/soap/UserDirectoryService/wsdl"); } catch (MalformedURLException ex) { e = new WebServiceException(ex); } USERDIRECTORYSERVICE_WSDL_LOCATION = url; USERDIRECTORYSERVICE_EXCEPTION = e; } ........
In order to override this default, it is necessary to use the alternate form of the
UserDirectoryService_Service constructor and pass in the WSDL location on the
server being accessed, and the Service QNAME.
// // Create the User Directory Service instance // WebServiceClient annotation = UserDirectoryService_Service.class.getAnnotation(WebServiceClient.class); UserDirectoryService_Service userdirectory_service = null; /****************************************************************/ /* Get WSDL without authentication */ /****************************************************************/ userdirectory_service = new UserDirectoryService_Service( new URL ( "http://" + server + ":" + port + strUserDirectoryServiceEndpoint + "/wsdl" ), new QName ( annotation.targetNamespace(), annotation.name() ) ); UserDirectoryService myUserDirectoryServiceClient = userdirectory_service.getUserDirectoryServicePort (); configureServiceSession((BindingProvider)myUserDirectoryServiceClient, strUserDirectoryServiceEndpoint);
One can also set the ENDPOINT_ADDRESS_PROPERTY to set the service URL:
requestContext.put( BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "http://" + server + ":" + port + strServiceURL );
The above code is only required if the JAX-WS libraries are used.
However other Web Services client libraries have similar behaviour, so a
similar workaround may be necessary.
31
TIBCO® Spotfire® Server Web Services API Samples
Known Issues
The table in this section lists known issues in this release.
Key Summary/Workaround
WSIMPORT-
WARN-1
Summary: When using either the Java wsimport utility or the Eclipse
Web Services Client Wizard to generate Java Proxy Classes from the
LibraryService WSDL URL (or file), the following warning messages
may be produced multiple times:
[WARNING] src-resolve: Cannot resolve the name 'ns1:GUID' to a(n) 'type definition' component.
line 19 of http://localhost:8713/spotfire/api/soap/LibraryService/wsdl#types?schema1
Workaround: None required. Despite the Warning messages, the
Java Proxy classes are successfully created and function as required.