Example usage for org.json.simple JSONValue parse

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

Introduction

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

Prototype

public static Object parse(String s) 

Source Link

Usage

From source file:com.backelite.sonarqube.objectivec.issues.fauxpas.FauxPasRulesDefinition.java

private void loadRules(NewRepository repository) throws IOException {

    Reader reader = new BufferedReader(
            new InputStreamReader(getClass().getResourceAsStream(RULES_FILE), CharEncoding.UTF_8));

    String jsonString = IOUtils.toString(reader);

    Object rulesObj = JSONValue.parse(jsonString);

    if (rulesObj != null) {
        JSONArray slRules = (JSONArray) rulesObj;
        for (Object obj : slRules) {
            JSONObject fpRule = (JSONObject) obj;

            RulesDefinition.NewRule rule = repository.createRule((String) fpRule.get("key"));
            rule.setName((String) fpRule.get("name"));
            rule.setSeverity((String) fpRule.get("severity"));
            rule.setHtmlDescription((String) fpRule.get("description"));

        }//from w ww  .jav  a2s  . c  o  m
    }

}

From source file:com.domsplace.DomBot.Object.Responders.DomBotWhatWeather.java

@Override
public boolean response(DomBotResponse response, DomBotResponseThread thread) {
    if (!response.getBasicResponse().toLowerCase().startsWith("dombot"))
        return true;
    if (!response.hasArgStartsWith("what"))
        return true;
    if (!response.hasArgStartsWith("weather"))
        return true;
    if (!response.hasArgStartsWith("in"))
        return true;

    String[] args = response.getArgs();
    int index = -1;
    for (int i = 0; i < args.length; i++) {
        if (!args[i].equalsIgnoreCase("in"))
            continue;
        index = i;/* w  ww  .j  av a 2 s  .c  o m*/
        break;
    }
    if (index < 0)
        return true;
    if (index >= args.length - 1)
        return true;

    String loc = "";
    for (int i = index + 1; i < args.length; i++) {
        loc += args[i] + " ";
    }
    loc = Base.trim(loc, loc.length() - 1);

    loc = loc.replaceAll(", ", ",");
    try {
        loc = "http://api.openweathermap.org/data/2.5/weather?q=" + URLEncoder.encode(loc, "ISO-8859-1");
        URL url = new URL(loc);

        URLConnection urlCon = url.openConnection();

        BufferedReader reader = new BufferedReader(new InputStreamReader(urlCon.getInputStream()));
        String r = reader.readLine();

        JSONObject obj = (JSONObject) JSONValue.parse(r);
        //JSONObject obj = (JSONObject) array.get(0);

        String country = ((JSONObject) obj.get("sys")).get("country").toString();
        String weather = ((JSONObject) ((JSONArray) obj.get("weather")).get(0)).get("main").toString();
        String temp = ((JSONObject) obj.get("main")).get("temp").toString();
        double temperature = Base.getDouble(temp) - 273.15d;
        String location = obj.get("name").toString();

        talk(new String[] { "The weather in " + location + ", " + country + " is " + weather + ", "
                + Base.twoDecimalPlaces(temperature) + "C" });
        return false;
    } catch (Exception ex) {
        talk(new String[] { "I don't know where that is." });
        return false;
    }
}

From source file:biomine.bmvis2.pipeline.GraphOperationSerializer.java

public static Map<String, Double> getNodesOfInterest(String json) {
    JSONArray arr = (JSONArray) JSONValue.parse(json);
    return getNodesOfInterest(arr);
}

From source file:com.noelportugal.amazonecho.WitAi.java

public WitEntity getEntity(String text) {
    WitEntity witEntity = new WitEntity();

    try {/*from  w w w.ja  v a2 s. com*/
        String json = getJson(text);

        //System.out.println(json);

        Object obj = JSONValue.parse(json);
        JSONObject jsonObject = (JSONObject) obj;
        JSONArray values = (JSONArray) jsonObject.get("outcomes");
        JSONObject outcome = (JSONObject) values.get(0);

        JSONObject entities = (JSONObject) outcome.get("entities");

        JSONArray subject = (JSONArray) entities.get("message_subject");
        JSONObject subject_value = (JSONObject) subject.get(0);
        witEntity.setSubject(subject_value.get("value").toString());

        JSONArray state = (JSONArray) entities.get("on_off");
        JSONObject state_value = (JSONObject) state.get(0);
        witEntity.setState(state_value.get("value").toString());

    } catch (Exception e) {
        witEntity = null;
    }

    return witEntity;
}

From source file:ly.stealth.punxsutawney.Marathon.java

private static JSONObject sendRequest(String uri, String method, JSONObject json) throws IOException {
    URL url = new URL(Marathon.url + uri);
    HttpURLConnection c = (HttpURLConnection) url.openConnection();
    try {/*w w  w  .j  a v  a 2s  .c o  m*/
        c.setRequestMethod(method);

        if (method.equalsIgnoreCase("POST")) {
            byte[] body = json.toString().getBytes("utf-8");
            c.setDoOutput(true);
            c.setRequestProperty("Content-Type", "application/json");
            c.setRequestProperty("Content-Length", "" + body.length);
            c.getOutputStream().write(body);
        }

        return (JSONObject) JSONValue.parse(new InputStreamReader(c.getInputStream(), "utf-8"));
    } catch (IOException e) {
        if (c.getResponseCode() == 404 && method.equals("GET"))
            return null;

        ByteArrayOutputStream response = new ByteArrayOutputStream();
        InputStream err = c.getErrorStream();
        if (err == null)
            throw e;

        Util.copyAndClose(err, response);
        IOException ne = new IOException(e.getMessage() + ": " + response.toString("utf-8"));
        ne.setStackTrace(e.getStackTrace());
        throw ne;
    } finally {
        c.disconnect();
    }
}

From source file:com.bigdata.dastor.client.RingCache.java

public void refreshEndPointMap() {
    for (String seed : seeds_) {
        try {/* ww w  . j  a v  a  2  s. c  o m*/
            TSocket socket = new TSocket(seed, port_);
            TBinaryProtocol binaryProtocol = new TBinaryProtocol(socket, false, false);
            Dastor.Client client = new Dastor.Client(binaryProtocol);
            socket.open();

            Map<String, String> tokenToHostMap = (Map<String, String>) JSONValue
                    .parse(client.get_string_property(DastorThriftServer.TOKEN_MAP));

            BiMap<Token, InetAddress> tokenEndpointMap = HashBiMap.create();
            for (Map.Entry<String, String> entry : tokenToHostMap.entrySet()) {
                Token token = StorageService.getPartitioner().getTokenFactory().fromString(entry.getKey());
                String host = entry.getValue();
                try {
                    tokenEndpointMap.put(token, InetAddress.getByName(host));
                } catch (UnknownHostException e) {
                    throw new AssertionError(e); // host strings are IPs
                }
            }

            tokenMetadata = new TokenMetadata(tokenEndpointMap);

            break;
        } catch (TException e) {
            /* let the Exception go and try another seed. log this though */
            logger_.debug("Error contacting seed " + seed + " " + e.getMessage());
        }
    }
}

From source file:formatter.handler.post.FormatterPostHandler.java

/**
 * Process a field we recognise/*from w w  w.  j  a  v a  2 s  .  c  o  m*/
 * @param fieldName the field's name
 * @param contents its contents
 */
void processField(String fieldName, String contents) {
    //System.out.println("Received field "+fieldName);
    if (fieldName.equals(Params.DOCID))
        docid = contents;
    if (fieldName.equals(Params.VERSION1))
        version1 = contents;
    else if (fieldName.equals(Params.USERDATA)) {
        String key = "I tell a settlers tale of the old times";
        int klen = key.length();
        char[] data = Base64.decode(contents);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < data.length; i++)
            sb.append((char) (data[i] ^ key.charAt(i % klen)));
        String json = sb.toString();
        //            System.out.println( "USERDATA: decoded json data="+json);
        userdata = (JSONObject) JSONValue.parse(json);
        //            System.out.println("json="+json);
        //            System.out.println( "user was "+userdata.get(JSONKeys.NAME));
        JSONArray roles = (JSONArray) userdata.get(JSONKeys.ROLES);
        //            if ( roles.size()>0 )
        //                System.out.println("role was "+roles.get(0));
        if (roles != null)
            for (int i = 0; i < roles.size(); i++)
                if (((String) roles.get(i)).equals("editor"))
                    isEditor = true;
    }
}

From source file:bhl.pages.handler.PagesCropRectHandler.java

/**
 * Get the plain text of a page. Assume parameters version1, pageid 
 * (image file name minus extension) and docid. Assume also that there 
 * is a corcode at docid/pages. (Should already have checked for this)
 * @param request the original http request
 * @param response the response/*  w  ww . j av a2 s .co  m*/
 * @param urn the urn used for the request
 * @throws MissingDocumentException 
 */
public void handle(HttpServletRequest request, HttpServletResponse response, String urn)
        throws MissingDocumentException {
    try {
        Connection conn = Connector.getConnection();
        String pageid = request.getParameter(Params.PAGEID);
        Integer num = new Integer(pageid);
        String content = conn.getFromDbByIntField(Database.PAGES, num.intValue(), JSONKeys.BHL_PAGE_ID);
        JSONObject jobj = (JSONObject) JSONValue.parse(content);
        JSONArray cropRect = (JSONArray) jobj.get(JSONKeys.CROP_RECT);
        if (cropRect == null)
            cropRect = getDefaultCropRect();
        response.setContentType("text/plain;charset=UTF-8");
        response.getWriter().println(cropRect.toJSONString());
    } catch (Exception e) {
        throw new MissingDocumentException(e);
    }
}

From source file:importer.handler.get.ImporterGetHandler.java

/**
 * Fetch and load an MVD/*www.  j av  a2 s.  c om*/
 * @param db the database 
 * @param docID
 * @return the loaded MVD
 * @throws an ImporterException if not found
 */
protected EcdosisMVD loadMVD(String db, String docID) throws ImporterException {
    try {
        String data = Connector.getConnection().getFromDb(db, docID);
        if (data.length() > 0) {
            JSONObject doc = (JSONObject) JSONValue.parse(data);
            if (doc != null)
                return new EcdosisMVD(doc);
        }
        throw new ImporterException("MVD not found " + docID);
    } catch (Exception e) {
        throw new ImporterException(e);
    }
}

From source file:biomine.bmvis2.crawling.CrawlerFetch.java

public void update() throws IOException {

    status = URLUtils.getURLContents(statusUrl);
    statusObject = (JSONObject) JSONValue.parse(status);
    JSONObject obj = (JSONObject) JSONValue.parse(status);
    JSONArray errors = ((JSONArray) obj.get("errors"));

    d("obj = " + obj);
    int age = ((Long) obj.get("age")).intValue();
    d("age = " + age);

    lastage = age;//from  w ww .j a v  a 2s.c om
    messages.clear();
    for (Object o : errors) {
        JSONObject error = (JSONObject) o;
        JSONArray mesarr = (JSONArray) error.get("messages");

        for (int i = 0; i < mesarr.size(); i++) {
            String err = mesarr.get(i).toString();
            messages.add(err);
            d("err = " + err);
        }
    }

    JSONArray mesarr = (JSONArray) obj.get("messages");

    for (int i = 0; i < mesarr.size(); i++) {
        String err = mesarr.get(i).toString();
        messages.add(err);
        d("err = " + err);
    }
}