Java client library to use the Watson Developer Cloud services, a collection of REST APIs and SDKs that use cognitive computing to solve complex problems.
- Installation
- Usage
- Getting the Service Credentials
- Questions
- IBM Watson Services
- Alchemy Language
- Alchemy Vision
- Alchemy Data News
- Concept Expansion
- Concept Insights
- Dialog
- Document Conversion
- Language Translation
- Natural Language Classifier
- Personality Insights
- Relationship Extraction
- Retrieve and Rank
- Speech to Text
- Text to Speech
- Tone Analyzer
- Tradeoff Analytics
- Visual Insights
- Visual Recognition
- Android
- Running in Bluemix
- Eclipse and Intellij
- License
- Contributing
<dependency>
<groupId>com.ibm.watson.developer_cloud</groupId>
<artifactId>java-sdk</artifactId>
<version>2.9.0</version>
</dependency>'com.ibm.watson.developer_cloud:java-sdk:2.9.0'Now, you are ready to see some examples.
The examples below assume that you already have service credentials. If not, you will have to create a service in Bluemix.
If you are running your application in Bluemix, you don't need to specify the
credentials; the library will get them for you by looking at the VCAP_SERVICES environment variable.
You will need the username and password (api_key for AlchemyAPI) credentials for each service. Service credentials are different from your Bluemix account username and password.
To get your service credentials, follow these steps:
Log in to Bluemix at https://bluemix.net.
Create an instance of the service:
- In the Bluemix Catalog, select the service you want to use.
- Under Add Service, type a unique name for the service instance in the Service name field. For example, type
my-service-name. Leave the default values for the other options. - Click Create.
Copy your credentials:
- On the left side of the page, click Service Credentials to view your service credentials.
- Copy
usernameandpassword(api_keyfor AlchemyAPI).
Once you have credentials, copy config.properties.example to src/test/resources/config.properties, and fill them in as necessary.
If you are having difficulties using the APIs or have a question about the IBM Watson Services, please ask a question on dW Answers or Stack Overflow.
The Watson Developer Cloud offers a variety of services for building cognitive applications.
Alchemy Language offers 12 API functions as part of its text analysis service, each of which uses sophisticated natural language processing techniques to analyze your content and add high-level semantic information.
Use the Sentiment Analysis endpoint to identify positive/negative sentiment within a sample text document.
AlchemyLanguageservice = newAlchemyLanguage();
service.setApiKey("<api_key>");
Map<String,Object> params = newHashMap<String, Object>();
params.put(AlchemyLanguage.TEXT, "IBM Watson won the Jeopardy television show hosted by Alex Trebek");
DocumentSentimentsentiment = service.getSentiment(params);
System.out.println(sentiment);Alchemy Vision uses deep learning innovations to understand a picture's content and context. It sees complex visual scenes in their entirety —without needing any textual clues— leveraging a holistic approach to understand the objects, faces, and words in an image.
Example: Extract keywords from an image.
AlchemyVisionservice = newAlchemyVision();
service.setApiKey("<api_key>");
Fileimage = newFile("src/test/resources/alchemy/obama.jpg");
BooleanforceShowAll = false;
BooleanknowledgeGraph = false;
ImageKeywordskeywords = service.getImageKeywords(image, forceShowAll, knowledgeGraph);
System.out.println(keywords);Alchemy Data News indexes 250k to 300k English language news and blog articles every day with historical search available for the past 60 days. Example: Get 7 documents between Friday 28th August 2015 and Friday 4th September 2015.
AlchemyDataNewsservice = newAlchemyDataNews();
service.setApiKey("<api_key>");
Map<String, Object> params = newHashMap<String, Object>();
String[] fields =
newString[] {"enriched.url.title", "enriched.url.url", "enriched.url.author",
"enriched.url.publicationDate", "enriched.url.enrichedTitle.entities",
"enriched.url.enrichedTitle.docSentiment"};
params.put(AlchemyDataNews.RETURN, StringUtils.join(fields, ","));
params.put(AlchemyDataNews.START, "1440720000");
params.put(AlchemyDataNews.END, "1441407600");
params.put(AlchemyDataNews.COUNT, 7);
DocumentsResultresult = service.getNewsDocuments(params);
System.out.println(result);Map euphemisms or colloquial terms to more commonly understood phrases using the Concept Expansion service. Example: Create a job, wait for it to finish, and then retrieve results.
ConceptExpansionservice = newConceptExpansion();
service.setUsernameAndPassword("<username>", "<password>");
String[] seeds = newString[] {"nyc", "dc", "london", "big cities"};
Stringlabel = "demo";
Jobjob = service.createJob(label, seeds);
while (service.getJobStatus(job) == Job.Status.AWAITING_WORK
|| service.getJobStatus(job) == Job.Status.IN_FLIGHT) {
try {
Thread.sleep(4000);
} catch (finalInterruptedExceptione) {
e.printStackTrace();
}
}
System.out.println(service.getJobResult(job));Use the Concept Insights service to identify words in the text that correspond to concepts in a Wikipedia graph.
ConceptInsightsservice = newConceptInsights();
service.setUsernameAndPassword("<username>", "<password>");
Annotationsannotations = service.annotateText(Graph.WIKIPEDIA,
"IBM Watson won the Jeopardy television show hosted by Alex Trebek");
System.out.println(annotations);Returns the dialog list using the Dialog service.
DialogServiceservice = newDialogService();
service.setUsernameAndPassword("<username>", "<password>");
List<Dialog> dialogs = service.getDialogs();
System.out.println(dialogs);The Document Conversion service allows to convert pdf, word, and html documents into formats useful to other Watson Cognitive services. Target formats include normalized html, plain text, and sets of potential answers for Watson question answering. You can convert documents synchronously one at a time, or asynchronously in batches
Returns the document list using the Document Conversion service.
DocumentConversionservice = newDocumentConversion("2015-12-01");
service.setUsernameAndPassword("<username>", "<password>");
Filedoc = newFile("src/test/resources/document_conversion/word-document-heading-input.doc");
AnswershtmlToAnswers = service.convertDocumentToAnswer(doc);
System.out.println(htmlToAnswers);Select a domain, then identify or select the language of text, and then translate the text from one supported language to another.
Example: Translate 'hello' from English to Spanish using the Language Translation service.
LanguageTranslationservice = newLanguageTranslation();
service.setUsernameAndPassword("<username>", "<password>");
TranslationResulttranslationResult = service.translate("hello", "en", "es");
System.out.println(translationResult);Use Natural Language Classifier service to create a classifier instance by providing a set of representative strings and a set of one or more correct classes for each as training. Then use the trained classifier to classify your new question for best matching answers or to retrieve next actions for your application.
NaturalLanguageClassifierservice = newNaturalLanguageClassifier();
service.setUsernameAndPassword("<username>", "<password>");
Classificationclassification = service.classify("<classifier-id>", "Is it sunny?");
System.out.println(classification);Note: You will need to create and train a classifier in order to be able to classify phrases.
Use linguistic analytics to infer personality and social characteristics, including Big Five, Needs, and Values, from text.
Example: Analyze text and get a personality profile using the Personality Insights service.
PersonalityInsightsservice = newPersonalityInsights();
service.setUsernameAndPassword("<username>", "<password>");
// Demo content from Moby Dick by Hermann Melville (Chapter 1)Stringtext = "Call me Ishmael. Some years ago-never mind how long precisely-having "
+ "little or no money in my purse, and nothing particular to interest me on shore, "
+ "I thought I would sail about a little and see the watery part of the world. "
+ "It is a way I have of driving off the spleen and regulating the circulation. "
+ "Whenever I find myself growing grim about the mouth; whenever it is a damp, "
+ "drizzly November in my soul; whenever I find myself involuntarily pausing before "
+ "coffin warehouses, and bringing up the rear of every funeral I meet; and especially "
+ "whenever my hypos get such an upper hand of me, that it requires a strong moral "
+ "principle to prevent me from deliberately stepping into the street, and methodically "
+ "knocking people's hats off-then, I account it high time to get to sea as soon as I can. "
+ "This is my substitute for pistol and ball. With a philosophical flourish Cato throws himself "
+ "upon his sword; I quietly take to the ship. There is nothing surprising in this. "
+ "If they but knew it, almost all men in their degree, some time or other, cherish "
+ "very nearly the same feelings towards the ocean with me. There now is your insular "
+ "city of the Manhattoes, belted round by wharves as Indian isles by coral reefs-commerce surrounds "
+ "it with her surf. Right and left, the streets take you waterward.";
Profileprofile = service.getProfile(text);
System.out.println(profile);Note: Don't forget to update the text variable! Also, if you experience
authentication errors, remember that the Personality Insights service is not
a free service.
Analyze an English news article and get the relationships between sentence components (nouns, verbs, subjects, objects, etc.) by using the Relationship Extraction service.
RelationshipExtractionservice = newRelationshipExtraction();
service.setUsernameAndPassword("<username>", "<password>");
service.setDataset(Dataset.ENGLISH_NEWS);
Stringresponse = service.extract("IBM Watson Developer Cloud");
System.out.println(response);The Retrieve and Rank service helps users find the most relevant information for their query by using a combination of search and machine learning to find “signals” in the data.
RetrieveAndRankservice = newRetrieveAndRank();
service.setUsernameAndPassword("<username>", "<password>");
// 1 create the Solr ClusterSolrClusterOptionsoptions = newSolrClusterOptions("my-cluster-name", 1);
SolrClustercluster = service.createSolrCluster(options);
System.out.println("Solr cluster: " + cluster);
// 2 wait until the Solr Cluster is availablewhile (cluster.getStatus() == Status.NOT_AVAILABLE) {
Thread.sleep(10000); // sleep 10 secondscluster = service.getSolrCluster(cluster.getId());
System.out.println("Solr cluster status: " + cluster.getStatus());
}
// 3 list Solr ClustersSystem.out.println("Solr clusters: " + service.getSolrClusters());Retrieve and Rank is built on top of Apache Solr. Look at this example to learn how to use Solrj.
Use the Speech to Text service to recognize the text from a .wav file.
SpeechToTextservice = newSpeechToText();
service.setUsernameAndPassword("<username>", "<password>");
Fileaudio = newFile("src/test/resources/sample1.wav");
SpeechResultstranscript = service.recognize(audio, HttpMediaType.AUDIO_WAV);
System.out.println(transcript);Speech to Text supports WebSocket, the url is:wss://stream.watsonplatform.net/speech-to-text/api/v1/recognize
We recommend you use this java client.
Use the Text to Speech service to get the available voices to synthesize.
TextToSpeechservice = newTextToSpeech();
service.setUsernameAndPassword("<username>", "<password>");
List<Voice> voices = service.getVoices();
System.out.println(voices);Use the Tone Analyzer service to get the tone of your email.
ToneAnalyzerservice = newToneAnalyzer(ToneAnalyzer.VERSION_DATE_2016_02_11);
service.setUsernameAndPassword("<username>", "<password>");
Stringtext =
"I know the times are difficult! Our sales have been "
+ "disappointing for the past three quarters for our data analytics "
+ "product suite. We have a competitive data analytics product "
+ "suite in the industry. But we need to do our job selling it! "
+ "We need to acknowledge and fix our sales challenges. "
+ "We can’t blame the economy for our lack of execution! "
+ "We are missing critical sales opportunities. "
+ "Our product is in no way inferior to the competitor products. "
+ "Our clients are hungry for analytical tools to improve their "
+ "business outcomes. Economy has nothing to do with it.";
// Call the service and get the toneToneAnalysistone = service.getTone(text);
System.out.println(tone);Use the Tradeoff Analytics service to find the best phone that minimizes price and weight and maximizes screen size.
TradeoffAnalyticsservice = newTradeoffAnalytics();
service.setUsernameAndPassword("<username>", "<password>");
Problemproblem = newProblem("phone");
Stringprice = "price";
Stringram = "ram";
Stringscreen = "screen";
// Define the objectivesList<Column> columns = newArrayList<Column>();
problem.setColumns(columns);
columns.add(newNumericColumn().withRange(0, 100).withKey(price).withGoal(Goal.MIN).withObjective(true));
columns.add(newNumericColumn().withKey(screen).withGoal(Goal.MAX).withObjective(true));
columns.add(newNumericColumn().withKey(ram).withGoal(Goal.MAX));
// Define the options to chooseList<Option> options = newArrayList<Option>();
problem.setOptions(options);
HashMap<String, Object> galaxySpecs = newHashMap<String, Object>();
galaxySpecs.put(price, 50);
galaxySpecs.put(ram, 45);
galaxySpecs.put(screen, 5);
options.add(newOption("1", "Galaxy S4").withValues(galaxySpecs));
HashMap<String, Object> iphoneSpecs = newHashMap<String, Object>();
iphoneSpecs.put(price, 99);
iphoneSpecs.put(ram, 40);
iphoneSpecs.put(screen, 4);
options.add(newOption("2", "iPhone 5").withValues(iphoneSpecs));
HashMap<String, Object> optimusSpecs = newHashMap<String, Object>();
optimusSpecs.put(price, 10);
optimusSpecs.put(ram, 300);
optimusSpecs.put(screen, 5);
options.add(newOption("3", "LG Optimus G").withValues(optimusSpecs));
// Call the service and get the resolutionDilemmadilemma = service.dilemmas(problem);
System.out.println(dilemma);Use the Visual Insights to get insight into the themes present in a collection of images based on their visual appearance/content.
VisualInsightsservice = newVisualInsights();
service.setUsernameAndPassword("<username>", "<password>");
Fileimages = newFile("src/test/resources/visual_insights/images.zip");
Summarysummary = service.getSummary(images);
System.out.println(summary);Use the Visual Recognition service to recognize the following picture.
VisualRecognitionservice = newVisualRecognition();
service.setUsernameAndPassword("<username>", "<password>");
Fileimage = newFile("src/test/resources/visual_recognition/car.png");
VisualRecognitionImagesrecognizedImage = service.recognize(image);
System.out.println(recognizedImage);The library supports Android 2.3 and above. For Java, the minimum requirement is 1.7.
It depends on OkHttp and gson.
When running in Bluemix, the library will automatically get the credentials from VCAP_SERVICES.
If you have more than one plan, you can use BluemixUtils to get the service credentials for an specific plan.
PersonalityInsightsservice = newPersonalityInsights();
StringapiKey = BluemixUtils.getAPIKey(service.getName(), BluemixUtils.PLAN_STANDARD);
service.setApiKey(apiKey);To build and test the project you can use Gradle (version 1.x): or Apache Maven.
Gradle:
$ cd java-sdk
$ gradle jar # build jar file (build/libs/watson-developer-cloud-2.9.0.jar)
$ gradle test# run testsor Maven:
$ cd java-sdk
$ mvn installIf 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 # Eclipseor maven:
$ mvn idea:idea # Intellij IDEA
$ mvn eclipse:eclipse # EclipseFind more open source projects on the IBM Github Page
This library is licensed under Apache 2.0. Full license text is available in LICENSE.
See CONTRIBUTING.md.

