Java Code Examples for org.json.JSONObject#get()

The following examples show how to use org.json.JSONObject#get() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FileManager.java    From KakaoBot with GNU General Public License v3.0 6 votes vote down vote up
public static Object readData(Type.Project project, String key) {
    File root = getProjectFile(project);
    File data = new File(root, "data.json");

    try {
        BufferedReader reader = new BufferedReader(new FileReader(data));
        BufferedWriter writer = new BufferedWriter(new FileWriter(data));

        String line;
        JSONObject json = new JSONObject();
        while((line = reader.readLine()) != null) {
            JSONObject object = new JSONObject(line);
            if(object.has(key)) {
                return object.get(key);
            }
        }
        writer.write(json.toString());
    } catch(IOException err) {}
    catch (JSONException e) {
        e.printStackTrace();
    }

    return null;
}
 
Example 2
Source File: TvShowListApi.java    From iview-android-tv with MIT License 6 votes vote down vote up
private List<EpisodeBaseModel> getEpisodesFromData(JSONObject data, boolean addToCollection) {
    List<EpisodeBaseModel> titles = new ArrayList<>();
    if (data != null) {
        Iterator<String> keys = data.keys();
        while (keys.hasNext()) {
            String key = keys.next();
            try {
                if (data.get(key) instanceof JSONArray) {
                    JSONArray groups = data.getJSONArray(key);
                    titles.addAll(getEpisodesFromList(groups, addToCollection));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
    return titles;
}
 
Example 3
Source File: CustomDataSet.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
private Map convertStringToMap(String _customData) {
	LogMF.debug(logger, "IN : {0}", _customData);
	Map toInsert = new HashMap<String, Object>();
	try {
		if (_customData != null && !_customData.equals("")) {
			JSONObject jsonObject = new JSONObject(_customData);

			String[] names = JSONObject.getNames(jsonObject);
			if(names!=null){
				for (int i = 0; i < names.length; i++) {
					String nm = names[i];
					Object value = jsonObject.get(nm);
					logger.debug("Property read: key is [" + nm
							+ "], value is [" + value + "]");
					toInsert.put(nm, value);
				}
			}

		}
	} catch (Exception e) {
		logger.error("cannot parse to Map the Json string " + customData, e);
	}
	LogMF.debug(logger, "OUT : {0}", toInsert);
	return toInsert;

}
 
Example 4
Source File: BlogRepositoryCustomImpl.java    From Spring-5.0-Projects with MIT License 6 votes vote down vote up
private List<Blog> getBlogListFromSearchJSON(String jsonResponse) {
	
	List<Blog> blogResults = new ArrayList<Blog>();
	ObjectMapper objMapper = new ObjectMapper();
	if(jsonResponse !=null) {
		JSONObject searchJson = new JSONObject(jsonResponse);
		if(searchJson.get("hits") !=null) {
			JSONObject resultJson = searchJson.getJSONObject("hits");
			try {
				if(resultJson !=null && resultJson.get("hits") !=null) {
					JSONArray blogArr = resultJson.getJSONArray("hits");
					for(int jsonIndex=0;jsonIndex < blogArr.length(); jsonIndex++) {
						blogResults.add(objMapper.readValue(blogArr.getJSONObject(jsonIndex).getJSONObject("_source").toString(), Blog.class));
					}
				}
			} catch (JSONException | IOException e) {
				logger.error("error occuired while fetching all comments "+e.getMessage(),e);
			}	
		}
	}
	return blogResults;
}
 
Example 5
Source File: PluginManager.java    From plugin-installation-manager-tool with MIT License 6 votes vote down vote up
/**
 * Gets the JSONArray containing plugin a
 *
 * @param plugin to get depedencies for
 * @param ucJson update center json from which to parse dependencies
 * @return JSONArray containing plugin dependencies
 */
public JSONArray getPluginDependencyJsonArray(Plugin plugin, JSONObject ucJson) {
    JSONObject plugins = ucJson.getJSONObject("plugins");
    if (!plugins.has(plugin.getName())) {
        return null;
    }

    JSONObject pluginInfo = (JSONObject) plugins.get(plugin.getName());

    if (ucJson.equals(pluginInfoJson)) {
        //plugin-versions.json has a slightly different structure than other update center json
        if (pluginInfo.has(plugin.getVersion().toString())) {
            JSONObject specificVersionInfo = pluginInfo.getJSONObject(plugin.getVersion().toString());
            plugin.setJenkinsVersion(specificVersionInfo.getString("requiredCore"));
            return (JSONArray) specificVersionInfo.get("dependencies");
        }
    } else {
        plugin.setJenkinsVersion(pluginInfo.getString("requiredCore"));
        //plugin version is latest or experimental
        String version = pluginInfo.getString("version");
        plugin.setVersion(new VersionNumber(version));
        return (JSONArray) pluginInfo.get("dependencies");
    }
    return null;
}
 
Example 6
Source File: RESTDataSet.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
protected Map<String, String> getRequestHeadersPropMap(String propName, JSONObject conf, boolean resolveParams) throws JSONException {
	if (!conf.has(propName) || conf.getString(propName).isEmpty()) {
		// optional property
		return Collections.emptyMap();
	}

	Object c = conf.get(propName);
	if (!(c instanceof JSONObject)) {
		throw new ConfigurationException(String.format("%s is not another json object in configuration: %s", propName, conf.toString()));
	}
	Assert.assertNotNull(c, "property is null");
	JSONObject r = (JSONObject) c;
	Map<String, String> res = new HashMap<String, String>(r.length());
	Iterator<String> it = r.keys();
	while (it.hasNext()) {
		String key = it.next();
		String value = r.getString(key);
		if (resolveParams) {
			key = parametersResolver.resolveAll(key, this);
			value = parametersResolver.resolveAll(value, this);
		}
		res.put(key, value);
	}
	return res;
}
 
Example 7
Source File: MapUtil.java    From Instabug-React-Native with MIT License 6 votes vote down vote up
public static Map<String, Object> toMap(JSONObject jsonObject) throws JSONException {
    Map<String, Object> map = new HashMap<>();
    Iterator<String> iterator = jsonObject.keys();

    while (iterator.hasNext()) {
        String key = iterator.next();
        Object value = jsonObject.get(key);

        if (value instanceof JSONObject) {
            value = MapUtil.toMap((JSONObject) value);
        }
        if (value instanceof JSONArray) {
            value = ArrayUtil.toArray((JSONArray) value);
        }

        map.put(key, value);
    }

    return map;
}
 
Example 8
Source File: Utility.java    From platform-friends-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
static Map<String, Object> convertJSONObjectToHashMap(JSONObject jsonObject) {
    HashMap<String, Object> map = new HashMap<String, Object>();
    JSONArray keys = jsonObject.names();
    for (int i = 0; i < keys.length(); ++i) {
        String key;
        try {
            key = keys.getString(i);
            Object value = jsonObject.get(key);
            if (value instanceof JSONObject) {
                value = convertJSONObjectToHashMap((JSONObject) value);
            }
            map.put(key, value);
        } catch (JSONException e) {
        }
    }
    return map;
}
 
Example 9
Source File: h2oService.java    From h2o-2 with Apache License 2.0 6 votes vote down vote up
public String JobStatus( String job_key, String destination_key )  {
    String status ;
    String h2oUrlJobStatusEndPoint = H2O_HOST_URL + H2O_PROGRESS_URL + "job_key=" + job_key + "&destination_key=" + destination_key;
    System.out.println(h2oUrlJobStatusEndPoint);
    log.debug("@@@ Calling endpoint {}", h2oUrlJobStatusEndPoint);
    RestTemplate restTemplate = new RestTemplate();
    try {
        while (true) {
            String responseBody = restTemplate.getForObject(h2oUrlJobStatusEndPoint, String.class);
            JSONObject jsonobject = new JSONObject(responseBody);
            JSONObject response_info = (JSONObject)jsonobject.get("response_info");
            status = (String)response_info.get("status");
            log.debug("!!!!!! JOB Status  {}", status);
            if (status.equalsIgnoreCase("redirect")) {
                break;
            }
            Thread.sleep(2000L); //Should use futures here
        }
    }catch(Exception ex){
        log.debug("!!!!!! Error Occured while getting job status  {}", ex);
        return null;
    }
    return status;
}
 
Example 10
Source File: IdentityManagementEndpointUtil.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
private static void buildService(JSONObject service, String consentType, boolean isPrimaryPurpose, boolean
        isThirdPartyDisclosure, String termination) {

    JSONArray purposes = (JSONArray) service.get(IdentityManagementEndpointConstants.Consent.PURPOSES);

    for (int purposeIndex = 0; purposeIndex < purposes.length(); purposeIndex++) {
        buildPurpose((JSONObject) purposes.get(purposeIndex), consentType, isPrimaryPurpose,
                isThirdPartyDisclosure, termination);
    }
}
 
Example 11
Source File: OpenAPIParser.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
/**
 * API 全体に適用されるセキュリティスキームを解析します.
 *
 * @param jsonObject API 全体に適用されるセキュリティスキームを格納したJSONオブジェクト
 * @return API 全体に適用されるセキュリティスキーム
 * @throws JSONException JSONの解析に失敗した場合に発生
 */
private static Map<String, String> parseSecurity(JSONObject jsonObject) throws JSONException {
    Map<String, String> securityScheme = new HashMap<>();
    for (Iterator<String> it = jsonObject.keys(); it.hasNext();) {
        String key = it.next();
        Object object = jsonObject.get(key);
        if (object instanceof String) {
            securityScheme.put(key, (String) object);
        }
    }
    return securityScheme;
}
 
Example 12
Source File: Compressor.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
/**
 * Write a JSON object.
 * 
 * @param jsonobject
 * @return
 * @throws JSONException
 */
private void writeObject(JSONObject jsonobject) throws JSONException {

	// JSONzip has two encodings for objects: Empty Objects (zipEmptyObject)
	// and
	// non-empty objects (zipObject).

	boolean first = true;
	Iterator keys = jsonobject.keys();
	while (keys.hasNext()) {
		if (probe) {
			log("\n");
		}
		Object key = keys.next();
		if (key instanceof String) {
			if (first) {
				first = false;
				write(zipObject, 3);
			} else {
				one();
			}
			writeName((String) key);
			Object value = jsonobject.get((String) key);
			if (value instanceof String) {
				zero();
				writeString((String) value);
			} else {
				one();
				writeValue(value);
			}
		}
	}
	if (first) {
		write(zipEmptyObject, 3);
	} else {
		zero();
	}
}
 
Example 13
Source File: Plugin.java    From OsmGo with MIT License 5 votes vote down vote up
public Object getConfigValue(String key) {
  try {
    JSONObject plugins = Config.getObject("plugins");
    if (plugins == null) {
      return null;
    }
    JSONObject pluginConfig = plugins.getJSONObject(getPluginHandle().getId());
    return pluginConfig.get(key);
  } catch (JSONException ex) {
    return null;
  }
}
 
Example 14
Source File: HstoreParser.java    From open-rmbt with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param json
 * @param key
 * @param toField
 * @return
 * @throws JSONException
 */
public static Object getFromJsonByField2(JSONObject json, String key, Field toField) throws JSONException {
	final Object o = json.get(key);
	final Class<?> fieldType = toField.getType();
	if (o != JSONObject.NULL) {
		if (fieldType.equals(Integer.class) || fieldType.equals(Integer.TYPE)) {
			return json.getInt(key);
		}
		else if (fieldType.equals(String.class)) {
			return o;
		}
		else if (fieldType.equals(Long.class) || fieldType.equals(Long.TYPE)) {
			return json.getLong(key);
		}
		else if (fieldType.equals(Boolean.class) || fieldType.equals(Boolean.TYPE)) {
			return json.getBoolean(key);
		}
		else if (fieldType.equals(Float.class) || fieldType.equals(Float.TYPE)) {
			return (float) json.getDouble(key);
		}
		else if (fieldType.equals(Double.class) || fieldType.equals(Double.TYPE)) {
			return json.getDouble(key);
		}
		else {
			return o;
		}			
	}

	return JSONObject.NULL;
}
 
Example 15
Source File: WebPlayerView.java    From unity-ads-android with Apache License 2.0 5 votes vote down vote up
private Object[] getValues(JSONArray parameters) throws JSONException, ClassNotFoundException, NoSuchMethodException {
	Object[] values;
	if(parameters == null) {
		return null;
	} else {
		values = new Object[parameters.length()];
	}

	Object[] params = new Object[parameters.length()];
	for (int i = 0; i < parameters.length(); i++) {
		if (parameters.get(i) instanceof JSONObject) {
			JSONObject param = (JSONObject)parameters.get(i);
			Object value = param.get("value");
			String type = param.getString("type");
			String className = null;

			if (param.has("className")) {
				className = param.getString("className");
			}

			if (className != null && type.equals("Enum")) {
				Class<?> enumClass = Class.forName(className);
				if (enumClass != null) {
					params[i] = Enum.valueOf((Class<Enum>)enumClass, (String)value);
				}
			}
		}
		else {
			params[i] = parameters.get(i);
		}
	}

	if(parameters != null) {
		System.arraycopy(params, 0, values, 0, parameters.length());
	}

	return values;
}
 
Example 16
Source File: ArtifactsUploader.java    From AppiumTestDistribution with GNU General Public License v3.0 5 votes vote down vote up
private HashMap<String, String> getArtifactForHost(String hostMachine) throws Exception {
    String platform = System.getenv("Platform");
    String app = "app";
    HashMap<String, String> artifactPaths = new HashMap<>();
    JSONObject android = capabilityManager
        .getCapabilityObjectFromKey("android");
    JSONObject iOSAppPath = capabilityManager
        .getCapabilityObjectFromKey("iOS");
    if (android != null && android.has(app)
        && (platform.equalsIgnoreCase("android")
        || platform.equalsIgnoreCase("both"))) {
        JSONObject androidApp = android.getJSONObject("app");
        String appPath = androidApp.getString("local");
        if (isCloud(hostMachine) && androidApp.has("cloud")) {
            appPath = androidApp.getString("cloud");
        }
        artifactPaths.put("APK", getArtifactPath(hostMachine, appPath));
    }
    if (iOSAppPath != null && iOSAppPath.has("app")
        && (platform.equalsIgnoreCase("ios")
        || platform.equalsIgnoreCase("both"))) {
        if (iOSAppPath.get("app") instanceof JSONObject) {
            JSONObject iOSApp = iOSAppPath.getJSONObject("app");
            if (iOSApp.has("simulator")) {
                String simulatorApp = iOSApp.getString("simulator");
                artifactPaths.put("APP", getArtifactPath(hostMachine, simulatorApp));
            }
            if (iOSApp.has("device")) {
                String deviceIPA = iOSApp.getString("device");
                artifactPaths.put("IPA", getArtifactPath(hostMachine, deviceIPA));
            }
            if (isCloud(hostMachine) && iOSApp.has("cloud")) {
                String cloudApp = iOSApp.getString("cloud");
                artifactPaths.put("APP", getArtifactPath(hostMachine, cloudApp));
            }
        }
    }
    return artifactPaths;
}
 
Example 17
Source File: BlogRepositoryCustomImpl.java    From Spring-5.0-Projects with MIT License 5 votes vote down vote up
private List<Comment> getAllCommentsFromJson(String commentJsonStr) {
	String commentArrStr = "{}";
	List<Comment> allComments = new ArrayList<Comment>();
	
	ObjectMapper objMapper = new ObjectMapper();
	if(commentJsonStr !=null) {
		JSONObject commentJsonObj = new JSONObject(commentJsonStr);
		if(commentJsonObj.getJSONObject("aggChild") !=null) {
			JSONObject aggChildObj = commentJsonObj.getJSONObject("aggChild");
			if(aggChildObj !=null && aggChildObj.getJSONObject("aggSortComment")!=null) {
				JSONObject aggSortCommentObj =aggChildObj.getJSONObject("aggSortComment");
				if(aggSortCommentObj !=null && aggSortCommentObj.getJSONObject("hits") !=null) {
					JSONObject hitObject = aggSortCommentObj.getJSONObject("hits");
					try {
						if(hitObject !=null && hitObject.get("hits") !=null) {
							JSONArray aggCommentArr = hitObject.getJSONArray("hits");
							for(int jsonIndex=0;jsonIndex < aggCommentArr.length(); jsonIndex++) {
								allComments.add(objMapper.readValue(aggCommentArr.getJSONObject(jsonIndex).getJSONObject("_source").toString(), Comment.class));
							}
						}
					} catch (JSONException | IOException e) {
						logger.error("error occuired while fetching all comments "+e.getMessage(),e);
					}	
				}
			}
		}
	}
	return allComments;
}
 
Example 18
Source File: RecommenderDetailsExtractor.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Update the recommendationsCache by  connecting with the recommendation engine and getting recommendations for
 * the given user for given tenant domain. A user can have several entries cache for different tenants
 *
 * @param userName     User's Name
 * @param tenantDomain tenantDomain
 */
public void updateRecommendationsCache(String userName, String tenantDomain) {

    long currentTime = System.currentTimeMillis();
    long lastUpdatedTime = 0;
    long waitDuration = recommendationEnvironment.getWaitDuration() * 60 * 1000;
    Cache recommendationsCache = CacheProvider.getRecommendationsCache();
    String cacheName = userName + "_" + tenantDomain;
    JSONObject cachedObject = (JSONObject) recommendationsCache.get(cacheName);
    if (cachedObject != null) {
        lastUpdatedTime = (long) cachedObject.get(APIConstants.LAST_UPDATED_CACHE_KEY);
    }
    if (currentTime - lastUpdatedTime < waitDuration) { // double checked locking to avoid unnecessary locking
        return;
    }
    synchronized (RecommenderDetailsExtractor.class) {
        // Only get recommendations if the last update was was performed more than 15 minutes ago
        if (currentTime - lastUpdatedTime < waitDuration) {
            return;
        }
        String recommendations = getRecommendations(userName, tenantDomain);
        JSONObject object = new JSONObject();
        object.put(APIConstants.RECOMMENDATIONS_CACHE_KEY, recommendations);
        object.put(APIConstants.LAST_UPDATED_CACHE_KEY, System.currentTimeMillis());
        recommendationsCache.put(cacheName, object);
    }
}
 
Example 19
Source File: Loader.java    From act with GNU General Public License v3.0 4 votes vote down vote up
private List<Precursor> getUpstreamPrecursors(Long parentId, JSONArray upstreamReactions) {
  Map<Long, InchiDescriptor> substrateCache = new HashMap<>();
  Map<List<InchiDescriptor>, Precursor> substratesToPrecursor = new HashMap<>();
  List<Precursor> precursors = new ArrayList<>();

  for (int i = 0; i < upstreamReactions.length(); i++) {
    JSONObject obj = upstreamReactions.getJSONObject(i);
    if (!obj.getBoolean("reachable")) {
      continue;
    }

    List<InchiDescriptor> thisRxnSubstrates = new ArrayList<>();

    JSONArray substratesArrays = (JSONArray) obj.get("substrates");
    for (int j = 0; j < substratesArrays.length(); j++) {
      Long subId = substratesArrays.getLong(j);
      InchiDescriptor parentDescriptor;
      if (subId >= 0 && !substrateCache.containsKey(subId)) {
        try {
          Chemical parent = sourceDBconn.getChemicalFromChemicalUUID(subId);
          upsert(constructOrFindReachable(parent.getInChI()));
          parentDescriptor = new InchiDescriptor(constructOrFindReachable(parent.getInChI()));
          thisRxnSubstrates.add(parentDescriptor);
          substrateCache.put(subId, parentDescriptor);
          // TODO Remove null pointer exception check
        } catch (NullPointerException e) {
          LOGGER.info("Null pointer, unable to write parent.");
        }
      } else if (substrateCache.containsKey(subId)) {
        thisRxnSubstrates.add(substrateCache.get(subId));
      }
    }

    if (!thisRxnSubstrates.isEmpty()) {
      // This is a previously unseen reaction, so add it to the list of precursors.
      List<SequenceData> rxnSequences =
              extractOrganismsAndSequencesForReactions(Collections.singleton(obj.getLong("rxnid")));
      List<String> sequenceIds = new ArrayList<>();
      for (SequenceData seq : rxnSequences) {
        WriteResult<SequenceData, String> result = jacksonSequenceCollection.insert(seq);
        sequenceIds.add(result.getSavedId());
      }

      // TODO: make sure this is what we actually want to do, and figure out why it's happening.
      // De-duplicate reactions based on substrates; somehow some duplicate cascade paths are appearing.
      if (substratesToPrecursor.containsKey(thisRxnSubstrates)) {
        substratesToPrecursor.get(thisRxnSubstrates).addSequences(sequenceIds);
      } else {
        Precursor precursor = new Precursor(thisRxnSubstrates, "reachables", sequenceIds);
        precursors.add(precursor);
        // Map substrates to precursor for merging later.
        substratesToPrecursor.put(thisRxnSubstrates, precursor);
      }
    }
  }

  if (parentId >= 0 && !substrateCache.containsKey(parentId)) {
    // Note: this should be impossible.
    LOGGER.error("substrate cache does not contain parent id %d after all upstream reactions processed", parentId);
  }

  return precursors;
}
 
Example 20
Source File: SelfRegistrationMgtClient.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
private boolean hasPIICategories(JSONObject purpose) {

        JSONArray piiCategories = (JSONArray) purpose.get(PII_CATEGORIES);
        return piiCategories.length() > 0;
    }