Coder Social home page Coder Social logo

ibm-garage-nice / java-sdk Goto Github PK

View Code? Open in Web Editor NEW

This project forked from watson-developer-cloud/java-sdk

0.0 1.0 0.0 254.38 MB

:1st_place_medal: Java SDK to use the IBM Watson services.

Home Page: http://watson-developer-cloud.github.io/java-sdk/

License: Apache License 2.0

Shell 0.19% Makefile 0.07% Python 0.01% Java 98.52% HTML 1.21%

java-sdk's Introduction

Watson APIs Java SDK

Build Status Slack Maven Central CLA assistant

Java client library to use the Watson APIs.

Table of Contents

Before you begin

Installation

Maven

All the services:

<dependency>
	<groupId>com.ibm.watson.developer_cloud</groupId>
	<artifactId>java-sdk</artifactId>
	<version>6.14.0</version>
</dependency>

Only Discovery:

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

All the services:

'com.ibm.watson.developer_cloud:java-sdk:6.14.0'

Only Assistant:

'com.ibm.watson.developer_cloud:assistant:6.14.0'
Development snapshots

Snapshots of the development version are available in Sonatype's snapshots repository.

Gradle

Add repository to your project Gradle file

allprojects {
    repositories {
        maven { url "https://oss.sonatype.org/content/repositories/snapshots" }
    }
}

And then reference the snapshot version on your app module gradle Only Speech to Text:

'com.ibm.watson.developer_cloud:speech-to-text:6.14.1-SNAPSHOT'
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.

Note: Previously, it was possible to authenticate using a token in a header called X-Watson-Authorization-Token. This method is deprecated. The token continues to work with Cloud Foundry services, but is not supported for services that use Identity and Access Management (IAM) authentication. See here for details.

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("2017-11-07");

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. If you want to switch to API key, override your stored IAM credentials with an IAM API key. Then call the setIamCredentials() method again.

Supplying the IAM API key:

// in the constructor, letting the SDK manage the IAM token
IamOptions options = new IamOptions.Builder()
  .apiKey("<iam_api_key>")
  .url("<iam_url>") // optional - the default value is https://iam.bluemix.net/identity/token
  .build();
Discovery service = new Discovery("2017-11-07", options);
// after instantiation, letting the SDK manage the IAM token
Discovery service = new Discovery("2017-11-07");
IamOptions options = new IamOptions.Builder()
  .apiKey("<iam_api_key>")
  .build();
service.setIamCredentials(options);

Supplying the access token:

// in the constructor, assuming control of managing IAM token
IamOptions options = new IamOptions.Builder()
  .accessToken("<access_token>")
  .build();
Discovery service = new Discovery("2017-11-07", options);
// after instantiation, assuming control of managing IAM token
Discovery service = new Discovery("2017-11-07");
IamOptions options = new IamOptions.Builder()
  .accessToken("<access_token>")
  .build();
service.setIamCredentials(options);

Username and password

// in the constructor
Discovery service = new Discovery("2017-11-07", "<username>", "<password>");
// after instantiation
Discovery service = new Discovery("2017-11-07");
service.setUsernameAndPassword("<username>", "<password>");

Android

The Android SDK utilizes the Java SDK while making some Android-specific additions. This repository can be found here. It depends on OkHttp and gson.

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 both of the above:

Discovery service = new Discovery("2017-11-07");

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

service.configureClient(options);

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:

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

Parsing HTTP response info

The basic execute(), enqueue(), and rx() methods make HTTP requests to your Watson service and return models based on the requested endpoint. If you would like access to some HTTP response information along with the response model, you can use the more detailed versions of those three methods: executeWithDetails(), enqueueWithDetails(), and rxWithDetails(). To capture the responses, use the new Response<T> class, with T being the expected response model.

Here is an example of calling the Watson Assistant listWorkspaces() method and parsing its response model as well as the response headers:

Response<WorkspaceCollection> response = service.listWorkspaces().executeWithDetails();

// getting result equivalent to execute()
WorkspaceCollection workspaces = response.getResult();

// getting returned HTTP headers
Headers responseHeaders = response.getHeaders();

Note that when using enqueueWithDetails(), you must also implement the new ServiceCallbackWithDetails interface. For example:

service.listWorkspaces().enqueueWithDetails(new ServiceCallbackWithDetails<WorkspaceCollection>() {
  @Override
  public void onResponse(Response<WorkspaceCollection> response) {
    WorkspaceCollection workspaces = response.getResult();
    Headers responseHeaders = response.getHeaders();
  }

  @Override
  public void onFailure(Exception e) { }
});

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("2016-10-19");

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

service.setDefaultHeaders(headers);

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

Specifying a service URL

You can set the correct API endpoint for your service calling setEndPoint().

For example, if you have the Discovery service in Germany, the endpoint may be https://gateway-fra.watsonplatform.net/discovery/api.

You will need to call

Discovery service = new Discovery("2017-11-07");
service.sentEndPoint("https://gateway-fra.watsonplatform.net/discovery/api")

401 unauthorized error

Make sure you are using the service credentials and not your IBM Cloud account/password. Check the API endpoint, you may need to update the default using setEndPoint().

Debug

HTTP requests can be logged by adding a logging.properties file to your classpath.

handlers=java.util.logging.ConsoleHandler
java.util.logging.ConsoleHandler.level=FINE
java.util.logging.ConsoleHandler.formatter=java.util.logging.SimpleFormatter
java.util.logging.SimpleFormatter.format=%1$tb %1$td, %1$tY %1$tl:%1$tM:%1$tS %1$Tp %2$s %4$s: %5$s%n
.level=SEVERE
# HTTP Logging - Basic
com.ibm.watson.developer_cloud.util.HttpLogging.level=INFO

The configuration above will log only the URL and query parameters for each request.

For example:

Mar 30, 2017 7:31:22 PM okhttp3.internal.platform.Platform log
INFO: --> POST https://gateway.watsonplatform.net/tradeoff-analytics/api/v1/dilemmas?generate_visualization=false http/1.1 (923-byte body)
Mar 30, 2017 7:31:22 PM okhttp3.internal.platform.Platform log
INFO: <-- 200 OK https://gateway.watsonplatform.net/tradeoff-analytics/api/v1/dilemmas?generate_visualization=false (104ms, unknown-length body)
Mar 30, 2017 7:31:23 PM okhttp3.internal.platform.Platform log
INFO: --> POST https://gateway.watsonplatform.net/tradeoff-analytics/api/v1/dilemmas?generate_visualization=true http/1.1 (12398-byte body)
Mar 30, 2017 7:31:35 PM okhttp3.internal.platform.Platform log
INFO: <-- 200 OK https://gateway.watsonplatform.net/tradeoff-analytics/api/v1/dilemmas?generate_visualization=true (12311ms, unknown-length body)

Warning: The logs generated by this logger when using the level FINE or ALL has the potential to leak sensitive information such as "Authorization" or "Cookie" headers and the contents of request and response bodies. This data should only be logged in a controlled way or in a non-production environment.

Build + test

To build and test the project you can use Gradle (version 1.x).

Gradle:

cd java-sdk
gradle jar  # build jar file (build/libs/watson-developer-cloud-6.14.0.jar)
gradle test # run tests
gradle check # performs quality checks on source files and generates reports
gradle testReport # run tests and generate the aggregated test report (build/reports/allTests)
gradle codeCoverageReport # run tests and generate the code coverage report (build/reports/jacoco)

Working with Eclipse and Intellij IDEA

If you want to work on the code in an IDE instead of a text editor you can easily create project files with gradle:

gradle idea     # Intellij IDEA
gradle eclipse  # Eclipse

Open source @ IBM

Find more open source projects on the IBM Github Page

License

This library is licensed under Apache 2.0. Full license text is available in LICENSE.

Contributing

See CONTRIBUTING.md.

Code of conduct

See CODE_OF_CONDUCT.md.

Other

If you are having difficulties using the APIs or you have a question about the IBM Watson Services, please ask a question on dW Answers or Stack Overflow.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.