Example usage for org.json.simple JSONObject keySet

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

Introduction

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

Prototype

Set<K> keySet();

Source Link

Document

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

Usage

From source file:sensorsActuators.DistanceSensor.java

@Override
public void sense() throws IOException {
    super.sense();

    sensorList.onSense((double) jsobj.get(codes[0]));

    Map<String, Double> objs = new HashMap<>();
    // Map<String, Double> robs = new HashMap<>();

    JSONObject JsObjs = (JSONObject) jsobj.get(codes[1]);
    // JSONObject JsRobs = (JSONObject) jsobj.get(codes[2]);

    Set objNames = JsObjs.keySet();
    for (Object s : objNames) {
        objs.put((String) s, (double) JsObjs.get((String) s));
    }/*w ww .  java2  s.  c o m*/

    //        Set robNames = JsRobs.keySet();
    //        for (Object s : robNames) {
    //            robs.put((String) s, (double) JsRobs.get((String) s));
    //        }

    sensorList.onSense("objects", (HashMap<String, Double>) objs);
    // sensorList.onSense("robots", (HashMap<String, Double>) robs);
}

From source file:test.java.ecplugins.esx.ConfigurationsParser.java

public static void configurationParser() {
    try {/*from  ww w  .  j  a v  a  2 s  . co  m*/
        HashMap<String, HashMap<String, String>> runs;
        HashMap<String, String> runProperties;
        BufferedReader reader = new BufferedReader(new FileReader(
                System.getProperty("user.dir") + "/src/test/java/ecplugins/esx/Configurations.json"));
        String line = null, configuration = "";
        while ((line = reader.readLine()) != null) {
            if (line.contains("*/")) {
                break;
            }
        }
        while ((line = reader.readLine()) != null) {
            configuration += line;
        }
        reader.close();
        JSONParser jsonParser = new JSONParser();
        JSONObject actionObject = (JSONObject) jsonParser.parse(configuration.toString());

        Iterator<?> keyAction = actionObject.keySet().iterator();
        while (keyAction.hasNext()) {
            String actionKey = (String) keyAction.next();
            if (actionObject.get(actionKey) instanceof JSONArray) {
                JSONArray runsArray = (JSONArray) actionObject.get(actionKey);
                runs = new HashMap<String, HashMap<String, String>>();
                for (int i = 0; i < runsArray.size(); i++) {
                    JSONObject propertiesObject = (JSONObject) runsArray.get(i);

                    Iterator<?> keyProperties = propertiesObject.keySet().iterator();
                    runProperties = new HashMap<String, String>();
                    while (keyProperties.hasNext()) {
                        String propertiesKey = (String) keyProperties.next();
                        runProperties.put(propertiesKey, (String) propertiesObject.get(propertiesKey));
                    }
                    runs.put("run" + i, runProperties);
                }
                actions.put(actionKey, runs);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:test.java.ecplugins.weblogic.ConfigurationsParser.java

public static void configurationParser() {
    try {//from ww w  .jav a2s . co  m
        HashMap<String, HashMap<String, String>> runs;
        HashMap<String, String> runProperties;
        BufferedReader reader = new BufferedReader(new FileReader(
                System.getProperty("user.dir") + "/src/test/java/ecplugins/weblogic/Configurations.json"));
        String line = null, configuration = "";
        while ((line = reader.readLine()) != null) {
            if (line.contains("*/")) {
                break;
            }
        }
        while ((line = reader.readLine()) != null) {
            configuration += line;
        }
        reader.close();
        JSONParser jsonParser = new JSONParser();
        JSONObject actionObject = (JSONObject) jsonParser.parse(configuration.toString());

        Iterator<?> keyAction = actionObject.keySet().iterator();
        while (keyAction.hasNext()) {
            String actionKey = (String) keyAction.next();
            if (actionObject.get(actionKey) instanceof JSONArray) {
                JSONArray runsArray = (JSONArray) actionObject.get(actionKey);
                runs = new HashMap<String, HashMap<String, String>>();
                for (int i = 0; i < runsArray.size(); i++) {
                    JSONObject propertiesObject = (JSONObject) runsArray.get(i);

                    Iterator<?> keyProperties = propertiesObject.keySet().iterator();
                    runProperties = new HashMap<String, String>();
                    while (keyProperties.hasNext()) {
                        String propertiesKey = (String) keyProperties.next();
                        runProperties.put(propertiesKey, (String) propertiesObject.get(propertiesKey));
                    }
                    runs.put("run" + i, runProperties);
                }
                actions.put(actionKey, runs);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:tilt.handler.post.Options.java

/**
 * Get the options for a given docid, if any
 * @param serverName the server where it all resides
 * @param docid the docid to get the options of
 * @return the options, default or privately set
 */// w ww .  j a  va  2s  .  c o  m
public static Options get(String serverName, String docid) {
    try {
        String url = "http://" + serverName + "/tilt/options?docid=" + docid;
        String jstr = Utils.getFromUrl(url);
        if (jstr != null) {
            JSONObject jobj = (JSONObject) JSONValue.parse(jstr);
            System.out.println("Custom options:");
            Set<String> keys = jobj.keySet();
            Iterator<String> iter = keys.iterator();
            while (iter.hasNext()) {
                String key = iter.next();
                System.out.println(key + ":" + jobj.get(key));
            }
            return new Options(jobj);
        } else {
            System.out.println("Using default options");
            return new Options(getDefaults());
        }
    } catch (Exception e) {
        //System.out.println("Options get:"+e.getMessage());
        return new Options(getDefaults());
    }
}

From source file:tk.elevenk.restfulrobot.testsuite.TestSuiteReader.java

/**
 * Reads the given file and populates the suite list
 * /*from www  .java2s. c o  m*/
 * @param file
 */
public void read(String file) {
    // set filename from parameter
    testSuiteFileName = file;

    try {

        // retrieve list of directories to look for suites in
        String path = new File(RestfulRobot.FILES_PATH).getAbsolutePath();
        File temp = new File(path);
        String[] directories = temp.list(new FilenameFilter() {
            @Override
            public boolean accept(File current, String name) {
                return new File(current, name).isDirectory();
            }
        });

        // create JSON object to hold the whole suite
        JSONObject jsonSuiteFile = null;

        // attempt to parse file from root files directory first
        logger.info("Searching for test suite file...");
        try {
            jsonSuiteFile = (JSONObject) JSONValue
                    .parse(new FileReader(RestfulRobot.FILES_PATH + testSuiteFileName));
        } catch (Exception e) {
            logger.trace(e.getMessage());
        }

        // attempt to parse file from each sub-directory until it is found
        if (directories != null) {
            for (int i = 0; i < directories.length && jsonSuiteFile == null; i++) {
                try {
                    jsonSuiteFile = (JSONObject) JSONValue.parse(
                            new FileReader(RestfulRobot.FILES_PATH + directories[i] + "/" + testSuiteFileName));
                } catch (Exception e) {
                    logger.trace(e.getMessage());
                }
            }
        }

        // log error if the file was not found
        if (jsonSuiteFile == null) {
            logger.error(JSON_PARSE_ERROR);
            System.out.println(JSON_PARSE_ERROR);
        }

        else {
            logger.info("Test suite file found. Processing...");

            // retrieve the set of keys from the JSON object which are each
            // test suites
            @SuppressWarnings("unchecked")
            Set<String> keys = jsonSuiteFile.keySet();

            /*
             * Test suite files are formatted to contain json objects for
             * each test suite in the file. Each test suite object has the
             * details of the suite such as cases and base URL.
             */
            for (String suiteName : keys) {

                // get the suite object to parse test cases from
                JSONObject suite = (JSONObject) jsonSuiteFile.get(suiteName);

                ArrayList<TestCase> testCasesArray = new ArrayList<TestCase>();

                // find the test cases array in the test suite and
                // add each test case script name to a list
                JSONArray testCases = (JSONArray) suite.get(TEST_CASES_KEY);
                for (int i = 0; i < testCases.size(); i++) {
                    testCasesArray.add(new TestCase((String) testCases.get(i)));
                }

                // get the base url from the suite
                String baseURL = (String) suite.get(BASE_URL_KEY);

                // create a test suite with the given test cases and add to
                // list of test suites
                TestSuite testSuite = new TestSuite(suiteName, baseURL, testCasesArray);
                testSuites.add(testSuite);
            }
        }
    } catch (Exception e) {
        logger.error(ExceptionUtils.getStackTrace(e));
    }
}

From source file:tk.itstake.steakgui.util.ItemStackConverter.java

public static ItemStack convert(JSONObject json) {
    ItemStack item = new ItemStack(Material.valueOf(((String) json.get("type")).toUpperCase()),
            (int) (long) json.get("amount"), (short) (long) json.get("data"));
    if (json.containsKey("meta")) {
        JSONObject metajson = (JSONObject) json.get("meta");
        ItemMeta meta = item.getItemMeta();
        if (metajson.containsKey("name")) {
            meta.setDisplayName((String) metajson.get("name"));
        }/*from w w w  .  j  av a  2  s.com*/
        if (metajson.containsKey("lore")) {
            meta.setLore((List<String>) metajson.get("lore"));
        }
        if (metajson.containsKey("enchantments")) {
            JSONObject enchantment = (JSONObject) metajson.get("enchantments");
            for (Object enchant : enchantment.keySet()) {
                Integer level = (int) (long) enchantment.get(enchant);
                meta.addEnchant(Enchantment.getByName((String) enchant), level, true);
            }
        }
        if (metajson.containsKey("flags")) {
            try {
                Class.forName("org.bukkit.inventory.ItemFlag");
                JSONArray flagobj = (JSONArray) metajson.get("flags");
                org.bukkit.inventory.ItemFlag[] flaglist = new org.bukkit.inventory.ItemFlag[flagobj.size()];
                int ai = 0;
                for (Object flag : flagobj.toArray()) {
                    flaglist[ai] = org.bukkit.inventory.ItemFlag.valueOf((String) flag);
                    ai++;
                }
                meta.addItemFlags(flaglist);
            } catch (ClassNotFoundException e) {
            }
        }
        item.setItemMeta(meta);
    }
    return item;
}

From source file:tk.itstake.steakgui.util.MenuFileHandler.java

public static Menu loadMenu(String name, boolean forcereload) {
    if (!loadedmenu.containsKey(name) || forcereload) {
        File dataFolder = SteakGUI.p.getDataFolder();
        if (!dataFolder.exists() || !dataFolder.isDirectory()) {
            dataFolder.mkdir();//from w w  w .  j a v  a 2 s . c  o  m
        }
        File menuFolder = new File(dataFolder.toString() + File.separator + "menu");
        if (!menuFolder.exists() || !menuFolder.isDirectory()) {
            menuFolder.mkdir();
        }
        File menuFile = new File(menuFolder.toString() + File.separator + name + ".json");
        try {
            FileReader fr = new FileReader(menuFile);
            JSONParser jp = new JSONParser();
            JSONObject menujson = (JSONObject) jp.parse(fr);
            JSONObject slotarray = (JSONObject) menujson.get("slot");
            HashMap<Integer, GUIItem> slotmap = new HashMap<>();
            for (Object slot : slotarray.keySet()) {
                JSONObject guiarray = (JSONObject) slotarray.get(slot);
                ItemStack item = ItemStackConverter.convert((JSONObject) guiarray.get("item"));
                ArrayList<ItemTask> taskarray = new ArrayList<>();
                for (Object obj : ((JSONArray) guiarray.get("task"))) {
                    ItemTask task = ItemTaskConverter.convert((JSONObject) obj);
                    taskarray.add(task);
                }

                GUIItem guiitem = new GUIItem(item, (String) guiarray.get("perm"), taskarray);
                slotmap.put(Integer.parseInt((String) slot), guiitem);
            }
            Menu menu = new Menu(name, (String) menujson.get("title"), (int) (long) menujson.get("size"),
                    slotmap);
            fr.close();
            loadedmenu.put(name, menu);
            return menu;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    } else {
        return loadedmenu.get(name);
    }
}

From source file:tk.itstake.util.LanguageHandler.java

private void updateFile() {
    // If Can't Load Language File
    plugin = Bukkit.getPluginManager().getPlugin("SteakGUI");
    File langfolder = new File(plugin.getDataFolder().toString() + File.separator + "lang");
    File langfile = new File(
            langfolder.toString() + File.separator + ConfigHandler.getConfig("lang").toString() + ".json");
    // Write New File
    try {// w w w.  ja  v a2s  .c om
        FileWriter fw = new FileWriter(langfile);
        JSONObject defaultlang = getDefaultLanguage();
        for (Object key : defaultlang.keySet()) {
            if (!language.containsKey(key)) {
                defaultlang.put(key, language.get(key));
            }
        }
        fw.write(JSONUtil.getPretty(defaultlang.toJSONString()));
        language = defaultlang;
        fw.flush();
        fw.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:uk.ac.susx.tag.method51.core.params.codec.generic.ParamsCodec.java

@Override
public Params decode(JSONObject value) throws DecodeException {
    Params instance = Params.instance(paramsClass);

    JSONObject globals = (JSONObject) value.get(ParamsRegistry.GLOBALS_KEY);

    if (globals != null) {
        for (String key : (Set<String>) globals.keySet()) {
            Class globalClass = new ClassCodec().decodeString(key);
            ParamsCodec codec = new ParamsCodec(globalClass);
            Params global = codec.decode((JSONObject) globals.get(key));
            instance.setGlobal(global);/*ww w .  j  a v  a 2s .com*/
        }
    }

    for (String fieldName : instance.getFieldNames()) {
        Params.Param param = instance.getParamByName(fieldName);

        if (value.containsKey(fieldName)) {
            try {
                IType type = param.getType();
                Object result = type.decode(value.get(fieldName));
                type.validate(result);
                param.set(result);
            } catch (InvalidParameterException e) {
                LOG.error("", e);
                throw new InvalidParameterException(
                        "Bad value for field '" + fieldName + "':\n" + e.getMessage());
            } catch (ClassCastException e) {

                try {
                    IType type = param.getType();
                    Object result = type.decode(Long.toString((Long) value.get(fieldName)));
                    type.validate(result);
                    param.set(result);
                } catch (NumberFormatException | ClassCastException e1) {
                    LOG.error("", e);
                    throw new InvalidParameterException(
                            "Bad type for field '" + fieldName + "':\n" + e.getMessage());
                }

            } catch (Exception e) {
                LOG.error("", e);
                throw new InvalidParameterException(
                        "Unknown error parsing field '" + fieldName + "' with value: " + value.get(fieldName));
            }
        }
    }

    instance.validate();

    return instance;
}

From source file:uk.ac.susx.tag.method51.twitter.geocoding.TimezoneFilter.java

public TimezoneFilter(Options options) {
    super(options);
    JSONObject gmtOffsets = null;
    try {/* w w  w  .ja v  a  2  s . c o m*/
        gmtOffsets = (JSONObject) JSONValue.parse(
                new InputStreamReader(Resources.getResource(this.getClass(), "gmt-offsets.json").openStream()));
    } catch (IOException e) {
        LOG.error("", e);
        throw new RuntimeException("Unable to find gmt-offsets file.");
    }
    try {
        torqbakTimezones = (JSONObject) JSONValue.parse(new InputStreamReader(
                Resources.getResource(this.getClass(), "iso-timezones.json").openStream()));
    } catch (IOException e) {
        LOG.error("", e);
        throw new RuntimeException("Unable to find torqbak-timezones file.");
    }

    Set<String> timezones = options.acceptedTimezones.get();

    if (timezones.size() == 0) {
        throw new IllegalArgumentException("Must include at least one timezone for TimezoneFilter");
    }

    acceptedTimezones = new double[timezones.size()];

    int i = 0;
    for (String tz : timezones) {
        if (!isLegitTimezone(tz)) {
            throw new RuntimeException(tz + " is not a legit timezone");
        }
        acceptedTimezones[i++] = (Double) ((Map) torqbakTimezones.get(tz)).get("lon");
    }

    twitterTimezones = new Object2DoubleRBTreeMap<>();

    for (String twitterTimezone : (Set<String>) gmtOffsets.keySet()) {
        twitterTimezones.put(twitterTimezone,
                offsetToLongitude(((Number) gmtOffsets.get(twitterTimezone)).doubleValue()));
    }

}