Java Examples for com.jayway.jsonpath.DocumentContext

The following java examples will help you to understand the usage of com.jayway.jsonpath.DocumentContext. These source code samples are taken from different open source projects.

Example 1
Project: karate-master  File: Script.java View source code
public static ScriptValue eval(String text, ScriptContext context) {
    text = StringUtils.trimToEmpty(text);
    if (text.isEmpty()) {
        return ScriptValue.NULL;
    }
    if (isCallSyntax(text) || isCallOnceSyntax(text)) {
        // special case in form "call foo arg"
        boolean once = isCallOnceSyntax(text);
        if (once) {
            text = text.substring(9);
        } else {
            text = text.substring(5);
        }
        // TODO handle read('file with spaces in the name')
        int pos = text.indexOf(' ');
        String arg;
        if (pos != -1) {
            arg = text.substring(pos);
            text = text.substring(0, pos);
        } else {
            arg = null;
        }
        if (!once) {
            return call(text, arg, context);
        }
        ScriptValue callResult = context.env.getFromCallCache(text);
        if (callResult != null) {
            context.logger.debug("callonce cache hit for: {}", text);
            return callResult;
        }
        callResult = call(text, arg, context);
        context.env.putInCallCache(text, callResult);
        context.logger.debug("cached callonce: {}", text);
        return callResult;
    } else if (isGetSyntax(text)) {
        // special case in form
        // get json[*].path
        // get /xml/path
        // get xpath-function(expression)
        text = text.substring(4);
        String left;
        String right;
        if (isVariableAndSpaceAndPath(text)) {
            int pos = text.indexOf(' ');
            right = text.substring(pos + 1);
            left = text.substring(0, pos);
        } else {
            Pair<String, String> pair = parseVariableAndPath(text);
            left = pair.getLeft();
            right = pair.getRight();
        }
        if (isXmlPath(right) || isXmlPathFunction(right)) {
            return evalXmlPathOnVarByName(left, right, context);
        } else {
            return evalJsonPathOnVarByName(left, right, context);
        }
    } else if (isJsonPath(text)) {
        return evalJsonPathOnVarByName(ScriptValueMap.VAR_RESPONSE, text, context);
    } else if (isJson(text)) {
        DocumentContext doc = JsonUtils.toJsonDoc(text);
        evalJsonEmbeddedExpressions(doc, context);
        return new ScriptValue(doc);
    } else if (isXml(text)) {
        Document doc = XmlUtils.toXmlDoc(text);
        evalXmlEmbeddedExpressions(doc, context);
        return new ScriptValue(doc);
    } else if (isXmlPath(text)) {
        return evalXmlPathOnVarByName(ScriptValueMap.VAR_RESPONSE, text, context);
    } else if (isStringExpression(text)) {
        // has to be above variableAndXml/JsonPath because of / in URL-s etc
        return evalInNashorn(text, context);
    } else if (isVariableAndJsonPath(text)) {
        Pair<String, String> pair = parseVariableAndPath(text);
        return evalJsonPathOnVarByName(pair.getLeft(), pair.getRight(), context);
    } else if (isVariableAndXmlPath(text)) {
        Pair<String, String> pair = parseVariableAndPath(text);
        return evalXmlPathOnVarByName(pair.getLeft(), pair.getRight(), context);
    } else {
        // including function declarations e.g. function() { }
        return evalInNashorn(text, context);
    }
}
Example 2
Project: JsonPath-master  File: IssuesTest.java View source code
@Test
public void issue_97() throws Exception {
    String json = "{ \"books\": [ " + "{ \"category\": \"fiction\" }, " + "{ \"category\": \"reference\" }, " + "{ \"category\": \"fiction\" }, " + "{ \"category\": \"fiction\" }, " + "{ \"category\": \"reference\" }, " + "{ \"category\": \"fiction\" }, " + "{ \"category\": \"reference\" }, " + "{ \"category\": \"reference\" }, " + "{ \"category\": \"reference\" }, " + "{ \"category\": \"reference\" }, " + "{ \"category\": \"reference\" } ]  }";
    Configuration conf = Configuration.builder().jsonProvider(new GsonJsonProvider()).mappingProvider(new GsonMappingProvider()).build();
    DocumentContext context = JsonPath.using(conf).parse(json);
    context.delete("$.books[?(@.category == 'reference')]");
    List<String> categories = context.read("$..category", List.class);
    assertThat(categories).containsOnly("fiction");
}
Example 3
Project: threatconnect-java-master  File: AbstractJsonPathParser.java View source code
@Override
public List<I> parseData() throws ParserException {
    try {
        // read the json as a string and allow it to be preprocessed if needed
        String rawJson = IOUtils.toString(getDataSource().read());
        String json = preProcessJson(rawJson);
        // parse the json into an element
        DocumentContext context = JsonPath.parse(json);
        // process the json and retrieve the result
        return processJson(context);
    } catch (IOException e) {
        throw new ParserException(e);
    }
}
Example 4
Project: semiot-platform-master  File: ModelJsonLdUtils.java View source code
public static Object deleteRedundantBNIds(Object json) throws IOException {
    String json_str = JsonUtils.toString(json);
    DocumentContext path = JsonPath.parse(json);
    JSONArray bnResources = path.read(JSONPATH_BN_OBJECTS);
    bnResources.stream().map(( resource) -> (Map<String, Object>) resource).map((Map<String, Object> m) -> (String) m.get(JSONLD_KEY_ID)).filter(( bnId) -> (StringUtils.countMatches(json_str, "\"" + bnId + "\"") < 2)).forEach(( bnId) -> path.delete("$..*[?(@.@id=~/" + bnId + "/i)].@id"));
    return path.json();
}
Example 5
Project: spring-data-commons-master  File: SpringDataWebConfiguration.java View source code
/*
	 * (non-Javadoc)
	 * @see org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter#extendMessageConverters(java.util.List)
	 */
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
    if (ClassUtils.isPresent("com.jayway.jsonpath.DocumentContext", context.getClassLoader()) && ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", context.getClassLoader())) {
        ProjectingJackson2HttpMessageConverter converter = new ProjectingJackson2HttpMessageConverter(new ObjectMapper());
        converter.setBeanClassLoader(context.getClassLoader());
        converter.setBeanFactory(context);
        converters.add(0, converter);
    }
    if (ClassUtils.isPresent("org.xmlbeam.XBProjector", context.getClassLoader())) {
        converters.add(0, new XmlBeamHttpMessageConverter());
    }
}
Example 6
Project: spring-boot-admin-master  File: ApplicationTest.java View source code
@Test
public void test_json_format() throws JsonProcessingException, IOException {
    ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().build();
    Application app = Application.create("test").withHealthUrl("http://health").withServiceUrl("http://service").withManagementUrl("http://management").build();
    DocumentContext json = JsonPath.parse(objectMapper.writeValueAsString(app));
    assertThat((String) json.read("$.name")).isEqualTo("test");
    assertThat((String) json.read("$.serviceUrl")).isEqualTo("http://service");
    assertThat((String) json.read("$.managementUrl")).isEqualTo("http://management");
    assertThat((String) json.read("$.healthUrl")).isEqualTo("http://health");
}
Example 7
Project: spring-cloud-dataflow-master  File: DeploymentStateResourceTests.java View source code
@Test
public void testSerializationOfSingleStepExecution() throws JsonProcessingException {
    final ObjectMapper objectMapper = new ObjectMapper();
    final DeploymentStateResource deploymentStateResource = DeploymentStateResource.DEPLOYED;
    final String result = objectMapper.writeValueAsString(deploymentStateResource);
    final DocumentContext documentContext = JsonPath.parse(result);
    assertThat(documentContext.read("$.key"), is("deployed"));
    assertThat(documentContext.read("$.displayName"), is("Deployed"));
    assertThat(documentContext.read("$.description"), is("All apps have been successfully deployed"));
}
Example 8
Project: BioSolr-master  File: JsonDocumentFactory.java View source code
public PathDocument read(InputStream in) {
    final DocumentContext json = JsonPath.parse(in);
    return new PathDocument() {

        @Override
        public Object getPathValue(String path) {
            Object value = json.read(path);
            if (value instanceof JSONArray) {
                JSONArray array = (JSONArray) value;
                return array.size() > 0 ? array.get(0) : null;
            }
            return value;
        }

        @Override
        public Object[] getPathValues(String path) {
            return json.read(path, Object[].class);
        }
    };
}
Example 9
Project: spring-boot-starter-master  File: AdditionalConfigurationMetadataTest.java View source code
@Test
public void testProperties() throws IOException {
    DocumentContext documentContext = JsonPath.parse(new FileSystemResource("src/main/resources/META-INF/additional-spring-configuration-metadata.json").getInputStream());
    List<Map<String, String>> properties = documentContext.read("$.properties");
    assertThat(properties.size(), is(1));
    // assert for default-scripting-language
    {
        Map<String, String> element = properties.get(0);
        assertThat(element.get("sourceType"), is("org.apache.ibatis.session.Configuration"));
        assertThat(element.get("defaultValue"), is("org.apache.ibatis.scripting.xmltags.XMLLanguageDriver"));
        assertThat(element.get("name"), is("mybatis.configuration.default-scripting-language"));
        assertThat(element.get("type"), is("java.lang.Class<? extends org.apache.ibatis.scripting.LanguageDriver>"));
    }
}
Example 10
Project: liferay-portal-master  File: DDMRESTDataProvider.java View source code
protected DDMDataProviderResponse createDDMDataProviderResponse(DocumentContext documentContext, DDMDataProviderRequest ddmDataProviderRequest, DDMRESTDataProviderSettings ddmRESTDataProviderSettings) {
    DDMDataProviderOutputParametersSettings[] outputParameterSettingsArray = ddmRESTDataProviderSettings.outputParameters();
    if ((outputParameterSettingsArray == null) || (outputParameterSettingsArray.length == 0)) {
        return DDMDataProviderResponse.of();
    }
    List<DDMDataProviderResponseOutput> ddmDataProviderResponseOutputs = new ArrayList<>();
    for (DDMDataProviderOutputParametersSettings outputParameterSettings : outputParameterSettingsArray) {
        String name = outputParameterSettings.outputParameterName();
        String type = outputParameterSettings.outputParameterType();
        String path = outputParameterSettings.outputParameterPath();
        if (Objects.equals(type, "text")) {
            String nomalizedPath = normalizePath(path);
            ddmDataProviderResponseOutputs.add(DDMDataProviderResponseOutput.of(name, "text", documentContext.read(nomalizedPath)));
        } else if (Objects.equals(type, "number")) {
            String nomalizedPath = normalizePath(path);
            ddmDataProviderResponseOutputs.add(DDMDataProviderResponseOutput.of(name, "number", documentContext.read(nomalizedPath)));
        } else if (Objects.equals(type, "list")) {
            String[] paths = StringUtil.split(path, CharPool.SEMICOLON);
            String normalizedValuePath = normalizePath(paths[0]);
            String normalizedKeyPath = normalizedValuePath;
            List<String> values = documentContext.read(normalizedValuePath);
            List<String> keys = new ArrayList<>(values);
            if (paths.length >= 2) {
                normalizedKeyPath = normalizePath(paths[1]);
                keys = documentContext.read(normalizedKeyPath);
            }
            List<KeyValuePair> keyValuePairs = new ArrayList<>();
            for (int i = 0; i < values.size(); i++) {
                keyValuePairs.add(new KeyValuePair(keys.get(i), values.get(i)));
            }
            if (ddmRESTDataProviderSettings.pagination()) {
                int start = Integer.valueOf(ddmDataProviderRequest.getParameter("paginationStart"));
                int end = Integer.valueOf(ddmDataProviderRequest.getParameter("paginationEnd"));
                if (keyValuePairs.size() > (end - start)) {
                    keyValuePairs = ListUtil.subList(keyValuePairs, start, end);
                }
            }
            ddmDataProviderResponseOutputs.add(DDMDataProviderResponseOutput.of(name, "list", keyValuePairs));
        }
    }
    int size = ddmDataProviderResponseOutputs.size();
    return DDMDataProviderResponse.of(ddmDataProviderResponseOutputs.toArray(new DDMDataProviderResponseOutput[size]));
}
Example 11
Project: play-hibernate-master  File: PlayUtils.java View source code
private static void printUsedConfig() {
    String config = System.getProperty("config.resource", "application.conf");
    info("Will use config file {} of {}.", config, FileUtils.listFiles(Play.application().getFile("/conf"), FileFilterUtils.suffixFileFilter(".conf"), null).stream().map(File::getName).sorted().collect(Collectors.toSet()));
    final StringBuilder configPrinter = startConfigPrinter("Config file: (" + config + ")");
    Properties loadedConfigFile = new Properties();
    try {
        loadedConfigFile.load(Play.application().classloader().getResourceAsStream(config));
    } catch (IOException e) {
    }
    DocumentContext ctx = JsonPath.parse(Json.toJson(Play.application().configuration().asMap()).toString());
    loadedConfigFile.keySet().stream().sorted().forEach( key -> {
        try {
            addKeyValue(configPrinter, key, ctx.read("$." + key));
        } catch (Exception e) {
            addKeyValue(configPrinter, key, " = n/a");
        }
    });
    info(withFooter(configPrinter).toString());
}
Example 12
Project: thingsboard-gateway-master  File: SigfoxDeviceDataConverter.java View source code
public DeviceData parseBody(String body) {
    try {
        DocumentContext document = JsonPath.parse(body);
        if (filterExpression != null && !filterExpression.isEmpty()) {
            try {
                log.debug("Data before filtering {}", body);
                List jsonArray = document.read(filterExpression);
                // take 1st element from filtered array (jayway jsonpath library limitation)
                Object jsonObj = jsonArray.get(0);
                document = JsonPath.parse(jsonObj);
                body = document.jsonString();
                log.debug("Data after filtering {}", body);
            } catch (RuntimeException e) {
                log.debug("Failed to apply filter expression: {}", filterExpression, e);
                throw new RuntimeException("Failed to apply filter expression " + filterExpression, e);
            }
        }
        long ts = System.currentTimeMillis();
        String deviceName = eval(document, deviceNameJsonExpression);
        if (!StringUtils.isEmpty(deviceName)) {
            List<KvEntry> attrData = getKvEntries(JsonPath.parse(body), attributes);
            List<TsKvEntry> tsData = getKvEntries(JsonPath.parse(body), timeseries).stream().map( kv -> new BasicTsKvEntry(ts, kv)).collect(Collectors.toList());
            return new DeviceData(deviceName, attrData, tsData);
        }
    } catch (Exception e) {
        log.error("Exception occurred while parsing json request body [{}]", body, e);
        throw new RuntimeException("Exception occurred while parsing json request body [" + body + "]", e);
    }
    return null;
}
Example 13
Project: jframe-master  File: TestJsonPath.java View source code
@Test
public void testRead() {
    String json = "{\"_scroll_id\":\"cXVlcnlBbmRGZXRjaDsxOzE2NTUwMDc6c0x6bWo0eERTSTZyYUdZVG9LYThfQTswOw==\",\"took\":2994,\"timed_out\":false,\"_shards\":{\"total\":1,\"successful\":1,\"failed\":0},\"hits\":{\"total\":117375727,\"max_score\":null,\"hits\":[{\"_index\":\"weike\",\"_type\":\"member\",\"_id\":\"AVeslHLGT4gPDlYJn1J2\",\"_score\":null,\"_source\":{\"birthday\":0,\"lm\":1447897716678,\"creditLevel\":0,\"relationSource\":0,\"fstp\":0,\"lt\":0,\"itemCloseCount\":0,\"type\":0,\"tradeFroms\":[\"WAP\"],\"tc\":0,\"ta\":0,\"minp\":0,\"province\":13,\"buyerNick\":\"闽丫丫\",\"receiverName\":\"陆小姐\",\"grade\":0,\"tradeAmount\":102.48,\"closeTradeAmount\":0,\"ft\":0,\"black\":false,\"itemNum\":1,\"closeTradeCount\":0,\"lastEdmTime\":0,\"hasRefund\":true,\"buyerId\":0,\"emailType\":2,\"avgPrice\":102.48,\"giveNBRate\":false,\"lastCouponTimeEnd\":0,\"tradeCount\":1,\"email\":\"sunny8286@163.com\",\"ap\":0,\"address\":\"莲前街道新景中心B2010\",\"items\":[523045242297],\"sellerId\":479184430,\"registered\":0,\"goodRate\":0,\"lastTradeTime\":1447256536000,\"lastSmsTime\":0,\"bizOrderId\":1403847313137758,\"maxp\":0,\"mobile\":\"18659211097\"},\"sort\":[0]},{\"_index\":\"weike\",\"_type\":\"member\",\"_id\":\"AVeslHLGT4gPDlYJn1J3\",\"_score\":null,\"_source\":{\"birthday\":0,\"lm\":1448650655763,\"creditLevel\":0,\"relationSource\":1,\"fstp\":0,\"lt\":0,\"itemCloseCount\":0,\"type\":0,\"city\":\"150100\",\"tradeFroms\":[\"WAP\"],\"tc\":0,\"ta\":0,\"minp\":0,\"province\":150000,\"buyerNick\":\"pengran0727\",\"receiverName\":\"彭冉\",\"grade\":1,\"tradeAmount\":238.63,\"closeTradeAmount\":0,\"ft\":0,\"black\":false,\"itemNum\":2,\"status\":\"normal\",\"lastEdmTime\":0,\"closeTradeCount\":0,\"hasRefund\":false,\"buyerId\":0,\"emailType\":0,\"groupIds\":\"418525357\",\"avgPrice\":238.63,\"giveNBRate\":false,\"lastCouponTimeEnd\":0,\"tradeCount\":1,\"ap\":0,\"address\":\"新华西街新华桥农行营业厅(监狱管理局西侧)\",\"items\":[522190672466,522917969407],\"sellerId\":479184430,\"registered\":0,\"goodRate\":0,\"lastTradeTime\":1447256537000,\"lastSmsTime\":0,\"bizOrderId\":0,\"maxp\":0,\"mobile\":\"13624848066\"},\"sort\":[1]}]}}";
    long start = System.currentTimeMillis();
    DocumentContext context = JsonPath.parse(json);
    List<MemberDO> source = context.read("$.hits.hits.._source");
    String scrollId = context.read("$._scroll_id");
    int total = context.<Integer>read("$.hits.total");
    System.out.println(System.currentTimeMillis() - start);
    // System.out.println(scrollId);
    System.out.println(total);
    // System.out.println(source);
    start = System.currentTimeMillis();
    Gson gson = new Gson();
    Map<String, String> obj = gson.fromJson(json, HashMap.class);
    System.out.println(System.currentTimeMillis() - start);
    System.out.println(obj.get("_scroll_id"));
    // System.out.println((obj.get("hits")).get("total"));
    // System.out.println(source);
    List<Map<String, String>> list = new LinkedList<Map<String, String>>();
    Map map = new HashMap<>();
    map.put("a", "1");
    list.add(map);
    map = new HashMap<>();
    map.put("a", "2");
    list.add(map);
    json = Gson.toJson(list);
    context = JsonPath.parse(json);
    System.out.println(context.<List>read("$..a"));
}
Example 14
Project: nifi-master  File: EvaluateJsonPath.java View source code
@Override
public void onTrigger(final ProcessContext processContext, final ProcessSession processSession) throws ProcessException {
    FlowFile flowFile = processSession.get();
    if (flowFile == null) {
        return;
    }
    final ComponentLog logger = getLogger();
    DocumentContext documentContext;
    try {
        documentContext = validateAndEstablishJsonContext(processSession, flowFile);
    } catch (InvalidJsonException e) {
        logger.error("FlowFile {} did not have valid JSON content.", new Object[] { flowFile });
        processSession.transfer(flowFile, REL_FAILURE);
        return;
    }
    Set<Map.Entry<String, JsonPath>> attributeJsonPathEntries = attributeToJsonPathEntrySetQueue.poll();
    if (attributeJsonPathEntries == null) {
        attributeJsonPathEntries = processContext.getProperties().entrySet().stream().filter( e -> e.getKey().isDynamic()).collect(Collectors.toMap( e -> e.getKey().getName(),  e -> JsonPath.compile(e.getValue()))).entrySet();
    }
    try {
        // We'll only be using this map if destinationIsAttribute == true
        final Map<String, String> jsonPathResults = destinationIsAttribute ? new HashMap<>(attributeJsonPathEntries.size()) : Collections.EMPTY_MAP;
        for (final Map.Entry<String, JsonPath> attributeJsonPathEntry : attributeJsonPathEntries) {
            final String jsonPathAttrKey = attributeJsonPathEntry.getKey();
            final JsonPath jsonPathExp = attributeJsonPathEntry.getValue();
            Object result;
            try {
                Object potentialResult = documentContext.read(jsonPathExp);
                if (returnType.equals(RETURN_TYPE_SCALAR) && !isJsonScalar(potentialResult)) {
                    logger.error("Unable to return a scalar value for the expression {} for FlowFile {}. Evaluated value was {}. Transferring to {}.", new Object[] { jsonPathExp.getPath(), flowFile.getId(), potentialResult.toString(), REL_FAILURE.getName() });
                    processSession.transfer(flowFile, REL_FAILURE);
                    return;
                }
                result = potentialResult;
            } catch (PathNotFoundException e) {
                if (pathNotFound.equals(PATH_NOT_FOUND_WARN)) {
                    logger.warn("FlowFile {} could not find path {} for attribute key {}.", new Object[] { flowFile.getId(), jsonPathExp.getPath(), jsonPathAttrKey }, e);
                }
                if (destinationIsAttribute) {
                    jsonPathResults.put(jsonPathAttrKey, StringUtils.EMPTY);
                    continue;
                } else {
                    processSession.transfer(flowFile, REL_NO_MATCH);
                    return;
                }
            }
            final String resultRepresentation = getResultRepresentation(result, nullDefaultValue);
            if (destinationIsAttribute) {
                jsonPathResults.put(jsonPathAttrKey, resultRepresentation);
            } else {
                flowFile = processSession.write(flowFile,  out -> {
                    try (OutputStream outputStream = new BufferedOutputStream(out)) {
                        outputStream.write(resultRepresentation.getBytes(StandardCharsets.UTF_8));
                    }
                });
                processSession.getProvenanceReporter().modifyContent(flowFile, "Replaced content with result of expression " + jsonPathExp.getPath());
            }
        }
        // jsonPathResults map will be empty if this is false
        if (destinationIsAttribute) {
            flowFile = processSession.putAllAttributes(flowFile, jsonPathResults);
        }
        processSession.transfer(flowFile, REL_MATCH);
    } finally {
        attributeToJsonPathEntrySetQueue.offer(attributeJsonPathEntries);
    }
}
Example 15
Project: graylog2-server-master  File: HTTPJSONPathDataAdapter.java View source code
@VisibleForTesting
static LookupResult parseBody(JsonPath singleJsonPath, @Nullable JsonPath multiJsonPath, InputStream body) {
    try {
        final DocumentContext documentContext = JsonPath.parse(body);
        LookupResult.Builder builder = LookupResult.builder().cacheTTL(Long.MAX_VALUE);
        if (multiJsonPath != null) {
            try {
                final Object multiValue = documentContext.read(multiJsonPath);
                if (multiValue instanceof Map) {
                    //noinspection unchecked
                    builder = builder.multiValue((Map<Object, Object>) multiValue);
                } else {
                    builder = builder.multiSingleton(multiValue);
                }
            } catch (PathNotFoundException e) {
                LOG.warn("Couldn't read multi JSONPath from response - skipping multi value ({})", e.getMessage());
            }
        }
        try {
            final Object singleValue = documentContext.read(singleJsonPath);
            if (singleValue instanceof CharSequence) {
                return builder.single((CharSequence) singleValue).build();
            } else if (singleValue instanceof Number) {
                return builder.single((Number) singleValue).build();
            } else if (singleValue instanceof Boolean) {
                return builder.single((Boolean) singleValue).build();
            } else {
                throw new IllegalArgumentException("Single value data type cannot be: " + singleValue.getClass().getCanonicalName());
            }
        } catch (PathNotFoundException e) {
            LOG.warn("Couldn't read single JSONPath from response - returning empty result ({})", e.getMessage());
            return LookupResult.empty();
        }
    } catch (InvalidJsonException e) {
        LOG.error("Couldn't parse JSON response", e);
        return LookupResult.empty();
    } catch (ClassCastException e) {
        LOG.error("Couldn't assign value type", e);
        return LookupResult.empty();
    } catch (Exception e) {
        LOG.error("Unexpected error parsing JSON response", e);
        return LookupResult.empty();
    }
}
Example 16
Project: iiif-presentation-api-master  File: IiifPresentationApiObjectMapperTest.java View source code
@Test
public void testCollectionToJson() throws JsonProcessingException {
    PropertyValue labelProp = new PropertyValueSimpleImpl("some label");
    List<Metadata> metadata = new ArrayList<>();
    metadata.add(new MetadataImpl(new PropertyValueSimpleImpl("some key"), new PropertyValueSimpleImpl("some value")));
    Collection coll = new CollectionImpl(URI.create("http://example.com/collection/some-collection"), labelProp, metadata);
    List<ManifestReference> manifests = new ArrayList<>();
    manifests.add(new ManifestReferenceImpl(URI.create("http://example.com/manifest/some-manifest"), new PropertyValueSimpleImpl("some label")));
    manifests.add(new ManifestReferenceImpl(URI.create("http://example.com/manifest/some-other-manifest")));
    coll.setManifests(manifests);
    List<CollectionReference> subColls = new ArrayList<>();
    subColls.add(new CollectionReferenceImpl(URI.create("http://example.com/collection/some-other-collection"), new PropertyValueSimpleImpl("some label")));
    subColls.add(new CollectionReferenceImpl(URI.create("http://example.com/collection/yet-another-collection")));
    coll.setSubCollections(subColls);
    String jsonString = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(coll);
    DocumentContext ctx = JsonPath.parse(jsonString);
    JsonPathAssert.assertThat(ctx).jsonPathAsInteger("$.collections.length()").isEqualTo(2);
    JsonPathAssert.assertThat(ctx).jsonPathAsInteger("$.manifests.length()").isEqualTo(2);
    JsonPathAssert.assertThat(ctx).jsonPathAsString("$.label").isEqualTo("some label");
    JsonPathAssert.assertThat(ctx).jsonPathAsString("$.metadata[0].label").isEqualTo("some key");
    JsonPathAssert.assertThat(ctx).jsonPathAsString("$.manifests[0]['@type']").isEqualTo("sc:Manifest");
    JsonPathAssert.assertThat(ctx).jsonPathAsString("$.collections[0]['@type']").isEqualTo("sc:Collection");
}
Example 17
Project: java-apikit-master  File: HDDevice.java View source code
/**
	 * Overlays specs onto a device
	 *
	 * @param string specsField : Either 'platform', 'browser', 'language'
	 **/
private void specsOverlay(String specsField, JsonElement device, JsonElement specs) {
    //		DocumentContext dcDevice = JsonPath.parse(gson.toJson(device));
    DocumentContext dcSpecs = JsonPath.parse(gson.toJson(specs));
    switch(specsField) {
        case "platform":
            if (!HDUtil.isNullOrEmpty((String) dcSpecs.read("$." + JsonConstants.HD_SPECS + "." + JsonConstants.GENERAL_PLATFORM))) {
                //					dcDevice.set("$." + JsonConstants.DEVICE + "." + JsonConstants.HD_SPECS + "." + JsonConstants.GENERAL_PLATFORM, 
                device.getAsJsonObject().get(JsonConstants.DEVICE).getAsJsonObject().get(JsonConstants.HD_SPECS).getAsJsonObject().addProperty(JsonConstants.GENERAL_PLATFORM, (String) dcSpecs.read("$." + JsonConstants.HD_SPECS + "." + JsonConstants.GENERAL_PLATFORM));
                //					dcDevice.set("$." + JsonConstants.DEVICE + "." + JsonConstants.HD_SPECS + "." + JsonConstants.GENERAL_PLATFORM_VERSION,
                device.getAsJsonObject().get(JsonConstants.DEVICE).getAsJsonObject().get(JsonConstants.HD_SPECS).getAsJsonObject().addProperty(JsonConstants.GENERAL_PLATFORM_VERSION, (String) dcSpecs.read("$." + JsonConstants.HD_SPECS + "." + JsonConstants.GENERAL_PLATFORM_VERSION));
            }
            break;
        case "browser":
            if (!HDUtil.isNullOrEmpty((String) dcSpecs.read("$." + JsonConstants.HD_SPECS + "." + JsonConstants.GENERAL_BROWSER))) {
                //					dcDevice.set("$." + JsonConstants.DEVICE + "." + JsonConstants.HD_SPECS + "." + JsonConstants.GENERAL_BROWSER, 
                device.getAsJsonObject().get(JsonConstants.DEVICE).getAsJsonObject().get(JsonConstants.HD_SPECS).getAsJsonObject().addProperty(JsonConstants.GENERAL_BROWSER, (String) dcSpecs.read("$." + JsonConstants.HD_SPECS + "." + JsonConstants.GENERAL_BROWSER));
                //					dcDevice.set("$." + JsonConstants.DEVICE + "." + JsonConstants.HD_SPECS + "." + JsonConstants.GENERAL_BROWSER_VERSION,
                device.getAsJsonObject().get(JsonConstants.DEVICE).getAsJsonObject().get(JsonConstants.HD_SPECS).getAsJsonObject().addProperty(JsonConstants.GENERAL_BROWSER_VERSION, (String) dcSpecs.read("$." + JsonConstants.HD_SPECS + "." + JsonConstants.GENERAL_BROWSER_VERSION));
            }
            break;
        case "app":
            if (!HDUtil.isNullOrEmpty((String) dcSpecs.read("$." + JsonConstants.HD_SPECS + "." + JsonConstants.GENERAL_APP))) {
                //					dcDevice.set("$." + JsonConstants.DEVICE + "." + JsonConstants.HD_SPECS + "." + JsonConstants.GENERAL_APP,
                device.getAsJsonObject().get(JsonConstants.DEVICE).getAsJsonObject().get(JsonConstants.HD_SPECS).getAsJsonObject().addProperty(JsonConstants.GENERAL_APP, (String) dcSpecs.read("$." + JsonConstants.HD_SPECS + "." + JsonConstants.GENERAL_APP));
                //					dcDevice.set("$." + JsonConstants.DEVICE + "." + JsonConstants.HD_SPECS + "." + JsonConstants.GENERAL_APP_VERSION,
                device.getAsJsonObject().get(JsonConstants.DEVICE).getAsJsonObject().get(JsonConstants.HD_SPECS).getAsJsonObject().addProperty(JsonConstants.GENERAL_APP_VERSION, (String) dcSpecs.read("$." + JsonConstants.HD_SPECS + "." + JsonConstants.GENERAL_APP_VERSION));
                //					dcDevice.set("$." + JsonConstants.DEVICE + "." + JsonConstants.HD_SPECS + "." + JsonConstants.GENERAL_APP_CATEGORY,
                device.getAsJsonObject().get(JsonConstants.DEVICE).getAsJsonObject().get(JsonConstants.HD_SPECS).getAsJsonObject().addProperty(JsonConstants.GENERAL_APP_CATEGORY, (String) dcSpecs.read("$." + JsonConstants.HD_SPECS + "." + JsonConstants.GENERAL_APP_CATEGORY));
            }
            break;
        case "language":
            if (!HDUtil.isNullOrEmpty((String) dcSpecs.read("$." + JsonConstants.HD_SPECS + "[0]." + JsonConstants.GENERAL_LANGUAGE))) {
                //					dcDevice.set("$." +  JsonConstants.DEVICE + "." + JsonConstants.HD_SPECS + "." + JsonConstants.GENERAL_LANGUAGE,
                device.getAsJsonObject().get(JsonConstants.DEVICE).getAsJsonObject().get(JsonConstants.HD_SPECS).getAsJsonObject().addProperty(JsonConstants.GENERAL_LANGUAGE, (String) dcSpecs.read("$." + JsonConstants.HD_SPECS + "[0]." + JsonConstants.GENERAL_LANGUAGE));
                //					dcDevice.put("$." + JsonConstants.DEVICE + "." + JsonConstants.HD_SPECS, JsonConstants.GENERAL_LANGUAGE_FULL,
                device.getAsJsonObject().get(JsonConstants.DEVICE).getAsJsonObject().get(JsonConstants.HD_SPECS).getAsJsonObject().addProperty(JsonConstants.GENERAL_LANGUAGE_FULL, (String) dcSpecs.read("$." + JsonConstants.HD_SPECS + "[1]." + JsonConstants.GENERAL_LANGUAGE_FULL));
            }
            break;
    }
}
Example 18
Project: divolte-collector-master  File: JsonPathSupport.java View source code
public static DocumentContext asDocumentContext(final TreeNode jsonDocument) {
    return JsonPath.parse(jsonDocument, JSON_PATH_CONFIGURATION);
}
Example 19
Project: hsac-fitnesse-fixtures-master  File: JsonPathHelper.java View source code
protected DocumentContext parseJson(String json) {
    DocumentContext result;
    if (lastContext != null && lastJson != null && lastJson.equals(json)) {
        result = lastContext;
    } else {
        result = getContext().parse(json);
        lastContext = result;
        lastJson = json;
    }
    return result;
}
Example 20
Project: collectors-master  File: JsonPathSupport.java View source code
public static DocumentContext asDocumentContext(final TreeNode jsonDocument) {
    return JsonPath.parse(jsonDocument, JSON_PATH_CONFIGURATION);
}