Example usage for org.json.simple JSONObject containsKey

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

Introduction

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

Prototype

boolean containsKey(Object key);

Source Link

Document

Returns true if this map contains a mapping for the specified key.

Usage

From source file:gwap.rest.User.java

@PUT
@Consumes(MediaType.APPLICATION_JSON)/*from   w w  w.  j  a  v a2 s. co m*/
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
@Transactional
@Path("/{id:[A-Za-z0-9][A-Za-z0-9]*}")
public Response updateUser(@PathParam("id") String deviceId, String payloadString) {
    log.info("updateUser(#0)", deviceId);
    JSONObject payload = parse(payloadString);
    Query query = entityManager.createNamedQuery("person.byDeviceId");
    query.setParameter("deviceId", deviceId);
    Person person = (Person) query.getSingleResult();

    if (payload.containsKey("username")) { // update user
        person.setExternalUsername(payload.get("username").toString());
    } else { // create new gamesession+gameround
        query = entityManager.createNamedQuery("gameSession.byGameType");
        query.setParameter("gameType", getGameType());
        GameSession gameSession;
        try {
            gameSession = (GameSession) query.getSingleResult();
        } catch (NoResultException e) {
            gameSession = new GameSession();
            gameSession.setGameType(getGameType());
            entityManager.persist(gameSession);
        }

        int score = Integer.parseInt(payload.get("score").toString());
        int playedTime = Integer.parseInt(payload.get("playedTime").toString());
        double coveredDistance = Double.parseDouble(payload.get("coveredDistance").toString());
        boolean successful = Integer.parseInt(payload.get("gamesPlayed").toString()) == 1;

        GameRound gameRound = new GameRound();
        entityManager.persist(gameRound);
        gameRound.setGameSession(gameSession);
        gameRound.setPerson(person);
        gameRound.setScore(score);
        Calendar cal = GregorianCalendar.getInstance();
        gameRound.setEndDate(cal.getTime());
        cal.add(Calendar.MILLISECOND, -1 * playedTime);
        gameRound.setStartDate(cal.getTime());
        gameRound.setCoveredDistance(coveredDistance);
        gameRound.setSuccessful(successful);

        // Unlock new badges
        JSONArray newBadges = (JSONArray) payload.get("badges");
        for (Object o : newBadges) {
            JSONObject badge = (JSONObject) o;
            long badgeId = Long.parseLong(badge.get("id").toString());
            if (Boolean.parseBoolean(badge.get("unlocked").toString())) {
                Badge b = entityManager.find(Badge.class, badgeId);
                person.getBadges().add(b);
            }
        }

    }
    entityManager.flush();
    log.info("Sucessfully updated user with deviceId #0", deviceId);
    return Response.ok().build();
}

From source file:hoot.services.nativeInterfaces.ProcessStreamInterface.java

/**
 * Remove from process queue if job exists
 *
 * @param cmd// www  . j av a  2s. co m
 * @throws Exception
 */
private void removeFromProcessQ(JSONObject cmd) {
    String jobId = "";
    try {
        if (_jobProcesses != null) {
            if (cmd.containsKey("jobId")) {
                jobId = cmd.get("jobId").toString();
                _jobProcesses.remove(jobId);
            }

        }
    } catch (Exception ex) {
        log.error("failed to remove from Q:" + jobId);
    }
}

From source file:de.Keyle.MyPet.skill.skilltreeloader.SkillTreeLoaderJSON.java

protected void loadSkillTree(ConfigurationJSON jsonConfiguration, SkillTreeMobType skillTreeMobType) {
    JSONArray skilltreeList = (JSONArray) jsonConfiguration.getJSONObject().get("Skilltrees");
    for (Object st_object : skilltreeList) {
        SkillTree skillTree;/*from  w  w  w .j  a v a  2 s  . c o  m*/
        int place;
        try {
            JSONObject skilltreeObject = (JSONObject) st_object;
            skillTree = new SkillTree((String) skilltreeObject.get("Name"));
            place = Integer.parseInt(String.valueOf(skilltreeObject.get("Place")));

            if (skilltreeObject.containsKey("Inherits")) {
                skillTree.setInheritance((String) skilltreeObject.get("Inherits"));
            }
            if (skilltreeObject.containsKey("Permission")) {
                skillTree.setPermission((String) skilltreeObject.get("Permission"));
            }
            if (skilltreeObject.containsKey("Display")) {
                skillTree.setDisplayName((String) skilltreeObject.get("Display"));
            }
            if (skilltreeObject.containsKey("Description")) {
                JSONArray descriptionArray = (JSONArray) skilltreeObject.get("Description");
                for (Object lvl_object : descriptionArray) {
                    skillTree.addDescriptionLine(String.valueOf(lvl_object));
                }
            }

            JSONArray levelList = (JSONArray) skilltreeObject.get("Level");
            for (Object lvl_object : levelList) {
                JSONObject levelObject = (JSONObject) lvl_object;
                int thisLevel = Integer.parseInt(String.valueOf(levelObject.get("Level")));

                SkillTreeLevel newLevel = skillTree.addLevel(thisLevel);
                if (levelObject.containsKey("Message")) {
                    String message = (String) levelObject.get("Message");
                    newLevel.setLevelupMessage(message);
                }

                JSONArray skillList = (JSONArray) levelObject.get("Skills");
                for (Object skill_object : skillList) {
                    JSONObject skillObject = (JSONObject) skill_object;
                    String skillName = (String) skillObject.get("Name");
                    JSONObject skillPropertyObject = (JSONObject) skillObject.get("Properties");

                    if (SkillsInfo.getSkillInfoClass(skillName) != null) {
                        ISkillInfo skill = SkillsInfo.getNewSkillInfoInstance(skillName);

                        if (skill != null) {
                            SkillProperties sp = skill.getClass().getAnnotation(SkillProperties.class);
                            if (sp != null) {
                                TagCompound propertiesCompound = skill.getProperties();
                                for (int i = 0; i < sp.parameterNames().length; i++) {
                                    String propertyName = sp.parameterNames()[i];
                                    NBTdatatypes propertyType = sp.parameterTypes()[i];
                                    if (!propertiesCompound.getCompoundData().containsKey(propertyName)
                                            && skillPropertyObject.containsKey(propertyName)) {
                                        String value = String.valueOf(skillPropertyObject.get(propertyName));
                                        switch (propertyType) {
                                        case Short:
                                            if (Util.isShort(value)) {
                                                propertiesCompound.getCompoundData().put(propertyName,
                                                        new TagShort(Short.parseShort(value)));
                                            }
                                            break;
                                        case Int:
                                            if (Util.isInt(value)) {
                                                propertiesCompound.getCompoundData().put(propertyName,
                                                        new TagInt(Integer.parseInt(value)));
                                            }
                                            break;
                                        case Long:
                                            if (Util.isLong(value)) {
                                                propertiesCompound.getCompoundData().put(propertyName,
                                                        new TagLong(Long.parseLong(value)));
                                            }
                                            break;
                                        case Float:
                                            if (Util.isFloat(value)) {
                                                propertiesCompound.getCompoundData().put(propertyName,
                                                        new TagFloat(Float.parseFloat(value)));
                                            }
                                            break;
                                        case Double:
                                            if (Util.isDouble(value)) {
                                                propertiesCompound.getCompoundData().put(propertyName,
                                                        new TagDouble(Double.parseDouble(value)));
                                            }
                                            break;
                                        case Byte:
                                            if (Util.isByte(value)) {
                                                propertiesCompound.getCompoundData().put(propertyName,
                                                        new TagByte(Byte.parseByte(value)));
                                            }
                                            break;
                                        case Boolean:
                                            if (value == null || value.equalsIgnoreCase("")
                                                    || value.equalsIgnoreCase("off")
                                                    || value.equalsIgnoreCase("false")) {
                                                propertiesCompound.getCompoundData().put(propertyName,
                                                        new TagByte(false));
                                            } else if (value.equalsIgnoreCase("on")
                                                    || value.equalsIgnoreCase("true")) {
                                                propertiesCompound.getCompoundData().put(propertyName,
                                                        new TagByte(true));
                                            }
                                            break;
                                        case String:
                                            propertiesCompound.getCompoundData().put(propertyName,
                                                    new TagString(value));
                                            break;
                                        }
                                    }
                                }

                                skill.setProperties(propertiesCompound);
                                skill.setDefaultProperties();
                                skillTree.addSkillToLevel(thisLevel, skill);
                            }
                        }
                    }
                }
            }
            skillTreeMobType.addSkillTree(skillTree, place);
        } catch (Exception e) {
            DebugLogger.info("Problem in" + skillTreeMobType.getMobTypeName());
            DebugLogger.info(Arrays.toString(e.getStackTrace()));
            e.printStackTrace();
            DebugLogger.printThrowable(e);
            MyPetLogger.write(ChatColor.RED + "Error in " + skillTreeMobType.getMobTypeName().toLowerCase()
                    + ".json -> Skilltree not loaded.");
        }
    }
}

From source file:com.mythesis.userbehaviouranalysis.WebParser.java

/**
 * Get meta info for a Youtube link//from w  ww.j  av  a 2  s .c om
 * @param ventry the id of the Youtube video
 * @return a String with all the meta info about the youtube video
 */
public String GetYoutubeDetails(String ventry) {
    try {
        String apikey = "AIzaSyDa18Hdo8Fky9HuxVZZP2uDhvpAGckmxSY";
        String output = "";
        URL link_ur = new URL("https://www.googleapis.com/youtube/v3/videos?id=" + ventry + "&key=" + apikey
                + "&part=snippet");
        String line = "";
        try {
            HttpURLConnection httpCon = (HttpURLConnection) link_ur.openConnection();
            if (httpCon.getResponseCode() != 200) {
                line = "fail";
            } else {
                try (BufferedReader rd = new BufferedReader(new InputStreamReader(httpCon.getInputStream()))) {
                    StringBuilder sb = new StringBuilder();
                    while ((line = rd.readLine()) != null) {
                        sb.append(line);
                    }
                    line = sb.toString();
                }
            }
        } catch (IOException ex) {
            Logger.getLogger(WebParser.class.getName()).log(Level.SEVERE, null, ex);
            line = "fail";
            return line;
        }
        JSONParser parser = new JSONParser();
        //Create the map
        Map json = (Map) parser.parse(line);
        // Get a set of the entries
        Set set = json.entrySet();
        Iterator iterator = set.iterator();
        Map.Entry entry = null;
        boolean flagfound = false;
        while (iterator.hasNext() && !flagfound) {
            entry = (Map.Entry) iterator.next();
            if (entry.getKey().toString().equalsIgnoreCase("items")) {
                flagfound = true;
            }
        }
        JSONArray jsonarray = (JSONArray) entry.getValue();
        Iterator iteratorarray = jsonarray.iterator();
        flagfound = false;
        JSONObject get = null;
        while (iteratorarray.hasNext() && !flagfound) {
            JSONObject next = (JSONObject) iteratorarray.next();
            if (next.containsKey("snippet")) {
                get = (JSONObject) next.get("snippet");
                flagfound = true;
            }
        }
        String description = "";
        String title = "";
        if (flagfound) {
            if (get.containsKey("description")) {
                description = get.get("description").toString();
            }
            if (get.containsKey("title")) {
                title = get.get("title").toString();
            }
            output = description + " " + title;
        }
        output = removeStopwords(output);
        return output;
    } catch (IOException | ArrayIndexOutOfBoundsException | ParseException ex) {
        Logger.getLogger(WebParser.class.getName()).log(Level.SEVERE, null, ex);
        String output = null;
        return output;
    }
}

From source file:com.pearson.eidetic.driver.threads.subthreads.SnapshotVolumeNoTime.java

public Integer getKeep(JSONObject eideticParameters, Volume vol) {
    if ((eideticParameters == null) | (vol == null)) {
        return null;
    }/*from  w  w  w.  j  av  a 2 s. c om*/

    JSONObject createSnapshot = null;
    if (eideticParameters.containsKey("CreateSnapshot")) {
        createSnapshot = (JSONObject) eideticParameters.get("CreateSnapshot");
    }
    if (createSnapshot == null) {
        logger.error("awsAccountNickname=\"" + uniqueAwsAccountIdentifier_
                + "\",Event=Error, Error=\"Malformed Eidetic Tag\", Volume_id=\"" + vol.getVolumeId() + "\"");
        return null;
    }

    Integer keep = null;
    if (createSnapshot.containsKey("Retain")) {
        try {
            keep = Integer.parseInt(createSnapshot.get("Retain").toString());
        } catch (Exception e) {
            logger.error("awsAccountNickname=\"" + uniqueAwsAccountIdentifier_
                    + "\",Event=Error, Error=\"Malformed Eidetic Tag\", Volume_id=\"" + vol.getVolumeId()
                    + "\", stacktrace=\"" + e.toString() + System.lineSeparator()
                    + StackTrace.getStringFromStackTrace(e) + "\"");
        }
    }

    return keep;
}

From source file:hoot.services.nativeInterfaces.ProcessStreamInterface.java

/**
 * add to process tracking queue if command contains job id
 *
 * @param cmd/*from w  w  w  . j  av  a  2  s  . com*/
 * @param cmdRunner
 * @return true if successfully added
 * @throws Exception
 */
private boolean addToProcessQ(JSONObject cmd, ICommandRunner cmdRunner) throws Exception {

    boolean success = false;
    if (_jobProcesses != null) {
        if (cmd.containsKey("jobId")) {
            _jobProcesses.put(cmd.get("jobId").toString(), cmdRunner);
            success = true;
        }

    }

    if (_progProcesses != null) {
        if (cmd.containsKey("jobId")) {
            _progProcesses.put(cmd.get("jobId").toString(), cmdRunner);
            success = true;
        }

    }
    return success;
}

From source file:functions.TestOptions.java

@Test
public void testLoadComplete() {

    String testconfig = Settings.TESTS_CONFIG_PATH + "/" + testconfigFile;
    boolean catched = false;

    try {// w  w  w .  j ava2  s  .  co  m
        JSONObject inputJSON = ParseOptions.parseSingleJsonFile(testconfig);
        //assertTrue(inputJSON.containsKey("options"));
        //JSONObject optionsJSON = ParseOptions.getOptionsKey(inputJSON);
        assertTrue(inputJSON.containsKey("exchangename"));
    } catch (Exception e) {

    }
    assertTrue(!catched);
}

From source file:gwap.rest.UserPicture.java

protected void persistPicturerating(String idString, String payloadString) {
    JSONObject jsonObject = parse(payloadString);

    Query query = entityManager.createNamedQuery("person.byDeviceId");
    query.setParameter("deviceId", jsonObject.get("userid").toString());
    Person person = (Person) query.getSingleResult();

    ArtResourceRating artResourceRating = new ArtResourceRating();
    artResourceRating.setPerson(person);

    if (jsonObject.containsKey("likes"))
        artResourceRating.setRating(1L);
    else//from   w  ww.j  ava2 s.c  o  m
        artResourceRating.setRating(-1L);

    entityManager.persist(artResourceRating);
    ArtResource artResource = entityManager.find(ArtResource.class, Long.parseLong(idString));
    artResource.getRatings().add(artResourceRating);
    artResourceRating.setResource(artResource);
    entityManager.flush();
    log.info("Added ArtResourceRating #0", artResourceRating.getId());

    log.info("Updated UserPicture #0", artResource.getId());
}

From source file:com.janoz.tvapilib.fanarttv.impl.FanartTvImpl.java

private void parsArtArray(Sh show, String key, List<JSONObject> artArray) {
    for (JSONObject jsonArt : artArray) {
        if (!"en".equals(jsonArt.get("lang")))
            continue;
        //only english for now
        Art art = artConstructor(key);//  w w w  . j ava2  s . c  o m
        art.setId(Integer.parseInt((String) jsonArt.get("id")));
        art.setRatingCount(Integer.parseInt((String) jsonArt.get("likes")));
        art.setUrl((String) jsonArt.get("url"));
        art.setThumbUrl(art.getUrl() + "/preview");
        if (jsonArt.containsKey("season")) {
            String strSeason = (String) jsonArt.get("season");
            int season = "all".equals(strSeason) ? -1 : "".equals(strSeason) ? 0 : Integer.parseInt(strSeason);
            show.getSeason(season).addArt(art);
        } else {
            show.addArt(art);
        }
    }
}

From source file:com.mycompany.jpegrenamer.MetaDataReader.java

private Map<String, String> getAddressByGpsCoordinates(String lat, String lng)
        throws MalformedURLException, IOException, org.json.simple.parser.ParseException {
    Map<String, String> res = new HashMap();
    URL url = new URL(
            "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + lat + "," + lng + "&sensor=true");
    logger.info(url.toString());//from www  .jav  a 2  s.c o m
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    String formattedAddress = null;
    PrintStream out = new PrintStream(System.out, true, "UTF-8");
    try {
        InputStream in = url.openStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
        String result;
        String line = reader.readLine();
        result = line;
        while ((line = reader.readLine()) != null) {
            result += line;
        }
        JSONParser parser = new JSONParser();
        JSONObject rsp = (JSONObject) parser.parse(result);
        logger.debug("JSON " + rsp.toString());
        if (rsp.containsKey("error_message")) {
            JSONObject msg = (JSONObject) rsp.get("error_message");
            logger.error("Error response from Google Maps: " + msg);
            res.put("formatted_address", msg.toString());
        } else if (rsp.containsKey("results")) {
            JSONArray matches = (JSONArray) rsp.get("results");
            String premise = null;
            String administrative_area_level_1 = null;
            String administrative_area_level_2 = null;
            String sublocality_level_1 = null;
            String locality = null;
            String postal_town = null;
            String country = null;
            List<String> types = null;
            String short_name = null;
            String long_name = null;
            for (int i = 0; i < matches.size(); i++) {
                JSONObject data = (JSONObject) matches.get(i); //TODO: check if idx=0 exists
                if (formattedAddress == null) {
                    formattedAddress = (String) data.get("formatted_address");
                    res.put("formatted_address", formattedAddress);
                }
                JSONObject comp = (JSONObject) ((JSONArray) data.get("address_components")).get(0);
                logger.debug("JSON " + comp.toString());
                types = (List<String>) ((JSONArray) comp.get("types"));
                short_name = (String) comp.get("short_name");
                long_name = (String) comp.get("long_name");
                logger.debug("JSON types" + types);
                logger.debug("JSON short_name" + short_name);
                logger.debug("JSON long_name" + long_name);
                if (types.contains("premise")) {
                    premise = long_name;
                    res.put("premise", premise);
                } else if (types.contains("sublocality_level_1")) {
                    sublocality_level_1 = long_name;
                    res.put("sublocality_level_1", sublocality_level_1);
                } else if (types.contains("postal_town")) {
                    postal_town = long_name;
                    res.put("postal_town", postal_town);
                } else if (types.contains("country")) {
                    logger.debug("Setting country to " + long_name);
                    country = long_name;
                    res.put("country", country);
                } else if (types.contains("locality") && locality == null) {
                    logger.debug("Setting locality to " + long_name);
                    locality = long_name;
                    res.put("locality", locality);
                } else if (types.contains("administrative_area_level_1")) {
                    logger.debug("Setting administrative_area_level_1 to " + long_name);
                    administrative_area_level_1 = long_name;
                    res.put("administrative_area_level_1", administrative_area_level_1);
                }
            }
        }
    } finally {
        urlConnection.disconnect();
        logger.debug("Reverse geocode returns " + res);
        logger.debug("Reverse geocode returns formatted_address = " + formattedAddress);
        return res;
    }
}