Example usage for org.json.simple JSONObject get

List of usage examples for org.json.simple JSONObject get

Introduction

In this page you can find the example usage for org.json.simple JSONObject get.

Prototype

V get(Object key);

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Usage

From source file:msuresh.raftdistdb.RaftClient.java

public static void SetValue(String name, String key, String value) throws FileNotFoundException {
    if (key == null || key.isEmpty()) {
        return;/*w  w w. jav a 2 s  . co  m*/
    }
    File configFile = new File(Constants.STATE_LOCATION + name + ".info");
    if (!configFile.exists() || configFile.isDirectory()) {
        FileNotFoundException ex = new FileNotFoundException();
        throw ex;
    }
    try {
        System.out.println("Adding key .. hold on..");
        String content = new Scanner(configFile).useDelimiter("\\Z").next();
        JSONObject config = (JSONObject) (new JSONParser()).parse(content);
        Long numPart = (Long) config.get("countPartitions");
        Integer shardId = key.hashCode() % numPart.intValue();
        JSONArray memberJson = (JSONArray) config.get(shardId.toString());
        List<Address> members = new ArrayList<>();
        for (int i = 0; i < memberJson.size(); i++) {
            JSONObject obj = (JSONObject) memberJson.get(i);
            Long port = (Long) obj.get("port");
            String address = (String) obj.get("address");
            members.add(new Address(address, port.intValue()));
        }
        CopycatClient client = CopycatClient.builder(members).withTransport(new NettyTransport()).build();
        client.open().join();
        client.submit(new PutCommand(key, value)).get();
        client.close().join();
        while (client.isOpen()) {
            Thread.sleep(1000);
        }
        System.out.println("key " + key + " with value : " + value + " has been added to the cluster");
    } catch (Exception ex) {
        System.out.println(ex.toString());
    }
}

From source file:msuresh.raftdistdb.RaftClient.java

public static void GetValue(String name, String key) throws FileNotFoundException {
    if (key == null || key.isEmpty()) {
        return;/*  w  w w  . ja v a  2  s .  c o m*/
    }
    File configFile = new File(Constants.STATE_LOCATION + name + ".info");
    if (!configFile.exists() || configFile.isDirectory()) {
        FileNotFoundException ex = new FileNotFoundException();
        throw ex;
    }
    try {
        System.out.println("Getting key .. Hold on.");
        String content = new Scanner(configFile).useDelimiter("\\Z").next();
        JSONObject config = (JSONObject) (new JSONParser()).parse(content);
        Long numPart = (Long) config.get("countPartitions");
        Integer shardId = key.hashCode() % numPart.intValue();
        JSONArray memberJson = (JSONArray) config.get(shardId.toString());
        List<Address> members = new ArrayList<>();
        for (int i = 0; i < memberJson.size(); i++) {
            JSONObject obj = (JSONObject) memberJson.get(i);
            Long port = (Long) obj.get("port");
            String address = (String) obj.get("address");
            members.add(new Address(address, port.intValue()));
        }
        CopycatClient client = CopycatClient.builder(members).withTransport(new NettyTransport()).build();
        client.open().join();
        Object str = client.submit(new GetQuery(key)).get();
        System.out.println("For the key : " + key + ", the database returned the value : " + (String) str);
        client.close().join();
        while (client.isOpen()) {
            Thread.sleep(1000);
        }
    } catch (Exception ex) {
        System.out.println(ex.toString());
    }
}

From source file:iracing.webapi.SeasonStandingsParser.java

public static long parse(String json, ItemHandler handler) {
    JSONParser parser = new JSONParser();
    //        System.err.println(json);
    long output = 0;
    try {//from w  w  w .  java  2s  . c o  m
        JSONObject root = (JSONObject) parser.parse(json);
        JSONObject arrayRoot = (JSONObject) root.get("d");
        output = getLong(arrayRoot, "27");
        JSONArray results = (JSONArray) arrayRoot.get("r");
        for (int i = 0; i < results.size(); i++) {
            JSONObject result = (JSONObject) results.get(i);
            SeasonStanding standing = new SeasonStanding();
            standing.setDroppedWeeks(getInt(result, "1"));
            standing.setClubName(getString(result, "2", true));
            standing.setCountryCode(getString(result, "3", true));
            standing.setLicenseSubLevel(getString(result, "4"));
            standing.setAverageFinish(getInt(result, "5"));
            standing.setIrating(getInt(result, "6"));
            standing.setTotalTopFives(getInt(result, "7"));
            standing.setMaxLicenseLevel(getInt(result, "8"));
            standing.setDriverName(getString(result, "9", true));
            standing.setClubId(getInt(result, "10"));
            standing.setTotalStarts(getInt(result, "11"));
            standing.setDisplayCountry(getString(result, "14", true));
            standing.setTotalLapsLed(getInt(result, "13"));
            standing.setCountry(getString(result, "15", true));
            standing.setTotalWins(getInt(result, "16"));
            standing.setTotalIncidents(getInt(result, "17"));
            Object o = result.get("18");
            double d;
            if (o instanceof Long) {
                Long l = (Long) o;
                d = l.doubleValue();
            } else {
                d = (Double) o;
            }
            standing.setTotalPoints(d);
            standing.setRank(getInt(result, "20"));
            standing.setDivision(getInt(result, "22"));
            standing.setDriverCustomerId(getLong(result, "24"));
            standing.setWeeksCounted(getInt(result, "26"));
            standing.setTotalLaps(getLong(result, "28"));
            standing.setAverageStart(getInt(result, "29"));
            standing.setTotalPoles(getInt(result, "30"));
            standing.setPosition(getLong(result, "31"));
            if (!handler.onSeasonStandingParsed(standing))
                break;
        }
    } catch (ParseException ex) {
        Logger.getLogger(SeasonStandingsParser.class.getName()).log(Level.SEVERE, null, ex);
    }
    return output;
}

From source file:me.timothy.ddd.quests.Quest_LearnAboutGant.java

public static Quest_LearnAboutGant fromObject(QuestManager qManager, JSONObject object) {
    Quest_LearnAboutGant result = new Quest_LearnAboutGant(qManager);
    result.talkCounter = ((Number) object.get("talkCounter")).intValue();
    return result;
}

From source file:models.Snack.java

public static ArrayList getsnackList() throws IOException {
    ArrayList<Snack> snackList = new ArrayList();

    try {//w ww  .j  av a2 s. c  o  m

        InputStream input = new URL(url).openStream();
        String genreJson = IOUtils.toString(input);

        JSONParser parser = new JSONParser();

        JSONArray tileJson = (JSONArray) parser.parse(genreJson);

        for (Object object : tileJson) {
            JSONObject aJson = (JSONObject) object;

            long id = (Long) aJson.get("id");
            String name = (String) aJson.get("name");
            boolean opt = (Boolean) aJson.get("optional");
            String loc = (String) aJson.get("purchaseLocations");
            long count = (Long) aJson.get("purchaseCount");
            String date = (String) aJson.get("lastPurchaseDate");
            JSONArray imgSize = (JSONArray) aJson.get("size");
            snackList.add(new Snack(id, name, opt, loc, count, date));

        }

    } catch (ParseException e) {
        e.printStackTrace();
    }

    return snackList;
}

From source file:myproject.MyServer.java

public static void Add(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {/*  www . j a  v a2s.c  o  m*/
        String jsonString = IOUtils.toString(request.getInputStream());
        JSONObject json = (JSONObject) JSONValue.parse(jsonString);
        String student_name = (String) json.get("student_name");
        Long regno = (Long) json.get("regno");
        Double cgpa = (Double) json.get("cgpa");

        String query = String.format(
                "INSERT INTO student " + "(student_name, regno, cgpa) " + "VALUES('%s',%d,%f)",
                JSONValue.escape(student_name), regno, cgpa);

        database.runUpdate(query);

        String result = database.getStudent(regno);
        response.getWriter().write(result);
    } catch (Exception ex) {
        JSONObject output = new JSONObject();
        output.put("error", "Connection failed: " + ex.getMessage());
        response.getWriter().write(JSONValue.toJSONString(output));
    }
}

From source file:cc.vidr.datum.util.FreebaseUtils.java

/**
 * Return the list of JSON objects returned by the API for the given query.
 * //from   w  ww . ja v a 2s .c  o m
 * @param path  the API service path
 * @return      the list of JSON objects
 * @throws      IOException if there was an error communicating with the
 *              server
 * @throws      ParseException if the server returns malformed JSON
 */
@SuppressWarnings("unchecked")
public static List<JSONObject> getResultList(String path) throws IOException, ParseException {
    URLConnection connection = new URL(endpoint + path).openConnection();
    connection.connect();
    InputStream stream = connection.getInputStream();
    Reader reader = new InputStreamReader(stream);
    JSONObject o = (JSONObject) JSONValue.parse(reader);
    return (List<JSONObject>) o.get("result");
}

From source file:com.AandC.GemsCraft.Configuration.ConfigKey.java

public static String getServerName() {
    try {//from   w w w  .java 2  s .  c om
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(new FileReader("/sdcard/GemsCraft/config.json"));
        JSONObject jsonObject = (JSONObject) obj;
        ServerName = String.valueOf(jsonObject.get("ServerName"));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return ServerName;
}

From source file:com.serena.rlc.provider.artifactory.domain.ArtifactoryObject.java

public static Object getJSONValue(JSONObject obj, String key) {
    Object retObj = null;/*ww  w  .j  ava 2  s. c  o  m*/
    if (obj.containsKey(key)) {
        return obj.get(key);
    }
    return retObj;
}

From source file:net.sourceforge.fenixedu.dataTransferObject.externalServices.TeacherPublicationsInformation.java

public static Map<Teacher, List<String>> getTeacherPublicationsInformations(Set<Teacher> teachers) {
    Map<Teacher, List<String>> teacherPublicationsInformationMap = new HashMap<Teacher, List<String>>();

    Client client = ClientBuilder.newClient();
    WebTarget resource = client.target(BASE_URL);
    List<String> teacherIds = new ArrayList<String>();

    for (Teacher teacher : teachers) {
        teacherIds.add(teacher.getTeacherId());
    }/*from  w w  w.j a v a2s  . c om*/

    resource = resource.path(CURRICULUM_PATH).queryParam("istids", StringUtils.join(teacherIds, ","));
    try {
        String allPublications = resource.request().get(String.class);
        JSONParser parser = new JSONParser();
        for (Object teacherPublications : (JSONArray) parser.parse(allPublications)) {
            JSONObject teacherPublicationsInfo = (JSONObject) teacherPublications;
            final String username = (String) teacherPublicationsInfo.get("istID");
            final Teacher teacher = Teacher.readByIstId(username);
            JSONArray preferredPublications = (JSONArray) teacherPublicationsInfo.get("preferred");

            List<String> teacherPublicationsList = new ArrayList<String>();
            for (Object publication : preferredPublications) {
                teacherPublicationsList.add(publication.toString());
            }

            teacherPublicationsInformationMap.put(teacher, teacherPublicationsList);
        }
    } catch (ParseException e) {
        logger.error(e.getMessage(), e);
    } finally {
        client.close();
    }

    return teacherPublicationsInformationMap;
}