Skip to content

Commit

Permalink
Fix android issue
Browse files Browse the repository at this point in the history
  • Loading branch information
Uli Fahrer committed Jan 18, 2016
1 parent 9a3ba33 commit 6a8ac46
Show file tree
Hide file tree
Showing 29 changed files with 185 additions and 123 deletions.
40 changes: 22 additions & 18 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
jwatson [![Build Status](https://magnum.travis-ci.com/Tooa/jwatson.svg?token=fU3LeFzvsi3Z9zuFsRzz)](https://magnum.travis-ci.com/Tooa/jwatson)
jwatson
=======

A Java wrapper for the IBM Watson DQA service
A Java wrapper for the IBM Watson DQA service.

Getting started
---------------
Expand All @@ -15,26 +15,30 @@ It is available in Maven Central as
<dependency>
<groupId></groupId>
<artifactId></artifactId>
<version>1.0</version>
<version></version>
</dependency>
```


Usage - In a Nutshell
-----
```java
// Create a Watson instance with your URL and credentials
JWatson watson = new JWatson("someuser", "xxxxxxx", "https://watson-wdc01.ihost.com/instance/518/deepqa");

// Query Watson to retrieve answers for a specific question
WatsonAnswer answer = watson.askQuestion("Who is Angela Merkel?");

// ... or use the QuestionBuilder to construct complex questions for Watson
WatsonQuestion question = new WatsonQuestion.QuestionBuilder("Who is Anglea Merkel?")
.setNumberOfAnswers(3) // Provide three possible answers
.formatAnswer() // Instruct Watson to deliver answers in HTML
.create();
WatsonAnswer answer = watson.askQuestion(question);
public static void main(String[] args) throws IOException {
// Create a Watson instance with your URL and credentials
JWatson watson = new JWatson("username", "password", "https://url/instance/xxxxx/deepqa/");

// Query Watson to retrieve answers for a specific question
// WatsonAnswer answer = watson.askQuestion("Who is Angela Merkel?");

// ... or use the QuestionBuilder to construct complex questions for Watson
WatsonQuestion question = new WatsonQuestion.QuestionBuilder("Who is Angela Merkel?")
.setNumberOfAnswers(3) // Provide three possible answers
.formatAnswer() // Instruct Watson to deliver answers in HTML
.create();

WatsonAnswer answer = watson.askQuestion(question);
System.out.println(answer);
}
```

Question & Answer Service
Expand All @@ -52,14 +56,14 @@ System.out.print(isAvailable ? "Watson Service is available" : "Watson Service i

Known bugs and issues
----------------

* University instances can't access the feedback and ping endpoint at the moment
* Ping and Feedback endpoints are not implemented yet.
* Make sure that the URL contains a trailing slash at the end.

License
-------

```
Copyright 2015 Technische Universität Darmstadt.
Copyright 2016 Technische Universität Darmstadt.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Expand Down
Binary file removed build/jwatson.jar
Binary file not shown.
7 changes: 1 addition & 6 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,6 @@
<version>2.2.4</version>
</dependency>

<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>fluent-hc</artifactId>
<version>4.3.6</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
Expand All @@ -27,4 +22,4 @@



</project>
</project>
25 changes: 23 additions & 2 deletions src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2015 Technische Universität Darmstadt
* Copyright 2016 Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -18,6 +18,27 @@
*
*/

import jwatson.JWatson;
import jwatson.answer.WatsonAnswer;
import jwatson.question.WatsonQuestion;

import java.io.IOException;

public class Main {
public static void main(String[] args) {}
public static void main(String[] args) throws IOException {
// Create a Watson instance with your URL and credentials
JWatson watson = new JWatson("username", "password", "https://url/instance/xxxxx/deepqa/");

// Query Watson to retrieve answers for a specific question
// WatsonAnswer answer = watson.askQuestion("Who is Angela Merkel?");

// ... or use the QuestionBuilder to construct complex questions for Watson
WatsonQuestion question = new WatsonQuestion.QuestionBuilder("Who is Angela Merkel?")
.setNumberOfAnswers(3) // Provide three possible answers
.formatAnswer() // Instruct Watson to deliver answers in HTML
.create();

WatsonAnswer answer = watson.askQuestion(question);
System.out.println(answer);
}
}
8 changes: 5 additions & 3 deletions src/main/java/jwatson/IWatsonRestService.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2015 Technische Universität Darmstadt
* Copyright 2016 Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -25,9 +25,11 @@
import jwatson.feedback.Feedback;
import jwatson.question.WatsonQuestion;

import java.io.IOException;

public interface IWatsonRestService {
WatsonAnswer askQuestion(WatsonQuestion question);
WatsonAnswer askQuestion(String questionText);
WatsonAnswer askQuestion(WatsonQuestion question) throws IOException;
WatsonAnswer askQuestion(String questionText) throws IOException;
boolean sendFeedback(Feedback feedback);
boolean ping();
}
177 changes: 109 additions & 68 deletions src/main/java/jwatson/JWatson.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2015 Technische Universität Darmstadt
* Copyright 2016 Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -23,14 +23,9 @@
import jwatson.answer.WatsonAnswer;
import jwatson.feedback.Feedback;
import jwatson.question.WatsonQuestion;
import org.apache.http.HttpResponse;
import org.apache.http.client.fluent.Content;
import org.apache.http.client.fluent.Executor;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.fluent.Response;
import org.apache.http.entity.ContentType;

import java.net.URI;

import java.io.*;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;

Expand All @@ -43,98 +38,144 @@ public class JWatson implements IWatsonRestService {

private static Logger logger = Logger.getLogger(JWatson.class.getName());

private final String url;
private final URL url;
private final String username;
private final String password;

private final Executor executor;

public JWatson(String username, String password, String url) {
public JWatson(String username, String password, String url) throws MalformedURLException {
this.username = username;
this.password = password;
this.url = url;

this.executor = Executor.newInstance().auth(username, password);
this.url = new URL(url);

setAuthentication();
}


private void setAuthentication() {
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(JWatson.this.username,
JWatson.this.password.toCharArray());
}
});
}


/**
* Pings the service to verify that it is available.
*
* @return <code>true</code> if the service is available. Otherwise <code>false</code>.
*/
public boolean ping() {
HttpResponse response = null;
try {
Executor executor = Executor.newInstance().auth(username, password);
URI serviceURI = new URI(url + "/v1/ping").normalize();

System.out.print(serviceURI.toString());

response = executor.execute(Request.Get(serviceURI)
.addHeader("X-SyncTimeout", "30")).returnResponse();

} catch (Exception ex) {
logger.log(Level.SEVERE, "Got the following error: " + ex.getMessage(), ex);
}
int statusCode = response.getStatusLine().getStatusCode();

//200: Service is available, 500: Server error
return (statusCode == 200);
// HttpResponse response = null;
// try {
// Executor executor = Executor.newInstance().auth(username, password);
// URI serviceURI = new URI(url + "/v1/ping").normalize();
//
// System.out.print(serviceURI.toString());
//
// response = executor.execute(Request.Get(serviceURI)
// .addHeader("X-SyncTimeout", "30")).returnResponse();
//
// } catch (Exception ex) {
// logger.log(Level.SEVERE, "Got the following error: " + ex.getMessage(), ex);
// }
// int statusCode = response.getStatusLine().getStatusCode();
//
// //200: Service is available, 500: Server error
// return (statusCode == 200);
return false;
}

/**
* Ask Watson a question via the Question and Answer API.
*
* @param questionText question to ask Watson
* @return WatsonAnswer
* @throws IOException
*/
public WatsonAnswer askQuestion(String questionText) {
public WatsonAnswer askQuestion(String questionText) throws IOException {
WatsonQuestion question = new WatsonQuestion.QuestionBuilder(questionText).create();
return queryService(question);
}

public WatsonAnswer askQuestion(WatsonQuestion question) {
public WatsonAnswer askQuestion(WatsonQuestion question) throws IOException {
return queryService(question);
}

public boolean sendFeedback(Feedback feedback) {
HttpResponse response = null;
try {
Executor executor = Executor.newInstance().auth(username, password);
URI serviceURI = new URI(url + "/v1/feedback").normalize();

response = executor.execute(Request.Put(serviceURI)
.addHeader("Accept", "application/json")
.addHeader("X-SyncTimeout", "30")
.bodyString(feedback.toJson().toString(), ContentType.APPLICATION_JSON)).returnResponse();

// HttpResponse response = null;
// try {
// Executor executor = Executor.newInstance().auth(username, password);
// URI serviceURI = new URI(url + "/v1/feedback").normalize();
//
// response = executor.execute(Request.Put(serviceURI)
// .addHeader("Accept", "application/json")
// .addHeader("X-SyncTimeout", "30")
// .bodyString(feedback.toJson().toString(), ContentType.APPLICATION_JSON)).returnResponse();
//
//
// } catch (Exception ex) {
// logger.log(Level.SEVERE, "Got the following error: " + ex.getMessage(), ex);
// }
//
// int statusCode = response.getStatusLine().getStatusCode();
//
// // 201 - Accepted, 400 - Bad request. Most likely the result of a missing required parameter.
// return (statusCode == 201);
return false;
}

} catch (Exception ex) {
logger.log(Level.SEVERE, "Got the following error: " + ex.getMessage(), ex);
private WatsonAnswer queryService(WatsonQuestion question) throws IOException {

HttpURLConnection urlConnection;
WatsonAnswer answer;
URL queryUrl = new URL(url, "v1/question/");
logger.log(Level.INFO, "Connecting to: " + queryUrl.toString());
urlConnection = (HttpURLConnection) queryUrl.openConnection();

// Connect
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestProperty("X-SyncTimeout", "30");
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "APPLICATION/JSON");
urlConnection.connect();

// Write
OutputStream out = urlConnection.getOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(out);
writer.write(question.toJsonString());
writer.close();
out.close();

logger.log(Level.INFO, "Sending Query: " + question.toJsonString());
int status = urlConnection.getResponseCode();
logger.log(Level.INFO, "Response Code " + status);

// Read
InputStream in = (status >= HttpURLConnection.HTTP_BAD_REQUEST) ? urlConnection.getErrorStream(): urlConnection.getInputStream();
String content = convertStreamToString(in);
in.close();

if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
logger.log(Level.SEVERE, content);
throw new IOException(String.format("%d : %s", status, in));
} else {
answer = WatsonAnswer.createAnswerFromContent(content);
}

int statusCode = response.getStatusLine().getStatusCode();

// 201 - Accepted, 400 - Bad request. Most likely the result of a missing required parameter.
return (statusCode == 201);
urlConnection.disconnect();
return answer;
}

private WatsonAnswer queryService(WatsonQuestion question) {
Content content = null;
try {
URI serviceURI = new URI(url + "/v1/question").normalize();

Response response = executor.execute(Request.Post(serviceURI)
.addHeader("Accept", "application/json")
.addHeader("X-SyncTimeout", "30")
.bodyString(question.toJsonString(), ContentType.APPLICATION_JSON));

content = response.returnContent();

} catch (Exception ex) {
logger.log(Level.SEVERE, "Got the following error: " + ex.getMessage(), ex);
private String convertStreamToString(InputStream is) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}

return WatsonAnswer.createAnswerFromContent(content);
is.close();
return sb.toString();
}
}
2 changes: 1 addition & 1 deletion src/main/java/jwatson/answer/Answer.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2015 Technische Universität Darmstadt
* Copyright 2016 Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/jwatson/answer/AnswerInformation.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2015 Technische Universität Darmstadt
* Copyright 2016 Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/jwatson/answer/ErrorNotification.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2015 Technische Universität Darmstadt
* Copyright 2016 Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down
Loading

0 comments on commit 6a8ac46

Please sign in to comment.