Search in sources :

Example 66 with JSONArray

use of net.minidev.json.JSONArray in project JsonPath by jayway.

the class JSONEntityPathFunctionTest method testPredicateWithFunctionCallSingleMatch.

/**
 * The fictitious use-case/story - is we have a collection of batches with values indicating some quality metric.
 * We want to determine the average of the values for only the batch's values where the number of items in the batch
 * is greater than the min batch size which is encoded in the JSON document.
 *
 * We use the length function in the predicate to determine the number of values in each batch and then for those
 * batches where the count is greater than min we calculate the average batch value.
 *
 * Its completely contrived example, however, this test exercises functions within predicates.
 */
@Test
public void testPredicateWithFunctionCallSingleMatch() {
    String path = "$.batches.results[?(@.values.length() >= $.batches.minBatchSize)].values.avg()";
    // Its an array because in some use-cases the min size might match more than one batch and thus we'll get
    // the average out for each collection
    JSONArray values = new JSONArray();
    values.add(12.2d);
    verifyFunction(conf, path, BATCH_JSON, values);
}
Also used : JSONArray(net.minidev.json.JSONArray) Test(org.junit.Test)

Example 67 with JSONArray

use of net.minidev.json.JSONArray in project c4sg-services by Code4SocialGood.

the class GoogleGeocodeService method getGeoCode.

@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;
}
Also used : JSONObject(net.minidev.json.JSONObject) HashMap(java.util.HashMap) JSONArray(net.minidev.json.JSONArray) JSONObject(net.minidev.json.JSONObject) BigDecimal(java.math.BigDecimal) URL(java.net.URL) MalformedURLException(java.net.MalformedURLException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 68 with JSONArray

use of net.minidev.json.JSONArray in project graylog2-server by Graylog2.

the class SearchAfterTest method sortKeysFrom.

private List<String> sortKeysFrom(Action<? extends JestResult> searchAction) {
    String rawJson = dataFrom(searchAction);
    JSONArray sorts = JsonPath.parse(rawJson).read("$.sort.*");
    return sorts.stream().map(this::singleKeyFrom).collect(Collectors.toList());
}
Also used : JSONArray(net.minidev.json.JSONArray)

Example 69 with JSONArray

use of net.minidev.json.JSONArray in project spring-security by spring-projects.

the class NimbusOpaqueTokenIntrospectorTests method introspectWhenIntrospectionTokenReturnsMalformedScopeThenEmptyAuthorities.

// gh-7563
@Test
public void introspectWhenIntrospectionTokenReturnsMalformedScopeThenEmptyAuthorities() {
    RestOperations restOperations = mock(RestOperations.class);
    OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations);
    given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(MALFORMED_SCOPE);
    OAuth2AuthenticatedPrincipal principal = introspectionClient.introspect("token");
    assertThat(principal.getAuthorities()).isEmpty();
    JSONArray scope = principal.getAttribute("scope");
    assertThat(scope).containsExactly("read", "write", "dolphin");
}
Also used : OAuth2AuthenticatedPrincipal(org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal) JSONArray(net.minidev.json.JSONArray) RestOperations(org.springframework.web.client.RestOperations) RequestEntity(org.springframework.http.RequestEntity) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 70 with JSONArray

use of net.minidev.json.JSONArray in project knox by apache.

the class AmbariServiceDiscovery method discover.

@Override
public Cluster discover(GatewayConfig gatewayConfig, ServiceDiscoveryConfig config, String clusterName) {
    AmbariCluster cluster = null;
    String discoveryAddress = config.getAddress();
    String discoveryUser = config.getUser();
    String discoveryPwdAlias = config.getPasswordAlias();
    // Handle missing discovery address value with the default if it has been defined
    if (discoveryAddress == null || discoveryAddress.isEmpty()) {
        discoveryAddress = gatewayConfig.getDefaultDiscoveryAddress();
        // If no default address could be determined
        if (discoveryAddress == null) {
            log.missingDiscoveryAddress();
        }
    }
    // Handle missing discovery cluster value with the default if it has been defined
    if (clusterName == null || clusterName.isEmpty()) {
        clusterName = gatewayConfig.getDefaultDiscoveryCluster();
        // If no default cluster could be determined
        if (clusterName == null) {
            log.missingDiscoveryCluster();
        }
    }
    // There must be a discovery address and cluster or discovery cannot be performed
    if (discoveryAddress != null && clusterName != null) {
        cluster = new AmbariCluster(clusterName);
        String encodedClusterName;
        try {
            encodedClusterName = URLEncoder.encode(clusterName, StandardCharsets.UTF_8.name());
        } catch (UnsupportedEncodingException e) {
            // TODO: Logging
            e.printStackTrace();
            encodedClusterName = clusterName;
        }
        Map<String, String> serviceComponents = new HashMap<>();
        init(gatewayConfig);
        Map<String, List<String>> componentHostNames = new HashMap<>();
        String hostRolesURL = String.format(Locale.ROOT, "%s" + AMBARI_HOSTROLES_URI, discoveryAddress, encodedClusterName);
        JSONObject hostRolesJSON = restClient.invoke(hostRolesURL, discoveryUser, discoveryPwdAlias);
        if (hostRolesJSON != null) {
            // Process the host roles JSON
            JSONArray items = (JSONArray) hostRolesJSON.get("items");
            for (Object obj : items) {
                JSONArray components = (JSONArray) ((JSONObject) obj).get("components");
                for (Object component : components) {
                    JSONArray hostComponents = (JSONArray) ((JSONObject) component).get("host_components");
                    for (Object hostComponent : hostComponents) {
                        JSONObject hostRoles = (JSONObject) ((JSONObject) hostComponent).get("HostRoles");
                        String serviceName = (String) hostRoles.get("service_name");
                        String componentName = (String) hostRoles.get("component_name");
                        serviceComponents.put(componentName, serviceName);
                        // Assuming public host name is more applicable than host_name
                        String hostName = (String) hostRoles.get("public_host_name");
                        if (hostName == null) {
                            // Some (even slightly) older versions of Ambari/HDP do not return public_host_name,
                            // so fall back to host_name in those cases.
                            hostName = (String) hostRoles.get("host_name");
                        }
                        if (hostName != null) {
                            log.discoveredServiceHost(serviceName, hostName);
                            if (!componentHostNames.containsKey(componentName)) {
                                componentHostNames.put(componentName, new ArrayList<>());
                            }
                            // Avoid duplicates
                            if (!componentHostNames.get(componentName).contains(hostName)) {
                                componentHostNames.get(componentName).add(hostName);
                            }
                        }
                    }
                }
            }
        }
        // Service configurations
        Map<String, Map<String, AmbariCluster.ServiceConfiguration>> serviceConfigurations = ambariClient.getActiveServiceConfigurations(discoveryAddress, encodedClusterName, discoveryUser, discoveryPwdAlias);
        if (serviceConfigurations.isEmpty()) {
            log.failedToAccessServiceConfigs(clusterName);
        }
        for (Entry<String, Map<String, AmbariCluster.ServiceConfiguration>> serviceConfiguration : serviceConfigurations.entrySet()) {
            for (Map.Entry<String, AmbariCluster.ServiceConfiguration> serviceConfig : serviceConfiguration.getValue().entrySet()) {
                cluster.addServiceConfiguration(serviceConfiguration.getKey(), serviceConfig.getKey(), serviceConfig.getValue());
            }
        }
        // Construct the AmbariCluster model
        for (Entry<String, String> entry : serviceComponents.entrySet()) {
            String componentName = entry.getKey();
            String serviceName = entry.getValue();
            List<String> hostNames = componentHostNames.get(componentName);
            Map<String, AmbariCluster.ServiceConfiguration> configs = serviceConfigurations.get(serviceName);
            String configType = componentServiceConfigs.get(componentName);
            if (configType != null) {
                AmbariCluster.ServiceConfiguration svcConfig = configs.get(configType);
                if (svcConfig != null) {
                    AmbariComponent c = new AmbariComponent(componentName, svcConfig.getVersion(), encodedClusterName, serviceName, hostNames, svcConfig.getProperties());
                    cluster.addComponent(c);
                }
            }
        }
        if (configChangeMonitor != null) {
            // Notify the cluster config monitor about these cluster configuration details
            configChangeMonitor.addClusterConfigVersions(cluster, config);
        }
    }
    return cluster;
}
Also used : HashMap(java.util.HashMap) JSONArray(net.minidev.json.JSONArray) UnsupportedEncodingException(java.io.UnsupportedEncodingException) JSONObject(net.minidev.json.JSONObject) ArrayList(java.util.ArrayList) List(java.util.List) JSONObject(net.minidev.json.JSONObject) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

JSONArray (net.minidev.json.JSONArray)71 JSONObject (net.minidev.json.JSONObject)52 Test (org.junit.Test)13 HashMap (java.util.HashMap)10 JSONParser (net.minidev.json.parser.JSONParser)10 ArrayList (java.util.ArrayList)9 Map (java.util.Map)9 HashSet (java.util.HashSet)6 List (java.util.List)6 UnsupportedEncodingException (java.io.UnsupportedEncodingException)5 JSONConverterException (org.btrplace.json.JSONConverterException)5 Test (org.testng.annotations.Test)5 DocumentContext (com.jayway.jsonpath.DocumentContext)3 JsonPath (com.jayway.jsonpath.JsonPath)3 Option (com.jayway.jsonpath.Option)3 ContentType (ddf.catalog.data.ContentType)3 SourceInfoResponse (ddf.catalog.operation.SourceInfoResponse)3 SourceInfoRequestEnterprise (ddf.catalog.operation.impl.SourceInfoRequestEnterprise)3 SourceDescriptor (ddf.catalog.source.SourceDescriptor)3 ByteArrayInputStream (java.io.ByteArrayInputStream)3