Java Code Examples for net.minidev.json.JSONArray#size()

The following examples show how to use net.minidev.json.JSONArray#size() . 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
private static JSONObject getJSONObjectFromTag(final JSONArray jsonArray, String tag) {
	JSONObject xsuaaBinding = null;
	for (int i = 0; i < jsonArray.size(); i++) {
		JSONObject binding = (JSONObject) jsonArray.get(i);
		JSONArray tags = (JSONArray) binding.get(TAGS);

		Optional<String> planName = Optional.ofNullable(binding.getAsString("plan"));
		boolean isApiAccessPlan = (planName.isPresent() && planName.get().equals("apiaccess"));
		for (int j = 0; j < tags.size(); j++) {
			if (tags.get(j).equals(tag) && !isApiAccessPlan) {
				if (xsuaaBinding == null) {
					xsuaaBinding = binding;
				} else {
					throw new IllegalStateException(
							"Found more than one xsuaa bindings. Please consider unified broker plan.");
				}
			}
		}
	}
	return xsuaaBinding;
}
 
Example 2
Source File: XsuaaToken.java    From cloud-security-xsuaa-integration with Apache License 2.0 6 votes vote down vote up
private String[] getStringListAttributeFromClaim(String attributeName, String claimName) {
	String[] attributeValues = null;

	Map<String, Object> claimMap = getClaimAsMap(claimName);
	if (claimMap == null) {
		logger.debug("Claim '{}' not found. Returning null.", claimName);
		return attributeValues;
	}

	// convert JSONArray to String[]
	JSONArray attributeJsonArray = (JSONArray) claimMap.get(attributeName);
	if (attributeJsonArray != null) {
		attributeValues = new String[attributeJsonArray.size()];
		for (int i = 0; i < attributeJsonArray.size(); i++) {
			attributeValues[i] = (String) attributeJsonArray.get(i);
		}
	}

	if (attributeValues == null) {
		logger.debug("Attribute '{}' in claim '{}' not found. Returning null.", attributeName, claimName);
		return attributeValues;
	}

	return attributeValues;
}
 
Example 3
Source File: MarcIteratorTest.java    From metadata-qa-marc with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testMarcSchemaIteration() {
  List<String> skippable = Arrays.asList("leader", "001", "003", "005", "006", "007", "008");
  // fixedValues
  for (JsonBranch branch : schema.getPaths()) {
    if (skippable.contains(branch.getLabel()) || branch.getParent() != null)
      continue;

    // List<Map<String, List<String>>> expectedList = fixedValues.get(branch.getLabel());
    JSONArray fieldInstances = (JSONArray) cache.getFragment(branch.getJsonPath());
    for (int fieldInsanceNr = 0; fieldInsanceNr < fieldInstances.size(); fieldInsanceNr++) {
      Map fieldInstance = (Map)fieldInstances.get(fieldInsanceNr);
      DataField field = MapToDatafield.parse(fieldInstance, MarcVersion.DNB);
      if (!fieldInstance.get("tag").equals("935")) {
        assertNotNull(fieldInstance.get("tag").toString() + " should not be null", field);
        assertEquals(fieldInstance.get("tag"), field.getTag());
      }
    }
  }
}
 
Example 4
Source File: SecretDetector.java    From snowflake-jdbc with Apache License 2.0 6 votes vote down vote up
public static JSONArray maskJsonArray(JSONArray array)
{
  for (int i = 0; i < array.size(); i++)
  {
    Object node = array.get(i);
    if (node instanceof JSONObject)
    {
      maskJsonObject((JSONObject) node);
    }
    else if (node instanceof JSONArray)
    {
      maskJsonArray((JSONArray) node);
    }
    else if (node instanceof String)
    {
      array.set(i, SecretDetector.maskSecrets((String) node));
    }
    // for other types, we can just leave it untouched
  }

  return array;
}
 
Example 5
Source File: JSON.java    From hawkular-apm with Apache License 2.0 6 votes vote down vote up
/**
 * This method evaluates the jsonpath expression on the supplied
 * node.
 *
 * @param jsonpath The jsonpath expression
 * @param data The json data
 * @return The result, or null if not found (which may be due to an expression error)
 */
public static String evaluate(String jsonpath, Object data) {
    String json = serialize(data);

    // No jsonpath means return serialized form
    if (jsonpath == null || jsonpath.trim().isEmpty()) {
        return json;
    }

    if (json != null) {
        Object result = JsonPath.parse(json).read(jsonpath);
        if (result != null) {
            if (result.getClass() == JSONArray.class) {
                JSONArray arr=(JSONArray)result;
                if (arr.isEmpty()) {
                    result = null;
                } else if (arr.size() == 1) {
                    result = arr.get(0);
                }
            }
            return serialize(result);
        }
    }
    return null;
}
 
Example 6
Source File: JsonHelper.java    From hsac-fitnesse-fixtures with Apache License 2.0 6 votes vote down vote up
private JSONArray sort(final JsonPathHelper pathHelper, JSONArray a, final String nestedPathExpr) {
    List<String> elements = new ArrayList<>(a.size());
    for (Object element : a) {
        net.minidev.json.JSONObject jsonObject = new net.minidev.json.JSONObject((Map<String, ?>) element);
        elements.add(jsonObject.toJSONString());
    }
    Collections.sort(elements, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            Comparable val1 = (Comparable) pathHelper.getJsonPath(o1, nestedPathExpr);
            Comparable val2 = (Comparable) pathHelper.getJsonPath(o2, nestedPathExpr);
            return val1.compareTo(val2);
        }
    });
    return convertToArray(elements);
}
 
Example 7
Source File: JSONs.java    From scheduler with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Convert an array of VM identifiers to a set of VMs.
 * This operation uses a cache of previously converted set of VMs.
 * @param mo the associated model to browse
 * @param a the json array
 * @return the set of VMs
 * @throws JSONConverterException if a error occurred during the conversion
 */
public static List<VM> vmsFromJSON(Model mo, JSONArray a) throws JSONConverterException {
    String json = a.toJSONString();
    List<VM> s = vmsCache.get(json);
    if (s != null) {
        return s;
    }
    s = new ArrayList<>(a.size());
    for (Object o : a) {
        s.add(getVM(mo, (int) o));
    }
    vmsCache.put(json, s);
    return s;
}
 
Example 8
Source File: ConstraintsConverter.java    From scheduler with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Convert a list of json-encoded sat-constraints.
 * @param mo the model to rely on
 * @param in the constraints to decode
 * @return the constraint list. Might be empty
 * @throws JSONConverterException if the conversion failed
 */
public List<SatConstraint> listFromJSON(Model mo, JSONArray in) throws JSONConverterException {
    List<SatConstraint> l = new ArrayList<>(in.size());
    for (Object o : in) {
        if (!(o instanceof JSONObject)) {
            throw new JSONConverterException("Expected an array of JSONObject but got an array of " + o.getClass().getName());
        }
        l.add((SatConstraint) fromJSON(mo, (JSONObject) o));
    }
    return l;
}
 
Example 9
Source File: JSONs.java    From scheduler with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Convert an array of VM identifiers to a set of VMs.
 * This operation uses a cache of previously converted set of nodes.
 * @param mo the associated model to browse
 * @param a the json array
 * @return the set of nodes
 * @throws JSONConverterException if a error occurred during the conversion
 */
public static List<Node> nodesFromJSON(Model mo, JSONArray a) throws JSONConverterException {
    String json = a.toJSONString();
    List<Node> s = nodesCache.get(json);
    if (s != null) {
        return s;
    }
    s = new ArrayList<>(a.size());
    for (Object o : a) {
        s.add(getNode(mo, (int) o));
    }
    nodesCache.put(json, s);
    return s;
}
 
Example 10
Source File: JavaCloudFoundryPaasWebAppImpl.java    From SeaCloudsPlatform with Apache License 2.0 5 votes vote down vote up
private JSONArray findResourceById(String json, String resourceId) {
    String path = "$.list[0].requests";
    JSONArray pathResult = JsonPath.read(json, path);

    if ((pathResult != null) && (pathResult.size() > 0)) {
        for (Object resourceDescription : pathResult) {
            if (((JSONArray) resourceDescription).get(0).equals(resourceId)) {
                return ((JSONArray) resourceDescription);
            }
        }
    }
    return null;
}
 
Example 11
Source File: JavaCloudFoundryPaasWebAppImpl.java    From SeaCloudsPlatform with Apache License 2.0 5 votes vote down vote up
private Map getResourceDescription(String json, String resourceId) {
    JSONArray resource = findResourceById(json, resourceId);
    Map resourceDescription = null;

    if ((resource != null) && (resource.size() > 1)) {
        resourceDescription = (Map) resource.get(1);
    }
    return resourceDescription;
}
 
Example 12
Source File: EleCheck.java    From jelectrum with MIT License 5 votes vote down vote up
public static void checkMempoolGetFeeHistogram(EleConn conn)
  throws Exception
{
  JSONArray params = new JSONArray();
  
  JSONObject msg = conn.request("mempool.get_fee_histogram");
  JSONArray result = (JSONArray) msg.get("result");

  if (result.size() == 0)
  {
    System.out.println("Warning: empty mempool or mempool.get_fee_histogram broken");
  }

}
 
Example 13
Source File: JsonArrayGet.java    From tajo with Apache License 2.0 5 votes vote down vote up
@Override
public Datum eval(Tuple params) {
  if (params.isBlankOrNull(0) || params.isBlankOrNull(1)) {
    return NullDatum.get();
  }

  try {
    Object parsed = parser.parse(params.getBytes(0));
    if (parsed instanceof JSONArray) {
      JSONArray array = (JSONArray) parsed;
      if (realIndex == Integer.MAX_VALUE) {
        int givenIndex = params.getInt4(1);
        // Zero and positive given index points out the element from the left side,
        // while negative given index points out the element from the right side.
        realIndex = givenIndex < 0 ? array.size() + givenIndex : givenIndex;
      }

      if (realIndex >= array.size() || realIndex < 0) {
        return NullDatum.get();
      } else {
        return DatumFactory.createText(array.get(realIndex).toString());
      }
    } else {
      return NullDatum.get();
    }
  } catch (ParseException e) {
    return NullDatum.get();
  }
}
 
Example 14
Source File: OpenIDConnectAuthenticator.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
protected void buildClaimMappings(Map<ClaimMapping, String> claims, Map.Entry<String, Object> entry, String
        separator) {
    String claimValue = null;
    if (StringUtils.isBlank(separator)) {
        separator = IdentityCoreConstants.MULTI_ATTRIBUTE_SEPARATOR_DEFAULT;
    }
    try {
        JSONArray jsonArray = (JSONArray) JSONValue.parseWithException(entry.getValue().toString());
        if (jsonArray != null && jsonArray.size() > 0) {
            Iterator attributeIterator = jsonArray.iterator();
            while (attributeIterator.hasNext()) {
                if (claimValue == null) {
                    claimValue = attributeIterator.next().toString();
                } else {
                    claimValue = claimValue + separator + attributeIterator.next().toString();
                }
            }

        }
    } catch (Exception e) {
        claimValue = entry.getValue().toString();
    }

    claims.put(ClaimMapping.build(entry.getKey(), entry.getKey(), null, false), claimValue);
    if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.USER_CLAIMS)) {
        log.debug("Adding claim mapping : " + entry.getKey() + " <> " + entry.getKey() + " : " + claimValue);
    }

}
 
Example 15
Source File: TrackerMetricsProvider.java    From incubator-heron with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private Collection<Measurement> parse(String response, String component, String metric) {
  Collection<Measurement> metricsData = new ArrayList();

  DocumentContext result = JsonPath.parse(response);
  JSONArray jsonArray = result.read("$.." + metric);
  if (jsonArray.size() != 1) {
    LOG.info(String.format("Did not get any metrics from tracker for %s:%s ", component, metric));
    return metricsData;
  }

  Map<String, Object> metricsMap = (Map<String, Object>) jsonArray.get(0);
  if (metricsMap == null || metricsMap.isEmpty()) {
    LOG.info(String.format("Did not get any metrics from tracker for %s:%s ", component, metric));
    return metricsData;
  }

  for (String instanceName : metricsMap.keySet()) {
    Map<String, String> tmpValues = (Map<String, String>) metricsMap.get(instanceName);
    for (String timeStamp : tmpValues.keySet()) {
      Measurement measurement = new Measurement(
          component,
          instanceName,
          metric,
          Instant.ofEpochSecond(Long.parseLong(timeStamp)),
          Double.parseDouble(tmpValues.get(timeStamp)));
      metricsData.add(measurement);
    }
  }

  return metricsData;
}
 
Example 16
Source File: ArraySizeAsserterImpl.java    From zerocode with Apache License 2.0 5 votes vote down vote up
public FieldAssertionMatcher processRelationalExpression(JSONArray actualArrayValue) {
    if (expectedSizeExpression.startsWith(ASSERT_VALUE_GREATER_THAN)) {
        String greaterThan = this.expectedSizeExpression.substring(ASSERT_VALUE_GREATER_THAN.length());
        if (actualArrayValue.size() > Integer.parseInt(greaterThan)) {
            return aMatchingMessage();
        }
    } else if (expectedSizeExpression.startsWith(ASSERT_VALUE_LESSER_THAN)) {
        String lesserThan = this.expectedSizeExpression.substring(ASSERT_VALUE_LESSER_THAN.length());
        if (actualArrayValue.size() < Integer.parseInt(lesserThan)) {
            return aMatchingMessage();
        }
    } else if (expectedSizeExpression.startsWith(ASSERT_VALUE_EQUAL_TO_NUMBER)) {
        String equalTo = this.expectedSizeExpression.substring(ASSERT_VALUE_EQUAL_TO_NUMBER.length());
        if (actualArrayValue.size() == Integer.parseInt(equalTo)) {
            return aMatchingMessage();
        }
    } else if (expectedSizeExpression.startsWith(ASSERT_VALUE_NOT_EQUAL_TO_NUMBER)) {
        String notEqualTo = this.expectedSizeExpression.substring(ASSERT_VALUE_NOT_EQUAL_TO_NUMBER.length());
        if (actualArrayValue.size() != Integer.parseInt(notEqualTo)) {
            return aMatchingMessage();
        }
    }

    return aNotMatchingMessage(
            path,
            String.format("Array of size %s", expectedSizeExpression),
            actualArrayValue.size());
}
 
Example 17
Source File: GatewayUtils.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * Validate whether the user is subscribed to the invoked API. If subscribed, return a JSON object containing
 * the API information.
 *
 * @param apiContext API context
 * @param apiVersion API version
 * @param payload    The payload of the JWT token
 * @return an JSON object containing subscribed API information retrieved from token payload.
 * If the subscription information is not found, return a null object.
 * @throws APISecurityException if the user is not subscribed to the API
 */
public static JSONObject validateAPISubscription(String apiContext, String apiVersion, JWTClaimsSet payload,
                                                 String[] splitToken, boolean isOauth)
        throws APISecurityException {

    JSONObject api = null;

    if (payload.getClaim(APIConstants.JwtTokenConstants.SUBSCRIBED_APIS) != null) {
        // Subscription validation
        JSONArray subscribedAPIs =
                (JSONArray) payload.getClaim(APIConstants.JwtTokenConstants.SUBSCRIBED_APIS);
        for (int i = 0; i < subscribedAPIs.size(); i++) {
            JSONObject subscribedAPIsJSONObject =
                    (JSONObject) subscribedAPIs.get(i);
            if (apiContext.equals(subscribedAPIsJSONObject.getAsString(APIConstants.JwtTokenConstants.API_CONTEXT)) &&
                    apiVersion.equals(subscribedAPIsJSONObject.getAsString(APIConstants.JwtTokenConstants.API_VERSION)
                                     )) {
                api = subscribedAPIsJSONObject;
                if (log.isDebugEnabled()) {
                    log.debug("User is subscribed to the API: " + apiContext + ", " +
                            "version: " + apiVersion + ". Token: " + getMaskedToken(splitToken[0]));
                }
                break;
            }
        }
        if (api == null) {
            if (log.isDebugEnabled()) {
                log.debug("User is not subscribed to access the API: " + apiContext +
                        ", version: " + apiVersion + ". Token: " + getMaskedToken(splitToken[0]));
            }
            log.error("User is not subscribed to access the API.");
            throw new APISecurityException(APISecurityConstants.API_AUTH_FORBIDDEN,
                    APISecurityConstants.API_AUTH_FORBIDDEN_MESSAGE);
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("No subscription information found in the token.");
        }
        // we perform mandatory authentication for Api Keys
        if (!isOauth) {
            log.error("User is not subscribed to access the API.");
            throw new APISecurityException(APISecurityConstants.API_AUTH_FORBIDDEN,
                    APISecurityConstants.API_AUTH_FORBIDDEN_MESSAGE);
        }
    }
    return api;
}
 
Example 18
Source File: GatewayUtils.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * Validate whether the user is subscribed to the invoked API. If subscribed, return a JSON object containing
 * the API information.
 *
 * @param apiContext API context
 * @param apiVersion API version
 * @param jwtValidationInfo    The payload of the JWT token
 * @return an JSON object containing subscribed API information retrieved from token payload.
 * If the subscription information is not found, return a null object.
 * @throws APISecurityException if the user is not subscribed to the API
 */
public static JSONObject validateAPISubscription(String apiContext, String apiVersion, JWTValidationInfo jwtValidationInfo,
                                                 String jwtHeader, boolean isOauth)
        throws APISecurityException {

    JSONObject api = null;

    if (jwtValidationInfo.getClaims().get(APIConstants.JwtTokenConstants.SUBSCRIBED_APIS) != null) {
        // Subscription validation
        JSONArray subscribedAPIs =
                (JSONArray) jwtValidationInfo.getClaims().get(APIConstants.JwtTokenConstants.SUBSCRIBED_APIS);
        for (int i = 0; i < subscribedAPIs.size(); i++) {
            JSONObject subscribedAPIsJSONObject =
                    (JSONObject) subscribedAPIs.get(i);
            if (apiContext.equals(subscribedAPIsJSONObject.getAsString(APIConstants.JwtTokenConstants.API_CONTEXT)) &&
                    apiVersion.equals(subscribedAPIsJSONObject.getAsString(APIConstants.JwtTokenConstants.API_VERSION)
                                     )) {
                api = subscribedAPIsJSONObject;
                if (log.isDebugEnabled()) {
                    log.debug("User is subscribed to the API: " + apiContext + ", " +
                            "version: " + apiVersion + ". Token: " + getMaskedToken(jwtHeader));
                }
                break;
            }
        }
        if (api == null) {
            if (log.isDebugEnabled()) {
                log.debug("User is not subscribed to access the API: " + apiContext +
                        ", version: " + apiVersion + ". Token: " + getMaskedToken(jwtHeader));
            }
            log.error("User is not subscribed to access the API.");
            throw new APISecurityException(APISecurityConstants.API_AUTH_FORBIDDEN,
                    APISecurityConstants.API_AUTH_FORBIDDEN_MESSAGE);
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("No subscription information found in the token.");
        }
        // we perform mandatory authentication for Api Keys
        if (!isOauth) {
            log.error("User is not subscribed to access the API.");
            throw new APISecurityException(APISecurityConstants.API_AUTH_FORBIDDEN,
                    APISecurityConstants.API_AUTH_FORBIDDEN_MESSAGE);
        }
    }
    return api;
}
 
Example 19
Source File: MarcFactory.java    From metadata-qa-marc with GNU General Public License v3.0 4 votes vote down vote up
public static MarcRecord create(JsonPathCache cache, MarcVersion version) {
  MarcRecord record = new MarcRecord();
  for (JsonBranch branch : schema.getPaths()) {
    if (branch.getParent() != null)
      continue;
    switch (branch.getLabel()) {
      case "leader":
        record.setLeader(new Leader(extractFirst(cache, branch)));
        break;
      case "001":
        record.setControl001(new MarcControlField(Control001Definition.getInstance(), extractFirst(cache, branch)));
        break;
      case "003":
        record.setControl003(new MarcControlField(Control003Definition.getInstance(), extractFirst(cache, branch)));
        break;
      case "005":
        record.setControl005(new MarcControlField(Control005Definition.getInstance(), extractFirst(cache, branch)));
        break;
      case "006":
        record.setControl006(
          new Control006(extractFirst(cache, branch), record.getType()));
        break;
      case "007":
        record.setControl007(
          new Control007(extractFirst(cache, branch)));
        break;
      case "008":
        record.setControl008(
          new Control008(extractFirst(cache, branch), record.getType()));
        break;
      default:
        JSONArray fieldInstances = (JSONArray) cache.getFragment(branch.getJsonPath());
        for (int fieldInsanceNr = 0; fieldInsanceNr < fieldInstances.size();
            fieldInsanceNr++) {
          Map fieldInstance = (Map) fieldInstances.get(fieldInsanceNr);
          DataField field = MapToDatafield.parse(fieldInstance, version);
          if (field != null) {
            record.addDataField(field);
            field.setRecord(record);
          } else {
            record.addUnhandledTags(branch.getLabel());
          }
        }
        break;
    }
  }
  return record;
}
 
Example 20
Source File: ArraySizeAsserterImpl.java    From zerocode with Apache License 2.0 3 votes vote down vote up
@Override
public FieldAssertionMatcher actualEqualsToExpected(Object result) {
    if (result instanceof JSONArray) {

        final JSONArray actualArrayValue = (JSONArray) result;

        if (this.expectedSize == -1 && this.expectedSizeExpression != null) {

            return processRelationalExpression(actualArrayValue);

        }

        if (actualArrayValue.size() == this.expectedSize) {

            return aMatchingMessage();
        }

        return aNotMatchingMessage(
                path,
                String.format("Array of size %d", expectedSize),
                actualArrayValue.size());

    } else {

        return aNotMatchingMessage(path, "[]", result);

    }
}