Java Code Examples for org.json.simple.JSONObject#containsKey()

The following examples show how to use org.json.simple.JSONObject#containsKey() . These examples are extracted from open source projects. 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
@Override
public boolean checkDatabaseConnection(){
	try{
		//Elasticsearch mappings
		JSONObject mappings = getDB().getMappings();
		boolean elasticOk = (
				mappings.containsKey(DB.USERS) && mappings.containsKey(DB.TICKETS) && 
				mappings.containsKey(DB.WHITELIST) && mappings.containsKey(GUID.INDEX) &&
				mappings.containsKey(DB.USERDATA)
		);
		//System.out.println(mappings);
		if (!elasticOk){
			Debugger.println("checkDatabaseConnection() - Elasticsearch mappings are incomplete or not valid!", 1);
			return false;
		}else{
			return true;
		}
		
	}catch (Exception e){
		errorCode = 3;
		e.printStackTrace();
		return false;
	}
}
 
Example 2
Source Project: istio-apim   File: IstioExecutor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Extract Endpoint url from the endpoints object
 *
 * @param endpoints Endpoints object
 * @return Returns endpoint url
 */
private String getEPUrl(Object endpoints) {

    if (endpoints instanceof JSONObject) {
        JSONObject endpointJson = (JSONObject) endpoints;
        if (endpointJson.containsKey("url") && endpointJson.get("url") != null) {
            String url = endpointJson.get("url").toString();
            if (org.apache.commons.lang.StringUtils.isNotBlank(url)) {
                return url;
            }
        }
    } else if (endpoints instanceof org.json.simple.JSONArray) {
        org.json.simple.JSONArray endpointsJson = (JSONArray) endpoints;

        for (int i = 0; i < endpointsJson.size(); ++i) {
            if (isEndpointURLNonEmpty(endpointsJson.get(i))) {
                return endpointsJson.get(i).toString();
            }
        }
    }

    return "";
}
 
Example 3
Source Project: Explvs-AIO   File: DurationPanel.java    License: MIT License 6 votes vote down vote up
@Override
public void fromJSON(final JSONObject jsonObject) {
    if (jsonObject.containsKey("time_type")) {
        timeTypeSelector.setSelectedItem(TimeType.valueOf((String) jsonObject.get("time_type")));
    }

    if (jsonObject.containsKey("duration")) {
        durationField.setText((String) jsonObject.get("duration"));
    }

    if (jsonObject.containsKey("datetime")) {
        String datetimeStr = (String) jsonObject.get("datetime");
        LocalDateTime datetime = LocalDateTime.parse(
                datetimeStr,
                dtFormatter
        );
        dateTimePanel.setDateTime(datetime);
    }
}
 
Example 4
private Optional<JSONObject> getUserStatisticsFile(UUID uuid, String worldName)
        throws IOException, ParseException {
    Objects.requireNonNull(uuid);
    Objects.requireNonNull(worldName);

    World world = Bukkit.getWorld(worldName);

    if (world == null) return Optional.empty();

    File worldFolder = new File(world.getWorldFolder(), "stats");
    File playerStatistics = new File(worldFolder, uuid.toString() + ".json");

    if (!playerStatistics.exists()) {
        return Optional.empty();
    }

    JSONObject rootObject = (JSONObject) new JSONParser().parse(new FileReader(playerStatistics));

    if (rootObject == null) return Optional.empty();

    if (rootObject.containsKey("stats")) {
        return Optional.ofNullable((JSONObject) rootObject.get("stats"));
    }

    return Optional.empty();
}
 
Example 5
public static void changePassword(String email, String newPwd){
	String idType = ID.Type.email;
	String newPass = Security.hashClientPassword(newPwd);

	JSONObject requestRes = auth.requestPasswordChange(JSON.make(
		"userid", email, 
		"type", idType
	));
	//System.out.println(requestRes);
	if (!requestRes.containsKey("token")){
		throw new RuntimeException("Password reset request failed with code: " + auth.getErrorCode());
	}
	
	JSON.put(requestRes, "userid", email);		
	JSON.add(requestRes, "new_pwd", newPass);
	JSON.add(requestRes, "type", idType);	
	
	if (!auth.changePassword(requestRes)){
		throw new RuntimeException("Password reset failed with code: " + auth.getErrorCode());
	}
}
 
Example 6
protected String getOrNull(JSONObject json, String key) throws JSONException
{
   if (json.containsKey(key))
   {
      return (String)json.get(key);
   }
   return null;
}
 
Example 7
Source Project: metron   File: BasicBroParser.java    License: Apache License 2.0 5 votes vote down vote up
private boolean replaceKey(JSONObject payload, String toKey, String[] fromKeys) {
  for (String fromKey : fromKeys) {
    if (payload.containsKey(fromKey)) {
      Object value = payload.remove(fromKey);
      payload.put(toKey, value);
      _LOG.trace("[Metron] Added {} to {}", toKey, payload);
      return true;
    }
  }
  return false;
}
 
Example 8
Source Project: offspring   File: JSONUtils.java    License: MIT License 5 votes vote down vote up
public static String getString(JSONObject map, String key) {
  if (map != null && map.containsKey(key)) {
    Object value = map.get(key);
    if (value instanceof String)
      return (String) value;
  }
  return "";
}
 
Example 9
static void exe(String key) {
    String data = exe.rmJSVar(exe.read(true, latest.exe.data.FN));
    if (data.startsWith("{") && data.endsWith("}")) {
        JSONObject res = (JSONObject) JSONValue.parse(data);
        if (res.containsKey(key)) {
            System.out.println((String) res.get(key));
        } else {
            LOG.log(Level.INFO, "ERROR:Key '{0}' not exist", key);
        }
    } else {
        System.out.println(data);
    }

}
 
Example 10
Source Project: EchoSim   File: EchoSimServlet.java    License: Apache License 2.0 5 votes vote down vote up
private String getDatum(HttpServletRequest request, JSONObject obj,
        String key, String def)
{
    if ((obj != null) && obj.containsKey(key))
        return (String)obj.get(key);
    if (request.getParameterMap().containsKey(key))
        return request.getParameter(key);
    return def;
}
 
Example 11
Source Project: metron   File: LEEFParser.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private JSONObject mutate(JSONObject json, String oldKey, String newKey) {
  if (json.containsKey(oldKey)) {
    json.put(newKey, json.remove(oldKey));
  }
  return json;
}
 
Example 12
private void parseQOS(JSONObject obj, Offering offering) {
    JSONObject qos = (JSONObject) obj.get("qos");

    if (qos == null || !qos.containsKey("uptime"))
        return;

    Double value = (Double) qos.get("uptime");

    if (value != null)
        offering.addProperty("availability", this.slaFormat.format(value/100.0));
}
 
Example 13
public static void createUser(String email, String pwd){
	String pass = Security.hashClientPassword(pwd);
	//String idType = ID.Type.email;

	JSONObject requestRes = auth.registrationByEmail(email);
	//System.out.println(requestRes);
	if (!requestRes.containsKey("token")){
		throw new RuntimeException("Registration request failed with code: " + auth.getErrorCode());
	}
	
	JSON.put(requestRes, "pwd", pass);
	if (!auth.createUser(requestRes)){
		throw new RuntimeException("Creating user failed with code: " + auth.getErrorCode());
	}
}
 
Example 14
Source Project: sepia-assist-server   File: Setup.java    License: MIT License 5 votes vote down vote up
/**
 * Test if Elasticsearch index exists and (optionally) create when missing.
 * @param createWhenMissing - true/false
 * @throws Exception
 */
public static void testAndUpdateElasticsearchMapping(boolean createWhenMissing) throws Exception{
	Elasticsearch db = new Elasticsearch();
	List<File> mappingFiles = FilesAndStreams.directoryToFileList(Config.dbSetupFolder + "ElasticsearchMappings/", null, false);
	//Test mappings
	JSONObject mappings = db.getMappings();
	if (mappings == null){
		throw new RuntimeException("ElasticSearch - Failed to check mappings! Is ES running and reachable?");
	}else if (mappings.isEmpty()){
		throw new RuntimeException("ElasticSearch - Failed to check mappings! Did you already run SEPIA setup?");
	}
	int mr = 0;
	int mf = 0;
	for (File f : mappingFiles){
		if (!f.getName().contains(".json")){
			//File has to be a .json map
			continue;
		}
		mr++;
		String index = f.getName().replaceFirst("\\.json$", "").trim();
		if (!mappings.containsKey(index)){
			//missing index
			Debugger.println("Elasticsearch - Missing index: " + index, 1);
			if (createWhenMissing){
				Debugger.println("Elasticsearch - Trying to create missing index: " + index, 3);
				writeElasticsearchMapping(index, true);
				mf++;
			}
		}else{
			mf++;
		}
	}
	if (mr == mf){
		Debugger.println("Elasticsearch: found " + mf + " of " + mr + " mapped indices. All good.", 3);
	}else{
		throw new RuntimeException("Elasticsearch: missing " + (mr-mf) + " of " + mr + " mapped indices. Please check database setup.");
	}
}
 
Example 15
Source Project: sepia-assist-server   File: DB.java    License: MIT License 4 votes vote down vote up
/**
 * Get addresses of user that fit to one or more tags.
 * @param userId - ID as usual
 * @param tags - 'specialTag' given by user to this address (e.g. user_home)
 * @param filters - additional filters tbd
 * @return list with addresses (can be empty), null for connection-error or throws an error
 */
public static List<Address> getAddressesByTag(String userId, List<String> tags, Map<String, Object> filters){
	long tic = Debugger.tic();
	//TODO: add version with specialName instead of tag
	
	//validate input
	if (userId == null || userId.isEmpty() || tags == null || tags.isEmpty()){
		throw new RuntimeException("getAddressesByTag - userId or tags invalid!");
	}
	if (userId.contains(",")){
		throw new RuntimeException("getListData - MULTIPLE userIds are not (yet) supported!");
	}
	
	//build query
	List<QueryElement> matches = new ArrayList<>(); 
	matches.add(new QueryElement("user", userId));
	List<QueryElement> oneOf = new ArrayList<>();
	for (String t : tags){
		oneOf.add(new QueryElement("specialTag", t));
	}
	JSONObject query = EsQueryBuilder.getBoolMustAndShoudMatch(matches, oneOf);
	//System.out.println("query: " + query);
	
	//call
	JSONObject data = new JSONObject();
	data = knowledge.searchByJson(USERDATA + "/" + Address.ADDRESSES_TYPE, query.toJSONString());
	
	List<Address> addresses = null;
	if (Connectors.httpSuccess(data)){
		JSONArray addressesArray = JSON.getJArray(data, new String[]{"hits", "hits"});
		addresses = new ArrayList<>();
		if (addressesArray != null){
			for (Object o : addressesArray){
				JSONObject jo = (JSONObject) o;
				if (jo.containsKey("_source")){
					JSONObject adrJson = (JSONObject) jo.get("_source");
					Address adr = new Address(Converters.json2HashMap(adrJson)); 	//we trust that this works ^^
					//get some additional info
					adr.user = JSON.getString(adrJson, "user");
					adr.userSpecialTag = JSON.getString(adrJson, "specialTag");
					adr.userSpecialName = JSON.getString(adrJson, "specialName");
					adr.dbId = JSON.getString(jo, "_id");
					//add
					addresses.add(adr);
				}
			}
		}
	}
	
	//statistics
	Statistics.addOtherApiHit("getAddressesByTagFromDB");
	Statistics.addOtherApiTime("getAddressesByTagFromDB", tic);
	      	
	return addresses;
}
 
Example 16
Source Project: metron   File: ThreatIntelUtils.java    License: Apache License 2.0 4 votes vote down vote up
public static JSONObject triage(JSONObject ret, SensorEnrichmentConfig config, FunctionResolver functionResolver, Context stellarContext) {
  LOG.trace("Received joined messages: {}", ret);
  boolean isAlert = ret.containsKey("is_alert");
  if(!isAlert) {
    for (Object key : ret.keySet()) {
      if (key.toString().startsWith("threatintels") && !key.toString().endsWith(".ts")) {
        isAlert = true;
        break;
      }
    }
  }
  else {
    Object isAlertObj = ret.get("is_alert");
    isAlert = ConversionUtils.convert(isAlertObj, Boolean.class);
    if(!isAlert) {
      ret.remove("is_alert");
    }
  }
  if(isAlert) {
    ret.put("is_alert" , "true");
    String sourceType = MessageUtils.getSensorType(ret);
    ThreatTriageConfig triageConfig = null;
    if(config != null) {
      triageConfig = config.getThreatIntel().getTriageConfig();
      if(LOG.isDebugEnabled()) {
        LOG.debug("{}: Found sensor enrichment config.", sourceType);
      }
    }
    else {
      LOG.debug("{}: Unable to find threat config.", sourceType );
    }
    if(triageConfig != null) {
      if(LOG.isDebugEnabled()) {
        LOG.debug("{}: Found threat triage config: {}", sourceType, triageConfig);
      }

      if(LOG.isDebugEnabled() && (triageConfig.getRiskLevelRules() == null || triageConfig.getRiskLevelRules().isEmpty())) {
        LOG.debug("{}: Empty rules!", sourceType);
      }

      // triage the threat
      ThreatTriageProcessor threatTriageProcessor = new ThreatTriageProcessor(config, functionResolver, stellarContext);
      ThreatScore score = threatTriageProcessor.apply(ret);

      if(LOG.isDebugEnabled()) {
        String rules = Joiner.on('\n').join(triageConfig.getRiskLevelRules());
        LOG.debug("Marked {} as triage level {} with rules {}", sourceType, score.getScore(),
            rules);
      }

      // attach the triage threat score to the message
      if(score.getRuleScores().size() > 0) {
        appendThreatScore(score, ret);
      }
    }
    else {
      LOG.debug("{}: Unable to find threat triage config!", sourceType);
    }
  }

  return ret;
}
 
Example 17
Source Project: java-sdk   File: JsonSimpleConfigParser.java    License: Apache License 2.0 4 votes vote down vote up
private List<Experiment> parseExperiments(JSONArray experimentJson, String groupId) {
    List<Experiment> experiments = new ArrayList<Experiment>(experimentJson.size());

    for (Object obj : experimentJson) {
        JSONObject experimentObject = (JSONObject) obj;
        String id = (String) experimentObject.get("id");
        String key = (String) experimentObject.get("key");
        Object statusJson = experimentObject.get("status");
        String status = statusJson == null ? ExperimentStatus.NOT_STARTED.toString() :
            (String) experimentObject.get("status");
        Object layerIdObject = experimentObject.get("layerId");
        String layerId = layerIdObject == null ? null : (String) layerIdObject;

        JSONArray audienceIdsJson = (JSONArray) experimentObject.get("audienceIds");
        List<String> audienceIds = new ArrayList<String>(audienceIdsJson.size());

        for (Object audienceIdObj : audienceIdsJson) {
            audienceIds.add((String) audienceIdObj);
        }

        Condition conditions = null;
        if (experimentObject.containsKey("audienceConditions")) {
            Object jsonCondition = experimentObject.get("audienceConditions");
            try {
                conditions = ConditionUtils.<AudienceIdCondition>parseConditions(AudienceIdCondition.class, jsonCondition);
            } catch (Exception e) {
                // unable to parse conditions.
                Logger.getAnonymousLogger().log(Level.ALL, "problem parsing audience conditions", e);
            }
        }
        // parse the child objects
        List<Variation> variations = parseVariations((JSONArray) experimentObject.get("variations"));
        Map<String, String> userIdToVariationKeyMap =
            parseForcedVariations((JSONObject) experimentObject.get("forcedVariations"));
        List<TrafficAllocation> trafficAllocations =
            parseTrafficAllocation((JSONArray) experimentObject.get("trafficAllocation"));

        experiments.add(new Experiment(id, key, status, layerId, audienceIds, conditions, variations, userIdToVariationKeyMap,
            trafficAllocations, groupId));
    }

    return experiments;
}
 
Example 18
private static Column restoreColumn(JSONObject obj) {
  String name = (String) obj.get(NAME);

  Boolean nullable = (Boolean) obj.get(NULLABLE);
  AbstractPrimitiveType key = null;
  Column value = null;
  Long arraySize = null;
  Column listType = null;
  java.util.Set<String> options = new HashSet<String>();

  // complex type attribute
  if (obj.containsKey(MAP)) {
    JSONObject map = (JSONObject) obj.get(MAP);

    if (map.containsKey(KEY)) {
      key = (AbstractPrimitiveType) restoreColumn((JSONObject) map.get(KEY));
    }
    if (map.containsKey(VALUE)) {
      value = restoreColumn((JSONObject) map.get(VALUE));
    }
  }
  if (obj.containsKey(LIST)) {
    JSONObject list = (JSONObject) obj.get(LIST);
    if (list.containsKey(LIST_TYPE)) {
      listType = restoreColumn((JSONObject) list.get(LIST_TYPE));
    }
    arraySize = (Long) list.get(SIZE);
    if (list.containsKey(ENUM_OPTIONS)) {
      JSONArray optionsArray = (JSONArray) list.get(ENUM_OPTIONS);
      for (int n = 0; n < optionsArray.size(); n++) {
        options.add((String) optionsArray.get(n));
      }
    }
  }
  ColumnType type = ColumnType.valueOf((String) obj.get(TYPE));
  Column output = null;
  switch (type) {
  case ARRAY:
    output = new Array(name, listType).setSize(arraySize);
    break;
  case BINARY:
    Long charSize = (Long) obj.get(CHAR_SIZE);
    output = new Binary(name).setCharSize(charSize);
    break;
  case BIT:
    output = new Bit(name);
    break;
  case DATE:
    output = new Date(name);
    break;
  case DATE_TIME:
    Boolean hasFraction = (Boolean) obj.get(FRACTION);
    Boolean hasTimezone = (Boolean) obj.get(TIMEZONE);
    output = new DateTime(name, hasFraction, hasTimezone);
    break;
  case DECIMAL:
    Integer precision = obj.get(PRECISION) != null ? ((Long) obj.get(PRECISION)).intValue() : null;
    Integer scale = obj.get(SCALE) != null ? ((Long) obj.get(SCALE)).intValue() : null;
    output = new Decimal(name, precision, scale);
    break;
  case ENUM:
    output = new Enum(name, options);
    break;
  case FIXED_POINT:
    Boolean signed = (Boolean) obj.get(SIGNED);
    Long fixedPointByteSize = (Long) obj.get(BYTE_SIZE);
    output = new FixedPoint(name, fixedPointByteSize, signed);
    break;
  case FLOATING_POINT:
    Long floatingPointByteSize = (Long) obj.get(BYTE_SIZE);
    output = new FloatingPoint(name, floatingPointByteSize);
    break;
  case MAP:
    output = new Map(name, key, value);
    break;
  case SET:
    output = new Set(name, listType);
    break;
  case TEXT:
    charSize = (Long) obj.get(CHAR_SIZE);
    output = new Text(name).setCharSize(charSize);
    break;
  case TIME:
    Boolean hasTimeFraction = (Boolean) obj.get(FRACTION);
    output = new Time(name, hasTimeFraction);
    break;
  case UNKNOWN:
    Long jdbcType = (Long) obj.get(JDBC_TYPE);
    output = new Unknown(name).setJdbcType(jdbcType);
    break;
  default:
    // TODO(Jarcec): Throw an exception of unsupported type?
  }
  output.setNullable(nullable);

  return output;
}
 
Example 19
/**
 * Generates an activity entry for the discussion item
 * 
 * @param event One of created, updated, deleted
 * @param blog Either post or reply
 * @param site site
 * @param req request
 * @param json json
 * @param nodeRef NodeRef
 */
protected void addActivityEntry(String event, BlogPostInfo blog, 
      SiteInfo site, WebScriptRequest req, JSONObject json, NodeRef nodeRef)
{
   // We can only add activities against a site
   if (site == null)
   {
      logger.info("Unable to add activity entry for blog " + event + " as no site given");
      return;
   }
   
   // What page is this for?
   String page = req.getParameter("page");
   if (page == null && json != null)
   {
      if (json.containsKey("page"))
      {
         page = (String)json.get("page");
      }
   }
   if (page == null)
   {
      // Default
      page = "blog-postview";
   }
   if (page.indexOf('?') == -1)
   {
      page += "?postId=" + blog.getSystemName();
   }
   
   // Get the title
   String title = blog.getTitle();
   
   try
   {
      JSONWriter jsonWriter = new JSONStringer()
          .object()
              .key(TITLE).value(title)
              .key(PAGE).value(page);
      
      if (nodeRef != null)
      {
          // ALF-10182: the nodeRef needs to be included in the activity
          // post to ensure read permissions are respected.
          jsonWriter.key(PostLookup.JSON_NODEREF).value(nodeRef.toString());
      }
      
      String data = jsonWriter.endObject().toString();
      
      activityService.postActivity(
            "org.alfresco.blog.post-" + event,
            site.getShortName(),
            "blog", data);
   }
   catch(Exception e)
   {
      // Warn, but carry on
      logger.warn("Error adding blog post " + event + " to activities feed", e);
   }
}
 
Example 20
Source Project: sepia-assist-server   File: IoBrokerConnector.java    License: MIT License 4 votes vote down vote up
@Override
public SmartHomeDevice loadDeviceData(SmartHomeDevice device){
	long tic = System.currentTimeMillis();
	String iobId = device.getId();
	if (Is.nullOrEmpty(iobId)){
		return null;
	}else{
		String url = URLBuilder.getStringP20(this.host + "/get/",
				"", iobId
		);
		//System.out.println("URL: " + url); 				//DEBUG
		JSONObject result = httpGET(url);
		//System.out.println("RESPONSE: " + result);		//DEBUG
		if (Connectors.httpSuccess(result)){
			Statistics.addExternalApiHit("ioBroker loadDevice");
			Statistics.addExternalApiTime("ioBroker loadDevice", tic);
			try{
				/* simplified result example
				 {
				    "val": 0,
				    "common": {
				        "name": "Hue white lamp 1.level",
				        "read": true,
				        "write": true,
				        "type": "number",
				        "role": "level.dimmer",
				        "min": 0,
				        "max": 100,
				        "def": 0
				    }
				}*/
				if (result.containsKey("val")){
					String state = JSON.getString(result, "val");
					String stateType = device.getStateType();
					if (state != null){
						if (stateType != null){
							//generalize state according to stateType
							state = SmartHomeDevice.convertAnyStateToGeneralizedState(state, stateType);
						}
						device.setState(state);
					}
					return device;
				}else{
					return null;
				}
			}catch (Exception e){
				Debugger.println("IoBrokerConnector - loadDeviceData FAILED with msg.: " + e.getMessage(), 1);
				Debugger.printStackTrace(e, 3);
				return null;
			}
		}else{
			Statistics.addExternalApiHit("ioBroker loadDevice ERROR");
			Statistics.addExternalApiTime("ioBroker loadDevice ERROR", tic);
			String error = JSON.getStringOrDefault(result, "error", "");
			if (error.contains("401") || error.contains("java.security") || error.contains("javax.net.ssl")){
				Debugger.println("IoBrokerConnector - loadDeviceData FAILED with msg.: " + result, 1);
			}
			return null;
		}
	}
}