GithubHelp home page GithubHelp logo

watson-developer-cloud / java-sdk Goto Github PK

View Code? Open in Web Editor NEW
587.0 103.0 532.0 394.22 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

Java 99.20% HTML 0.65% Shell 0.10% Makefile 0.04% Python 0.01% Dockerfile 0.01%
ibm-watson-services bluemix java gradle java-sdk hacktoberfest ibm-cloud watson-services sdk watson-apis iam

java-sdk's Introduction

Watson APIs Java SDK

Build and Test Deploy and Publish Maven Central CLA assistant

Deprecated builds

Build Status

Java client library to use the Watson APIs.

Before you begin

Installation

Maven

All the services:

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

Only Discovery:

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

All the services:

'com.ibm.watson:ibm-watson:13.0.0'

Only Assistant:

'com.ibm.watson:assistant:13.0.0'

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.

As of v9.2.1, the preferred approach of initializing an authenticator is the builder pattern. This pattern supports constructing the authenticator with only the properties that you need. Also, if you're authenticating to a Watson service on Cloud Pak for Data that supports IAM, you must use the builder pattern.

  • You can initialize the authenticator with either of the following approaches:
    • In the builder of the authenticator (builder pattern).
    • In the constructor of the authenticator (deprecated, but still available).
  • 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:

Builder pattern approach:

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

Deprecated constructor approach:

// 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

Builder pattern approach:

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

Deprecated constructor approach:

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.

Builder pattern approach:

// letting the SDK manage the token
Authenticator authenticator = new CloudPakForDataAuthenticator.Builder()
            .url("<CP4D token exchange base URL>")
            .username("<username>")
            .password("<password>")
            .disableSSLVerification(true)
            .headers(null)
            .build();
Discovery service = new Discovery("2019-04-30", authenticator);
service.setServiceUrl("<service CP4D URL>");

Deprecated constructor approach:

// 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.

MCSP

To use the SDK through a third party cloud provider (such as AWS), use the MCSPAuthenticator. This will require the base endpoint URL for the MCSP token service (e.g. https://iam.platform.saas.ibm.com) and an apikey.

// letting the SDK manage the token
Authenticator authenticator = new MCSPAuthenticator.Builder()
            .apikey("apikey")
            .url("token_service_endpoint")
            .build();
Assistant service = new Assistant("2023-06-15", authenticator);
service.setServiceUrl("<url_as_per_region>");

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 setProxy() method on your authenticator and using the configureClient() method on your service object, passing in an HttpConfigOptions object. For a full list of configurable options look at this linked Builder class for HttpConfigOptions. Currently, the following options are supported:

  • Disabling SSL verification (only do this if you really mean to!) ⚠️
  • Setting gzip compression
  • Setting max retry and retry interval
  • Using a proxy (more info here: OkHTTPClient Proxy authentication how to?)
  • Setting HTTP logging verbosity

Here's an example of setting the above:

Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxyHost", 8080));
IamAuthenticator authenticator = new IamAuthenticator(apiKey);
authenticator.setProxy(proxy);

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

// setting configuration options
HttpConfigOptions options = new HttpConfigOptions.Builder()
  .disableSslVerification(true)
  .proxy(proxy)
  .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

💻 🎨 📖 ⚠️

Kevin Kowalski

💻 🎨 🐛 📖 ⚠️ 💬️

Jeff Arn

💻 🎨 🐛 📖 ⚠️ 💬️

Angelo Paparazzi

💻 🎨 🐛 📖 ⚠️ 💬️ 🥷🏼

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

java-sdk's People

Contributors

adityagai avatar allcontributors[bot] avatar alseddnm avatar apaparazzi0329 avatar aprilwebster avatar blakesteve avatar doconnor78 avatar germanattanasio avatar gjs29 avatar grapebaba avatar hsaylor avatar jeff-arn avatar jeffpk62 avatar kevinkowa avatar kognate avatar lpatino10 avatar mamoonraja avatar maniax89 avatar martinhrvn avatar max-vogler avatar mediumtaj avatar mikemosca avatar nastacio avatar nfriedly avatar rmartinsanta avatar samir-patel avatar schen22 avatar semantic-release-bot avatar sirspidey avatar tanmayb123 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

java-sdk's Issues

UTF-8 compatible

Looks like the wrapper is not encoding the requests as UTF-8.

Specially for the dialog service when we try to update the profile

Invalid use of BasicClientConnManager: connection still allocated

Currently the execute() method is single thread and try to use only one HTTP connection. This is a big problem if the wrapper is being used in a multi-thread environment so we need to add a http connection pool.

See:

Concept Insights: fix corpus id in createCorpus

Concept Insights API requires corpus id to be of the form /corpora/{account_id}/{corpus}. createCorpus() takes in a Corpus object, where an id is required. createCorpus() creates a URL for the request by concatenating /v2/corpora/{account_id} and the id from the Corpus object; currently this concatenation results in /v2/corpora/{account_id}/corpora/{account_id}/corpus.

Proposed solution: since Concept Insights API does not require an id for the corpus, allow Corpus.id to be null in createCorpus(). Add a name field to Corpus and use that when calling createCorpusIdPath() from createCorpus().

Add test cases

We need tests cases to make sure that code changes don't break the existing functionality. We need to choose a good framework to mock rest calls.

I heard good comments about http://www.mock-server.com/

  • Add coveralls.io
  • Choose the test framework to use
  • Add test cases for the GA services

Uploading dialog file using java wrapper returns BadRequestException

Hi

When trying to upload an XML file to the dialog service to create a dialog I receive an error with the following message:

[error] c.i.w.d.s.WatsonService - HTTP Status: 400, message: Failed to import file. Possibly due to corrupt or invalid file or system error. - Input length (with padding) not multiple of 16 bytes

I am not sure why, I suspect that is due to a bad header sent in the request, If I use the dialog tool same file works flawlessly, but through the java wrapper does not.

v2.0.0 goals

I'm going to summarize all the tasks we need to accomplish in order to release the v2.0.0

  • Add Retrieve and Rank #25
  • Switch from HttpClient to OkHttp
  • Encode form-urlencoded requests. (#64, #62)
  • raw responses from services, see #54
  • metadata to responses, similar to #54
  • Add support for custom headers #22

Alchemy News URLs empty

When trying to grab alchemy news URLs, they are not populate (as the original API suggests they should).

[speech-to-text] Investigate the use if WebSocket

HI @daniel-bolanos I was thinking we can provide support for WebSockets in the wrapper by adding an existing library and handling the authorization using the authorization service.
What do you think?

We should:

  • Find a websocket library
  • Design a listener/observer pattern to model websockets

Update ResponseUtils to always throw Runtime Exceptions

ResponseUtils currently throw IOExceptions and we are always doing a try/catch on each service call for each Watson service to transform that into a Runtime Exception. Why don't we just update ResponseUtils to always throw a runtime exception and remove the try/catch from the services...

Current implementation

ResponseUtils:

public static String getString(HttpResponse response) throws IOException {
    HttpEntity entity;
    try {
        entity = response.getEntity();
        if (entity == null)
            return null;
        else
            return EntityUtils.toString(entity, "UTF-8");
    } catch (ParseException e) {
        log.log(Level.SEVERE,"Could not parse service response", e);
        throw new IOException("Could not parse service response:" + e.getMessage());
    }  catch (IOException e) {
        log.log(Level.SEVERE,"Could not read service response", e);
        throw new IOException("Could not read service response:" + e.getMessage());
    }
}

Example service call:

public Corpora getCorpora(String accountId) {
    Validate.notNull(accountId, "account_id can't be null");
    HttpRequestBase request = Request.Get(CORPORA_PATH + FORWARD_SLASH + accountId).build();

    try {
        HttpResponse response = execute(request);
        String jsonString = ResponseUtil.getString(response);
        Corpora corpora = GsonSingleton.getGson().fromJson(jsonString, Corpora.class);
        return corpora;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

Proposed change

ResponseUtils will throw RuntimeExceptions:

public static String getString(HttpResponse response) {
    HttpEntity entity;
    try {
        entity = response.getEntity();
        if (entity == null)
            return null;
        else
            return EntityUtils.toString(entity, "UTF-8");
    } catch (ParseException e) {
        log.log(Level.SEVERE,"Could not parse service response", e);
        throw new RuntimeException("Could not parse service response:" + e.getMessage());
    }  catch (IOException e) {
        log.log(Level.SEVERE,"Could not read service response", e);
        throw new RuntimeException("Could not read service response:" + e.getMessage());
    }
}

And the service call will be:

public Corpora getCorpora(String accountId) {
    Validate.notNull(accountId, "account_id can't be null");
    HttpRequestBase request = Request.Get(CORPORA_PATH + FORWARD_SLASH + accountId).build();

    HttpResponse response = execute(request);
    String jsonString = ResponseUtil.getString(response);
    Corpora corpora = GsonSingleton.getGson().fromJson(jsonString, Corpora.class);
    return corpora;
}

updateProfile method sometimes throws com.ibm.watson.developer_cloud.service.NotFoundException

The exception is thrown sometimes and sometimes it works fine with the same input and dialogid.
Stack trace:

com.ibm.watson.developer_cloud.service.NotFoundException: The dialog_id specified is invalid or does not exist. Include a valid dialog_id on the URL. 
at com.ibm.watson.developer_cloud.service.WatsonService.execute(WatsonService.java:193) 
at com.ibm.watson.developer_cloud.service.WatsonService.executeWithoutResponse(WatsonService.java:244) 
at com.ibm.watson.developer_cloud.dialog.v1.DialogService.updateProfile(DialogService.java:428) 
// Internal classes

Doubt - how to retrieve documents from Alchemy News?

Sorry, I can see that DocumentsResult toString() returns a clear JSON with all the results.
But I am kind of lost about iterating on the objects.

DocumentsResult docs = s.getNewsDocuments(map);
Documents documents = docs.getDocuments();
System.out.println(documents.getNext()); => returns something I can't understand that seems like some serialized object

How do I access the elements inside the Documents object?

TIA

Leo

Unable to Execute Tradeoff Analytics

I attempted to use your Java SDK to integrate Tradeoff Analytics into an application that we are developing at the Mobile Innovation Lab. We imported your jar (even downloaded and re-built it with gradle) and tried to execute the example test for Tradeoff Analytics, but were greeted with an error.

The error seemed to be related to GSON, which required the Column class to have a default constructor with no arguments. To resolve the error for our particular use-case, we had to modify the source code by adding a default constructor with no arguments, and by changing the abstract Column class to a concrete class.

These changes obviously aren't ideal, but they were enough for our use-case to get us back in business.

CSV results from Personality Insights not accessible

Wondering if it'd be possible to include a .getCSV(String text) method to the PersonalityInsights service. This is a native capability of the service. (Not sure if this request is more of a feature request - but included it here as it is a missing feature that comes from the actual API).

Thanks

Classification object should have getTopClassConfidence()

Without a method like this, I have to get all the classes, iterate through the list, and check each ClassifiedClass name with the string returned to me by Classification.getTopClass()

It'd be nice and more efficient to have that confidence built into the Classification object.

Date Format Exception for Android

While using jar file, I got an exception in android " Unknown pattern charecter 'X' "

Solution for this issue.

package name: com.ibm.watson.developer_cloud.util
class name: GsonSingleton
change string constant
String DATE_FORMAT_UTC = "yyyy-MM-dd'T'HH:mm:ss.SSSX";
like this
String DATE_FORMAT_UTC = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";

Please change one line above and deploy new jar.

New Alchemy API does not support standard characters

I get

{"error":"unsupported-text-language", "code":400}

when running text that has characters like & in them.

I think we either need a definition of supported characters or some automated encoding in the method:

service.getEntities()

Tradeoff Analytics Example Out-Of-Sync

The Tradeoff Analytics example contained within the repository's readme does not seem to be consistent with the most recent version of the API you provide for the Tradeoff Analytics service.

While investigating the use of your Java SDK in an application we are building at the Mobile Innovation Lab, I started by trying to execute the provided example in the readme. Unfortunately, it failed to compile.

The source code of the Tradeoff Analytics test, however, compiles. Perhaps the API you provide for Tradeoff Analytics was updated, but the readme was not updated to reflect those changes?

UnsupportedEncodingException is never thrown from the try statement body

com.ibm.watson.developer_cloud.service.Request

Unreachable catch block for UnsupportedEncodingException. This exception is never thrown from the try statement body

public Request withContent(String content, String contentType) {
    try {
        StringEntity stringEntity = new StringEntity(content, UTF_8);
        if (contentType != null) {
            stringEntity.setContentType(contentType);
        }
        return withEntity(stringEntity);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}

[documentation] Automatically update gh-pages with maven on every commit

We should use maven:site to update our javadocs and examples in the github site.
Right now this is a manual process I do for every release we have. The idea is to have something like:

  1. http://watson-developer-cloud.github.io/java-wrapper/docs/latest to see the latest javadocs for the latest release in maven central.
  2. http://watson-developer-cloud.github.io/java-wrapper/docs/1.0.3 for 1.0.3 javadocs
  3. http://watson-developer-cloud.github.io/java-wrapper/docs/ redirects to latest
  4. http://watson-developer-cloud.github.io/java-wrapper/docs/dev to see the javadoc from the dev branch in github (?). This is the one we will be generating and updating on each commit.

info

Just 2 suggestions (speech to text and language translation)

First of all, congrats for this fine piece of software. Extremely useful.
Here go my suggestions:

Speech to text

I'm getting much better results using

recognize(audio, "audio/wav");

instead of

recognize(audio, "audio/l16; rate=44100")

my wav file properties, when I right click using linux UI says

Codec: Uncompressed 16-bit PCM audio
Channels: Stereo
Sample rate: 44100 Hz
Bitrate: N/A

LanguageTranslation

When I try to translate "obrigacão" from pt to en, Watson does not recognize the tilde.

But if I submit "obrigacao", then it correctly translate it to "duty".

So my suggestion is to "clean up" the string like this

s = Normalizer.normalize(s, Normalizer.Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+", "");

before using the translate() method

TIA

Leo

Add support for custom headers

Users should be able to specify a list of custom headers and values that are passed to the service along with every request.

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.