Java Code Examples for net.minidev.json.JSONObject#containsKey()

The following examples show how to use net.minidev.json.JSONObject#containsKey() . 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: XsuaaServicesParser.java    From cloud-security-xsuaa-integration with Apache License 2.0 6 votes vote down vote up
@Nullable
private static JSONObject parseCredentials(String vcapServices) throws IOException {
	if (vcapServices == null || vcapServices.isEmpty()) {
		logger.warn("VCAP_SERVICES could not be load.");
		return null;
	}
	try {
		JSONObject vcapServicesJSON = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(vcapServices);
		JSONObject xsuaaBinding = searchXsuaaBinding(vcapServicesJSON);

		if (Objects.nonNull(xsuaaBinding) && xsuaaBinding.containsKey(CREDENTIALS)) {
			return (JSONObject) xsuaaBinding.get(CREDENTIALS);
		}
	} catch (ParseException ex) {
		throw new IOException("Error while parsing XSUAA credentials from VCAP_SERVICES: {}.", ex);
	}
	return null;
}
 
Example 2
Source File: YDLoginResponse.java    From mclauncher-api with MIT License 6 votes vote down vote up
public YDLoginResponse(JSONObject json) {
    super(json);
    sessionID = json.get("accessToken").toString();
    clientToken = json.get("clientToken").toString();
    selectedProfile = new YDPartialGameProfile((JSONObject) json.get("selectedProfile"));
    JSONArray profiles = (JSONArray) json.get("availableProfiles");
    if (profiles != null) {
        for (Object object : profiles) {
            JSONObject jsonObj = (JSONObject) object;
            YDPartialGameProfile p = new YDPartialGameProfile(jsonObj);
            this.profiles.put(p.getName(), p);
        }
    }
    if (json.containsKey("user"))
        user = new YDUserObject((JSONObject) json.get("user"));
}
 
Example 3
Source File: AssertHandler.java    From restfiddle with Apache License 2.0 6 votes vote down vote up
private boolean evaluate(String expectedValue, String comparator, JSONObject actualValue) {
    boolean result = false;

    switch (comparator) {
    case "Contains Key":
	result = actualValue.containsKey(expectedValue);
	break;
    case "! Contains Key":
	result = !actualValue.containsKey(expectedValue);
	break;
    case "Contains Value":
	result = actualValue.containsValue(expectedValue);
	;
	break;
    case "! Contains Value":
	result = !actualValue.containsValue(expectedValue);
	break;
	default:
		break;

    }

    return result;
}
 
Example 4
Source File: Artifact.java    From mclauncher-api with MIT License 5 votes vote down vote up
static Artifact fromJson(JSONObject json) {
    Objects.requireNonNull(json);
    Long totalSize = null;
    if (json.containsKey("totalSize"))
        Long.parseLong(json.get("totalSize").toString());
    return new Artifact(json.get("url").toString(), json.get("sha1").toString(), Long.parseLong(json.get("size").toString()), totalSize);
}
 
Example 5
Source File: Rule.java    From mclauncher-api with MIT License 5 votes vote down vote up
static Rule fromJson(JSONObject json) {
    Action action;
    IOperatingSystem restrictedOs;
    String restrictedOsVersionPattern;
    String architecture;
    Map<String, Boolean> features;
    action = Action.valueOf(json.get("action").toString().toUpperCase());
    if (json.containsKey("os")) {
        JSONObject os = (JSONObject) json.get("os");
        if (os.containsKey("name"))
            restrictedOs = Platform.osByName(os.get("name").toString());
        else
            restrictedOs = null;
        if (os.containsKey("arch"))
            architecture = os.get("arch").toString().toUpperCase();
        else
            architecture = null;
        if (os.containsKey("version"))
            restrictedOsVersionPattern = os.get("version").toString();
        else
            restrictedOsVersionPattern = null;
    } else {
        restrictedOs = null;
        restrictedOsVersionPattern = null;
        architecture = null;
    }
    if (json.containsKey("features")) {
        JSONObject featuresMap = (JSONObject) json.get("features");
        Map<String, Boolean> f = new HashMap<>();
        for (Map.Entry<String, Object> entry : featuresMap.entrySet()) {
            f.put(entry.getKey(), Boolean.valueOf(entry.getValue().toString()));
        }
        features = Collections.unmodifiableMap(f);
    } else {
        features = Collections.emptyMap();
    }

    return new Rule(action,restrictedOs,restrictedOsVersionPattern, architecture,features);
}
 
Example 6
Source File: AssetIndex.java    From mclauncher-api with MIT License 5 votes vote down vote up
static AssetIndex fromJson(String name, JSONObject json) {
    boolean virtual = json.containsKey("virtual") && Boolean.parseBoolean(json.get("virtual").toString());
    JSONObject objsObj = (JSONObject) json.get("objects");
    Set<Asset> objects = new HashSet<>();
    for (Entry<String, Object> objectEntry : objsObj.entrySet()) {
        objects.add(Asset.fromJson((JSONObject) objectEntry.getValue(), objectEntry.getKey()));
    }

    return new AssetIndex(virtual, name, objects);
}
 
Example 7
Source File: ScheduleConverter.java    From scheduler with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public Schedule fromJSON(Model mo, JSONObject o) throws JSONConverterException {
    checkId(o);
    if (o.containsKey("node")) {
        return new Schedule(JSONs.requiredNode(mo, o, "node"), JSONs.requiredInt(o, "start"), JSONs.requiredInt(o, "END"));
    }
    return new Schedule(JSONs.requiredVM(mo, o, "vm"), JSONs.requiredInt(o, "start"), JSONs.requiredInt(o, "END"));
}
 
Example 8
Source File: JSONs.java    From scheduler with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Check if some keys are present.
 *
 * @param o    the object to parse
 * @param keys the keys to check
 * @throws JSONConverterException when at least a key is missing
 */
public static void checkKeys(JSONObject o, String... keys) throws JSONConverterException {
    for (String k : keys) {
        if (!o.containsKey(k)) {
            throw new JSONConverterException("Missing key '" + k + "'");
        }
    }
}
 
Example 9
Source File: JSONs.java    From scheduler with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Read an optional integer.
 *
 * @param o  the object to parse
 * @param id the key in the map that points to an integer
 * @param def the default integer value if the key is absent
 * @return the resulting integer
 * @throws JSONConverterException if the key does not point to a int
 */
public static int optInt(JSONObject o, String id, int def) throws JSONConverterException {
    if (o.containsKey(id)) {
        try {
            return (Integer) o.get(id);
        } catch (ClassCastException e) {
            throw new JSONConverterException("Unable to read a int from string '" + id + "'", e);
        }
    }
    return def;
}
 
Example 10
Source File: RoomResponse.java    From kurento-room-client-android with Apache License 2.0 5 votes vote down vote up
private String getJSONObjectSessionId(JSONObject obj){
    if(obj.containsKey("sessionId")) {
        return obj.get("sessionId").toString();
    } else {
        return null;
    }
}
 
Example 11
Source File: Jwt.java    From JWT with MIT License 5 votes vote down vote up
/**
    * 校验token是否合法,返回Map集合,集合中主要包含    state状态码   data鉴权成功后从token中提取的数据
    * 该方法在过滤器中调用,每次请求API时都校验
    * @param token
    * @return  Map<String, Object>
    */
public static Map<String, Object> validToken(String token) {
	Map<String, Object> resultMap = new HashMap<String, Object>();
	try {
		JWSObject jwsObject = JWSObject.parse(token);
		Payload payload = jwsObject.getPayload();
		JWSVerifier verifier = new MACVerifier(SECRET);

		if (jwsObject.verify(verifier)) {
			JSONObject jsonOBj = payload.toJSONObject();
			// token校验成功(此时没有校验是否过期)
			resultMap.put("state", TokenState.VALID.toString());
			// 若payload包含ext字段,则校验是否过期
			if (jsonOBj.containsKey("ext")) {
				long extTime = Long.valueOf(jsonOBj.get("ext").toString());
				long curTime = new Date().getTime();
				// 过期了
				if (curTime > extTime) {
					resultMap.clear();
					resultMap.put("state", TokenState.EXPIRED.toString());
				}
			}
			resultMap.put("data", jsonOBj);

		} else {
			// 校验失败
			resultMap.put("state", TokenState.INVALID.toString());
		}

	} catch (Exception e) {
		//e.printStackTrace();
		// token格式不合法导致的异常
		resultMap.clear();
		resultMap.put("state", TokenState.INVALID.toString());
	}
	return resultMap;
}
 
Example 12
Source File: Skin.java    From Nukkit with GNU General Public License v3.0 5 votes vote down vote up
private boolean isValidResourcePatch() {
    if (skinResourcePatch == null) {
        return false;
    }
    try {
        JSONObject object = (JSONObject) JSONValue.parse(skinResourcePatch);
        JSONObject geometry = (JSONObject) object.get("geometry");
        return geometry.containsKey("default") && geometry.get("default") instanceof String;
    } catch (ClassCastException | NullPointerException e) {
        return false;
    }
}
 
Example 13
Source File: SerializedSkin.java    From Protocol with Apache License 2.0 5 votes vote down vote up
private static boolean validateSkinResourcePatch(String skinResourcePatch) {
    try {
        JSONObject object = (JSONObject) JSONValue.parse(skinResourcePatch);
        JSONObject geometry = (JSONObject) object.get("geometry");
        return geometry.containsKey("default") && geometry.get("default") instanceof String;
    } catch (ClassCastException | NullPointerException e) {
        return false;
    }
}
 
Example 14
Source File: Playlist.java    From RecSys2018 with Apache License 2.0 5 votes vote down vote up
public Playlist(final JSONObject obj) {
	this.pid = obj.getAsString("pid");
	this.name = obj.getAsString("name");

	if (obj.containsKey("collaborative") == true) {
		this.collaborative = obj.getAsString("collaborative").toLowerCase()
				.equals("true");
	}
	if (obj.containsKey("modified_at") == true) {
		this.modified_at = obj.getAsNumber("modified_at").longValue();
	}
	if (obj.containsKey("num_albums") == true) {
		this.num_albums = obj.getAsNumber("num_albums").intValue();
	}
	if (obj.containsKey("num_tracks") == true) {
		this.num_tracks = obj.getAsNumber("num_tracks").intValue();
	}
	if (obj.containsKey("num_followers") == true) {
		this.num_followers = obj.getAsNumber("num_followers").intValue();
	}
	if (obj.containsKey("num_edits") == true) {
		this.num_edits = obj.getAsNumber("num_edits").intValue();
	}
	if (obj.containsKey("duration_ms") == true) {
		this.duration_ms = obj.getAsNumber("duration_ms").intValue();
	}
	if (obj.containsKey("num_artists") == true) {
		this.num_artists = obj.getAsNumber("num_artists").intValue();
	}
}
 
Example 15
Source File: SplitByFieldMessageParser.java    From secor with Apache License 2.0 4 votes vote down vote up
protected String extractEventType(JSONObject jsonObject) {
    if (!jsonObject.containsKey(mSplitFieldName)) {
        throw new RuntimeException("Could not find key " + mSplitFieldName + " in Json message");
    }
    return jsonObject.get(mSplitFieldName).toString();
}
 
Example 16
Source File: GatewayUtils.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
public static AuthenticationContext generateAuthenticationContext(String tokenSignature,
                                                                  JWTValidationInfo jwtValidationInfo,
                                                                  JSONObject api,
                                                                  APIKeyValidationInfoDTO apiKeyValidationInfoDTO,
                                                                  String apiLevelPolicy, String endUserToken,
                                                                  boolean isOauth) throws java.text.ParseException {


    AuthenticationContext authContext = new AuthenticationContext();
    authContext.setAuthenticated(true);
    authContext.setApiKey(tokenSignature);
    authContext.setUsername(jwtValidationInfo.getUser());

    if (apiKeyValidationInfoDTO != null) {
        authContext.setApiTier(apiKeyValidationInfoDTO.getApiTier());
        authContext.setKeyType(apiKeyValidationInfoDTO.getType());
        authContext.setApplicationId(apiKeyValidationInfoDTO.getApplicationId());
        authContext.setApplicationName(apiKeyValidationInfoDTO.getApplicationName());
        authContext.setApplicationTier(apiKeyValidationInfoDTO.getApplicationTier());
        authContext.setSubscriber(apiKeyValidationInfoDTO.getSubscriber());
        authContext.setTier(apiKeyValidationInfoDTO.getTier());
        authContext.setSubscriberTenantDomain(apiKeyValidationInfoDTO.getSubscriberTenantDomain());
        authContext.setApiName(apiKeyValidationInfoDTO.getApiName());
        authContext.setApiPublisher(apiKeyValidationInfoDTO.getApiPublisher());
        authContext.setStopOnQuotaReach(apiKeyValidationInfoDTO.isStopOnQuotaReach());
        authContext.setSpikeArrestLimit(apiKeyValidationInfoDTO.getSpikeArrestLimit());
        authContext.setSpikeArrestUnit(apiKeyValidationInfoDTO.getSpikeArrestUnit());
        authContext.setConsumerKey(apiKeyValidationInfoDTO.getConsumerKey());
        authContext.setIsContentAware(apiKeyValidationInfoDTO.isContentAware());
    } else {
        if (jwtValidationInfo.getClaims().get(APIConstants.JwtTokenConstants.KEY_TYPE)!= null) {
            authContext.setKeyType(
                    (String) jwtValidationInfo.getClaims().get(APIConstants.JwtTokenConstants.KEY_TYPE));
        } else {
            authContext.setKeyType(APIConstants.API_KEY_TYPE_PRODUCTION);
        }

        authContext.setApiTier(apiLevelPolicy);

        if (jwtValidationInfo.getClaims().get(APIConstants.JwtTokenConstants.APPLICATION) != null) {
            JSONObject applicationObj =
                    (JSONObject) jwtValidationInfo.getClaims().get(APIConstants.JwtTokenConstants.APPLICATION);

            authContext
                    .setApplicationId(String.valueOf(applicationObj.getAsNumber(APIConstants.JwtTokenConstants.APPLICATION_ID)));
            authContext.setApplicationName(applicationObj.getAsString(APIConstants.JwtTokenConstants.APPLICATION_NAME));
            authContext.setApplicationTier(applicationObj.getAsString(APIConstants.JwtTokenConstants.APPLICATION_TIER));
            authContext.setSubscriber(applicationObj.getAsString(APIConstants.JwtTokenConstants.APPLICATION_OWNER));
            if (applicationObj.containsKey(APIConstants.JwtTokenConstants.QUOTA_TYPE)
                    && APIConstants.JwtTokenConstants.QUOTA_TYPE_BANDWIDTH
                    .equals(applicationObj.getAsString(APIConstants.JwtTokenConstants.QUOTA_TYPE))) {
                authContext.setIsContentAware(true);;
            }
        }
    }
    if (isOauth) {
        authContext.setConsumerKey(jwtValidationInfo.getConsumerKey());
    }
    if (apiKeyValidationInfoDTO == null && api != null) {

        // If the user is subscribed to the API
        String subscriptionTier = api.getAsString(APIConstants.JwtTokenConstants.SUBSCRIPTION_TIER);
        authContext.setTier(subscriptionTier);
        authContext.setSubscriberTenantDomain(
                api.getAsString(APIConstants.JwtTokenConstants.SUBSCRIBER_TENANT_DOMAIN));
        JSONObject tierInfo =
                (JSONObject) jwtValidationInfo.getClaims().get(APIConstants.JwtTokenConstants.TIER_INFO);
        authContext.setApiName(api.getAsString(APIConstants.JwtTokenConstants.API_NAME));
        authContext.setApiPublisher(api.getAsString(APIConstants.JwtTokenConstants.API_PUBLISHER));
        if (tierInfo.get(subscriptionTier) != null) {
            JSONObject subscriptionTierObj = (JSONObject) tierInfo.get(subscriptionTier);
            authContext.setStopOnQuotaReach(
                    Boolean.parseBoolean(
                            subscriptionTierObj.getAsString(APIConstants.JwtTokenConstants.STOP_ON_QUOTA_REACH)));
            authContext.setSpikeArrestLimit
                    (subscriptionTierObj.getAsNumber(APIConstants.JwtTokenConstants.SPIKE_ARREST_LIMIT).intValue());
            if (!"null".equals(
                    subscriptionTierObj.getAsString(APIConstants.JwtTokenConstants.SPIKE_ARREST_UNIT))) {
                authContext.setSpikeArrestUnit(
                        subscriptionTierObj.getAsString(APIConstants.JwtTokenConstants.SPIKE_ARREST_UNIT));
            }
            //check whether the quota type is there and it is equal to bandwithVolume type.
            if (subscriptionTierObj.containsKey(APIConstants.JwtTokenConstants.QUOTA_TYPE)
                    && APIConstants.JwtTokenConstants.QUOTA_TYPE_BANDWIDTH
                    .equals(subscriptionTierObj.getAsString(APIConstants.JwtTokenConstants.QUOTA_TYPE))) {
                authContext.setIsContentAware(true);;
            }
        }
    }
    // Set JWT token sent to the backend
    if (StringUtils.isNotEmpty(endUserToken)) {
        authContext.setCallerToken(endUserToken);
    }

    return authContext;
}
 
Example 17
Source File: JsonLineSerializer.java    From tajo with Apache License 2.0 4 votes vote down vote up
private void putValue(JSONObject json,
                      String fullPath,
                      String [] pathElements,
                      int depth,
                      int fieldIndex,
                      Tuple input) throws IOException {
  String fieldName = pathElements[depth];

  if (input.isBlankOrNull(fieldIndex)) {
    return;
  }

  switch (types.get(fullPath)) {

  case BOOLEAN:
    json.put(fieldName, input.getBool(fieldIndex));
    break;

  case INT1:
  case INT2:
    json.put(fieldName, input.getInt2(fieldIndex));
    break;

  case INT4:
    json.put(fieldName, input.getInt4(fieldIndex));
    break;

  case INT8:
    json.put(fieldName, input.getInt8(fieldIndex));
    break;

  case FLOAT4:
    json.put(fieldName, input.getFloat4(fieldIndex));
    break;

  case FLOAT8:
    json.put(fieldName, input.getFloat8(fieldIndex));
    break;


  case TEXT:
  case VARCHAR:
    json.put(fieldName, input.getText(fieldIndex));
    break;

  case CHAR:
  case DATE:
  case INTERVAL:
    json.put(fieldName, input.asDatum(fieldIndex).asChars());
    break;

  case TIMESTAMP:
    json.put(fieldName, TimestampDatum.asChars(input.getTimeDate(fieldIndex), timezone, false));
    break;
  case TIME:
    json.put(fieldName, input.asDatum(fieldIndex).asChars());
    break;

  case BIT:
  case BINARY:
  case BLOB:
  case VARBINARY:
    json.put(fieldName,  Base64.encodeBase64String(input.getBytes(fieldIndex)));
    break;

  case NULL_TYPE:
    break;

  case RECORD:
    JSONObject record = json.containsKey(fieldName) ? (JSONObject) json.get(fieldName) : new JSONObject();
    json.put(fieldName, record);
    putValue(record, fullPath + "/" + pathElements[depth + 1], pathElements, depth + 1, fieldIndex, input);
    break;

  default:
    throw new TajoRuntimeException(
        new NotImplementedException("" + types.get(fullPath).name() + " for json"));
  }
}
 
Example 18
Source File: YDResponse.java    From mclauncher-api with MIT License 4 votes vote down vote up
public YDResponse(JSONObject json) {
    if (json.containsKey("error"))
        setError(json.get("error").toString());
    if (json.containsKey("errorMessage"))
        setMessage(json.get("errorMessage").toString());
}