PageRenderTime 33ms CodeModel.GetById 28ms app.highlight 4ms RepoModel.GetById 0ms app.codeStats 0ms

/src/getDDG.java

https://github.com/lipka/Iris-Voice-Automation
Java | 138 lines | 71 code | 23 blank | 44 comment | 11 complexity | b8db97a5f7ebd6fb44ff0a4d37e5d5f9 MD5 | raw file
  1package com.samir_ahmed.Iris;
  2
  3import java.net.URLEncoder;
  4import java.util.concurrent.Callable;
  5
  6import org.apache.commons.lang.StringEscapeUtils;
  7
  8import com.google.gson.JsonObject;
  9import com.google.gson.JsonParser;
 10
 11
 12/**
 13 * getDDG : Callable class for querying duckduckgo.com
 14 * 
 15 * Time: Ranges from 100ms to 400ms
 16 *
 17 * Description: This is a callable class. Any external references are static to ensure safe concurrency
 18 * getDDG is intended to be run as a threaded task and has only one public facing function: String call()
 19 * 
 20 * Only use this class with an executorService.
 21 */
 22
 23public class getDDG implements Callable<String> {
 24
 25	/**
 26	public static void main(String[] args) {
 27		// TODO Auto-generated method stub
 28		//Toolkit.getDefaultToolkit().beep();
 29		getDDG ddg = new getDDG("Port Moresby");
 30		System.out.println(ddg.call()); 
 31	}
 32	 */
 33
 34
 35	/**
 36	 * ALL PRIVATE DATA MEMBERS
 37	 **/
 38	private String ddgJSON;
 39	private String xQuery;
 40	private String ddgURL;
 41	private String Answer;
 42	private String Query;
 43
 44	/**Constructor : Takes in a query string **/
 45	public getDDG(String Query){
 46		// This Constructor does not check if the query is not null of empty
 47		// Ensure this check is done before hand
 48		this.Query = Query;
 49	}
 50
 51	/** extraction: Uses GSON to extract Abstract Text **/
 52	private void extraction(){
 53
 54		// Create a new jSON object and get the type
 55		JsonObject ddgJO = new JsonParser().parse(ddgJSON).getAsJsonObject();
 56		String ddgType = ddgJO.get("Type").toString();
 57
 58		// Case 1: It is ambiguous
 59		if(ddgType.contains("\"D\"")){
 60			Answer = whoWhat.isAmbiguous;
 61		}
 62		// Case 2: It is not ambiguous
 63		else if(ddgType.contains("\"A\"")){
 64
 65			// Extract answer
 66			Answer = ddgJO.get("AbstractText").toString();
 67
 68			// If we have a definition in the answer, discard the answer
 69			if(Answer=="" || Answer.contains("definition:")){
 70				Answer = whoWhat.noAnswer;
 71			}
 72
 73			// If the source is not wikipedia, we discard the answer
 74			else if(!ddgJO.get("AbstractSource").toString().equalsIgnoreCase("\"Wikipedia\"")){
 75				Answer = whoWhat.noAnswer;
 76			}
 77
 78			// Straight forward escaping of any html residue
 79			else{
 80				Answer = StringEscapeUtils.unescapeHtml(Answer);				//Remove html escape characters
 81				Answer = Answer.replaceAll("\\<.*?>","");						//Remove any html tags remaining
 82				Answer = Answer.replaceAll("\"","");							//Remove enclosing "" marks
 83				Answer = Answer.replaceAll("\\(.*?\\)","");						//Remove anything in parenthesis
 84			}
 85			// Any other case we assume that we have no answer
 86		}
 87		else{
 88			Answer = whoWhat.noAnswer;
 89		}
 90	}
 91
 92	/** duckduckget :  Method for downloading ddg JSON **/
 93	private String duckduckGet() {
 94
 95		// Uncomment for timing
 96		//long start = System.currentTimeMillis();
 97		try {
 98			// Safely encode the query as a URL
 99			xQuery = URLEncoder.encode(Query,"UTF-8");
100			ddgURL = "http://api.duckduckgo.com/?q="+xQuery+"&format=json";
101			
102			// Use Blocking IO with httpGET class
103			try{
104				ddgJSON = httpGET.download(ddgURL,this);
105			}
106			catch(InterruptedException InterE){
107				return whoWhat.cancelled;
108			}
109
110			// If we have null or empty string, httpGET failed
111			if (ddgJSON== null || ddgJSON.equals("")){
112				Answer = whoWhat.failed;
113			}
114			// If we dont have any type; Download has failed 
115			else if (ddgJSON.contains("\"Type\":\"\"")){
116				Answer = whoWhat.failed;
117			}
118			// Assume true and pass to extraction method
119			else{
120				extraction();
121			}
122			//Uncomment for timing
123			//System.out.println("Duck-Duck-Go Response Time: " + (System.currentTimeMillis()-start));
124		}
125		catch (Exception Ee){Ee.printStackTrace(); return whoWhat.failed ; }
126		return Answer;
127	}
128
129	/** call :  Method implementing Callable interface, returns a future <string> **/
130	public String call(){
131		try{
132			duckduckGet();
133			return Answer;
134		}
135		catch (Exception ee){ee.printStackTrace(); return whoWhat.failed;}
136	}
137
138}