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:com.hmsonline.virgil.CassandraStorage.java

@PooledConnection
public void setColumn(String keyspace, String column_family, String key, JSONObject json,
        ConsistencyLevel consistency_level, boolean index, long timestamp) throws InvalidRequestException,
        UnavailableException, TimedOutException, TException, HttpException, IOException {
    List<Mutation> slice = new ArrayList<Mutation>();
    for (Object field : json.keySet()) {
        String name = (String) field;
        String value = (String) json.get(name);
        Column c = new Column();
        c.setName(ByteBufferUtil.bytes(name));
        c.setValue(ByteBufferUtil.bytes(value));
        c.setTimestamp(timestamp);/*  w w  w  . j a  va2s  . c o  m*/

        Mutation m = new Mutation();
        ColumnOrSuperColumn cc = new ColumnOrSuperColumn();
        cc.setColumn(c);
        m.setColumn_or_supercolumn(cc);
        slice.add(m);
    }
    Map<ByteBuffer, Map<String, List<Mutation>>> mutationMap = new HashMap<ByteBuffer, Map<String, List<Mutation>>>();
    Map<String, List<Mutation>> cfMutations = new HashMap<String, List<Mutation>>();
    cfMutations.put(column_family, slice);
    mutationMap.put(ByteBufferUtil.bytes(key), cfMutations);
    getConnection(keyspace).batch_mutate(mutationMap, consistency_level);

    if (config.isIndexingEnabled() && index)
        indexer.index(column_family, key, json);
}

From source file:com.tempescope.wunderground.WundergroundManager.java

public WundergroundQueryResult queryForCoords(Coordinate coord) {
    InputStream in = null;//from  ww w.  j  a v  a2  s.  c  om
    try {
        rateLimiter.waitEnoughTime();

        URL url = getURLForConditions(coord);
        URLConnection con = url.openConnection();
        in = con.getInputStream();

        JSONParser parser = new JSONParser();
        JSONObject rootObj = (JSONObject) parser.parse(new InputStreamReader(in));
        JSONObject currentObservation = (JSONObject) rootObj.get("current_observation");
        if (currentObservation != null) {
            for (Object key : rootObj.keySet())
                System.out.println(key + "\t" + rootObj.get(key));

            String weather = "" + currentObservation.get("weather");
            String timezone = "" + currentObservation.get("local_tz_long");
            WeatherLocation location = null;
            try {
                location = new WeatherLocation((JSONObject) currentObservation.get("observation_location"));
            } catch (Exception e) {
                System.err.println((JSONObject) currentObservation.get("observation_location"));
                e.printStackTrace();
            }

            return new WundergroundQueryResult(TimeZone.getTimeZone(timezone), weather, location, new Date());
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (in != null)
            try {
                in.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
    }
    return null;
}

From source file:com.nwn.NwnUpdater.java

/**
 * Parse json file containing files required for server
* Convert those files into ServerFile objects and store them 
 *///from   w w w  . j  a v a  2s  . co  m
private boolean parseServerFileJson() {
    boolean success = true;
    String compressedFileName;
    currentGui.setTaskProgressBarValue(0);
    int currentProgress = 0;
    int statusIncrement;
    currentGui.appendOutputText("\n\nReading file list");
    try {
        Thread.sleep(500);
        FileReader reader = new FileReader(serverFileJson.toString());
        JSONParser jsonParser = new JSONParser();
        JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
        Set<String> folders = jsonObject.keySet();
        if (folders.size() > 0) {
            statusIncrement = 100 / folders.size();
        } else {
            statusIncrement = 100;
        }
        for (String folderName : folders) {
            if (!folderName.contains("..") && !folderName.contains(":")) {
                affectedFolders.add(folderName);
                JSONArray filesByFolder = (JSONArray) jsonObject.get(folderName);
                Iterator fileItr = filesByFolder.iterator();
                while (fileItr.hasNext()) {
                    currentGui.appendOutputText(".");
                    JSONObject fileJson = (JSONObject) fileItr.next();
                    URL fileUrl = new URL(fileJson.get("url").toString());
                    if (folderName.equalsIgnoreCase(FolderByExt.COMPRESSED.toString())) {
                        ArrayList<String> compressedFileList = new ArrayList<>();
                        JSONArray compressedFileArray = (JSONArray) fileJson.get("files");
                        Iterator cfItr = compressedFileArray.iterator();
                        while (cfItr.hasNext()) {
                            compressedFileName = cfItr.next().toString();
                            affectedFolders.add(NwnFileHandler.getFileExtension(compressedFileName));
                            compressedFileList.add(compressedFileName);
                        }
                        serverFileList.add(new ServerFile(fileJson.get("name").toString(), fileUrl, folderName,
                                compressedFileList));
                    } else {
                        serverFileList
                                .add(new ServerFile(fileJson.get("name").toString(), fileUrl, folderName));
                    }
                }
            } else {
                currentGui.appendOutputText("An unusual folder path was detected: " + folderName
                        + "\nServer owner may be attempting to place files outside of NWN."
                        + "\nThis folder has been excluded from the update.");
            }
            currentProgress = currentProgress + statusIncrement;
            currentGui.setTaskProgressBarValue(currentProgress);
        }
        currentGui.appendOutputText("done");
        reader.close();
    } catch (IOException ex) {
        //            ex.printStackTrace();
        currentGui.appendOutputText("...failed\nERROR: Cannot read server file list.");
        error[0] = true;
        success = false;
    } catch (ParseException ex) {
        //            ex.printStackTrace();
        currentGui.appendOutputText("...failed\nERROR: Cannot parse server file list.");
        error[0] = true;
        success = false;
    } catch (InterruptedException ex) {
        currentGui.appendOutputText("...canceled");
        success = false;
    }
    return success;
}

From source file:eu.juniper.MonitoringLib.java

private ArrayList<String> readJson(ArrayList<String> elementsList, JSONObject jsonObject, PrintWriter writer,
        String TagName) throws FileNotFoundException, IOException, ParseException {
    String appId = "";
    if (jsonObject.get(TagName) == null) {
        elementsList.add("null");
    } else {// www  .java 2s .  c  om
        String Objectscontent = jsonObject.get(TagName).toString();
        if (Objectscontent.startsWith("[{") && Objectscontent.endsWith("}]")) {
            JSONArray jsonArray = (JSONArray) jsonObject.get(TagName);

            for (int temp = 0; temp < jsonArray.size(); temp++) {
                System.out.println("Array:" + jsonArray.toJSONString());
                JSONObject jsonObjectResult = (JSONObject) jsonArray.get(temp);
                System.out.println("Result:" + jsonObjectResult.toJSONString());

                Set<String> jsonObjectResultKeySet = jsonObjectResult.keySet();
                System.out.println("KeySet:" + jsonObjectResultKeySet.toString());

                for (String s : jsonObjectResultKeySet) {
                    System.out.println(s);
                    readJson(elementsList, jsonObjectResult, writer, s);
                }
            }
        } else {
            appId = jsonObject.get(TagName).toString();
            elementsList.add(appId);
        }
    }
    return elementsList;
}

From source file:battleheartlegacybuilder.mainWindow.java

private void createInGameClassesFromJson() {
    String filePath = mainWindow.class.getResource("/classes/data.json").getPath();
    try {//from  w  w w  . ja va  2 s  . c  o m
        FileReader reader = new FileReader(filePath);
        JSONParser jsonParser = new JSONParser();
        JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
        JSONArray ingameClasses = (JSONArray) jsonObject.get("ingameClass");
        //set object (hashMap)
        Set set = this.dictionary.entrySet();
        Iterator iteratorSet = set.iterator();

        for (Object ingameClasse : ingameClasses) {
            JSONObject currentJsonObject = (JSONObject) ingameClasse;
            String className = (String) currentJsonObject.get("className");

            //once we have the name of the ingameClass we need the skillsArray
            JSONArray skills = (JSONArray) currentJsonObject.get("skills");

            //list of skills
            List<Skills> skillList = new ArrayList<>();
            for (Object skill : skills) {
                Skills classSkills = new Skills();
                JSONObject currentSkillObject = (JSONObject) skill;

                //adding skills data to skills object
                classSkills.setSkillName((String) currentSkillObject.get("skillName"));
                classSkills.setSkillType((String) currentSkillObject.get("type"));
                classSkills.setImagePath((String) currentSkillObject.get("imgurl"));
                classSkills.setDescription((String) currentSkillObject.get("description"));
                classSkills.setCoolDown((String) currentSkillObject.get("cooldown"));
                classSkills.setIngameClassName(className);

                //we need a variable for the requirements array
                JSONObject requirementsJson = (JSONObject) currentSkillObject.get("requirements");
                //loop to get the requirements form each skill
                for (Iterator iterator = requirementsJson.keySet().iterator(); iterator.hasNext();) {
                    String key = (String) iterator.next();
                    String value = (String) requirementsJson.get(key);
                    Requirements requir = new Requirements(key, Integer.parseInt(value));
                    classSkills.setRequirements(requir);
                }

                skillList.add(classSkills);

            } //skills for
              //ingameClass Object
            ingameClass ingameClassObject = new ingameClass(className, skillList);
            this.dictionary.put(className, ingameClassObject);
        }

    } catch (FileNotFoundException ex) {
        Logger.getLogger(mainWindow.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException | ParseException ex) {
        Logger.getLogger(mainWindow.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.ecofactor.qa.automation.consumerapi.ThermostatRuntimeSavings_Test.java

/**
 * APPS-205 Verify thermostat disconnected.
 * @param username the username/*  w w w . ja v  a 2  s  .  co m*/
 * @param password the password
 * @param thermostatId the thermostat id
 * @throws ParseException
 */
@Test(groups = { Groups.SANITY1,
        Groups.BROWSER }, dataProvider = "missingsavingsmonth", dataProviderClass = ApiDataProvider.class, priority = 9)
public void thermostatDisconnected(final String username, final String password, final String thermostatId)
        throws ParseException {

    setLogString("Verify that given thermostat has missing data to simulate disconnected thermostat.", true);
    final Response response = consumerApiURL.getThermostatRuntimeSavings(thermostatId, securityCookie);
    Assert.assertTrue(response.getStatus() == 200, "Error status: " + response.getStatus());
    setLogString("Response :'" + response + "'", true);

    final String content = response.readEntity(String.class);

    setLogString(JSON_RESPONSE, true, CustomLogLevel.MEDIUM);
    setLogString(content, true, CustomLogLevel.MEDIUM);

    final JSONObject jsonObject = JsonUtil.parseObject(content);
    final JSONObject mesgs = (JSONObject) jsonObject.get(MONTHS);

    final Object[] monthyear = mesgs.keySet().toArray();

    Assert.assertTrue(monthyear.length > 0, "No runtime savings data found.");

    Calendar calendar;
    final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM");

    final ArrayList<Calendar> yearMonths = new ArrayList<>();

    for (final Object runtime : monthyear) {
        final Date date = dateFormat.parse(runtime.toString());

        calendar = Calendar.getInstance();
        calendar.setTime(date);

        yearMonths.add(calendar);
    }

    Collections.sort(yearMonths);

    boolean offline = false;
    for (int i = 0; i < yearMonths.size() - 1; i++) {
        if (checkIfMonthGapsExistsBetweenCalendar(yearMonths.get(i), yearMonths.get(i + 1))) {
            offline = true;
            break;
        }
    }

    Assert.assertTrue(offline, "Unable to verify missing monthly runtimes in given thermostat (Disconnected).");
    setLogString("Verified that given thermostat has missing data to simulate disconnected thermostat.", true);
}

From source file:blog.cobablog.java

@WebMethod(operationName = "listUnpublishedPost")
public List<Post> listUnpublishedPost() {
    List<Post> out = new ArrayList<Post>();
    try {/* w  ww. j av  a2 s.  co m*/
        //TODO write your implementation code here:
        String linkString = LINK_FIREBASE + "posts.json";
        URL link = new URL(linkString);
        BufferedReader reader = new BufferedReader(new InputStreamReader(link.openStream()));

        String s = "";
        String tmp;
        while ((tmp = reader.readLine()) != null) {
            s += tmp;
        }

        JSONParser parser = new JSONParser();
        JSONObject o = (JSONObject) parser.parse(s);

        int i;
        for (i = 0; i < o.size(); i++) {
            Post p = new Post();
            p.setId(o.keySet().toArray()[i].toString());
            JSONObject postEntry = (JSONObject) parser.parse(o.get(p.getId()).toString());
            p.setAuthor((String) postEntry.get("author"));
            p.setJudul((String) postEntry.get("judul"));
            p.setKonten((String) postEntry.get("konten"));
            p.setTanggal((String) postEntry.get("tanggal"));
            p.setDeleted((String) postEntry.get("deleted"));
            p.setPublished((String) postEntry.get("published"));

            if ((!p.isDeleted()) && (!p.isPublished())) {
                out.add(p);
            }
        }

        return out;
        //System.out.println(array.get(0));
    } catch (MalformedURLException ex) {
        Logger.getLogger(cobablog.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(cobablog.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParseException ex) {
        Logger.getLogger(cobablog.class.getName()).log(Level.SEVERE, null, ex);
    }
    return out;
}

From source file:blog.cobablog.java

@WebMethod(operationName = "listDeletedPost")
public List<Post> listDeletedPost() {
    List<Post> out = new ArrayList<Post>();
    try {//from www .j ava 2  s. c  om
        //TODO write your implementation code here:
        String linkString = LINK_FIREBASE + "posts.json";
        URL link = new URL(linkString);
        BufferedReader reader = new BufferedReader(new InputStreamReader(link.openStream()));

        String s = "";
        String tmp;
        while ((tmp = reader.readLine()) != null) {
            s += tmp;
        }

        JSONParser parser = new JSONParser();
        JSONObject o = (JSONObject) parser.parse(s);

        int i;
        for (i = 0; i < o.size(); i++) {
            Post p = new Post();
            p.setId(o.keySet().toArray()[i].toString());
            JSONObject postEntry = (JSONObject) parser.parse(o.get(p.getId()).toString());
            p.setAuthor((String) postEntry.get("author"));
            p.setJudul((String) postEntry.get("judul"));
            p.setKonten((String) postEntry.get("konten"));
            p.setTanggal((String) postEntry.get("tanggal"));
            p.setDeleted((String) postEntry.get("deleted"));
            p.setPublished((String) postEntry.get("published"));

            if ((p.isDeleted())) {
                out.add(p);
            }
        }

        return out;
        //System.out.println(array.get(0));
    } catch (MalformedURLException ex) {
        Logger.getLogger(cobablog.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(cobablog.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParseException ex) {
        Logger.getLogger(cobablog.class.getName()).log(Level.SEVERE, null, ex);
    }
    return out;
}

From source file:blog.cobablog.java

/**
 * Web service operation//www .j av  a2  s .  c o  m
 * @return 
 */
@WebMethod(operationName = "listPost")
public List<Post> listPost() {
    List<Post> out = new ArrayList<Post>();
    try {
        //TODO write your implementation code here:
        String linkString = LINK_FIREBASE + "posts.json";
        URL link = new URL(linkString);
        BufferedReader reader = new BufferedReader(new InputStreamReader(link.openStream()));

        String s = "";
        String tmp;
        while ((tmp = reader.readLine()) != null) {
            s += tmp;
        }

        JSONParser parser = new JSONParser();
        JSONObject o = (JSONObject) parser.parse(s);

        int i;
        for (i = 0; i < o.size(); i++) {
            Post p = new Post();
            p.setId(o.keySet().toArray()[i].toString());
            JSONObject postEntry = (JSONObject) parser.parse(o.get(p.getId()).toString());
            p.setAuthor((String) postEntry.get("author"));
            p.setJudul((String) postEntry.get("judul"));
            p.setKonten((String) postEntry.get("konten"));
            p.setTanggal((String) postEntry.get("tanggal"));
            p.setDeleted((String) postEntry.get("deleted"));
            p.setPublished((String) postEntry.get("published"));

            if ((!p.isDeleted()) && p.isPublished()) {
                out.add(p);
            }
        }

        return out;
        //System.out.println(array.get(0));
    } catch (MalformedURLException ex) {
        Logger.getLogger(cobablog.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(cobablog.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParseException ex) {
        Logger.getLogger(cobablog.class.getName()).log(Level.SEVERE, null, ex);
    }
    return out;
}

From source file:blog.cobablog.java

/**
 * Web service operation/*ww w. j  av a2  s.  co  m*/
 * @param query
 * @return 
 */
@WebMethod(operationName = "search")
public List<Post> search(@WebParam(name = "query") String query) {
    List<Post> out = new ArrayList<Post>();
    try {
        //TODO write your implementation code here:
        String linkString = LINK_FIREBASE + "posts.json";
        URL link = new URL(linkString);
        BufferedReader reader = new BufferedReader(new InputStreamReader(link.openStream()));

        String s = "";
        String tmp;
        while ((tmp = reader.readLine()) != null) {
            s += tmp;
        }

        JSONParser parser = new JSONParser();
        JSONObject o = (JSONObject) parser.parse(s);

        int i;
        for (i = 0; i < o.size(); i++) {
            Post p = new Post();
            p.setId(o.keySet().toArray()[i].toString());
            JSONObject postEntry = (JSONObject) parser.parse(o.get(p.getId()).toString());
            p.setAuthor((String) postEntry.get("author"));
            p.setJudul((String) postEntry.get("judul"));
            p.setKonten((String) postEntry.get("konten"));
            p.setTanggal((String) postEntry.get("tanggal"));
            p.setDeleted((String) postEntry.get("deleted"));
            p.setPublished((String) postEntry.get("published"));

            boolean kontenFound = p.getKonten().toLowerCase().contains(query.toLowerCase());
            boolean judulFound = p.getJudul().toLowerCase().contains(query.toLowerCase());
            if ((!p.isDeleted()) && (p.isPublished()) && (judulFound || kontenFound)) {
                out.add(p);
            }
        }

        return out;
        //System.out.println(array.get(0));
    } catch (MalformedURLException ex) {
        Logger.getLogger(cobablog.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(cobablog.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParseException ex) {
        Logger.getLogger(cobablog.class.getName()).log(Level.SEVERE, null, ex);
    }
    return out;
}