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

The following examples show how to use net.minidev.json.JSONArray#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: 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: CloudFoundryServiceImpl.java    From SeaCloudsPlatform with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public Map<String, String> getServiceCredentialsFromApp(CloudFoundryWebAppImpl webapp){
    String vcapServices = webapp.getAttribute(CloudFoundryWebApp.VCAP_SERVICES);
    String path = String.format("$.%s[?(@.name =~/.*%s/i)].credentials",
            this.getServiceTypeId(),
            getConfig(CloudFoundryService.SERVICE_INSTANCE_NAME));

    JSONArray pathResult= JsonPath.read(vcapServices, path);
    if((pathResult!=null)&&(pathResult.size()==1)){
        return ((Map<String, String>) pathResult.get(0));
    } else {
        throw new RuntimeException("Error finding a service credentials in driver" + this +
                " deploying service " + getId());
    }
}
 
Example 7
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 8
Source File: TestNumberPrecision.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
public void testMaxBig() {
	BigInteger v = BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.ONE);
	String s = "[" + v + "]";
	JSONArray array = (JSONArray) JSONValue.parse(s);
	Object r = array.get(0);
	assertEquals(v, r);
}
 
Example 9
Source File: TestNumberPrecision.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
public void testMinBig() {
	BigInteger v = BigInteger.valueOf(Long.MIN_VALUE).subtract(BigInteger.ONE);
	String s = "[" + v + "]";
	JSONArray array = (JSONArray) JSONValue.parse(s);
	Object r = array.get(0);
	assertEquals(v, r);
}
 
Example 10
Source File: TestNumberPrecision.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
public void testMinLong() {
	Long v = Long.MIN_VALUE;
	String s = "[" + v + "]";
	JSONArray array = (JSONArray) JSONValue.parse(s);
	Object r = array.get(0);
	assertEquals(v, r);
}
 
Example 11
Source File: TestNumberPrecision.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
public void testMaxLong() {		
	Long v = Long.MAX_VALUE;
	String s = "[" + v + "]";
	JSONArray array = (JSONArray) JSONValue.parse(s);
	Object r = array.get(0);
	assertEquals(v, r);
}
 
Example 12
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 13
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 14
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 15
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 16
Source File: EleCheck.java    From jelectrum with MIT License 4 votes vote down vote up
public static void checkServerVersion(EleConn conn)
{

  JSONArray params = new JSONArray();
  params.add("EleCheck");

  JSONArray range = new JSONArray();
  range.add("0.10");
  range.add("1.4.2");

  params.add(range);

  JSONObject msg = conn.request("server.version", params);
  JSONArray result = (JSONArray) msg.get("result");

  String server_id = (String)result.get(0);
  String ver = (String)result.get(1);

  System.out.println("Server id: " + server_id);
  System.out.println("Server selected version: " + ver);

}
 
Example 17
Source File: GoogleGeocodeService.java    From c4sg-services with MIT License 4 votes vote down vote up
@Override
public Map<String, BigDecimal> getGeoCode(String state, String country) throws Exception {
	
	Map<String,BigDecimal> geocode = new HashMap<String,BigDecimal>();
	
	// validate input
	if(country != null && !country.isEmpty()) {
		StringBuilder address = new StringBuilder();
		if (state != null && !state.isEmpty()) {
			address.append(state);
			address.append(",");
		}
		String countryCode = CountryCodeConverterUtil.convertToIso2(country);
		address.append(countryCode);
		
		try {
			URL url = getRequestUrl(address.toString());
			String response = getResponse(url);
			if(response != null) {
				Object obj = JSONValue.parse(response);
				
				if(obj instanceof JSONObject) {
					JSONObject jsonObject = (JSONObject) obj;
					JSONArray array = (JSONArray) jsonObject.get("results");					
					JSONObject element = (JSONObject) array.get(0);
					JSONObject geometry = (JSONObject) element.get("geometry");
					JSONObject location = (JSONObject) geometry.get("location");
					Double lng = (Double) location.get("lng");
					Double lat = (Double) location.get("lat");
					geocode.put("lng", new BigDecimal(lng));
					geocode.put("lat", new BigDecimal(lat));
				}
				return geocode;				
			} else {
				throw new Exception("Fail to convert to geocode");
			}
		}
		catch(Exception ex) {
			throw new Exception(ex.getMessage());
			
		}
		
	}
	
	return geocode;
}
 
Example 18
Source File: AuditEntryHandlerTestIT.java    From blackduck-alert with Apache License 2.0 4 votes vote down vote up
@Test
public void getTestIT() throws Exception {
    NotificationEntity savedNotificationEntity = notificationContentRepository.save(mockNotification.createEntity());

    notificationContentRepository
        .save(new MockNotificationContent(DateUtils.createCurrentDateTimestamp(), "provider", DateUtils.createCurrentDateTimestamp(), "notificationType", "{}", 234L, providerConfigModel.getConfigurationId()).createEntity());

    Collection<ConfigurationFieldModel> slackFields = MockConfigurationModelFactory.createSlackDistributionFields();
    ConfigurationJobModel configurationJobModel = configurationAccessor.createJob(Set.of(slackChannelKey.getUniversalKey(), blackDuckProviderKey.getUniversalKey()), slackFields);

    AuditEntryEntity savedAuditEntryEntity = auditEntryRepository.save(
        new AuditEntryEntity(configurationJobModel.getJobId(), DateUtils.createCurrentDateTimestamp(), DateUtils.createCurrentDateTimestamp(), AuditEntryStatus.SUCCESS.toString(), null, null));

    auditNotificationRepository.save(new AuditNotificationRelation(savedAuditEntryEntity.getId(), savedNotificationEntity.getId()));

    AuthorizationManager authorizationManager = Mockito.mock(AuthorizationManager.class);
    Mockito.when(authorizationManager.hasReadPermission(Mockito.eq(ConfigContextEnum.GLOBAL.name()), Mockito.eq(AuditDescriptor.AUDIT_COMPONENT))).thenReturn(true);
    AuditEntryController auditEntryController = new AuditEntryController(auditEntryActions, contentConverter, responseFactory, authorizationManager, new AuditDescriptorKey());

    ResponseEntity<String> response = auditEntryController.get(null, null, null, null, null, true);
    AlertPagedModel<AuditEntryModel> auditEntries = gson.fromJson(response.getBody(), AlertPagedModel.class);
    assertEquals(1, auditEntries.getContent().size());

    ResponseEntity<String> auditEntryResponse = auditEntryController.get(savedNotificationEntity.getId());
    assertNotNull(auditEntryResponse);
    assertEquals(HttpStatus.OK, auditEntryResponse.getStatusCode());

    JSONArray jsonContentArray = JsonPath.read(response.getBody(), "$.content");
    LinkedHashMap auditEntryModelFieldMap = (LinkedHashMap) jsonContentArray.get(0);
    String auditEntryModelString = gson.toJson(auditEntryModelFieldMap);
    AuditEntryModel auditEntry = gson.fromJson(auditEntryModelString, AuditEntryModel.class);

    String auditEntryModelByIdString = JsonPath.read(auditEntryResponse.getBody(), "$.message");
    AuditEntryModel auditEntryById = gson.fromJson(auditEntryModelByIdString, AuditEntryModel.class);
    assertEquals(auditEntryById, auditEntry);

    assertEquals(savedNotificationEntity.getId().toString(), auditEntry.getId());
    assertFalse(auditEntry.getJobs().isEmpty());
    assertEquals(1, auditEntry.getJobs().size());
    FieldAccessor keyToFieldMap = configurationJobModel.getFieldAccessor();
    assertEquals(keyToFieldMap.getString(ChannelDistributionUIConfig.KEY_CHANNEL_NAME).get(), auditEntry.getJobs().get(0).getEventType());
    assertEquals(keyToFieldMap.getString(ChannelDistributionUIConfig.KEY_NAME).get(), auditEntry.getJobs().get(0).getName());

    NotificationConfig notification = auditEntry.getNotification();
    String createdAtStringValue = DateUtils.formatDate(savedNotificationEntity.getCreatedAt(), DateUtils.AUDIT_DATE_FORMAT);
    assertEquals(createdAtStringValue, notification.getCreatedAt());
    assertEquals(savedNotificationEntity.getNotificationType(), notification.getNotificationType());
    assertNotNull(notification.getContent());
    response = auditEntryController.get(null, null, null, null, null, false);
    auditEntries = gson.fromJson(response.getBody(), AlertPagedModel.class);
    assertEquals(2, auditEntries.getContent().size());
}