Example usage for org.json.simple JSONValue parseWithException

List of usage examples for org.json.simple JSONValue parseWithException

Introduction

In this page you can find the example usage for org.json.simple JSONValue parseWithException.

Prototype

public static Object parseWithException(String s) throws ParseException 

Source Link

Usage

From source file:de.instantouch.model.io.SnakeJSONReader.java

public Object parse() throws IOException, SnakeModelException {
    Object jsonObject = null;//from w  w w.  j  a  v a2s .c o  m

    try {
        if (content != null) {
            jsonObject = JSONValue.parseWithException(content);
        } else if (reader != null) {
            jsonObject = JSONValue.parseWithException(reader);
        }
    } catch (ParseException e) {
        throw new SnakeModelException(e);
    }

    return jsonObject;
}

From source file:com.johncroth.histo.logging.LogHistogramParser.java

public void parse(Reader reader) throws Exception {
    BufferedReader r = new BufferedReader(reader);
    boolean expectingJson = false;
    String line = r.readLine();//  w w  w .j  a  v  a2s  .c o  m
    while (line != null) {
        EventType type = EventType.IGNORED;
        Object detail = null;
        if (line.startsWith(MESSAGE_START_LINE)) {
            if (expectingJson) {
                type = EventType.ERROR;
                detail = "Duplicate message start.";
                notifyListeners(type, line, detail);
            }
            expectingJson = true;
        } else {
            if (expectingJson) {
                try {
                    Object jv = JSONValue.parseWithException(line);
                    RecordedInterval<LogHistogramRecorder> ri = parseIntervalJson((JSONObject) jv);
                    type = EventType.INTERVAL_READ;
                    detail = ri;
                } catch (Exception e) {
                    type = EventType.ERROR;
                    detail = e;
                }
                expectingJson = false;
            }
        }
        if (!expectingJson) {
            notifyListeners(type, line, detail);
        }
        line = r.readLine();
    }

}

From source file:eu.edisonproject.training.wsd.WikiRequestor.java

private Map<String, List<String>> getWikidataNumProperty() throws IOException, ParseException {
    String jsonString = IOUtils.toString(url);
    Map<String, List<String>> map = new HashMap<>();
    JSONObject jsonObj = (JSONObject) JSONValue.parseWithException(jsonString);

    JSONObject claims = (JSONObject) jsonObj.get("claims");
    //        "?action=wbgetclaims&format=json&props=&property=" + prop + "&entity="
    String prop = getPropertyName();

    JSONArray Jprop = (JSONArray) claims.get(prop);
    List<String> ids = new ArrayList<>();
    if (Jprop != null) {
        for (Object obj : Jprop) {
            JSONObject jobj = (JSONObject) obj;

            JSONObject mainsnak = (JSONObject) jobj.get("mainsnak");
            //                System.err.println(mainsnak);
            JSONObject datavalue = (JSONObject) mainsnak.get("datavalue");
            //                System.err.println(datavalue);
            if (datavalue != null) {
                JSONObject value = (JSONObject) datavalue.get("value");
                //            System.err.println(value);
                java.lang.Long numericID = (java.lang.Long) value.get("numeric-id");
                //                System.err.println(id + " -> Q" + numericID);
                ids.add("Q" + numericID);
            }/*from  w ww.j  a  v  a 2  s. c  o  m*/
        }
    }
    map.put(termUID, ids);
    return map;
}

From source file:com.bigfatgun.fixjures.json.JSONSource.java

private Object parseJson(final String json) {
    assert json != null : "JSON data cannot be null.";
    try {/*w  w w.  ja  va2 s .  c o  m*/
        return JSONValue.parseWithException(json);
    } catch (ParseException e) {
        return FixtureException.convertAndThrowAs(e);
    }
}

From source file:eu.edisonproject.training.wsd.Wikipedia.java

protected Set<String> getTitles(String lemma) throws ParseException, UnsupportedEncodingException, IOException {
    String URLquery = lemma.replaceAll("_", " ");
    URLquery = URLEncoder.encode(URLquery, "UTF-8");
    //sroffset=10
    URL url = new URL(
            PAGE + "?action=query&format=json&redirects&list=search&srlimit=500&srsearch=" + URLquery);
    Logger.getLogger(Wikipedia.class.getName()).log(Level.FINE, url.toString());
    String jsonString = IOUtils.toString(url);

    Set<String> titles = new TreeSet<>();
    JSONObject jsonObj = (JSONObject) JSONValue.parseWithException(jsonString);
    JSONObject query = (JSONObject) jsonObj.get("query");
    JSONArray search = (JSONArray) query.get("search");
    if (search != null) {
        for (Object o : search) {
            JSONObject res = (JSONObject) o;
            String title = (String) res.get("title");
            //                System.err.println(title);
            if (title != null && !title.toLowerCase().contains("(disambiguation)")) {
                //                if (title != null) {
                title = title.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
                title = title.replaceAll("\\+", "%2B");
                title = java.net.URLDecoder.decode(title, "UTF-8");
                title = title.replaceAll("_", " ").toLowerCase();
                lemma = java.net.URLDecoder.decode(lemma, "UTF-8");
                lemma = lemma.replaceAll("_", " ");
                titles.add(title);//from  www. java2 s  .  c  o m
            }

        }
    }
    titles.add(lemma);
    return titles;
}

From source file:com.bigdata.dastor.tools.SSTableImport.java

/**
 * Convert a JSON formatted file to an SSTable.
 * /*ww  w.  j  av  a 2s .com*/
 * @param jsonFile the file containing JSON formatted data
 * @param keyspace keyspace the data belongs to
 * @param cf column family the data belongs to
 * @param ssTablePath file to write the SSTable to
 * @throws IOException for errors reading/writing input/output
 * @throws ParseException for errors encountered parsing JSON input
 */
public static void importJson(String jsonFile, String keyspace, String cf, String ssTablePath)
        throws IOException, ParseException {
    ColumnFamily cfamily = ColumnFamily.create(keyspace, cf);
    String cfType = cfamily.type(); // Super or Standard
    IPartitioner<?> partitioner = DatabaseDescriptor.getPartitioner();
    DataOutputBuffer headerBuffer = new DataOutputBuffer(); // BIGDATA
    DataOutputBuffer dob = new DataOutputBuffer();

    try {
        JSONObject json = (JSONObject) JSONValue.parseWithException(new FileReader(jsonFile));

        SSTableWriter writer = new SSTableWriter(ssTablePath, json.size(), partitioner);
        List<DecoratedKey<?>> decoratedKeys = new ArrayList<DecoratedKey<?>>();

        for (String key : (Set<String>) json.keySet())
            decoratedKeys.add(partitioner.decorateKey(key));
        Collections.sort(decoratedKeys);

        for (DecoratedKey<?> rowKey : decoratedKeys) {
            if (cfType.equals("Super"))
                addToSuperCF((JSONObject) json.get(rowKey.key), cfamily);
            else
                addToStandardCF((JSONArray) json.get(rowKey.key), cfamily);

            ColumnFamily.serializer().serializeWithIndexes(cfamily, headerBuffer, dob,
                    DatabaseDescriptor.getCompressAlgo(keyspace, cf)); // BIGDATA
            writer.append(rowKey, headerBuffer, dob);
            headerBuffer.reset(); // BIGDATA
            dob.reset();
            cfamily.clear();
        }

        writer.closeAndOpenReader();
    } catch (ClassCastException cce) {
        throw new RuntimeException("Invalid JSON input, or incorrect column family.", cce);
    }
}

From source file:com.dnastack.ga4gh.impl.BeaconizeVariantImpl.java

/**
 * Queries the Variant API implementation for variants at the given position
 *
 * @param reference The reference (or chromosome)
 * @param position  Position on the reference
 * @param alt       The alternate allele to match against (currently not supported by GASearchVariantsRequest)
 * @return A JSON Object containing a GASearchVariantsResponse
 * @throws IOException    Problems contacting API
 * @throws ParseException Problems parsing response
 *///from  www . j a  va  2 s.c o m
private JSONObject submitVariantSearchRequest(String reference, long position, String alt)
        throws IOException, ParseException {
    JSONObject obj = new JSONObject();

    JSONArray list = new JSONArray();
    list.addAll(Arrays.asList(variantSetIds));

    obj.put("variantSetIds", list);
    obj.put("referenceName", reference);
    obj.put("start", position);
    obj.put("end", (position + 1));

    String json = obj.toJSONString();

    URL url = new URL(fullVariantSearchURL);

    StringBuilder postData = new StringBuilder();
    postData.append(json);

    byte[] postDataBytes = postData.toString().getBytes("UTF-8");

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json");
    conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
    conn.setDoOutput(true);
    conn.getOutputStream().write(postDataBytes);

    StringBuilder sb = new StringBuilder();

    Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
    for (int c; (c = in.read()) >= 0;) {
        sb.append((char) c);
    }

    String jsonString = sb.toString();

    return (JSONObject) JSONValue.parseWithException(jsonString);
}

From source file:eu.edisonproject.training.wsd.WikiRequestor.java

private Map<String, List<String>> getWikidataLables() throws IOException, ParseException {
    String jsonString = IOUtils.toString(url);
    Map<String, List<String>> map = new HashMap<>();
    JSONObject jsonObj = (JSONObject) JSONValue.parseWithException(jsonString);

    JSONObject entities = (JSONObject) jsonObj.get("entities");
    //        System.err.println(entities);
    String catID = this.url.toString().split("ids=")[1];
    JSONObject jID = (JSONObject) entities.get(catID);

    JSONObject labels = (JSONObject) jID.get("labels");
    //        System.err.println(labels);
    JSONObject en = (JSONObject) labels.get("en");
    //        System.err.println(en);
    if (en != null) {
        String value = (String) en.get("value");
        List<String> v = new ArrayList<>();
        v.add(value.substring("Category:".length()).toLowerCase().replaceAll(" ", "_"));
        map.put(termUID, v);/*from  w  w w .  j  a va 2  s  .  c o  m*/
        return map;
    }
    return null;

}

From source file:eu.edisonproject.training.wsd.WikipediaOnline.java

private Set<Term> queryTerms(String jsonString, String originalTerm)
        throws ParseException, IOException, MalformedURLException, InterruptedException, ExecutionException {
    Set<Term> terms = new HashSet<>();
    Set<Term> termsToReturn = new HashSet<>();
    JSONObject jsonObj = (JSONObject) JSONValue.parseWithException(jsonString);
    JSONObject query = (JSONObject) jsonObj.get("query");
    JSONObject pages = (JSONObject) query.get("pages");
    Set<String> keys = pages.keySet();
    for (String key : keys) {
        JSONObject jsonpage = (JSONObject) pages.get(key);
        Term t = TermFactory.create(jsonpage, originalTerm);
        if (t != null) {
            terms.add(t);//w ww  .ja v  a  2s .c o  m
        }
    }
    if (terms.size() > 0) {
        Map<CharSequence, List<CharSequence>> cats = getCategories(terms);
        for (Term t : terms) {
            boolean add = true;
            List<CharSequence> cat = cats.get(t.getUid());
            t.setCategories(cat);
            for (CharSequence g : t.getGlosses()) {
                if (g != null && g.toString().contains("may refer to:")) {
                    Set<Term> referToTerms = getReferToTerms(g.toString(), originalTerm);
                    if (referToTerms != null) {
                        for (Term rt : referToTerms) {
                            String url = "https://en.wikipedia.org/?curid=" + rt.getUid();
                            rt.setUrl(url);
                            termsToReturn.add(rt);
                        }
                    }
                    add = false;
                    break;
                }
            }
            if (add) {
                String url = "https://en.wikipedia.org/?curid=" + t.getUid();
                t.setUrl(url);
                termsToReturn.add(t);
            }
        }
    }
    return termsToReturn;
}

From source file:eu.edisonproject.training.wsd.Wikidata.java

private Set<Term> queryTerms(String jsonString, String originalTerm)
        throws ParseException, IOException, MalformedURLException, InterruptedException, ExecutionException {
    Set<Term> terms = new HashSet<>();

    JSONObject jsonObj = (JSONObject) JSONValue.parseWithException(jsonString);
    JSONArray search = (JSONArray) jsonObj.get("search");

    for (Object obj : search) {
        JSONObject jObj = (JSONObject) obj;
        String label = (String) jObj.get("label");
        if (label != null && !label.toLowerCase().contains("(disambiguation)")) {

            label = label.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
            label = label.replaceAll("\\+", "%2B");
            label = java.net.URLDecoder.decode(label, "UTF-8");
            label = label.replaceAll("_", " ").toLowerCase();
            originalTerm = java.net.URLDecoder.decode(originalTerm, "UTF-8");
            originalTerm = originalTerm.replaceAll("_", " ");

            stemer.setDescription(label);
            String stemTitle = stemer.execute();

            stemer.setDescription(originalTerm);
            String stemLema = stemer.execute();

            int dist = edu.stanford.nlp.util.StringUtils.editDistance(stemLema, stemTitle);
            if (stemTitle.contains(stemLema) && dist <= 10) {
                String url = null;
                Term t = new Term();
                t.setLemma(label);//ww w  . ja v  a  2  s  .c o m
                t.setUrl(url);
                t.setOriginalTerm(originalTerm);
                JSONArray aliases = (JSONArray) jObj.get("aliases");
                if (aliases != null) {
                    List<CharSequence> altLables = new ArrayList<>();
                    for (Object aObj : aliases) {
                        String alt = (String) aObj;
                        altLables.add(alt);
                    }
                    t.setAltLables(altLables);
                }
                String description = (String) jObj.get("description");
                if (description == null
                        || !description.toLowerCase().contains("wikipedia disambiguation page")) {
                    String id = (String) jObj.get("id");
                    url = "https://www.wikidata.org/wiki/" + id;
                    t.setUrl(url);
                    List<CharSequence> glosses = new ArrayList<>();
                    glosses.add(description);
                    t.setGlosses(glosses);
                    t.setUid(id);

                    //                        List<String> broaderID = getBroaderID(id);
                    //                        t.setBroaderUIDS(broaderID);
                    //                        List<String> cat = getCategories(id);
                    //                        t.setCategories(cat);
                    terms.add(t);
                }
            }
        }
    }
    Set<Term> catTerms = new HashSet<>();

    Map<CharSequence, List<CharSequence>> cats = getCategories(terms);
    for (Term t : terms) {
        List<CharSequence> cat = cats.get(t.getUid());
        t.setCategories(cat);
        catTerms.add(t);
    }

    Map<CharSequence, List<CharSequence>> broaderIDs = getbroaderIDS(terms);
    Set<Term> returnTerms = new HashSet<>();
    for (Term t : catTerms) {
        List<CharSequence> broaderID = broaderIDs.get(t.getUid());
        t.setBuids(broaderID);
        returnTerms.add(t);
    }

    return returnTerms;
}