Search in sources :

Example 66 with JSONParser

use of org.json.simple.parser.JSONParser in project cogcomp-nlp by CogComp.

the class QueryMQL method getCursorAndResponse.

public JSONObject getCursorAndResponse(String mqlQuery, String cursor) throws IOException, ParseException {
    HttpTransport httpTransport = new NetHttpTransport();
    HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
    JSONParser parser = new JSONParser();
    GenericUrl url = new GenericUrl("https://www.googleapis.com/freebase/v1/mqlread");
    url.put("query", mqlQuery);
    url.put("key", apikey);
    url.put("cursor", cursor);
    logger.debug("QUERY URL: " + url.toString());
    HttpRequest request = requestFactory.buildGetRequest(url);
    HttpResponse httpResponse = request.execute();
    JSONObject response = (JSONObject) parser.parse(httpResponse.parseAsString());
    return response;
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) NetHttpTransport(com.google.api.client.http.javanet.NetHttpTransport) HttpTransport(com.google.api.client.http.HttpTransport) JSONObject(org.json.simple.JSONObject) HttpRequestFactory(com.google.api.client.http.HttpRequestFactory) NetHttpTransport(com.google.api.client.http.javanet.NetHttpTransport) HttpResponse(com.google.api.client.http.HttpResponse) JSONParser(org.json.simple.parser.JSONParser) GenericUrl(com.google.api.client.http.GenericUrl)

Example 67 with JSONParser

use of org.json.simple.parser.JSONParser in project cogcomp-nlp by CogComp.

the class QueryMQL method lookupMidFromTitle.

//	public List<String> lookupType(String title) throws Exception{
//		List<String> ans = new ArrayList<String>();
//		
//		if (this.title_types.containsKey(title)) {
//			ans = title_types.get(title);
//			return ans;
//		} else {
//			try{
//				String mid = this.lookupMid(this.buildQuery(null, "/wikipedia/en", QueryMQL.encodeMQL(title)));
//				MQLQueryWrapper mql = this.buildQuery(mid);
//				JSONObject response;
//				String mqlQuery = mql.MQLquery;
//				response = getResponse(mqlQuery);
//				JSONObject result = (JSONObject) response.get("result");
//				if (result != null) {
//					JSONArray types = (JSONArray) result.get("type");
//					for (Object value : types) {
//						ans.add(value.toString());
//					}
//				}
//			} catch (HttpResponseException e){
//				logger.info("title: "+title);
//				e.printStackTrace();
//				if(e.getStatusCode() == 403)
//					System.exit(0);
//			}
//		}
//		return ans;
//	}
public String lookupMidFromTitle(MQLQueryWrapper mql) throws Exception {
    JSONObject response;
    String mqlQuery = mql.MQLquery;
    logger.debug("QUERY IS " + mqlQuery);
    String title = mql.value;
    String checksum = getMD5Checksum(title);
    // first check mid in cache
    if (IOUtils.exists(typeCacheLocation + "/" + checksum + ".cached")) {
        found++;
        logger.info("Found! " + found);
        JSONParser jsonParser = new JSONParser();
        response = (JSONObject) jsonParser.parse(FileUtils.readFileToString(new File(typeCacheLocation + "/" + checksum + ".cached"), "UTF-8"));
    } else {
        response = getResponse(mqlQuery);
        if (response == null)
            return null;
        cacheMiss++;
        logger.info("Caching " + cacheMiss);
        FileUtils.writeStringToFile(new File(typeCacheLocation + "/" + checksum + ".cached"), response.toString(), "UTF-8");
    }
    JSONObject result = (JSONObject) response.get("result");
    if (result != null) {
        return (String) result.get("mid");
    }
    return null;
}
Also used : JSONObject(org.json.simple.JSONObject) JSONParser(org.json.simple.parser.JSONParser) File(java.io.File)

Example 68 with JSONParser

use of org.json.simple.parser.JSONParser in project cogcomp-nlp by CogComp.

the class QueryMQL method lookupTypeFromTitle.

public List<String> lookupTypeFromTitle(MQLQueryWrapper mql) throws Exception {
    List<String> ans = new ArrayList<String>();
    JSONObject response;
    String mqlQuery = mql.MQLquery;
    logger.debug("QUERY IS " + mqlQuery);
    String title = mql.value;
    String checksum = getMD5Checksum(title);
    // first check mid in cache
    if (IOUtils.exists(typeCacheLocation + "/" + checksum + ".cached")) {
        found++;
        logger.info("Found! " + found);
        JSONParser jsonParser = new JSONParser();
        response = (JSONObject) jsonParser.parse(FileUtils.readFileToString(new File(typeCacheLocation + "/" + checksum + ".cached"), "UTF-8"));
    } else {
        response = getResponse(mqlQuery);
        if (response == null)
            return ans;
        cacheMiss++;
        logger.info("Caching " + cacheMiss);
        FileUtils.writeStringToFile(new File(typeCacheLocation + "/" + checksum + ".cached"), response.toString(), "UTF-8");
    }
    JSONObject result = (JSONObject) response.get("result");
    if (result != null) {
        JSONArray types = (JSONArray) result.get("type");
        for (Object value : types) {
            ans.add(value.toString());
        }
    }
    return ans;
}
Also used : JSONObject(org.json.simple.JSONObject) ArrayList(java.util.ArrayList) JSONArray(org.json.simple.JSONArray) JSONParser(org.json.simple.parser.JSONParser) JSONObject(org.json.simple.JSONObject) File(java.io.File)

Example 69 with JSONParser

use of org.json.simple.parser.JSONParser in project ddf by codice.

the class RrdMetricsRetrieverTest method testMetricsJsonDataWithCounter.

@Test
public void testMetricsJsonDataWithCounter() throws Exception {
    String rrdFilename = TEST_DIR + "queryCount_Counter" + RRD_FILE_EXTENSION;
    long endTime = new RrdFileBuilder().rrdFileName(rrdFilename).build();
    MetricsRetriever metricsRetriever = new RrdMetricsRetriever();
    String json = metricsRetriever.createJsonData("queryCount", rrdFilename, START_TIME, endTime);
    JSONParser parser = new JSONParser();
    JSONObject jsonObj = (JSONObject) parser.parse(json);
    // Verify the title, totalCount, and data (i.e., samples) are present
    assertThat(jsonObj.size(), equalTo(3));
    assertThat(jsonObj.get("title"), not(nullValue()));
    assertThat(jsonObj.get("totalCount"), not(nullValue()));
    // Verify 2 samples were retrieved from the RRD file and put in the JSON fetch results
    JSONArray samples = (JSONArray) jsonObj.get("data");
    // 6 because that's the max num rows configured for
    assertThat(samples.size(), equalTo(6));
    // Verify each retrieved sample has a timestamp and value
    for (int i = 0; i < samples.size(); i++) {
        JSONObject sample = (JSONObject) samples.get(i);
        LOGGER.debug("timestamp = {},   value= {}", (String) sample.get("timestamp"), sample.get("value"));
        assertThat(sample.get("timestamp"), not(nullValue()));
        assertThat(sample.get("value"), not(nullValue()));
    }
}
Also used : JSONObject(org.json.simple.JSONObject) JSONArray(org.json.simple.JSONArray) MetricsRetriever(ddf.metrics.reporting.internal.MetricsRetriever) JSONParser(org.json.simple.parser.JSONParser) Test(org.junit.Test)

Example 70 with JSONParser

use of org.json.simple.parser.JSONParser in project tika by apache.

the class NLTKNERecogniser method recognise.

/**
     * recognises names of entities in the text
     * @param text text which possibly contains names
     * @return map of entity type -> set of names
     */
public Map<String, Set<String>> recognise(String text) {
    Map<String, Set<String>> entities = new HashMap<>();
    try {
        String url = restHostUrlStr + "/nltk";
        Response response = WebClient.create(url).accept(MediaType.TEXT_HTML).post(text);
        int responseCode = response.getStatus();
        if (responseCode == 200) {
            String result = response.readEntity(String.class);
            JSONParser parser = new JSONParser();
            JSONObject j = (JSONObject) parser.parse(result);
            Iterator<?> keys = j.keySet().iterator();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                if (!key.equals("result")) {
                    ENTITY_TYPES.add(key);
                    entities.put(key.toUpperCase(Locale.ENGLISH), new HashSet((Collection) j.get(key)));
                }
            }
        }
    } catch (Exception e) {
        LOG.debug(e.getMessage(), e);
    }
    return entities;
}
Also used : Response(javax.ws.rs.core.Response) Set(java.util.Set) HashSet(java.util.HashSet) JSONObject(org.json.simple.JSONObject) HashMap(java.util.HashMap) Collection(java.util.Collection) JSONParser(org.json.simple.parser.JSONParser) IOException(java.io.IOException) HashSet(java.util.HashSet)

Aggregations

JSONParser (org.json.simple.parser.JSONParser)200 JSONObject (org.json.simple.JSONObject)168 JSONArray (org.json.simple.JSONArray)73 ParseException (org.json.simple.parser.ParseException)49 HttpClient (org.apache.commons.httpclient.HttpClient)44 GetMethod (org.apache.commons.httpclient.methods.GetMethod)34 Test (org.junit.Test)28 HashMap (java.util.HashMap)23 Map (java.util.Map)19 IOException (java.io.IOException)18 File (java.io.File)16 Before (org.junit.Before)15 URL (java.net.URL)14 ArrayList (java.util.ArrayList)13 InputStreamReader (java.io.InputStreamReader)12 PostMethod (org.apache.commons.httpclient.methods.PostMethod)11 MapLayer (au.org.emii.portal.menu.MapLayer)9 Point (com.vividsolutions.jts.geom.Point)9 FileReader (java.io.FileReader)9 InputStream (java.io.InputStream)7