Example usage for org.json.simple JSONObject entrySet

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

Introduction

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

Prototype

Set<Map.Entry<K, V>> entrySet();

Source Link

Document

Returns a Set view of the mappings contained in this map.

Usage

From source file:de.hstsoft.sdeep.model.TerrainGeneration.java

public static TerrainGeneration parse(JSONObject json) {
    TerrainGeneration terrainGeneration = new TerrainGeneration();

    JSONObject origin = (JSONObject) json.get(WORLD_ORIGIN_POINT);
    terrainGeneration.worldOrigin = Position.parseVector(origin);

    JSONObject playerPosition = (JSONObject) json.get(PLAYER_POSITION);
    terrainGeneration.playerPosition = Position.parseVector(playerPosition);

    terrainGeneration.worldSeed = Utils.toInt(json.get(WORLD_SEED).toString());

    JSONObject nodes = (JSONObject) json.get(NODES);
    Iterator<?> iter = nodes.entrySet().iterator();
    while (iter.hasNext()) {
        Map.Entry<?, ?> entry = (Map.Entry<?, ?>) iter.next();

        String key = entry.getKey().toString();
        JSONObject node = (JSONObject) nodes.get(entry.getKey().toString());
        TerrainNode terrainNode = TerrainNode.parseNode(key, node);
        terrainGeneration.terrainNodes.add(terrainNode);

    }/*from   ww w  .  j  a  v  a2 s.co  m*/

    return terrainGeneration;
}

From source file:net.amigocraft.mpt.command.ListRepositoriesCommand.java

@SuppressWarnings("unchecked")
public static List<String[]> getRepositories() throws MPTException {
    if (Main.repoStore.containsKey("repositories")) {
        JSONObject repos = (JSONObject) Main.repoStore.get("repositories");
        Set<Map.Entry<String, Object>> entries = repos.entrySet();
        List<String[]> repoList = new ArrayList<>();
        for (Map.Entry<String, Object> e : entries) {
            if (((JSONObject) e.getValue()).containsKey("url")) {
                repoList.add(new String[] { e.getKey().toLowerCase(),
                        ((JSONObject) e.getValue()).get("url").toString() });
            } else if (VERBOSE) {
                Main.log.warning("Invalid repository definition \"" + e.getKey().toLowerCase() + "\"");
            }//from   w w w . j  a va  2s. c  o  m
        }
        return repoList;
    } else {
        throw new MPTException("Repository store is malformed!");
    }
}

From source file:net.amigocraft.mpt.command.ListInstalledCommand.java

@SuppressWarnings("unchecked")
public static List<String[]> getPackages() throws MPTException {
    if (Main.packageStore.containsKey("packages")) {
        JSONObject packs = (JSONObject) Main.packageStore.get("packages");
        Set<Map.Entry<String, Object>> entries = packs.entrySet();
        List<String[]> packList = new ArrayList<>();
        for (Map.Entry<String, Object> e : entries) {
            if (((JSONObject) e.getValue()).containsKey("installed")) {
                if (((JSONObject) e.getValue()).containsKey("name")) {
                    packList.add(new String[] { e.getKey().toLowerCase(),
                            ((JSONObject) e.getValue()).get("name").toString(),
                            ((JSONObject) e.getValue()).get("installed").toString(), });
                } else if (VERBOSE) {
                    Main.log.warning("Invalid package definition \"" + e.getKey().toLowerCase() + "\"");
                }/*from  w ww  .  j av  a 2 s  . c  o  m*/
            }
        }
        return packList;
    } else {
        throw new MPTException("Package store is malformed!");
    }
}

From source file:net.amigocraft.mpt.command.ListAvailableCommand.java

@SuppressWarnings("unchecked")
public static List<String[]> getPackages() throws MPTException {
    if (Main.packageStore.containsKey("packages")) {
        JSONObject packs = (JSONObject) Main.packageStore.get("packages");
        Set<Map.Entry<String, Object>> entries = packs.entrySet();
        List<String[]> packList = new ArrayList<>();
        for (Map.Entry<String, Object> e : entries) {
            if (((JSONObject) e.getValue()).containsKey("name")
                    && ((JSONObject) e.getValue()).containsKey("version")) {
                packList.add(new String[] { e.getKey().toLowerCase(),
                        ((JSONObject) e.getValue()).get("name").toString(),
                        ((JSONObject) e.getValue()).get("version").toString(), });
            } else if (VERBOSE) {
                Main.log.warning("Invalid package definition \"" + e.getKey().toLowerCase() + "\"");
            }//  w w  w  .j  a va2s.  c o  m
        }
        return packList;
    } else {
        throw new MPTException("Package store is malformed!");
    }
}

From source file:de.hstsoft.sdeep.model.TerrainNode.java

public static TerrainNode parseNode(String key, JSONObject node) {

    TerrainNode terrainNode = new TerrainNode(key);

    terrainNode.name = node.get(NAME).toString();
    terrainNode.biome = node.get(BIOME).toString();
    terrainNode.fullyGernerated = Utils.toBool(node.get(FULLY_GENERATED).toString());
    terrainNode.heightValue = Utils.toInt(node.get(HEIGHT_VALUE).toString());
    terrainNode.seedEffect = Utils.toInt(node.get(SEED_EFFECT).toString());

    JSONObject position = (JSONObject) node.get(POSITION);
    terrainNode.position = Position.parseVector(position);

    JSONObject positionOffset = (JSONObject) node.get(POSITION_OFFSET);
    terrainNode.positionOffset = Position.parseVector(positionOffset);

    JSONObject objects = (JSONObject) node.get(OBJECTS);

    if (objects != null) {
        Iterator<?> iter = objects.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<?, ?> entry = (Map.Entry<?, ?>) iter.next();

            JSONObject childJson = (JSONObject) objects.get(entry.getKey().toString());
            GameObject child = GameObject.parse(childJson);
            terrainNode.children.add(child);
        }/*from   w ww  . j  ava2 s  .c o m*/
    }
    Collections.sort(terrainNode.children, new GameObjectComparator());
    return terrainNode;
}

From source file:com.conwet.silbops.model.Constraint.java

/**
 * Deserialize from a JSON representation
 *
 * @param json JSON representation//from  w  ww .ja v a 2 s  .c  o m
 * @return A new constraint
 */
public static Constraint fromJSON(JSONObject json) {

    @SuppressWarnings("unchecked")
    Set<Map.Entry<String, Object>> entries = json.entrySet();

    if (entries.size() != 1) {

        throw new IllegalArgumentException("Malformed object: " + json);
    }

    Entry<String, Object> entry = entries.iterator().next();
    Operator operator = Operator.fromJSON(entry.getKey());
    return (operator == Operator.EXISTS) ? EXIST : new Constraint(operator, Value.fromJSON(entry.getValue()));
}

From source file:eu.riscoss.rdc.GithubAPI_Test.java

/**
 * GIT API Test method //from  w  ww.  j  a va 2s .  c o m
 * @param req
 * @return
 */
static JSONArray gitJSONGetter() {
    String json = "";
    //String repository = values.get("repository");

    String owner = "RISCOSS/";
    //String repo = "riscoss-analyser/";
    String repo = "riscoss-data-collector/";

    String r = owner + repo;

    String req;
    req = r + "commits";

    //NST: needs some time to be calculated. 1st time it returns Status 202!
    req = r + "stats/contributors"; //NST single contributors with weekly efforts: w:week, a:add, d:del, c:#commits

    //https://developer.github.com/v3/repos/statistics/#commit-activity
    req = r + "stats/commit_activity";//NST data per week (1y):  The days array is a group of commits per day, starting on Sunday.

    req = r + "collaborators"; //needs authorization! Error 401

    req = r + "events"; //committs and other events. Attention: max 10x30 events, max 90days!

    req = r + "issues?state=all"; //all issues. Of interest: state=open, closed, 

    //      req = r + "stats/participation";//NST  weekly commit count

    //req = r + "stats/code_frequency";  //NST: week,  number of additions, number of deletions per week

    //HttpGet( "https://api.github.com/rate_limit");  //rate limit is 60 requests per hour!!
    /**
     * TODO:
     * participation: week list, analysis value
     * issues open, issues closed today status
     *  
     */

    HttpGet get = new HttpGet("https://api.github.com/repos/" + req);
    //get = new HttpGet( "https://api.github.com/rate_limit");

    //only for getting the License
    //get.setHeader("Accept", "application/vnd.github.drax-preview+json");

    HttpResponse response;
    try {
        response = client.execute(get);

        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity entity = response.getEntity();
            json = EntityUtils.toString(entity);

        } else if (response.getStatusLine().getStatusCode() == 202) {
            System.err.println("WARNING 202 Accept: Computing....try again in some seconds.");
            return null;
        } else {
            // something has gone wrong...
            System.err.println(response.getStatusLine().getStatusCode());
            System.err.println(response.getStatusLine().toString());
            return null;
        }
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    System.out.println("****JSON****\n" + json + "\n************");

    try {
        JSONAware jv = (JSONAware) new JSONParser().parse(json);

        if (jv instanceof JSONObject) {
            JSONObject jo = (JSONObject) jv;
            System.out.println("JO: ");
            for (Object o : jo.entrySet()) {
                System.out.println("\t" + o);
            }

        }

        if (jv instanceof JSONArray) {
            JSONArray ja = (JSONArray) jv;

            int size = ja.size();
            System.out.println("JA Size = " + size);
            for (Object o : ja) {
                if (o instanceof JSONObject) {
                    JSONObject jo = (JSONObject) o;
                    System.out.println("JA Object:");
                    for (Object o2 : jo.entrySet()) {
                        System.out.println("\t" + o2);
                    }
                } else {
                    System.out.println("JA Array: " + (JSONArray) o);
                }
            }
            return ja;
        }

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

From source file:com.jadarstudios.rankcapes.bukkit.CapePackValidator.java

/**
 * Validates the pack metadata.//from w w  w  .  java  2s.  com
 *
 * @param object the root json object
 *
 * @throws InvalidCapePackException thrown if the cape pack is invalid
 */
public static void validatePack(JSONObject object) throws InvalidCapePackException {
    // loops through every entry in the base of the JSON file.
    for (Object entryObj : object.entrySet()) {
        if (entryObj instanceof Map.Entry) {
            Object key = ((Map.Entry) entryObj).getKey();
            Object value = ((Map.Entry) entryObj).getValue();

            if (!(key instanceof String)) {
                throw new InvalidCapePackException(String.format("The key \"%s\" is not a string.", key));
            }

            if (value instanceof Map) {
                try {
                    validateAnimatedCapeNode((Map) value);
                } catch (InvalidCapePackException initialException) {
                    InvalidCapePackException exception = new InvalidCapePackException(
                            String.format("Error while validating Animated cape element \"%s\"", key));
                    exception.initCause(initialException);
                    throw exception;
                }
            } else {
                try {
                    validateStaticCapeNode(value);
                } catch (InvalidCapePackException initialException) {
                    InvalidCapePackException exception = new InvalidCapePackException(
                            String.format("Error while validating Static cape element \"%s\"", key));
                    exception.initCause(initialException);
                    throw exception;
                }
            }
        }
    }
}

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

/**
 * Add super columns to a column family.
 * //from   w  w w.  jav a 2  s .  c o  m
 * @param row the super columns associated with a row
 * @param cfamily the column family to add columns to
 */
private static void addToSuperCF(JSONObject row, ColumnFamily cfamily) {
    // Super columns
    for (Map.Entry<String, JSONObject> entry : (Set<Map.Entry<String, JSONObject>>) row.entrySet()) {
        byte[] superName = hexToBytes(entry.getKey());
        long deletedAt = (Long) entry.getValue().get("deletedAt");
        JSONArray subColumns = (JSONArray) entry.getValue().get("subColumns");

        // Add sub-columns
        for (Object c : subColumns) {
            JsonColumn col = new JsonColumn(c);
            QueryPath path = new QueryPath(cfamily.name(), superName, hexToBytes(col.name));
            cfamily.addColumn(path, hexToBytes(col.value), col.timestamp, col.isDeleted);
        }

        SuperColumn superColumn = (SuperColumn) cfamily.getColumn(superName);
        superColumn.markForDeleteAt((int) (System.currentTimeMillis() / 1000), deletedAt);
    }
}

From source file:net.amigocraft.mpt.command.UpdateCommand.java

@SuppressWarnings("unchecked")
public static void updateStore() throws MPTException {
    if (Thread.currentThread().getId() == Main.mainThreadId)
        throw new MPTException(ERROR_COLOR + "Package store may not be updated from the main thread!");
    lockStores();//from ww w.  ja  v a  2 s . c o m
    final File rStoreFile = new File(Main.plugin.getDataFolder(), "repositories.json");
    if (!rStoreFile.exists())
        Main.initializeRepoStore(rStoreFile); // gotta initialize it before using it
    final File pStoreFile = new File(Main.plugin.getDataFolder(), "packages.json");
    if (!pStoreFile.exists())
        Main.initializePackageStore(pStoreFile);
    JSONObject repos = (JSONObject) Main.repoStore.get("repositories");
    Set<Map.Entry> entries = repos.entrySet();
    JSONObject localPackages = (JSONObject) Main.packageStore.get("packages");
    List<Object> remove = new ArrayList<Object>();
    for (Object k : localPackages.keySet()) {
        if (!((JSONObject) localPackages.get(k)).containsKey("installed"))
            remove.add(k);
    }
    for (Object r : remove)
        localPackages.remove(r);
    for (Map.Entry<String, JSONObject> e : entries) {
        final String id = e.getKey().toLowerCase();
        JSONObject repo = e.getValue();
        final String url = repo.get("url").toString();
        if (VERBOSE)
            Main.log.info("Updating repository \"" + id + "\"");
        JSONObject json = MiscUtil.getRemoteIndex(url);
        String repoId = json.get("id").toString();
        JSONObject packages = (JSONObject) json.get("packages");
        Set<Map.Entry> pEntries = packages.entrySet();
        for (Map.Entry en : pEntries) {
            String packId = en.getKey().toString().toLowerCase();
            JSONObject o = (JSONObject) en.getValue();
            if (o.containsKey("name") && o.containsKey("version") && o.containsKey("url")) {
                if (o.containsKey("sha1") || !Config.ENFORCE_CHECKSUM) {
                    String name = o.get("name").toString();
                    String desc = o.containsKey("description") ? o.get("description").toString() : "";
                    String version = o.get("version").toString();
                    String contentUrl = o.get("url").toString();
                    String sha1 = o.containsKey("sha1") ? o.get("sha1").toString() : "";
                    if (VERBOSE)
                        Main.log.info("Fetching package \"" + packId + "\"");
                    String installed = localPackages.containsKey(packId)
                            && ((JSONObject) localPackages.get(packId)).containsKey("installed")
                                    ? (((JSONObject) localPackages.get(packId)).get("installed")).toString()
                                    : "";
                    JSONArray files = localPackages.containsKey(packId)
                            && ((JSONObject) localPackages.get(packId)).containsKey("files")
                                    ? ((JSONArray) ((JSONObject) localPackages.get(packId)).get("files"))
                                    : null;
                    JSONObject pObj = new JSONObject();
                    pObj.put("repo", repoId);
                    pObj.put("name", name);
                    if (!desc.isEmpty())
                        pObj.put("description", desc);
                    pObj.put("version", version);
                    pObj.put("url", contentUrl);
                    if (!sha1.isEmpty())
                        pObj.put("sha1", sha1);
                    if (!installed.isEmpty())
                        pObj.put("installed", installed);
                    if (files != null)
                        pObj.put("files", files);
                    localPackages.put(packId, pObj);
                } else if (VERBOSE)
                    Main.log.warning("Missing checksum for package \"" + packId + ".\" Ignoring package...");
            } else if (VERBOSE)
                Main.log.warning(
                        "Found invalid package definition \"" + packId + "\" in repository \"" + repoId + "\"");
        }
    }
    Main.packageStore.put("packages", localPackages);
    try {
        writePackageStore();
    } catch (IOException ex) {
        throw new MPTException(ERROR_COLOR + "Failed to save repository store to disk!");
    }
    unlockStores();
}