1
votes

Does anyone have an example of making a call to Watson Natural Language Understanding using Java ? The API docs only show Node. However there is a class in the SDK to support it - but no documentation on how to construct the required 'Features' 'AnalyzeOptions' or 'Builder' input.

Here's a snippet that throws a 'Features cannot be Null' - I'm just fumbling in the dark at this point

        String response = docConversionService.convertDocumentToHTML(doc).execute();

        Builder b = new AnalyzeOptions.Builder();
        b.html(response);

        AnalyzeOptions ao = b.build();
        nlu.analyze(ao);
1

1 Answers

1
votes

Until the API reference is published, have you tried looking at the tests on github? See here for NaturalLanguageUnderstandingIT

I've gotten it working with a text string, and looking at the above test, it won't be too much to get it working with a URL or HTML (changing the AnalyzeOptions builder call from text() to html() for example).

Code example:

final NaturalLanguageUnderstanding understanding =
  new NaturalLanguageUnderstanding(
    NaturalLanguageUnderstanding.VERSION_DATE_2017_02_27);
understanding.setUsernameAndPassword(serviceUsername, servicePassword);
understanding.setEndPoint(url);
understanding.setDefaultHeaders(getDefaultHeaders());

final String testString =
  "In remote corners of the world, citizens are demanding respect"
    + " for the dignity of all people no matter their gender, or race, or religion, or disability,"
    + " or sexual orientation, and those who deny others dignity are subject to public reproach."
    + " An explosion of social media has given ordinary people more ways to express themselves,"
    + " and has raised people's expectations for those of us in power. Indeed, our international"
    + " order has been so successful that we take it as a given that great powers no longer"
    + " fight world wars; that the end of the Cold War lifted the shadow of nuclear Armageddon;"
    + " that the battlefields of Europe have been replaced by peaceful union; that China and India"
    + " remain on a path of remarkable growth.";
final ConceptsOptions concepts =
  new ConceptsOptions.Builder().limit(5).build();

final Features features =
  new Features.Builder().concepts(concepts).build();
final AnalyzeOptions parameters = new AnalyzeOptions.Builder()
  .text(testString).features(features).returnAnalyzedText(true).build();

final AnalysisResults results =
  understanding.analyze(parameters).execute();
System.out.println(results);

Make sure you populate your NLU service with default headers (setDefaultHeaders()). I pulled these from WatsonServiceTest (I'd post the link but my rep is too low. Just use the FindFile option on WDC github)

final Map<String, String> headers = new HashMap<String, String>();
headers.put(HttpHeaders.X_WATSON_LEARNING_OPT_OUT, String.valueOf(true));
headers.put(HttpHeaders.X_WATSON_TEST, String.valueOf(true));
return headers;