List of usage examples for org.json.simple JSONObject containsKey
boolean containsKey(Object key);
From source file:com.memetix.mst.MicrosoftTranslatorAPI.java
private static String[] jsonToStringArr(final String inputString, final String propertyName) throws Exception { final JSONArray jsonArr = (JSONArray) JSONValue.parse(inputString); String[] values = new String[jsonArr.size()]; int i = 0;/* www .ja va2 s . co m*/ for (Object obj : jsonArr) { if (propertyName != null && propertyName.length() != 0) { final JSONObject json = (JSONObject) obj; if (json.containsKey(propertyName)) { values[i] = json.get(propertyName).toString(); } } else { values[i] = obj.toString(); } i++; } return values; }
From source file:com.walmartlabs.mupd8.application.Config.java
public static Object getScopedValue(JSONObject object, String[] path) { if (path == null) { throw new NullPointerException("path parameter to getScopedValue may not be null"); }//w w w . j av a 2 s. c o m if (path.length == 0) { return object; } String key = path[0]; if (!object.containsKey(key)) { // TODO ...or return new JSONObject()? return null; } if (path.length == 1) { return object.get(key); // not necessarily JSONObject } return getScopedValue((JSONObject) object.get(key), Arrays.copyOfRange(path, 1, path.length)); }
From source file:net.amigocraft.mpt.util.MiscUtil.java
public static JSONObject getRemoteIndex(String path) throws MPTException { try {//from ww w. j a v a 2s . c o m URL url = new URL(path + (!path.endsWith("/") ? "/" : "") + "mpt.json"); // get URL object for data file URLConnection conn = url.openConnection(); if (conn instanceof HttpURLConnection) { HttpURLConnection http = (HttpURLConnection) conn; // cast the connection int response = http.getResponseCode(); // get the response if (response >= 200 && response <= 299) { // verify the remote isn't upset at us InputStream is = http.getInputStream(); // open a stream to the URL BufferedReader reader = new BufferedReader(new InputStreamReader(is)); // get a reader JSONParser parser = new JSONParser(); // get a new parser String line; StringBuilder content = new StringBuilder(); while ((line = reader.readLine()) != null) content.append(line); JSONObject json = (JSONObject) parser.parse(content.toString()); // parse JSON object // vefify remote config is valid if (json.containsKey("packages") && json.get("packages") instanceof JSONObject) { return json; } else throw new MPTException( ERROR_COLOR + "Index for repository at " + path + "is missing required elements!"); } else { String error = ERROR_COLOR + "Remote returned bad response code! (" + response + ")"; if (!http.getResponseMessage().isEmpty()) error += " The remote says: " + ChatColor.GRAY + ChatColor.ITALIC + http.getResponseMessage(); throw new MPTException(error); } } else throw new MPTException(ERROR_COLOR + "Bad protocol for URL!"); } catch (MalformedURLException ex) { throw new MPTException(ERROR_COLOR + "Cannot parse URL!"); } catch (IOException ex) { throw new MPTException(ERROR_COLOR + "Cannot open connection to URL!"); } catch (ParseException ex) { throw new MPTException(ERROR_COLOR + "Repository index is not valid JSON!"); } }
From source file:jGPIO.DTO.java
public static JSONObject findDetails(String gpio_name) { // Do we have a valid definition file, or should we just direct map? if (pinDefinitions == null) { autoDetectSystemFile();//from w ww .j a v a 2 s .c o m } if (pinDefinitions == null) { System.out.println("No definitions file found, assuming direct mapping"); return null; } for (Object obj : pinDefinitions) { JSONObject jObj = (JSONObject) obj; String key = (String) jObj.get("key"); if (key.equalsIgnoreCase(gpio_name)) { return jObj; } if (jObj.containsKey("options")) { JSONArray options = (JSONArray) jObj.get("options"); for (int i = 0; i < options.size(); i++) { String option = (String) options.get(i); if (option.equalsIgnoreCase(gpio_name)) { return jObj; } } } } // not found return null; }
From source file:at.ac.tuwien.dsg.rSybl.planningEngine.staticData.ActionEffects.java
public static void setActionEffects(String eff) { PlanningLogger.logger.info("~~~~~~~~~~Action effects set through web serv, setting the effects ! "); JSONParser parser = new JSONParser(); applicationSpecificActionEffects = new HashMap<String, List<ActionEffect>>(); Object obj;/* w w w. j a v a2 s . c o m*/ try { obj = parser.parse(eff); JSONObject jsonObject = (JSONObject) obj; for (Object actionName : jsonObject.keySet()) { String myaction = (String) actionName; JSONObject object = (JSONObject) jsonObject.get(myaction); for (Object actions : object.keySet()) { ActionEffect actionEffect = new ActionEffect(); actionEffect.setActionType((String) myaction); actionEffect.setActionName((String) actions); JSONObject scaleinDescription = (JSONObject) object.get(actions); if (scaleinDescription.containsKey("conditions")) { JSONArray conditions = (JSONArray) jsonObject.get("conditions"); for (int i = 0; i < conditions.size(); i++) { actionEffect.addCondition((String) conditions.get(i)); } } String targetUnit = (String) scaleinDescription.get("targetUnit"); actionEffect.setTargetedEntityID(targetUnit); JSONObject effects = (JSONObject) scaleinDescription.get("effects"); for (Object effectPerUnit : effects.keySet()) { //System.out.println(effects.toString()); String affectedUnit = (String) effectPerUnit; JSONObject metriceffects = (JSONObject) effects.get(affectedUnit); for (Object metric : metriceffects.keySet()) { String metricName = (String) metric; try { actionEffect.setActionEffectForMetric(metricName, (Double) metriceffects.get(metricName), affectedUnit); } catch (Exception e) { actionEffect.setActionEffectForMetric(metricName, ((Long) metriceffects.get(metricName)).doubleValue(), affectedUnit); } } } if (!applicationSpecificActionEffects.containsKey(actionEffect.getTargetedEntityID().trim())) { List<ActionEffect> l = new ArrayList<ActionEffect>(); l.add(actionEffect); applicationSpecificActionEffects.put(actionEffect.getTargetedEntityID().trim(), l); //PlanningLogger.logger.info("New Action effects "+actionEffect.getActionType()+" "+actionEffect.getActionName()+" "+actionEffect.getTargetedEntityID()); } else { applicationSpecificActionEffects.get(actionEffect.getTargetedEntityID().trim()) .add(actionEffect); //PlanningLogger.logger.info("Adding Action effects "+actionEffect.getActionType()+" "+actionEffect.getActionName()+" "+actionEffect.getTargetedEntityID()); } } } } catch (ParseException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }
From source file:at.ac.tuwien.dsg.rSybl.planningEngine.staticData.ActionEffects.java
public static HashMap<String, List<ActionEffect>> getActionConditionalEffects() { if (applicationSpecificActionEffects.isEmpty() && defaultActionEffects.isEmpty()) { PlanningLogger.logger.info("~~~~~~~~~~Action effects is empty, reading the effects ! "); JSONParser parser = new JSONParser(); try {/* w w w. ja v a 2 s . co m*/ InputStream inputStream = Configuration.class.getClassLoader() .getResourceAsStream(Configuration.getEffectsPath()); Object obj = parser.parse(new InputStreamReader(inputStream)); JSONObject jsonObject = (JSONObject) obj; for (Object actionName : jsonObject.keySet()) { String myaction = (String) actionName; JSONObject object = (JSONObject) jsonObject.get(myaction); for (Object actions : object.keySet()) { ActionEffect actionEffect = new ActionEffect(); actionEffect.setActionType((String) myaction); actionEffect.setActionName((String) actions); JSONObject scaleinDescription = (JSONObject) object.get(actions); if (scaleinDescription.containsKey("conditions")) { JSONArray conditions = (JSONArray) jsonObject.get("conditions"); for (int i = 0; i < conditions.size(); i++) { actionEffect.addCondition((String) conditions.get(i)); } } String targetUnit = (String) scaleinDescription.get("targetUnit"); actionEffect.setTargetedEntityID(targetUnit); JSONObject effects = (JSONObject) scaleinDescription.get("effects"); for (Object effectPerUnit : effects.keySet()) { //System.out.println(effects.toString()); String affectedUnit = (String) effectPerUnit; JSONObject metriceffects = (JSONObject) effects.get(affectedUnit); for (Object metric : metriceffects.keySet()) { String metricName = (String) metric; try { actionEffect.setActionEffectForMetric(metricName, (Double) metriceffects.get(metricName), affectedUnit); } catch (Exception e) { actionEffect.setActionEffectForMetric(metricName, ((Long) metriceffects.get(metricName)).doubleValue(), affectedUnit); } } } if (applicationSpecificActionEffects.get(actionEffect.getTargetedEntityID()) == null) { List<ActionEffect> l = new ArrayList<ActionEffect>(); l.add(actionEffect); applicationSpecificActionEffects.put(actionEffect.getTargetedEntityID(), l); } else { applicationSpecificActionEffects.get(actionEffect.getTargetedEntityID()) .add(actionEffect); } } } } catch (Exception e) { PlanningLogger.logger.info("~~~~~~~~~~Retrying reading the effects "); parser = new JSONParser(); try { InputStream inputStream = Configuration.class.getClassLoader() .getResourceAsStream(Configuration.getEffectsPath()); Object obj = parser.parse(new InputStreamReader(inputStream)); JSONObject jsonObject = (JSONObject) obj; for (Object actionName : jsonObject.keySet()) { String myaction = (String) actionName; ActionEffect actionEffect = new ActionEffect(); actionEffect.setActionType((String) myaction); actionEffect.setActionName((String) myaction); JSONObject object = (JSONObject) jsonObject.get(myaction); JSONObject metrics = (JSONObject) object.get("effects"); for (Object me : metrics.keySet()) { String metric = (String) me; Double metricEffect = (Double) metrics.get(metric); actionEffect.setActionEffectForMetric(metric, metricEffect, ""); } defaultActionEffects.put(myaction, actionEffect); } } catch (Exception ex) { PlanningLogger.logger .error("Error when reading the effects!!!!!!!!!!!!!!!!!!" + ex.getMessage()); } } } return applicationSpecificActionEffects; }
From source file:at.ac.tuwien.dsg.quelle.cloudServicesModel.util.conversions.ConvertToJSON.java
public static String convertToJSON(MultiLevelRequirements multiLevelRequirements) { //traverse the tree to do the JSON properly List<JSONObject> jsontree = new ArrayList<JSONObject>(); List<MultiLevelRequirements> multiLevelRequirementsTree = new ArrayList<MultiLevelRequirements>(); JSONObject root = processMultiLevelRequirementsElement(multiLevelRequirements); jsontree.add(root);//from w w w . j a v a2s . co m multiLevelRequirementsTree.add(multiLevelRequirements); //traverse the tree in a DFS manner while (!multiLevelRequirementsTree.isEmpty()) { MultiLevelRequirements currentlyProcessed = multiLevelRequirementsTree.remove(0); JSONObject currentlyProcessedJSONObject = jsontree.remove(0); JSONArray childrenArray = new JSONArray(); //process children for (MultiLevelRequirements child : currentlyProcessed.getContainedElements()) { JSONObject childJSON = processMultiLevelRequirementsElement(child); childrenArray.add(childJSON); //next to process are children jsontree.add(childJSON); multiLevelRequirementsTree.add(child); } if (currentlyProcessedJSONObject.containsKey("children")) { JSONArray array = (JSONArray) currentlyProcessedJSONObject.get("children"); array.addAll(childrenArray); } else { currentlyProcessedJSONObject.put("children", childrenArray); } } return root.toJSONString(); }
From source file:com.dynamobi.network.DynamoNetworkUdr.java
/** * Full form./* www . j a v a 2 s .c o m*/ */ public static void download(String publisher, String pkgName, String version, boolean install) throws SQLException { List<RepoInfo> repos = getRepoUrls(); for (RepoInfo inf : repos) { if (!inf.accessible) continue; String repo = inf.url; // by default, we pick the package from the first repo we find it in. // Enhancement: supply repo url in function call. JSONObject repo_data = downloadMetadata(repo); JSONArray pkgs = (JSONArray) repo_data.get("packages"); for (JSONObject obj : (List<JSONObject>) pkgs) { if (isPkg(publisher, pkgName, version, obj)) { String jar = jarName(obj); String url = repo; if (!url.endsWith("/")) url += "/"; if (obj.containsKey("url")) url = obj.get("url").toString(); else url += jar; fetchJar(url, jar, obj.get("md5sum").toString()); if (install) installJar(jarName(obj)); // automatically install dependencies, and the deps of deps, // recursively. // Enhancement: optional function call param for this. for (String fullName : (List<String>) obj.get("depend")) { // we have to find which package it is without relying on // splitting the string... and it could be in any repo! // Yes this is very slow. for (RepoInfo depinf : repos) { if (!depinf.accessible) continue; for (JSONObject depobj : (List<JSONObject>) downloadMetadata(inf.url).get("packages")) { if (jarNameMatches(depobj, fullName)) { download(depobj.get("publisher").toString(), depobj.get("package").toString(), depobj.get("version").toString(), install); break; } } } } return; } } } }
From source file:it.polimi.diceH2020.plugin.control.FileManager.java
private static boolean setMachineLearningHadoop(InstanceDataMultiProvider data) { // Set mapJobMLProfile - MACHINE LEARNING Map<String, JobMLProfile> jmlMap = new HashMap<String, JobMLProfile>(); JSONParser parser = new JSONParser(); try {//from w w w . j a v a 2 s .co m for (ClassDesc cd : Configuration.getCurrent().getClasses()) { Map<String, SVRFeature> map = new HashMap<String, SVRFeature>(); Object obj = parser.parse(new FileReader(cd.getMlPath())); JSONObject jsonObject = (JSONObject) obj; JSONObject parameter = (JSONObject) jsonObject.get("mlFeatures"); Map<String, String> toCheck = cd.getAltDtsmHadoop() .get(cd.getAltDtsmHadoop().keySet().iterator().next()); for (String st : toCheck.keySet()) { if (!st.equals("file")) { if (!parameter.containsKey(st)) { JOptionPane.showMessageDialog(null, "Missing field in machine learning file: " + st + "\n" + "for class: " + cd.getId(), "Error: ", JOptionPane.ERROR_MESSAGE); return false; } } } double b = (double) jsonObject.get("b"); double mu_t = (double) jsonObject.get("mu_t"); double sigma_t = (double) jsonObject.get("sigma_t"); if (!parameter.containsKey("x")) { JOptionPane.showMessageDialog(null, "Missing field in machine learning file: " + "x " + "\n" + "for class: " + cd.getId(), "Error: ", JOptionPane.ERROR_MESSAGE); return false; } if (!parameter.containsKey("h")) { JOptionPane.showMessageDialog(null, "Missing field in machine learning file: " + "h" + "\n" + "for class: " + cd.getId(), "Error: ", JOptionPane.ERROR_MESSAGE); return false; } Iterator<?> iterator = parameter.keySet().iterator(); while (iterator.hasNext()) { String key = (String) iterator.next(); if (!toCheck.containsKey(key) && !key.equals("x") && !key.equals("h")) continue; JSONObject locObj = (JSONObject) parameter.get(key); SVRFeature feat = new SVRFeature(); feat.setMu((double) locObj.get("mu")); feat.setSigma((double) locObj.get("sigma")); feat.setW((double) locObj.get("w")); map.put(key, feat); } jmlMap.put(String.valueOf(cd.getId()), new JobMLProfile(map, b, mu_t, sigma_t)); } } catch (Exception e) { e.printStackTrace(); } JobMLProfilesMap jML = JobMLProfilesMapGenerator.build(); jML.setMapJobMLProfile(jmlMap); data.setMapJobMLProfiles(jML); return true; }
From source file:com.worldline.easycukes.commons.helpers.JSONHelper.java
/** * Returns <b>true</b> if JSON object o1 is equals to JSON object o2. * * @param o1 a {@link JSONObject} containing some JSON data * @param o2 another {@link JSONObject} containing some JSON data * @return true if the json objects are equals *///from w ww.ja v a2 s. com public static boolean equals(@NonNull JSONObject o1, @NonNull JSONObject o2) { if (o1 == o2) return true; if (o1.size() != o2.size()) return false; try { final Iterator<Entry<String, Object>> i = o1.entrySet().iterator(); while (i.hasNext()) { final Entry<String, Object> e = i.next(); final String key = e.getKey(); final Object value1 = e.getValue(); final Object value2 = o2.get(key); if (value1 == null) { if (!(o2.get(key) == null && o2.containsKey(key))) return false; } else if (value1 instanceof JSONObject) { if (!(value2 instanceof JSONObject)) return false; if (!equals((JSONObject) value1, (JSONObject) value2)) return false; } else if (value1 instanceof JSONArray) { if (!(value2 instanceof JSONArray)) return false; if (!equals((JSONArray) value1, (JSONArray) value2)) return false; } else if (!value1.equals(value2)) return false; } } catch (final Exception unused) { unused.printStackTrace(); return false; } return true; }