package net.dotmyself.restclient.yahoosearch;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
/**
*
* A class designed to wrap the Yahoo! Term Extraction service.
*
* @author Hyacinthe MENIET
*/
public class TermExtractionMapper {
private static final String BASE_URL = "http://api.search.yahoo.com/ContentAnalysisService/V1/termExtraction";
private static final String APP_ID = "YahooDemo"; //replace with your own code
private static final String URL_ENCODING = "UTF-8";
/**
* Retrieves the important words and phrases in a block of text.
*
* @param context The block of text that the terms will be extracted from.
* @param query A query to help identify the topic of the context.
* @return List of extracted String or null
if no String could
* be found.
*/
public static List getTerms(String context, String query) {
List terms = null;
try {
// builds de query string
StringBuilder sb = new StringBuilder("appid=");
sb.append(URLEncoder.encode(APP_ID, URL_ENCODING));
if (context != null && context.length() > 1) {
sb.append("&context=");
sb.append(URLEncoder.encode(context, URL_ENCODING));
}
if (query != null && query.length() > 1) {
sb.append("&query=");
sb.append(URLEncoder.encode(query, URL_ENCODING));
}
// perform a POST connection
URL url = new URL(BASE_URL);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(sb.toString());
writer.flush();
// reads the response
JAXBContext jbctx = JAXBContext.newInstance("net.dotmyself.restclient.yahoosearch");
Unmarshaller unmarshaller = jbctx.createUnmarshaller();
ResultSet rs = (ResultSet) unmarshaller.unmarshal(conn.getInputStream());
terms = (rs != null) ? rs.getResult() : null;
} catch (UnsupportedEncodingException | MalformedURLException | JAXBException ex) {
Logger.getLogger(TermExtractionMapper.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(TermExtractionMapper.class.getName()).log(Level.SEVERE, null, ex);
}
return terms;
}
}