watson-developer-cloud / Java Sdk

Licence: apache-2.0
🥇 Java SDK to use the IBM Watson services.

Programming Languages

java
68154 projects - #9 most used programming language

Projects that are alternatives of or similar to Java Sdk

Kotlin Gradle Plugin Template
🐘 A template to let you started with custom Gradle Plugins + Kotlin in a few seconds
Stars: ✭ 141 (-75.98%)
Mutual labels:  gradle, hacktoberfest
Multimodulegithubclient
Example multi-module Android project with unit tests, dagger 2, test coverage and others
Stars: ✭ 244 (-58.43%)
Mutual labels:  gradle, hacktoberfest
Worldedit
🗺️ Minecraft map editor and mod
Stars: ✭ 2,288 (+289.78%)
Mutual labels:  gradle, hacktoberfest
Refreshversions
Life is too short to google for dependencies and versions
Stars: ✭ 841 (+43.27%)
Mutual labels:  gradle, hacktoberfest
Hexagon
Hexagon is a microservices toolkit written in Kotlin. Its purpose is to ease the building of services (Web applications, APIs or queue consumers) that run inside a cloud platform.
Stars: ✭ 336 (-42.76%)
Mutual labels:  gradle, hacktoberfest
Spongeapi
A Minecraft plugin API
Stars: ✭ 1,043 (+77.68%)
Mutual labels:  gradle, hacktoberfest
Sponge
The SpongeAPI implementation targeting vanilla Minecraft and 3rd party platforms.
Stars: ✭ 241 (-58.94%)
Mutual labels:  gradle, hacktoberfest
Pan Os Python
The PAN-OS SDK for Python is a package to help interact with Palo Alto Networks devices (including physical and virtualized Next-generation Firewalls and Panorama). The pan-os-python SDK is object oriented and mimics the traditional interaction with the device via the GUI or CLI/API.
Stars: ✭ 194 (-66.95%)
Mutual labels:  hacktoberfest, sdk
Minecolonies
Minecolonies minecraft mod
Stars: ✭ 303 (-48.38%)
Mutual labels:  gradle, hacktoberfest
Janephp
🌱 Jane is a set of libraries to generate Models & API Clients based on JSON Schema / OpenAPI specs
Stars: ✭ 300 (-48.89%)
Mutual labels:  hacktoberfest, sdk
Sdk
The jMonkeyEngine3 SDK based on netbeans
Stars: ✭ 240 (-59.11%)
Mutual labels:  hacktoberfest, sdk
Skript
Skript is a Bukkit plugin which allows server admins to customize their server easily, but without the hassle of programming a plugin or asking/paying someone to program a plugin for them.
Stars: ✭ 458 (-21.98%)
Mutual labels:  gradle, hacktoberfest
Amplitude Javascript
JavaScript SDK for Amplitude
Stars: ✭ 234 (-60.14%)
Mutual labels:  hacktoberfest, sdk
Downlords Faf Client
Official client for Forged Alliance Forever
Stars: ✭ 121 (-79.39%)
Mutual labels:  gradle, hacktoberfest
Amplitude Ios
Native iOS/tvOS/macOS SDK
Stars: ✭ 216 (-63.2%)
Mutual labels:  hacktoberfest, sdk
Worldwindandroid
The NASA WorldWind Java SDK for Android (WWA) includes the library, examples and tutorials for building 3D virtual globe applications for phones and tablets.
Stars: ✭ 204 (-65.25%)
Mutual labels:  gradle, sdk
Amplitude Android
Native Android SDK for Amplitude
Stars: ✭ 129 (-78.02%)
Mutual labels:  hacktoberfest, sdk
Parse Sdk Android
The Android SDK for the Parse Platform
Stars: ✭ 1,806 (+207.67%)
Mutual labels:  hacktoberfest, sdk
Iam Policy Json To Terraform
Small tool to convert an IAM Policy in JSON format into a Terraform aws_iam_policy_document
Stars: ✭ 282 (-51.96%)
Mutual labels:  hacktoberfest, iam
Trailscraper
A command-line tool to get valuable information out of AWS CloudTrail
Stars: ✭ 352 (-40.03%)
Mutual labels:  hacktoberfest, iam

Watson APIs Java SDK

Build Status Slack Maven Central CLA assistant All Contributors

Java client library to use the Watson APIs.

Table of Contents

ANNOUNCEMENTS!

Updating endpoint URLs from watsonplatform.net

Watson API endpoint URLs at watsonplatform.net are changing and will not work after 26 May 2021. Update your calls to use the newer endpoint URLs. For more information, see https://cloud.ibm.com/docs/watson?topic=watson-endpoint-change.

Personality Insights deprecation

IBM Watson™ Personality Insights is discontinued. For a period of one year from 1 December 2020, you will still be able to use Watson Personality Insights. However, as of 1 December 2021, the offering will no longer be available.

As an alternative, we encourage you to consider migrating to IBM Watson™ Natural Language Understanding, a service on IBM Cloud® that uses deep learning to extract data and insights from text such as keywords, categories, sentiment, emotion, and syntax to provide insights for your business or industry. For more information, see About Natural Language Understanding.

Visual Recognition deprecation

IBM Watson™ Visual Recognition is discontinued. Existing instances are supported until 1 December 2021, but as of 7 January 2021, you can't create instances. Any instance that is provisioned on 1 December 2021 will be deleted.

Compare and Comply deprecation

IBM Watson™ Compare and Comply is discontinued. Existing instances are supported until 30 November 2021, but as of 1 December 2020, you can't create instances. Any instance that exists on 30 November 2021 will be deleted. Consider migrating to Watson Discovery Premium on IBM Cloud for your Compare and Comply use cases. To start the migration process, visit https://ibm.biz/contact-wdc-premium.

Before you begin

Installation

Maven

All the services:

<dependency>
	<groupId>com.ibm.watson</groupId>
	<artifactId>ibm-watson</artifactId>
	<version>9.0.2</version>
</dependency>

Only Discovery:

<dependency>
	<groupId>com.ibm.watson</groupId>
	<artifactId>discovery</artifactId>
	<version>9.0.2</version>
</dependency>
Gradle

All the services:

'com.ibm.watson:ibm-watson:9.0.2'

Only Assistant:

'com.ibm.watson:assistant:9.0.2'
JAR

Download the jar with dependencies here.

Now, you are ready to see some examples.

Usage

The examples within each service assume that you already have service credentials. If not, you will have to create a service in IBM Cloud.

If you are running your application in IBM Cloud (or other platforms based on Cloud Foundry), you don't need to specify the credentials; the library will get them for you by looking at the VCAP_SERVICES environment variable.

Running in IBM Cloud

When running in IBM Cloud (or other platforms based on Cloud Foundry), the library will automatically get the credentials from VCAP_SERVICES. If you have more than one plan, you can use CredentialUtils to get the service credentials for an specific plan.

Authentication

Watson services are migrating to token-based Identity and Access Management (IAM) authentication.

  • With some service instances, you authenticate to the API by using IAM.
  • In other instances, you authenticate by providing the username and password for the service instance.
  • If you're using a Watson service on Cloud Pak for Data, you'll need to authenticate in a specific way.

Getting credentials

To find out which authentication to use, view the service credentials. You find the service credentials for authentication the same way for all Watson services:

  1. Go to the IBM Cloud Dashboard page.
  2. Either click an existing Watson service instance in your resource list or click Create resource > AI and create a service instance.
  3. Click on the Manage item in the left nav bar of your service instance.

On this page, you should be able to see your credentials for accessing your service instance.

In your code, you can use these values in the service constructor or with a method call after instantiating your service.

Supplying credentials

There are two ways to supply the credentials you found above to the SDK for authentication.

Credential file (easier!)

With a credential file, you just need to put the file in the right place and the SDK will do the work of parsing it and authenticating. You can get this file by clicking the Download button for the credentials in the Manage tab of your service instance.

The file downloaded will be called ibm-credentials.env. This is the name the SDK will search for and must be preserved unless you want to configure the file path (more on that later). The SDK will look for your ibm-credentials.env file in the following places (in order):

  • Your system's home directory
  • The top-level directory of the project you're using the SDK in

As long as you set that up correctly, you don't have to worry about setting any authentication options in your code. So, for example, if you created and downloaded the credential file for your Discovery instance, you just need to do the following:

Discovery service = new Discovery("2019-04-30");

And that's it!

If you're using more than one service at a time in your code and get two different ibm-credentials.env files, just put the contents together in one ibm-credentials.env file and the SDK will handle assigning credentials to their appropriate services.

If you would like to configure the location/name of your credential file, you can set an environment variable called IBM_CREDENTIALS_FILE. This will take precedence over the locations specified above. Here's how you can do that:

export IBM_CREDENTIALS_FILE="<path>"

where <path> is something like /home/user/Downloads/<file_name>.env.

Manually

If you'd prefer to set authentication values manually in your code, the SDK supports that as well. The way you'll do this depends on what type of credentials your service instance gives you.

IAM

Some services use token-based Identity and Access Management (IAM) authentication. IAM authentication uses a service API key to get an access token that is passed with the call. Access tokens are valid for approximately one hour and must be regenerated.

You supply either an IAM service API key or an access token:

  • Use the API key to have the SDK manage the lifecycle of the access token. The SDK requests an access token, ensures that the access token is valid, and refreshes it if necessary.
  • Use the access token if you want to manage the lifecycle yourself. For details, see Authenticating with IAM tokens.

Supplying the IAM API key:

// letting the SDK manage the IAM token
Authenticator authenticator = new IamAuthenticator("<iam_api_key>");
Discovery service = new Discovery("2019-04-30", authenticator);

Supplying the access token:

// assuming control of managing IAM token
Authenticator authenticator = new BearerTokenAuthenticator("<access_token>");
Discovery service = new Discovery("2019-04-30", authenticator);

Username and password

Authenticator authenticator = new BasicAuthenticator("<username>", "<password>");
Discovery service = new Discovery("2019-04-30", authenticator);

ICP

Authenticating with ICP is similar to the basic username and password method, except that you need to make sure to disable SSL verification to authenticate properly. See here for more information.

Authenticator authenticator = new BasicAuthenticator("<username>", "<password>");
Discovery service = new Discovery("2019-04-30", authenticator);

HttpConfigOptions options = new HttpConfigOptions.Builder()
  .disableSslVerification(true)
  .build();

service.configureClient(options);

Cloud Pak for Data

Like IAM, you can pass in credentials to let the SDK manage an access token for you or directly supply an access token to do it yourself.

// letting the SDK manage the token
Authenticator authenticator = new CloudPakForDataAuthenticator(
  "<CP4D token exchange base URL>",
  "<username>",
  "<password>",
  true, // disabling SSL verification
  null,
);
Discovery service = new Discovery("2019-04-30", authenticator);
service.setServiceUrl("<service CP4D URL>");
// assuming control of managing the access token
Authenticator authenticator = new BearerTokenAuthenticator("<access_token>");
Discovery service = new Discovery("2019-04-30", authenticator);
service.setServiceUrl("<service CP4D URL>");

Be sure to both disable SSL verification when authenticating and set the endpoint explicitly to the URL given in Cloud Pak for Data.

Using the SDK

Parsing responses

No matter which method you use to make an API request (execute(), enqueue(), or reactiveRequest()), you'll get back an object of form Response<T>, where T is the model representing the specific response model.

Here's an example of how to parse that response and get additional information beyond the response model:

// listing our workspaces with an instance of the Assistant v1 service
Response<WorkspaceCollection> response = service.listWorkspaces().execute();

// pulling out the specific API method response, which we can manipulate as usual
WorkspaceCollection collection = response.getResult();
System.out.println("My workspaces: " + collection.getWorkspaces());

// grabbing headers that came back with our API response
Headers responseHeaders = response.getHeaders();
System.out.println("Response header names: " + responseHeaders.names());

Configuring the HTTP client

The HTTP client can be configured by using the configureClient() method on your service object, passing in an HttpConfigOptions object. Currently, the following options are supported:

Here's an example of setting the above:

Discovery service = new Discovery("2019-04-30");

// setting configuration options
HttpConfigOptions options = new HttpConfigOptions.Builder()
  .disableSslVerification(true)
  .proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxyHost", 8080)))
  .loggingLevel(HttpConfigOptions.LoggingLevel.BASIC)
  .build();

service.configureClient(options);

Making asynchronous API calls

The basic, synchronous way to make API calls with this SDK is through the use of the execute() method. Using this method looks something like this:

// make API call
Response<ListEnvironmentsResponse> response = service.listEnvironments().execute();

// continue execution

However, if you need to perform these calls in the background, there are two other methods to do this asynchronously: enqueue() and reactiveRequest().

enqueue()

This method allows you to set a callback for the service response through the use of the ServiceCallback object. Here's an example:

// make API call in the background
service.listEnvironments().enqueue(new ServiceCallback<ListEnvironmentsResponse>() {
  @Override
  public void onResponse(Response<ListEnvironmentsResponse> response) {
    System.out.println("We did it! " + response);
  }

  @Override
  public void onFailure(Exception e) {
    System.out.println("Whoops...");
  }
});

// continue working in the meantime!

reactiveRequest()

If you're a fan of the RxJava library, this method lets you leverage that to allow for "reactive" programming. The method will return a Single<T> which you can manipulate how you please. Example:

// get stream with request
Single<Response<ListEnvironmentsResponse>> observableRequest
  = service.listEnvironments().reactiveRequest();

// make API call in the background
observableRequest
  .subscribeOn(Schedulers.single())
  .subscribe(response -> System.out.println("We did it with s~t~r~e~a~m~s! " + response));

// continue working in the meantime!

Default headers

Default headers can be specified at any time by using the setDefaultHeaders(Map<String, String> headers) method.

The example below sends the X-Watson-Learning-Opt-Out header in every request preventing Watson from using the payload to improve the service.

PersonalityInsights service = new PersonalityInsights("2017-10-13", new NoAuthAuthenticator());

Map<String, String> headers = new HashMap<String, String>();
headers.put(WatsonHttpHeaders.X_WATSON_LEARNING_OPT_OUT, "true");

service.setDefaultHeaders(headers);

// All the api calls from now on will send the default headers

Sending request headers

Custom headers can be passed with any request. To do so, add the header to the ServiceCall object before executing the request. For example, this is what it looks like to send the header Custom-Header along with a call to the Watson Assistant service:

Response<WorkspaceCollection> workspaces = service.listWorkspaces()
  .addHeader("Custom-Header", "custom_value")
  .execute();

Canceling requests

It's possible that you may want to cancel a request you make to a service. For example, you may set some timeout threshold and just want to cancel an asynchronous if it doesn't respond in time. You can do that by calling the cancel() method on your ServiceCall object. For example:

// time to consider timeout (in ms)
long timeoutThreshold = 3000;

// storing ServiceCall object we'll use to list our Assistant v1 workspaces
ServiceCall<WorkspaceCollection> call = service.listWorkspaces();

long startTime = System.currentTimeMillis();
call.enqueue(new ServiceCallback<WorkspaceCollection>() {
  @Override
  public void onResponse(Response<WorkspaceCollection> response) {
    // store the result somewhere
    fakeDb.store("my-key", response.getResult());
  }

  @Override
  public void onFailure(Exception e) {
    System.out.println("The request failed :(");
  }
});

// keep waiting for the call to complete while we're within the timeout bounds
while ((fakeDb.retrieve("my-key") == null) && (System.currentTimeMillis() - startTime < timeoutThreshold)) {
  Thread.sleep(500);
}

// if we timed out and it's STILL not complete, we'll just cancel the call
if (fakeDb.retrieve("my-key") == null) {
    call.cancel();
}

Doing so will call your onFailure() implementation.

Transaction IDs

Every SDK call returns a response with a transaction ID in the X-Global-Transaction-Id header. This transaction ID is useful for troubleshooting and accessing relevant logs from your service instance.

Assistant service = new Assistant("2019-02-28");
ListWorkspacesOptions options = new ListWorkspacesOptions.Builder().build();
Response<WorkspaceCollection> response;

try {
  // In a successful case, you can grab the ID with the following code.
  response = service.listWorkspaces(options).execute();
  String transactionId = response.getHeaders().values("X-Global-Transaction-Id").get(0);
} catch (ServiceResponseException e) {
  // This is how you get the ID from a failed request.
  // Make sure to use the ServiceResponseException class or one of its subclasses!
  String transactionId = e.getHeaders().values("X-Global-Transaction-Id").get(0);
}

However, the transaction ID isn't available when the API doesn't return a response for some reason. In that case, you can set your own transaction ID in the request. For example, replace <my-unique-transaction-id> in the following example with a unique transaction ID.

Authenticator authenticator = new IamAuthenticator("apiKey");
service = new Assistant("{version-date}", authenticator);
service.setServiceUrl("{serviceUrl}");

Map<String, String> headers = new HashMap<>();
headers.put("X-Global-Transaction-Id", "<my-unique-transaction-id>");
service.setDefaultHeaders(headers);

MessageOptions options = new MessageOptions.Builder(workspaceId).build();
MessageResponse result = service.message(options).execute().getResult();

FAQ

Does this SDK play well with Android?

It does! You should be able to plug this dependency into your Android app without any issue. In addition, we have an Android SDK meant to be used with this library that adds some Android-specific functionality, which you can find here.

How can I contribute?

Great question (and please do)! You can find contributing information here.

Where can I get more help with using Watson APIs?

If you have issues with the APIs or have a question about the Watson services, see Stack Overflow.

Does IBM have any other open source work?

We do 😎 http://ibm.github.io/

Featured projects

We'd love to highlight cool open-source projects that use this SDK! If you'd like to get your project added to the list, feel free to make an issue linking us to it.

Contributors ✨

Thanks goes to these wonderful people (emoji key):


Logan Patino

💻 🎨 🐛

Ajiemar Santiago

💻 🎨 🐛

German Attanasio

💻 🎨 📖 ⚠️

This project follows the all-contributors specification. Contributions of any kind welcome!

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].