Java Examples for com.jayway.jsonpath.JsonPath

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

Example 1
Project: JsonPath-master  File: FilterTest.java View source code
@Test
public void combine_filter_deep_criteria() {
    String json = "[\n" + "   {\n" + "      \"first-name\" : \"John\",\n" + "      \"last-name\" : \"Irving\",\n" + "      \"address\" : {\"state\" : \"Texas\"}\n" + "   },\n" + "   {\n" + "      \"first-name\" : \"Jock\",\n" + "      \"last-name\" : \"Ewing\",\n" + "      \"address\" : {\"state\" : \"Texas\"}\n" + "   },\n" + "   {\n" + "      \"first-name\" : \"Jock\",\n" + "      \"last-name\" : \"Barnes\",\n" + "      \"address\" : {\"state\" : \"Nevada\"}\n" + "   } \n" + "]";
    Filter filter = filter(where("first-name").is("Jock").and("address.state").is("Texas"));
    List<Map<String, Object>> jocksInTexas1 = JsonPath.read(json, "$[?]", filter);
    List<Map<String, Object>> jocksInTexas2 = JsonPath.read(json, "$[?(@.first-name == 'Jock' && @.address.state == 'Texas')]");
    JsonPath.parse(json).json();
    assertThat((String) JsonPath.read(jocksInTexas1, "$[0].address.state"), is("Texas"));
    assertThat((String) JsonPath.read(jocksInTexas1, "$[0].first-name"), is("Jock"));
    assertThat((String) JsonPath.read(jocksInTexas1, "$[0].last-name"), is("Ewing"));
}
Example 2
Project: batfish-master  File: JsonPathQuestionPlugin.java View source code
@Override
public JsonPathAnswerElement answer() {
    ConfigurationBuilder b = new ConfigurationBuilder();
    b.jsonProvider(new JacksonJsonNodeJsonProvider());
    final Configuration c = b.build();
    JsonPathQuestion question = (JsonPathQuestion) _question;
    List<JsonPathQuery> paths = question.getPaths();
    _batfish.checkConfigurations();
    Question innerQuestion = question._innerQuestion;
    String innerQuestionName = innerQuestion.getName();
    Answerer innerAnswerer = _batfish.getAnswererCreators().get(innerQuestionName).apply(innerQuestion, _batfish);
    AnswerElement innerAnswer = innerAnswerer.answer();
    BatfishObjectMapper mapper = new BatfishObjectMapper();
    String nodesAnswerStr = null;
    try {
        nodesAnswerStr = mapper.writeValueAsString(innerAnswer);
    } catch (IOException e) {
        throw new BatfishException("Could not get JSON string from nodes answer", e);
    }
    Object jsonObject = JsonPath.parse(nodesAnswerStr, c).json();
    Map<Integer, JsonPathResult> results = new ConcurrentHashMap<>();
    List<Integer> indices = new ArrayList<>();
    for (int i = 0; i < paths.size(); i++) {
        indices.add(i);
    }
    AtomicInteger completed = _batfish.newBatch("NodesPath queries", indices.size());
    indices.parallelStream().forEach( i -> {
        JsonPathQuery nodesPath = paths.get(i);
        String path = nodesPath.getPath();
        ConfigurationBuilder prefixCb = new ConfigurationBuilder();
        prefixCb.mappingProvider(c.mappingProvider());
        prefixCb.jsonProvider(c.jsonProvider());
        prefixCb.evaluationListener(c.getEvaluationListeners());
        prefixCb.options(c.getOptions());
        prefixCb.options(Option.ALWAYS_RETURN_LIST);
        prefixCb.options(Option.AS_PATH_LIST);
        Configuration prefixC = prefixCb.build();
        ConfigurationBuilder suffixCb = new ConfigurationBuilder();
        suffixCb.mappingProvider(c.mappingProvider());
        suffixCb.jsonProvider(c.jsonProvider());
        suffixCb.evaluationListener(c.getEvaluationListeners());
        suffixCb.options(c.getOptions());
        suffixCb.options(Option.ALWAYS_RETURN_LIST);
        Configuration suffixC = suffixCb.build();
        ArrayNode prefixes = null;
        ArrayNode suffixes = null;
        JsonPath jsonPath = JsonPath.compile(path);
        try {
            prefixes = jsonPath.read(jsonObject, prefixC);
            suffixes = jsonPath.read(jsonObject, suffixC);
        } catch (PathNotFoundException e) {
            suffixes = JsonNodeFactory.instance.arrayNode();
            prefixes = JsonNodeFactory.instance.arrayNode();
        } catch (Exception e) {
            throw new BatfishException("Error reading JSON path: " + path, e);
        }
        int numResults = prefixes.size();
        JsonPathResult nodePathResult = new JsonPathResult();
        nodePathResult.setPath(nodesPath);
        nodePathResult.setNumResults(numResults);
        boolean includeSuffix = nodesPath.getSuffix();
        if (!nodesPath.getSummary()) {
            SortedMap<String, JsonPathResultEntry> result = new TreeMap<>();
            Iterator<JsonNode> p = prefixes.iterator();
            Iterator<JsonNode> s = suffixes.iterator();
            while (p.hasNext()) {
                JsonNode prefix = p.next();
                JsonNode suffix = includeSuffix ? s.next() : null;
                String prefixStr = prefix.textValue();
                if (prefixStr == null) {
                    throw new BatfishException("Did not expect null value");
                }
                ConcreteJsonPath concretePath = new ConcreteJsonPath(prefixStr);
                result.put(concretePath.toString(), new JsonPathResultEntry(concretePath, suffix));
            }
            nodePathResult.setResult(result);
        }
        results.put(i, nodePathResult);
        completed.incrementAndGet();
    });
    JsonPathAnswerElement answerElement = new JsonPathAnswerElement();
    answerElement.getResults().putAll(results);
    return answerElement;
}
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: bior_pipeline-master  File: SameVariantITCase.java View source code
@Test
public void testMatch() throws IOException, InterruptedException {
    String catRelativePath = "src/test/resources/sameVariantCatalog.tsv.bgz";
    String catCanonicalPath = (new File(catRelativePath)).getCanonicalPath();
    String stdin = "##fileformat=VCFv4.0\n" + "#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tJUNIT_JSON\n" + "21\t26960070\trs116645811\tG\tA\t.\t.\t.\t{\"CHROM\":\"21\",\"POS\":\"26960070\",\"ID\":\"rs116645811\",\"REF\":\"G\",\"ALT\":\"A\",\"QUAL\":\".\",\"FILTER\":\".\",\"_id\":\"rs116645811\",\"_type\":\"variant\",\"_landmark\":\"21\",\"_refAllele\":\"G\",\"_altAlleles\":[\"A\"],\"_minBP\":26960070,\"_maxBP\":26960070}";
    CommandOutput out = executeScript("bior_same_variant", stdin, "-d", catRelativePath);
    assertEquals(out.stderr, 0, out.exit);
    assertEquals("", out.stderr);
    String header = getHeader(out.stdout);
    String[] headerLines = header.split("\n");
    assertEquals(3, headerLines.length);
    assertEquals("##fileformat=VCFv4.0", headerLines[0]);
    assertEquals(String.format("##BIOR=<ID=\"bior.sameVariantCatalog\",Operation=\"bior_same_variant\",DataType=\"JSON\",ShortUniqueName=\"sameVariantCatalog\",Path=\"%s\">", catCanonicalPath), headerLines[1]);
    assertEquals("#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tJUNIT_JSON\tbior.sameVariantCatalog", headerLines[2]);
    // pull out just data rows
    String data = out.stdout.replace(header, "");
    String[] cols = data.split("\t");
    // If variant is not found, results in empty json string
    //System.out.println(cols.length + cols[9]);
    assertEquals(10, cols.length);
    String json = cols[cols.length - 1];
    assertEquals("21", JsonPath.compile("CHROM").read(json));
}
Example 5
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 6
Project: nifi-master  File: TestJsonPathRowRecordReader.java View source code
@Before
public void populateJsonPaths() {
    allJsonPaths.clear();
    allJsonPaths.put("id", JsonPath.compile("$.id"));
    allJsonPaths.put("name", JsonPath.compile("$.name"));
    allJsonPaths.put("balance", JsonPath.compile("$.balance"));
    allJsonPaths.put("address", JsonPath.compile("$.address"));
    allJsonPaths.put("city", JsonPath.compile("$.city"));
    allJsonPaths.put("state", JsonPath.compile("$.state"));
    allJsonPaths.put("zipCode", JsonPath.compile("$.zipCode"));
    allJsonPaths.put("country", JsonPath.compile("$.country"));
}
Example 7
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 8
Project: sift-java-master  File: TransactionBodyTest.java View source code
/**
	 * 
	 * @throws JsonGenerationException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
@Test
@SuppressWarnings("unchecked")
public void transactionTest() throws JsonGenerationException, JsonMappingException, IOException {
    /*
		 * Instantiate an {@link Transaction} instance with the same values found in $transactions.json.
		 */
    final Address billingAddress = new Address();
    billingAddress.setName("Bill Jones").setPhone("1-415-555-6041").setAddressLine1("2100 Main Street").setAddressLine2("Apt 3B").setCity("New London").setRegion("New Hampshire").setCountry("US").setZipCode("03257");
    final PaymentMethod paymentMethod = new PaymentMethod();
    paymentMethod.setPaymentType(PaymentType.CREDIT_CARD).setPaymentGateway(PaymentGateway.BRAINTREE).setCardBIN("542486").setCardLast4("4444");
    final Address shippingAddress = new Address();
    shippingAddress.setAddressLine1("2100 Main Street").setAddressLine2("Apt 3B").setCity("New London").setRegion("New Hampshire").setCountry("US").setZipCode("03257");
    final Transaction transaction = new Transaction();
    transaction.setApiKey("INSERT_API_KEY_HERE");
    transaction.setUserId("billy_jones_301").setUserEmail("bill@gmail.com").setTransactionType(TransactionType.SALE).setTransactionStatus(TransactionStatus.SUCCESS).setAmount(5067900000l).setCurrencyCode("USD").setOrderId("ORDER-123124124").setTransactionId("719637215").setBillingAddress(billingAddress).setPaymentMethod(paymentMethod).setShippingAddress(shippingAddress).setSessionId("gigtleqddo84l8cm15qe4il3q3").setSellerUserId("slinkys_emporium");
    /*
		 * Assert.
		 */
    // the json object we will be asserting		
    final String json = SiftScienceHelper.serialize(transaction);
    final Object read = JsonPath.read(json, "$");
    final LinkedHashMap<String, Object> $ = (LinkedHashMap<String, Object>) read;
    // assert first level
    final List<String> $expectedKeys = Arrays.asList("$type", "$api_key", "$user_id", "$user_email", "$transaction_type", "$transaction_status", "$amount", "$currency_code", "$order_id", "$transaction_id", "$billing_address", "$payment_method", "$shipping_address", "$session_id", "$seller_user_id");
    assertEquals($.keySet(), $expectedKeys);
    // then assert the values
    Assert.assertEquals("INSERT_API_KEY_HERE", $.get("$api_key"));
    Assert.assertEquals("$transaction", $.get("$type"));
    Assert.assertEquals("billy_jones_301", $.get("$user_id"));
    Assert.assertEquals("bill@gmail.com", $.get("$user_email"));
    Assert.assertEquals("$sale", $.get("$transaction_type"));
    Assert.assertEquals("$success", $.get("$transaction_status"));
    Assert.assertEquals(5067900000l, $.get("$amount"));
    Assert.assertEquals("USD", $.get("$currency_code"));
    Assert.assertEquals("ORDER-123124124", $.get("$order_id"));
    Assert.assertEquals("719637215", $.get("$transaction_id"));
    Assert.assertEquals("gigtleqddo84l8cm15qe4il3q3", $.get("$session_id"));
    Assert.assertEquals("slinkys_emporium", $.get("$seller_user_id"));
    // then assert the child keys and values
    final LinkedHashMap<String, Object> ba = (LinkedHashMap<String, Object>) JsonPath.read(json, "$.$billing_address");
    final List<String> baexpectedKeys = Arrays.asList("$name", "$phone", "$address_1", "$address_2", "$city", "$region", "$country", "$zipcode");
    assertEquals(ba.keySet(), baexpectedKeys);
    Assert.assertEquals("Bill Jones", ba.get("$name"));
    Assert.assertEquals("1-415-555-6041", ba.get("$phone"));
    Assert.assertEquals("2100 Main Street", ba.get("$address_1"));
    Assert.assertEquals("Apt 3B", ba.get("$address_2"));
    Assert.assertEquals("New London", ba.get("$city"));
    Assert.assertEquals("New Hampshire", ba.get("$region"));
    Assert.assertEquals("US", ba.get("$country"));
    Assert.assertEquals("03257", ba.get("$zipcode"));
    final LinkedHashMap<String, Object> pm = (LinkedHashMap<String, Object>) JsonPath.read(json, "$.$payment_method");
    final List<String> pmexpectedKeys = Arrays.asList("$payment_type", "$payment_gateway", "$card_bin", "$card_last4");
    assertEquals(pm.keySet(), pmexpectedKeys);
    Assert.assertEquals("$credit_card", pm.get("$payment_type"));
    Assert.assertEquals("$braintree", pm.get("$payment_gateway"));
    Assert.assertEquals("542486", pm.get("$card_bin"));
    Assert.assertEquals("4444", pm.get("$card_last4"));
    final LinkedHashMap<String, Object> sa = (LinkedHashMap<String, Object>) JsonPath.read(json, "$.$shipping_address");
    final List<String> saexpectedKeys = Arrays.asList("$address_1", "$address_2", "$city", "$region", "$country", "$zipcode");
    assertEquals(sa.keySet(), saexpectedKeys);
    Assert.assertEquals("2100 Main Street", sa.get("$address_1"));
    Assert.assertEquals("Apt 3B", sa.get("$address_2"));
    Assert.assertEquals("New London", sa.get("$city"));
    Assert.assertEquals("New Hampshire", sa.get("$region"));
    Assert.assertEquals("US", sa.get("$country"));
    Assert.assertEquals("03257", sa.get("$zipcode"));
}
Example 9
Project: SmartHome-master  File: JSonPathTransformationService.java View source code
/**
     * Transforms the input <code>source</code> by JSonPath expression.
     *
     * @param function JsonPath expression
     * @param source String which contains JSON
     * @throws TransformationException If the JsonPath expression is invalid, a {@link InvalidPathException} is thrown,
     *             which is encapsulated in a {@link TransformationException}.
     */
@Override
public String transform(String jsonPathExpression, String source) throws TransformationException {
    if (jsonPathExpression == null || source == null) {
        throw new TransformationException("the given parameters 'JSonPath' and 'source' must not be null");
    }
    logger.debug("about to transform '{}' by the function '{}'", source, jsonPathExpression);
    try {
        Object transformationResult = JsonPath.read(source, jsonPathExpression);
        logger.debug("transformation resulted in '{}'", transformationResult);
        return (transformationResult != null) ? transformationResult.toString() : null;
    } catch (PathNotFoundException e) {
        return null;
    } catch (InvalidPathException e) {
        throw new TransformationException("An error occurred while transforming JSON expression.", e);
    }
}
Example 10
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 11
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 12
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 13
Project: spring-data-commons-master  File: JsonProjectingMethodInterceptorFactory.java View source code
/* 
		 * (non-Javadoc)
		 * @see org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept.MethodInvocation)
		 */
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
    Method method = invocation.getMethod();
    TypeInformation<Object> returnType = ClassTypeInformation.fromReturnTypeOf(method);
    ResolvableType type = ResolvableType.forMethodReturnType(method);
    String jsonPath = getJsonPath(method);
    if (returnType.getActualType().getType().isInterface()) {
        List<?> result = context.read(jsonPath);
        return result.isEmpty() ? null : result.get(0);
    }
    boolean isCollectionResult = Collection.class.isAssignableFrom(type.getRawClass());
    type = isCollectionResult ? type : ResolvableType.forClassWithGenerics(List.class, type);
    type = isCollectionResult && JsonPath.isPathDefinite(jsonPath) ? ResolvableType.forClassWithGenerics(List.class, type) : type;
    List<?> result = (List<?>) context.read(jsonPath, new ResolvableTypeRef(type));
    if (isCollectionResult && JsonPath.isPathDefinite(jsonPath)) {
        result = (List<?>) result.get(0);
    }
    return isCollectionResult ? result : result.isEmpty() ? null : result.get(0);
}
Example 14
Project: spring-hateoas-master  File: ChangelogCreator.java View source code
public static void main(String... args) throws Exception {
    RestTemplate template = new RestTemplate();
    String response = template.getForObject(URI_TEMPLATE, String.class, MILESTONE_ID);
    JsonPath titlePath = JsonPath.compile("$[*].title");
    JsonPath idPath = JsonPath.compile("$[*].number");
    JSONArray titles = titlePath.read(response);
    Iterator<Object> ids = ((JSONArray) idPath.read(response)).iterator();
    System.out.println("Milestone - " + JsonPath.read(response, "$[1].milestone.title"));
    for (Object title : titles) {
        String format = String.format("- #%s - %s", ids.next(), title);
        System.out.println(format.endsWith(".") ? format : format.concat("."));
    }
}
Example 15
Project: spring-integration-master  File: IntegrationRegistrar.java View source code
/**
	 * Register {@code jsonPath} and {@code xpath} SpEL-function beans, if necessary.
	 * @param registry The {@link BeanDefinitionRegistry} to register additional {@link BeanDefinition}s.
	 */
private void registerBuiltInBeans(BeanDefinitionRegistry registry) {
    int registryId = System.identityHashCode(registry);
    String jsonPathBeanName = "jsonPath";
    boolean alreadyRegistered = false;
    if (registry instanceof ListableBeanFactory) {
        alreadyRegistered = ((ListableBeanFactory) registry).containsBean(jsonPathBeanName);
    } else {
        alreadyRegistered = registry.isBeanNameInUse(jsonPathBeanName);
    }
    if (!alreadyRegistered && !registriesProcessed.contains(registryId)) {
        Class<?> jsonPathClass = null;
        try {
            jsonPathClass = ClassUtils.forName("com.jayway.jsonpath.JsonPath", this.classLoader);
        } catch (ClassNotFoundException e) {
            logger.debug("The '#jsonPath' SpEL function cannot be registered: " + "there is no jayway json-path.jar on the classpath.");
        }
        if (jsonPathClass != null) {
            try {
                ClassUtils.forName("com.jayway.jsonpath.Predicate", this.classLoader);
            } catch (ClassNotFoundException e) {
                jsonPathClass = null;
                logger.warn("The '#jsonPath' SpEL function cannot be registered. " + "An old json-path.jar version is detected in the classpath." + "At least 1.2.0 is required; see version information at: " + "https://github.com/jayway/JsonPath/releases", e);
            }
        }
        if (jsonPathClass != null) {
            IntegrationConfigUtils.registerSpelFunctionBean(registry, jsonPathBeanName, IntegrationConfigUtils.BASE_PACKAGE + ".json.JsonPathUtils", "evaluate");
        }
    }
    alreadyRegistered = false;
    String xpathBeanName = "xpath";
    if (registry instanceof ListableBeanFactory) {
        alreadyRegistered = ((ListableBeanFactory) registry).containsBean(xpathBeanName);
    } else {
        alreadyRegistered = registry.isBeanNameInUse(xpathBeanName);
    }
    if (!alreadyRegistered && !registriesProcessed.contains(registryId)) {
        Class<?> xpathClass = null;
        try {
            xpathClass = ClassUtils.forName(IntegrationConfigUtils.BASE_PACKAGE + ".xml.xpath.XPathUtils", this.classLoader);
        } catch (ClassNotFoundException e) {
            logger.debug("SpEL function '#xpath' isn't registered: " + "there is no spring-integration-xml.jar on the classpath.");
        }
        if (xpathClass != null) {
            IntegrationConfigUtils.registerSpelFunctionBean(registry, xpathBeanName, IntegrationConfigUtils.BASE_PACKAGE + ".xml.xpath.XPathUtils", "evaluate");
        }
    }
    alreadyRegistered = false;
    if (registry instanceof ListableBeanFactory) {
        alreadyRegistered = ((ListableBeanFactory) registry).containsBean(IntegrationContextUtils.TO_STRING_FRIENDLY_JSON_NODE_TO_STRING_CONVERTER_BEAN_NAME);
    } else {
        alreadyRegistered = registry.isBeanNameInUse(IntegrationContextUtils.TO_STRING_FRIENDLY_JSON_NODE_TO_STRING_CONVERTER_BEAN_NAME);
    }
    if (!alreadyRegistered && !registriesProcessed.contains(registryId) && this.jackson2Present) {
        registry.registerBeanDefinition(IntegrationContextUtils.TO_STRING_FRIENDLY_JSON_NODE_TO_STRING_CONVERTER_BEAN_NAME, BeanDefinitionBuilder.genericBeanDefinition(IntegrationConfigUtils.BASE_PACKAGE + ".json.ToStringFriendlyJsonNodeToStringConverter").getBeanDefinition());
        INTEGRATION_CONVERTER_INITIALIZER.registerConverter(registry, new RuntimeBeanReference(IntegrationContextUtils.TO_STRING_FRIENDLY_JSON_NODE_TO_STRING_CONVERTER_BEAN_NAME));
    }
    registriesProcessed.add(registryId);
}
Example 16
Project: spring-xd-master  File: NewJsonPathUtils.java View source code
public static <T> T evaluate(Object json, String jsonPath, Predicate... filters) throws Exception {
    if (json instanceof String) {
        return JsonPath.read((String) json, jsonPath, filters);
    } else if (json instanceof File) {
        return JsonPath.read((File) json, jsonPath, filters);
    } else if (json instanceof URL) {
        return JsonPath.read((URL) json, jsonPath, filters);
    } else if (json instanceof InputStream) {
        return JsonPath.read((InputStream) json, jsonPath, filters);
    } else {
        return JsonPath.read(json, jsonPath, filters);
    }
}
Example 17
Project: spring-xd-samples-master  File: TopTags.java View source code
@Override
public Stream<Tuple> process(Stream<String> stream) {
    return stream.flatMap( tweet -> {
        JSONArray array = JsonPath.read(tweet, "$.entities.hashtags[*].text");
        return Streams.from(array.toArray(new String[array.size()]));
    }).map( w -> reactor.fn.tuple.Tuple.of(w, 1)).window(timeWindow, SECONDS).flatMap( s -> BiStreams.reduceByKey(s, ( acc,  next) -> acc + next).sort(( a,  b) -> -a.t2.compareTo(b.t2)).take(topN)).map( entry -> tuple().of("hashtag", entry.t1, "count", entry.t2));
}
Example 18
Project: useful-java-links-master  File: JsonPathHelloWorld.java View source code
public static void main(String[] args) {
    List<String> authors = JsonPath.read(json, "$.store.book[*].author");
    // print ["Nigel Rees","Evelyn Waugh","Herman Melville","J. R. R. Tolkien"]
    System.out.println("authors: " + authors);
    List<Map<String, Object>> expensiveBooks = JsonPath.using(Configuration.defaultConfiguration()).parse(json).read("$.store.book[?(@.price > 22)].title", List.class);
    // print ["Hello, Middle-earth! "]
    System.out.println(expensiveBooks);
    System.out.println();
    String jsonHiWorld = "{\"message\":\"Hi\",\"place\":{\"name\":\"World!\"}}\"";
    String message = JsonPath.read(jsonHiWorld, "$.message");
    String place = JsonPath.read(jsonHiWorld, "$.place.name");
    // print "Hi World!"
    System.out.println(message + " " + place);
}
Example 19
Project: xmlsh-master  File: jsonpath.java View source code
@Override
public int run(List<XValue> args) throws Exception {
    Options opts = new Options("c=context:,cf=context-file:,p=path,f=file:,i=input:,q=query:,n,e=exists,b=bool,s=string", SerializeOpts.getOptionDefs());
    opts.parse(args);
    // boolean bReadStdin = false ;
    JsonNode context = null;
    SerializeOpts serializeOpts = setSerializeOpts(opts);
    if (// Has XML data input
    !opts.hasOpt("n")) {
        if (opts.hasOpt("c"))
            context = opts.getOptValue("c").asJson();
        else if (opts.hasOpt("cf"))
            context = (getInput(XValue.newXValue(opts.getOptString("cf", "-")))).asJson(serializeOpts);
        else if (opts.hasOpt("i"))
            context = (getInput(opts.getOptValue("i"))).asJson(serializeOpts);
        else
            context = (getStdin()).asJson(serializeOpts);
    }
    List<XValue> xvargs = opts.getRemainingArgs();
    OptionValue ov = opts.getOpt("f");
    String xpath = null;
    if (ov != null)
        xpath = readString(ov.getValue(), serializeOpts);
    else {
        ov = opts.getOpt("q");
        if (ov != null)
            xpath = ov.getValue().toString();
    }
    if (xpath == null)
        xpath = xvargs.remove(0).toString();
    Configuration conf = Configuration.defaultConfiguration();
    if (opts.hasOpt("path"))
        conf = conf.addOptions(Option.AS_PATH_LIST);
    OutputPort stdout = getStdout();
    JsonNode result = JsonPath.using(conf).parse(context).read(xpath);
    try (JsonGenerator gen = stdout.asJsonGenerator(serializeOpts)) {
        JSONUtils.writeJsonNode(gen, result);
    }
    return 0;
}
Example 20
Project: xmlsh1_3-master  File: jsonpath.java View source code
@Override
public int run(List<XValue> args) throws Exception {
    Options opts = new Options("c=context:,cf=context-file:,f=file:,i=input:,q=query:,n,e=exists,b=bool,s=string", SerializeOpts.getOptionDefs());
    opts.parse(args);
    boolean bString = opts.hasOpt("s");
    JsonModel context = null;
    InputPort in = null;
    // boolean bReadStdin = false ;
    SerializeOpts serializeOpts = getSerializeOpts(opts);
    if (// Has XML data input
    !opts.hasOpt("n")) {
        if (opts.hasOpt("c"))
            context = opts.getOptValue("c").asJson();
        else if (opts.hasOpt("cf"))
            context = (in = getInput(new XValue(opts.getOptString("cf", "-")))).asJson(serializeOpts);
        else if (opts.hasOpt("i"))
            context = (in = getInput(opts.getOptValue("i"))).asJson(serializeOpts);
        else
            context = (in = getStdin()).asJson(serializeOpts);
    }
    List<XValue> xvargs = opts.getRemainingArgs();
    boolean bQuiet = opts.hasOpt("e");
    boolean bBool = opts.hasOpt("b");
    if (bBool)
        bQuiet = true;
    OptionValue ov = opts.getOpt("f");
    String xpath = null;
    if (ov != null)
        xpath = readString(ov.getValue(), serializeOpts);
    else {
        ov = opts.getOpt("q");
        if (ov != null)
            xpath = ov.getValue().toString();
    }
    if (xpath == null)
        xpath = xvargs.remove(0).toString();
    JsonPath path = JsonPath.compile(xpath);
    Object result = context.get(path);
    XValue xvr = new XValue(result);
    // Hack - cant get at JsonProvider
    if (result instanceof List || result instanceof Map)
        result = JsonModel.create(result);
    OutputPort stdout = getStdout();
    PrintStream os = stdout.asPrintStream(getSerializeOpts());
    os.println(xvr.toString());
    return 0;
}
Example 21
Project: unravl-master  File: TestJsonPath.java View source code
@Test
public void testJsonPath() throws UnRAVLException {
    // drives configuration
    UnRAVLRuntime r = new UnRAVLRuntime();
    assertNotNull(r);
    String document = "{ \"s\": \"string\", \"b\": true, \"i\": 100, \"n\": 0.5, \"o\": { \"x\": 0, \"y\" : 0 }, \"a\": [ 0,1,2,3,4,5] }";
    JsonNode node = Json.parse(document);
    ObjectMapper m = new ObjectMapper();
    Object jo;
    if (node instanceof ObjectNode)
        jo = m.convertValue(node, Map.class);
    else
        // (node instanceof ArrayNode)
        jo = m.convertValue(node, List.class);
    // JsonPath parses strings into java.util.Map and java.util.List
    // objects.
    // If we have a Jackson JsonNode (an ObjectNode or an ArrayNode), we
    // must convert the Jackson types to Maps or Lists to use JsonPath.
    JsonProvider jp = Configuration.defaultConfiguration().jsonProvider();
    assertNotNull(jo);
    String s = JsonPath.read(jo, "$.s");
    Object o = JsonPath.read(jo, "$.o");
    Object a = JsonPath.read(jo, "$.a");
    assertTrue(s.equals("string"));
    assertNotNull(o);
    assertNotNull(a);
    assertTrue(jp.isMap(o));
    assertTrue(jp.isArray(a));
    ObjectNode on = m.valueToTree(o);
    ArrayNode an = m.valueToTree(a);
    assertNotNull(on);
    assertNotNull(an);
    assertEquals(2, on.size());
    assertEquals(6, an.size());
}
Example 22
Project: ehri-search-tools-master  File: Utils.java View source code
public static Map<String, List<JsonPath>> loadPaths() {
    Properties pathProperties = loadProperties("paths.properties");
    ImmutableMap.Builder<String, List<JsonPath>> builder = ImmutableMap.builder();
    for (String pathKey : pathProperties.stringPropertyNames()) {
        // NB: Paths given in the properties file do not include the
        // leading '$.' JsonPath expects, so we add that.
        String commaSepPaths = pathProperties.getProperty(pathKey);
        Iterable<String> paths = splitter.split(commaSepPaths);
        List<JsonPath> compiledPaths = Lists.newArrayList();
        for (String path : paths) {
            compiledPaths.add(JsonPath.compile("$." + path));
        }
        builder.put(pathKey, compiledPaths);
    }
    return builder.build();
}
Example 23
Project: graylog2-server-master  File: IndicesTest.java View source code
@Test
public void testIndexTemplateCanBeOverridden() throws Exception {
    final String customTemplateName = "custom-template";
    final IndicesAdminClient client = client().admin().indices();
    // Create custom index template
    final Map<String, Object> customMapping = ImmutableMap.of("_source", ImmutableMap.of("enabled", false), "properties", ImmutableMap.of("message", ImmutableMap.of("type", "string", "index", "not_analyzed")));
    final PutIndexTemplateResponse putIndexTemplateResponse = client.preparePutTemplate(customTemplateName).setTemplate(indexSet.getIndexWildcard()).setOrder(1).addMapping(IndexMapping.TYPE_MESSAGE, customMapping).get();
    assertThat(putIndexTemplateResponse.isAcknowledged()).isTrue();
    // Validate existing index templates
    final GetIndexTemplatesResponse getTemplatesResponse = client.prepareGetTemplates().get();
    final List<IndexTemplateMetaData> indexTemplates = getTemplatesResponse.getIndexTemplates();
    assertThat(indexTemplates).extracting(IndexTemplateMetaData::getName).contains(customTemplateName);
    // Create index with custom template
    final String testIndexName = "graylog_override_template";
    indices.create(testIndexName, indexSet);
    // Check index mapping
    final GetMappingsResponse indexMappingResponse = client.prepareGetMappings(testIndexName).get();
    final String mapping = indexMappingResponse.getMappings().get(testIndexName).get(IndexMapping.TYPE_MESSAGE).source().string();
    final ReadContext ctx = JsonPath.parse(mapping);
    final boolean sourceEnabled = ctx.read("$.message._source.enabled");
    assertThat(sourceEnabled).isFalse();
    final String messageField = ctx.read("$.message.properties.message.index");
    assertThat(messageField).isEqualTo("not_analyzed");
    // Clean up
    final DeleteIndexTemplateResponse deleteResponse = client.prepareDeleteTemplate(customTemplateName).get();
    assertThat(deleteResponse.isAcknowledged()).isTrue();
    indices.delete(testIndexName);
}
Example 24
Project: hsac-fitnesse-fixtures-master  File: JsonPathHelper.java View source code
/**
     * Evaluates a JsonPath expression returning a multiple elements.
     * @param json JSON value.
     * @param jsonPath expression to evaluate.
     * @return result results of expression.
     * @throws java.lang.RuntimeException if jsonPath would return a single element.
     */
public List<Object> getAllJsonPath(String json, String jsonPath) {
    List<Object> result;
    if (JsonPath.isPathDefinite(jsonPath)) {
        Object val = getJsonPath(json, jsonPath);
        if (val == null) {
            result = Collections.emptyList();
        } else {
            result = Collections.singletonList(val);
        }
    } else {
        result = parseJson(json).read(jsonPath);
    }
    return result;
}
Example 25
Project: karate-master  File: ScriptTest.java View source code
@Test
public void testMatchJsonPath() {
    DocumentContext doc = JsonPath.parse("{ foo: 'bar', baz: { ban: [1, 2, 3]} }");
    ScriptContext ctx = getContext();
    ctx.vars.put("myJson", doc);
    ScriptValue myJson = ctx.vars.get("myJson");
    assertTrue(Script.matchJsonPath(MatchType.EQUALS, myJson, "$.foo", "'bar'", ctx).pass);
    assertTrue(Script.matchJsonPath(MatchType.EQUALS, myJson, "$.baz", "{ ban: [1, 2, 3]} }", ctx).pass);
    assertTrue(Script.matchJsonPath(MatchType.EQUALS, myJson, "$.baz.ban[1]", "2", ctx).pass);
    assertTrue(Script.matchJsonPath(MatchType.EQUALS, myJson, "$.baz", "{ ban: [1, '#ignore', 3]} }", ctx).pass);
}
Example 26
Project: liferay-portal-master  File: DDMRESTDataProvider.java View source code
protected DDMDataProviderResponse doGetData(DDMDataProviderRequest ddmDataProviderRequest) {
    DDMDataProviderContext ddmDataProviderContext = ddmDataProviderRequest.getDDMDataProviderContext();
    DDMRESTDataProviderSettings ddmRESTDataProviderSettings = ddmDataProviderContext.getSettingsInstance(DDMRESTDataProviderSettings.class);
    HttpRequest httpRequest = HttpRequest.get(ddmRESTDataProviderSettings.url());
    if (Validator.isNotNull(ddmRESTDataProviderSettings.username())) {
        httpRequest.basicAuthentication(ddmRESTDataProviderSettings.username(), ddmRESTDataProviderSettings.password());
    }
    setRequestParameters(ddmDataProviderRequest, ddmRESTDataProviderSettings, httpRequest);
    String cacheKey = getCacheKey(httpRequest);
    DDMRESTDataProviderResult ddmRESTDataProviderResult = _portalCache.get(cacheKey);
    if ((ddmRESTDataProviderResult != null) && ddmRESTDataProviderSettings.cacheable()) {
        return ddmRESTDataProviderResult.getDDMDataProviderResponse();
    }
    HttpResponse httpResponse = httpRequest.send();
    DocumentContext documentContext = JsonPath.parse(httpResponse.body());
    DDMDataProviderResponse ddmDataProviderResponse = createDDMDataProviderResponse(documentContext, ddmDataProviderRequest, ddmRESTDataProviderSettings);
    if (ddmRESTDataProviderSettings.cacheable()) {
        _portalCache.put(cacheKey, new DDMRESTDataProviderResult(ddmDataProviderResponse));
    }
    return ddmDataProviderResponse;
}
Example 27
Project: SOAP-master  File: JsonPathFacade.java View source code
public void writeValue(String jsonPathExpression, Object value) {
    PlainJavaJsonProvider provider = new PlainJavaJsonProvider();
    Configuration configuration = Configuration.builder().jsonProvider(provider).build();
    jsonObject = provider.parse(currentJson);
    JsonPath path = JsonPath.compile(jsonPathExpression);
    LinkedList<PathToken> pathTokens = getPathTokensFrom(path);
    PathToken endToken = pathTokens.removeLast();
    int index = pathTokens.size();
    JsonWriteDecorator writeDecorator = new JsonWriteDecorator(provider, index, endToken, value);
    pathTokens.addLast(writeDecorator);
    path.read(jsonObject, configuration);
    jsonObject = MutableValue.FROM_MUTABLE_VALUE.apply(jsonObject);
    currentJson = buildJsonStringFrom(jsonObject);
}
Example 28
Project: soapui-master  File: JsonPathFacade.java View source code
public void writeValue(String jsonPathExpression, Object value) {
    PlainJavaJsonProvider provider = new PlainJavaJsonProvider();
    Configuration configuration = Configuration.builder().jsonProvider(provider).build();
    jsonObject = provider.parse(currentJson);
    JsonPath path = JsonPath.compile(jsonPathExpression);
    LinkedList<PathToken> pathTokens = getPathTokensFrom(path);
    PathToken endToken = pathTokens.removeLast();
    int index = pathTokens.size();
    JsonWriteDecorator writeDecorator = new JsonWriteDecorator(provider, index, endToken, value);
    pathTokens.addLast(writeDecorator);
    path.read(jsonObject, configuration);
    jsonObject = MutableValue.FROM_MUTABLE_VALUE.apply(jsonObject);
    currentJson = buildJsonStringFrom(jsonObject);
}
Example 29
Project: spring-restbucks-master  File: PaymentProcessIntegrationTest.java View source code
/**
	 * Looks up the first {@link Order} from the orders representation using a JSONPath expression of
	 * {@value #FIRST_ORDER_EXPRESSION}. Looks up the {@value Link#REL_SELF} link from the nested object and follows it to
	 * lookup the representation. Verifies the {@code self}, {@code cancel}, and {@code update} link to be present.
	 * 
	 * @param source
	 * @return
	 * @throws Exception
	 */
private MockHttpServletResponse accessFirstOrder(MockHttpServletResponse source) throws Exception {
    String content = source.getContentAsString();
    String order = JsonPath.parse(content).read(JsonPath.compile(FIRST_ORDER_EXPRESSION), JSONObject.class).toString();
    Link orderLink = getDiscovererFor(source).findLinkWithRel("self", order).expand();
    LOG.info(String.format("Picking first order using JSONPath expression %s…", FIRST_ORDER_EXPRESSION));
    LOG.info(String.format("Discovered self link pointing to %s… Following", orderLink));
    return mvc.perform(get(//
    orderLink.getHref())).andExpect(linkWithRelIsPresent(Link//
    .REL_SELF)).andExpect(linkWithRelIsPresent(//
    CANCEL_REL)).andExpect(linkWithRelIsPresent(//
    UPDATE_REL)).andExpect(linkWithRelIsPresent(//
    PAYMENT_REL)).andReturn().getResponse();
}
Example 30
Project: spring-restbucks-training-master  File: PaymentProcessIntegrationTest.java View source code
/**
	 * Looks up the first {@link Order} from the orders representation using a JSONPath expression of
	 * {@value #FIRST_ORDER_EXPRESSION}. Looks up the {@value Link#REL_SELF} link from the nested object and follows it to
	 * lookup the representation. Verifies the {@code self}, {@code cancel}, and {@code update} link to be present.
	 * 
	 * @param source
	 * @return
	 * @throws Exception
	 */
private MockHttpServletResponse accessFirstOrder(MockHttpServletResponse source) throws Exception {
    String content = source.getContentAsString();
    String order = JsonPath.read(content, FIRST_ORDER_EXPRESSION).toString();
    Link orderLink = getDiscovererFor(source).findLinkWithRel("self", order);
    LOG.info(String.format("Picking first order using JSONPath expression %s…", FIRST_ORDER_EXPRESSION));
    LOG.info(String.format("Discovered self link pointing to %s… Following", orderLink));
    return mvc.perform(get(//
    orderLink.getHref())).andExpect(linkWithRelIsPresent(Link//
    .REL_SELF)).andExpect(linkWithRelIsPresent(//
    CANCEL_REL)).andExpect(linkWithRelIsPresent(//
    UPDATE_REL)).andExpect(linkWithRelIsPresent(//
    PAYMENT_REL)).andReturn().getResponse();
}
Example 31
Project: thingsboard-gateway-master  File: SigfoxDeviceDataConverter.java View source code
public boolean isApplicable(String body) {
    if (filterExpression == null || filterExpression.isEmpty()) {
        return true;
    } else {
        try {
            List jsonArray = JsonPath.parse(body).read(filterExpression);
            return !jsonArray.isEmpty();
        } catch (RuntimeException e) {
            log.debug("Failed to apply filter expression: {}", filterExpression, e);
            throw new RuntimeException("Failed to apply filter expression " + filterExpression, e);
        }
    }
}
Example 32
Project: _Whydah-UserAdminService-master  File: UserAggregateRepresentation.java View source code
private static List<String> findJsonpathList(String jsonString, String expression) throws PathNotFoundException {
    List<String> result = null;
    try {
        Object document = Configuration.defaultConfiguration().jsonProvider().parse(jsonString);
        result = JsonPath.read(document, expression);
    } catch (Exception e) {
        log.warn("Failed to parse JSON. Expression {}, JSON {}, ", expression, jsonString, e);
    }
    return result;
}
Example 33
Project: core-master  File: ProbeSessionBeansTest.java View source code
@Test
public void testEjbSessionBeans() throws IOException {
    JsonObject allBeans = getPageAsJSONObject(BEANS_PATH_ALL, url);
    JsonArray beansData = allBeans.getJsonArray(DATA);
    List<JsonObject> statefulEjbSessionList = getAllJsonObjectsByClass(StatefulEjbSession.class, beansData);
    assertEquals(statefulEjbSessionList.size(), 1);
    JsonObject statefulEjbJson = statefulEjbSessionList.get(0);
    String statefulEjbSessionId = statefulEjbJson.getString(ID);
    JsonObject sessionBeansDetail = getPageAsJSONObject(BEANS_PATH + "/" + statefulEjbSessionId, url);
    ReadContext ctx = JsonPath.parse(sessionBeansDetail.toString());
    List<String> types = ctx.read("$." + TYPES, List.class);
    assertEquals(BeanType.SESSION.name(), sessionBeansDetail.getString(KIND));
    assertTrue(types.contains(DecoratedInterface.class.getName()));
    assertEquals(Boolean.TRUE.booleanValue(), sessionBeansDetail.getBoolean(IS_ALTERNATIVE));
    assertEquals(Boolean.TRUE.booleanValue(), sessionBeansDetail.getBoolean(EJB_NAME));
    assertEquals(SessionBeanType.STATEFUL.name(), sessionBeansDetail.getString(SESSION_BEAN_TYPE));
    JsonObject sessionBeanEnablement = sessionBeansDetail.getJsonObject(ENABLEMENT);
    // TODO introduce enum with priority ranges
    assertEquals("APPLICATION", sessionBeanEnablement.getString(PRIORITY_RANGE));
    assertEquals(2500, sessionBeanEnablement.getInt(PRIORITY));
}
Example 34
Project: drools-fipa-agent-master  File: InspectMessageHelper.java View source code
public static String inspect(ACLMessage message, String path) throws ParseException, XPathExpressionException, ParserConfigurationException, IOException, SAXException {
    AbstractMessageContent content = inspectContent(message);
    if (content.getEncodedContent() != null || !content.getEncodedContent().equals("")) {
        switch(message.getEncoding()) {
            case JSON:
                Object res = JsonPath.read(content.getEncodedContent(), path);
                return (res != null) ? res.toString() : null;
            case XML:
                XPath accessor = XPathFactory.newInstance().newXPath();
                InputStream inStream = new ByteArrayInputStream(content.getEncodedContent().getBytes());
                Document dox = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inStream);
                return (String) accessor.evaluate(path, dox, XPathConstants.STRING);
            default:
                throw new ParseException("Unable to access byte-encoded message body", 0);
        }
    }
    return null;
}
Example 35
Project: drools-mas-master  File: InspectMessageHelper.java View source code
public static String inspect(ACLMessage message, String path) throws ParseException, XPathExpressionException, ParserConfigurationException, IOException, SAXException {
    AbstractMessageContent content = inspectContent(message);
    if (content.getEncodedContent() != null || !content.getEncodedContent().equals("")) {
        switch(message.getEncoding()) {
            case JSON:
                Object res = JsonPath.read(content.getEncodedContent(), path);
                return (res != null) ? res.toString() : null;
            case XML:
                XPath accessor = XPathFactory.newInstance().newXPath();
                InputStream inStream = new ByteArrayInputStream(content.getEncodedContent().getBytes());
                Document dox = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inStream);
                return (String) accessor.evaluate(path, dox, XPathConstants.STRING);
            default:
                throw new ParseException("Unable to access byte-encoded message body", 0);
        }
    }
    return null;
}
Example 36
Project: elasticsearch-readonlyrest-plugin-master  File: GroupsProviderServiceHttpClient.java View source code
private Function<HttpResponse, Set<String>> groupsFromResponse() {
    return  response -> {
        if (response.getStatusCode() == 200) {
            try {
                List<String> groups = JsonPath.read(response.getContent().get(), responseGroupsJsonPath);
                logger.debug("Groups returned by groups provider '" + name + "': " + Joiner.on(",").join(groups));
                return Sets.newHashSet(groups);
            } catch (Exception e) {
                logger.error("Group based authorization response exception", e);
                return Sets.newHashSet();
            }
        }
        return Sets.newHashSet();
    };
}
Example 37
Project: find-master  File: MvcIntegrationTestUtils.java View source code
public String[] getFields(final MockMvc mockMvc, final String subPath, final String... fieldTypes) throws Exception {
    final MockHttpServletRequestBuilder requestBuilder = get(FieldsController.FIELDS_PATH + subPath).with(authentication(userAuth()));
    requestBuilder.param(FieldsController.FIELD_TYPES_PARAM, fieldTypes);
    addFieldRequestParams(requestBuilder);
    final MvcResult mvcResult = mockMvc.perform(requestBuilder).andReturn();
    final Collection<Map<String, String>> tagNames = JsonPath.compile("$").read(mvcResult.getResponse().getContentAsString());
    return tagNames.stream().map( tagName -> tagName.get("id")).toArray(String[]::new);
}
Example 38
Project: fullstop-master  File: CloudTrailEventSupport.java View source code
/**
     * Reads the given 'responseElements' and extracts information based on given 'pattern'.<br/>
     * If 'responseElements' is null or empty you can handle the {@link IllegalArgumentException} raised or got an empty
     * list.
     */
public static List<String> read(final String responseElements, final String pattern, final boolean emptyListOnNullOrEmptyResponse) {
    if (isNullOrEmpty(responseElements) && emptyListOnNullOrEmptyResponse) {
        return emptyList();
    }
    try {
        return JsonPath.read(responseElements, pattern);
    } catch (final PathNotFoundException e) {
        if (emptyListOnNullOrEmptyResponse) {
            return emptyList();
        } else {
            throw e;
        }
    }
}
Example 39
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 40
Project: jmeter-master  File: JSONManager.java View source code
/**
     * 
     * @param jsonString JSON String from which data is extracted
     * @param jsonPath JSON-PATH expression
     * @return List of JSON Strings of the extracted data
     * @throws ParseException when parsing fails
     */
public List<Object> extractWithJsonPath(String jsonString, String jsonPath) throws ParseException {
    JsonPath jsonPathParser = getJsonPath(jsonPath);
    List<Object> extractedObjects;
    try {
        extractedObjects = jsonPathParser.read(jsonString, DEFAULT_CONFIGURATION);
    } catch (PathNotFoundException e) {
        if (log.isDebugEnabled()) {
            log.debug("Could not find JSON Path {} in [{}]: {}", jsonPath, jsonString, e.getLocalizedMessage());
        }
        return Collections.emptyList();
    }
    List<Object> results = new ArrayList<>(extractedObjects.size());
    for (Object obj : extractedObjects) {
        results.add(stringifyJSONObject(obj));
    }
    return results;
}
Example 41
Project: levelup-java-examples-master  File: TestJsonpath.java View source code
/**
	 * Test fields
	 */
@Test
public void test_json_fields() {
    String rawJson = "{\r\n   \"id\":1,\r\n   \"description\":\"Biodiesel XOXO pug, irony roof party Helvetica selfies vinyl...\",\r\n   \"url\":\"http://hipsteripsum.me/\"\r\n}";
    String description = JsonPath.read(rawJson, "$.description");
    String url = JsonPath.read(rawJson, "$.url");
    logger.info(description);
    assertEquals("Biodiesel XOXO pug, irony roof party Helvetica selfies vinyl...", description);
    assertThat(url, containsString("http://"));
}
Example 42
Project: light-4j-master  File: MaskTest.java View source code
@Test
public void testMaskRequestBody() {
    String input = "{\"name\":\"Steve\",\"contact\":{\"phone\":\"416-111-1111\"},\"password\":\"secret\"}";
    String output = Mask.maskJson(input, "test1");
    System.out.println(output);
    Assert.assertEquals(JsonPath.parse(output).read("$.contact.phone"), "************");
    Assert.assertEquals(JsonPath.parse(output).read("$.password"), "******");
    Assert.assertEquals(output, "{\"name\":\"Steve\",\"contact\":{\"phone\":\"************\"},\"password\":\"******\"}");
}
Example 43
Project: linkshortener-master  File: PhishTankUrlVerifier.java View source code
@Override
public final boolean isSafe(final String url) {
    boolean safe = true;
    try {
        final MultiValueMap<String, String> formParameters = this.config.getParameters();
        formParameters.add(PARAMETER_URL, url);
        final ResponseEntity<String> response = this.client.postForEntity(this.config.getApiUrl(), formParameters, String.class);
        if (response.getStatusCode() == HttpStatus.OK) {
            final boolean phish = JsonPath.parse(response.getBody()).read(IN_DATABASE_PARSE_EXPRESSION);
            if (phish) {
                LOGGER.warn("Possible malicious link posted: {}", url);
                LOGGER.debug("PhishTank response: {}", response);
                safe = false;
            }
        } else {
            LOGGER.warn("Request for PhishTank API failed with status: {} - : {}", response.getStatusCode(), response);
        }
    } catch (final RestClientExceptionPathNotFoundException |  exception) {
        LOGGER.warn("Something went wrong while processing PhishTank API: {}", exception);
    }
    return safe;
}
Example 44
Project: opensearchserver-master  File: SearchCommands.java View source code
@Override
public void run(ScriptCommandContext context, String id, String... parameters) throws ScriptException {
    checkParameters(5, parameters);
    String template = parameters[0];
    String query = context.replaceVariables(parameters[1]);
    JsonPath jsonPath = JsonPath.compile(parameters[2]);
    Action_Trigger trigger = Action_Trigger.valueOf(parameters[3]);
    Action_Option option = Action_Option.valueOf(parameters[4]);
    String cmd = getParameterString(5);
    CommandEnum command = StringUtils.isEmpty(cmd) ? null : CommandEnum.find(cmd);
    AbstractResultSearch<?> result = this.search(context, template, query);
    SearchResult searchResult = new SearchResult(result);
    try {
        Object object = jsonPath.read(JsonUtils.toJsonString(searchResult));
        checkAction(trigger, option, command, object != null);
    } catch (PathNotFoundException e) {
        checkAction(trigger, option, command, false);
    } catch (JsonProcessingException e) {
        throw new ScriptException(e);
    }
}
Example 45
Project: oryx-flume-master  File: OryxJSONEventParser.java View source code
@Override
public void parseEvent(Event event, List<List<String>> fields, List<String> batch) {
    ReadContext context = JsonPath.parse(new String(event.getBody()));
    for (List<String> keys : fields) {
        StringBuilder record = new StringBuilder();
        // add user and item
        for (int i = 0; i < 2; i++) {
            String val = null;
            try {
                val = context.read(keys.get(i));
            } catch (Exception ex) {
                if (ex instanceof PathNotFoundException) {
                    log.error("Unable to find key '{}'", keys.get(i), ex);
                } else if (ex instanceof ClassCastException) {
                    log.error("Unable to cast value for key '{}'", keys.get(i), ex);
                }
                if (log.isDebugEnabled()) {
                    log.debug("Skipping record '{}'", new String(event.getBody()));
                }
                record.setLength(0);
                break;
            }
            record.append(StringEscapeUtils.escapeCsv(val)).append(',');
        }
        if (record.length() > 0) {
            if (keys.size() == 3) {
                // add strength
                record.append(keys.get(2));
            } else {
                record.deleteCharAt(record.length() - 1);
            }
            if (log.isDebugEnabled()) {
                log.debug("Adding record '{}' to batch", record);
            }
            batch.add(record.toString());
        }
    }
}
Example 46
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 47
Project: rest-driver-master  File: HasJsonPath.java View source code
@Override
public boolean matchesSafely(JsonNode jsonNode) {
    Object jsonPathResult = null;
    try {
        jsonPathResult = JsonPath.read(jsonNode.toString(), jsonPath);
        if (matcher == null) {
            return jsonPathResult != null;
        }
        boolean initialMatchResult = matcher.matches(jsonPathResult);
        // if matcher is for longs and jsonPath returns an integer, do our best
        if (!initialMatchResult && jsonPathResult instanceof Integer) {
            return matcher.matches(intToLong(jsonPathResult));
        }
        return initialMatchResult;
    } catch (InvalidPathException e) {
        return false;
    } catch (ClassCastException cce) {
        if (matcher.matches(intToLong(jsonPathResult))) {
            return true;
        } else {
            throw new RuntimeJsonTypeMismatchException("JSONpath returned a type unsuitable for matching with the given matcher: " + cce.getMessage(), cce);
        }
    }
}
Example 48
Project: restfiddle-master  File: AssertHandler.java View source code
@SuppressWarnings("unchecked")
public void doAssert(BodyAssertDTO bodyAssertDTO) {
    String propertyName = bodyAssertDTO.getPropertyName();
    if (propertyName.startsWith("[")) {
        propertyName = "$" + propertyName;
    } else {
        propertyName = "$." + propertyName;
    }
    boolean success = false;
    try {
        Object actualValue = JsonPath.read(body, propertyName);
        bodyAssertDTO.setActualValue(actualValue.toString());
        if (actualValue instanceof Number) {
            success = evaluate(bodyAssertDTO.getExpectedValue(), bodyAssertDTO.getComparator(), (Number) actualValue);
        } else if (actualValue instanceof String) {
            success = evaluate(bodyAssertDTO.getExpectedValue(), bodyAssertDTO.getComparator(), (String) actualValue);
        } else if (actualValue instanceof Map) {
            JSONObject json = new JSONObject((Map<String, ?>) actualValue);
            bodyAssertDTO.setActualValue(json.toString());
            success = evaluate(bodyAssertDTO.getExpectedValue(), bodyAssertDTO.getComparator(), json);
        } else if (actualValue instanceof List) {
            success = evaluate(bodyAssertDTO.getExpectedValue(), bodyAssertDTO.getComparator(), (List<Object>) actualValue);
        }
    } catch (Exception e) {
        logger.debug("propery not found");
    }
    bodyAssertDTO.setSuccess(success);
}
Example 49
Project: RMLProcessor-master  File: JSONPathProcessor.java View source code
@Override
public void execute(SesameDataSet dataset, TriplesMap map, RMLPerformer performer, InputStream input) {
    try {
        String reference = getReference(map.getLogicalSource());
        //This is a none streaming solution. A streaming parser requires own implementation, possibly based on https://code.google.com/p/json-simple/wiki/DecodingExamples
        JsonPath path = JsonPath.compile(reference);
        Object val = path.read(input);
        log.info("[JSONPathProcessor:execute] input " + input.toString());
        execute(dataset, map, performer, val);
    } catch (FileNotFoundException ex) {
        Logger.getLogger(JSONPathProcessor.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(JSONPathProcessor.class.getName()).log(Level.SEVERE, null, ex);
    }
}
Example 50
Project: SeaCloudsPlatform-master  File: JavaCloudFoundryPaasWebAppImpl.java View source code
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 51
Project: spring-data-rest-master  File: JpaWebTests.java View source code
// DATAREST-95
@Test
public void createThenPatch() throws Exception {
    Link peopleLink = client.discoverUnique("people");
    MockHttpServletResponse bilbo = postAndGet(peopleLink, "{ \"firstName\" : \"Bilbo\", \"lastName\" : \"Baggins\" }", MediaType.APPLICATION_JSON);
    Link bilboLink = client.assertHasLinkWithRel("self", bilbo);
    assertThat((String) JsonPath.read(bilbo.getContentAsString(), "$.firstName")).isEqualTo("Bilbo");
    assertThat((String) JsonPath.read(bilbo.getContentAsString(), "$.lastName")).isEqualTo("Baggins");
    MockHttpServletResponse frodo = patchAndGet(bilboLink, "{ \"firstName\" : \"Frodo\" }", MediaType.APPLICATION_JSON);
    assertThat((String) JsonPath.read(frodo.getContentAsString(), "$.firstName")).isEqualTo("Frodo");
    assertThat((String) JsonPath.read(frodo.getContentAsString(), "$.lastName")).isEqualTo("Baggins");
    frodo = patchAndGet(bilboLink, "{ \"firstName\" : null }", MediaType.APPLICATION_JSON);
    assertThat((String) JsonPath.read(frodo.getContentAsString(), "$.firstName")).isNull();
    assertThat((String) JsonPath.read(frodo.getContentAsString(), "$.lastName")).isEqualTo("Baggins");
}
Example 52
Project: struts-examples-master  File: OrderControllerTest.java View source code
@Test
public void testDelete() throws Exception {
    request.setParameter("request_locale", "en");
    ActionProxy proxy = getActionProxy("DELETE", "/data/order/3.json");
    String result = proxy.execute();
    assertThat(result, nullValue());
    assertThat(ServletActionContext.getResponse().getContentType(), is(equalTo("application/json;charset=UTF-8")));
    String jsonResult = ((MockHttpServletResponse) ServletActionContext.getResponse()).getContentAsString();
    assertThat(JsonPath.read(jsonResult, "$.actionError"), is(equalTo("Delete is currently not supported!")));
    assertThat(ServletActionContext.getResponse().getStatus(), is(equalTo(400)));
}
Example 53
Project: tajo-master  File: JsonExtractPathText.java View source code
@Override
public Datum eval(Tuple params) {
    if (params.isBlankOrNull(0) || params.isBlankOrNull(1)) {
        return NullDatum.get();
    }
    // default is JsonSmartMappingProvider
    try {
        JSONObject object = (JSONObject) parser.parse(params.getBytes(0));
        if (jsonPath == null) {
            jsonPath = JsonPath.compile(params.getText(1));
        }
        return DatumFactory.createText(jsonPath.read(object).toString());
    } catch (Exception e) {
        return NullDatum.get();
    }
}
Example 54
Project: uaa-master  File: SearchResultsFactory.java View source code
public static <T> SearchResults<Map<String, Object>> buildSearchResultFrom(List<T> input, int startIndex, int count, int total, String[] attributes, AttributeNameMapper mapper, List<String> schemas) {
    Assert.state(input.size() <= count, "Cannot build search results from parent list. Use subList before you call this method.");
    Map<String, JsonPath> jsonPaths = asList(attributes).stream().collect(new MapCollector<>( attribute -> attribute,  attribute -> {
        String jsonPath = "$." + mapper.mapToInternal(attribute);
        return JsonPath.compile(jsonPath);
    }));
    Collection<Map<String, Object>> results = new ArrayList<>();
    for (T object : input) {
        Map<String, Object> map = new LinkedHashMap<>();
        String serializedObject = JsonUtils.writeValueAsString(object);
        for (Map.Entry<String, JsonPath> attribute : jsonPaths.entrySet()) {
            try {
                Object value = attribute.getValue().read(serializedObject);
                map.put(attribute.getKey(), value);
            } catch (PathNotFoundException e) {
                map.put(attribute.getKey(), null);
            }
        }
        results.add(map);
    }
    return new SearchResults<>(schemas, results, startIndex, count, total);
}
Example 55
Project: viola-master  File: ConfigurationWebTest.java View source code
private void assertResult(String jobName, String expectedResult) {
    webDriver.get(getJenkinsBaseUrl() + "/job/" + jobName + "/lastBuild/api/json?pretty=true");
    String json = webDriver.getPageSource().replaceAll("<.+?>", "");
    String result = JsonPath.read(json, "$.['result']");
    assertEquals("Not unstable!\n" + json, expectedResult.toUpperCase(), result.toUpperCase());
}
Example 56
Project: violations-plugin-master  File: ConfigurationWebTest.java View source code
private void assertResult(String jobName, String expectedResult) {
    webDriver.get(getJenkinsBaseUrl() + "/job/" + jobName + "/lastBuild/api/json?pretty=true");
    String json = webDriver.getPageSource().replaceAll("<.+?>", "");
    String result = JsonPath.read(json, "$.['result']");
    assertEquals("Not unstable!\n" + json, expectedResult.toUpperCase(), result.toUpperCase());
}
Example 57
Project: Wilma-master  File: JsonPathChecker.java View source code
@Override
public boolean checkCondition(final WilmaHttpRequest request, final ParameterList parameters) {
    String expected = parameters.get(EXPECTED_KEY);
    String path = parameters.get(JSONPATH_KEY);
    boolean equals;
    try {
        String actualValue = JsonPath.read(request.getBody(), path);
        equals = evaluate(expected, actualValue);
    } catch (Exception e) {
        logger.debug("Request body isn't of JSON format, message:" + request.getWilmaMessageLoggerId(), e);
        equals = false;
    }
    return equals;
}
Example 58
Project: 2015-SpaceInvaders-Bot-Java-master  File: BasicGameStateReader.java View source code
private Player loadPlayer(File jsonFile, String playerPath) throws IOException {
    Player player = new Player();
    try {
        Map<String, Object> playerMap = JsonPath.read(jsonFile, playerPath);
        player.setPlayerName((String) playerMap.get("PlayerName"));
        player.setPlayerNumber((Integer) playerMap.get("PlayerNumber"));
        player.setPlayerNumberReal((Integer) playerMap.get("PlayerNumberReal"));
        player.setKills((Integer) playerMap.get("Kills"));
        player.setLives((Integer) playerMap.get("Lives"));
        player.setMissileLimit((Integer) playerMap.get("MissileLimit"));
        JSONArray missiles = (JSONArray) playerMap.get("Missiles");
        player.setMissiles(loadMissiles(missiles));
        Ship ship = loadShip((Map) playerMap.get("Ship"));
        player.setShip(ship);
    } catch (PathNotFoundException pnfe) {
        LogHelper.log("Index out of bounds when evaluating path " + playerPath);
        pnfe.printStackTrace();
    }
    return player;
}
Example 59
Project: brooklyn-ambari-master  File: AmbariServerImpl.java View source code
Function<JsonElement, List<String>> getHosts() {
    Function<JsonElement, List<String>> path = new Function<JsonElement, List<String>>() {

        @Nullable
        @Override
        public List<String> apply(@Nullable JsonElement jsonElement) {
            String jsonString = jsonElement.toString();
            return JsonPath.read(jsonString, "$.items[*].Hosts.host_name");
        }
    };
    return path;
}
Example 60
Project: elasticsearch-batch-percolator-master  File: BatchPercolatorRestTest.java View source code
@Test
public void basicRestPercolationTest() throws ExecutionException, InterruptedException, IOException {
    AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
    final String docId = "docId";
    logger.info("--> Add dummy doc");
    client.admin().indices().prepareDelete("_all").execute().actionGet();
    client.prepareIndex("test", "type", "1").setSource("field1", "value", "field2", "value").execute().actionGet();
    logger.info("--> register query1 with highlights");
    client.prepareIndex("test", BatchPercolatorService.TYPE_NAME, "1").setSource(getSource(termQuery("field1", "fox"), new HighlightBuilder().field("field1").preTags("<b>").postTags("</b>"))).execute().actionGet();
    logger.info("--> register query2 with highlights");
    client.prepareIndex("test", BatchPercolatorService.TYPE_NAME, "2").setSource(getSource(termQuery("field2", "meltwater"), new HighlightBuilder().requireFieldMatch(true).order("score").highlightQuery(termQuery("field2", "meltwater")).field("field2").preTags("<b>").postTags("</b>"))).execute().actionGet();
    logger.info("--> Doing percolation with Rest API");
    BytesReference source = new BatchPercolateSourceBuilder().addDoc(docBuilder().setDoc(jsonBuilder().startObject().field("_id", docId).field("field1", "the fox is here").field("field2", "meltwater percolator").endObject())).toXContent(JsonXContent.contentBuilder(), EMPTY_PARAMS).bytes();
    Response restResponse = asyncHttpClient.preparePost("http://localhost:9200/test/type/_batchpercolate").setHeader("Content-type", "application/json").setBody(source.toUtf8()).execute().get();
    assertThat(restResponse.getStatusCode(), equalTo(200));
    String responseBody = restResponse.getResponseBody();
    List<String> results = JsonPath.read(responseBody, "$.results");
    assertThat(results.size(), is(1));
    String matchedDoc = JsonPath.read(responseBody, "$.results[0].doc");
    assertThat(matchedDoc, is(docId));
    List<String> matches = JsonPath.read(responseBody, "$.results[0].matches");
    assertThat(matches.size(), is(2));
    assertThat(JsonPath.<List<String>>read(responseBody, "$.results[0].matches[?(@.query_id==1)].query_id").get(0), is("1"));
    assertThat(JsonPath.<List<String>>read(responseBody, "$.results[0].matches[?(@.query_id==1)].highlights.field1[0]").get(0), is("the <b>fox</b> is here"));
    assertThat(JsonPath.<List<String>>read(responseBody, "$.results[0].matches[?(@.query_id==2)].query_id").get(0), is("2"));
    assertThat(JsonPath.<List<String>>read(responseBody, "$.results[0].matches[?(@.query_id==2)].highlights.field2[0]").get(0), is("<b>meltwater</b> percolator"));
}
Example 61
Project: iiif-presentation-api-master  File: IiifPresentationApiObjectMapperTest.java View source code
@Test
public void testManifestToJson() throws JsonProcessingException {
    Manifest manifest = new ManifestImpl("testId", new PropertyValueSimpleImpl("testLabel"));
    Thumbnail thumb = new ThumbnailImpl();
    thumb.setId(URI.create("http://example.com/iiif/test/thumb"));
    Service service = new ServiceImpl();
    service.setId("htp://example.com/iiif/test");
    thumb.setService(service);
    manifest.setThumbnail(thumb);
    String jsonString = objectMapper.writeValueAsString(manifest);
    ReadContext ctx = JsonPath.parse(jsonString);
    Assert.assertEquals("testId", ctx.read("$['@id']"));
    Assert.assertEquals("testLabel", ctx.read("$.label"));
    Assert.assertEquals("http://iiif.io/api/presentation/2/context.json", ctx.read("$['@context']"));
    Assert.assertEquals("sc:Manifest", ctx.read("$['@type']"));
}
Example 62
Project: incubator-streams-master  File: JsonPathFilter.java View source code
@Override
public void prepare(Object configurationObject) {
    if (configurationObject instanceof Map) {
        Map<String, String> params = (Map<String, String>) configurationObject;
        pathExpression = params.get("pathExpression");
        jsonPath = JsonPath.compile(pathExpression);
        destNodeName = pathExpression.substring(pathExpression.lastIndexOf(".") + 1);
    }
}
Example 63
Project: intellij-community-master  File: JsonPathResponseHandler.java View source code
@Nullable
private Object extractRawValue(@NotNull Selector selector, @NotNull String source) throws Exception {
    if (StringUtil.isEmpty(selector.getPath())) {
        return null;
    }
    JsonPath jsonPath = lazyCompile(selector.getPath());
    Object value;
    try {
        value = jsonPath.read(source);
    } catch (InvalidPathException e) {
        throw new Exception(String.format("JsonPath expression '%s' doesn't match", selector.getPath()), e);
    }
    if (value == null) {
        return null;
    }
    return value;
}
Example 64
Project: jena-sparql-api-master  File: E_JsonPath.java View source code
//    public static NodeValue jsonToNodeValue(Object o) {
//    	NodeValue result;
//    	if(o == null) {
//    		result = NodeValue.nvNothing;
//    	} else if(o instanceof Number) {
//        	RDFDatatype dtype = TypeMapper.getInstance().getTypeByValue(o);
//        	Node node = NodeFactory.createUncachedLiteral(o, dtype);
//        	result = NodeValue.makeNode(node);
//        } else if(o instanceof String) {
//        	result = NodeValue.makeString((String)o);
//        } else {
//            result = new NodeValueJson(o);
//        }
//
//        return result;
//    }
@Override
public NodeValue exec(NodeValue nv, NodeValue query) {
    JsonElement json = asJson(nv);
    NodeValue result;
    if (query.isString() && json != null) {
        //JsonTransformerObject.toJava.apply(json);
        Object tmp = gson.fromJson(json, Object.class);
        String queryStr = query.getString();
        try {
            // If parsing the JSON fails, we return nothing, yet we log an error
            Object o = JsonPath.read(tmp, queryStr);
            result = jsonToNodeValue(o, gson);
        } catch (Exception e) {
            logger.warn(e.getLocalizedMessage());
            result = NodeValue.nvNothing;
        }
    } else {
        result = NodeValue.nvNothing;
    }
    return result;
}
Example 65
Project: jmeter-plugins-master  File: JSONPathExtractor.java View source code
@Override
public void process() {
    JMeterContext context = getThreadContext();
    JMeterVariables vars = context.getVariables();
    SampleResult previousResult = context.getPreviousResult();
    String responseData;
    if (getSubject().equals(SUBJECT_VARIABLE)) {
        responseData = vars.get(getSrcVariableName());
    } else {
        responseData = previousResult.getResponseDataAsString();
    }
    try {
        Object jsonPathResult = JsonPath.read(responseData, getJsonPath());
        if (jsonPathResult instanceof JSONArray) {
            Object[] arr = ((JSONArray) jsonPathResult).toArray();
            if (arr.length == 0) {
                throw new PathNotFoundException("Extracted array is empty");
            }
            vars.put(this.getVar(), objectToString(jsonPathResult));
            vars.put(this.getVar() + "_matchNr", objectToString(arr.length));
            int k = 1;
            while (vars.get(this.getVar() + "_" + k) != null) {
                vars.remove(this.getVar() + "_" + k);
                k++;
            }
            for (int n = 0; n < arr.length; n++) {
                vars.put(this.getVar() + "_" + (n + 1), objectToString(arr[n]));
            }
        } else {
            vars.put(this.getVar(), objectToString(jsonPathResult));
        }
    } catch (Exception e) {
        log.warn("Extract failed", e);
        vars.put(this.getVar(), getDefaultValue());
        vars.put(this.getVar() + "_matchNr", "0");
        int k = 1;
        while (vars.get(this.getVar() + "_" + k) != null) {
            vars.remove(this.getVar() + "_" + k);
            k++;
        }
    }
}
Example 66
Project: nodebox-master  File: NetworkFunctions.java View source code
public static Iterable<?> queryJSON(final Object json, final String query) {
    if (json instanceof Map) {
        Map<?, ?> requestMap = (Map<?, ?>) json;
        if (requestMap.containsKey("body")) {
            return queryJSON(requestMap.get("body"), query);
        } else {
            throw new IllegalArgumentException("Cannot parse JSON input.");
        }
    } else if (json instanceof String) {
        Object results = JsonPath.read((String) json, query);
        if (!(results instanceof Iterable)) {
            return ImmutableList.of(results);
        } else {
            return (Iterable<?>) results;
        }
    } else {
        throw new IllegalArgumentException("Cannot parse JSON input.");
    }
}
Example 67
Project: NotificationPortlet-master  File: SSPTaskNotificationService.java View source code
/**
     * Map and SSP Response to a NotificationResponse.
     *
     * @param request the portlet request
     * @param response the response from the REST call to SSP
     * @return the mapped notification response
     */
private NotificationResponse mapToNotificationResponse(PortletRequest request, ResponseEntity<String> response) {
    Configuration config = Configuration.builder().options(Option.DEFAULT_PATH_LEAF_TO_NULL).build();
    ReadContext readContext = JsonPath.using(config).parse(response.getBody());
    // check the status embedded in the response too...
    String success = readContext.read(SUCCESS_QUERY);
    // grr. SSP returns this as a string...
    if (!"true".equalsIgnoreCase(success)) {
        String error = readContext.read(MESSAGE_QUERY);
        return notificationError(error);
    }
    // read the actual tasks...
    Object rows = readContext.read(ROWS_QUERY);
    if (!(rows instanceof JSONArray)) {
        throw new RuntimeException("Expected 'rows' to be an array of tasks");
    }
    String source = getNotificationSource(request);
    List<NotificationEntry> list = new ArrayList<>();
    for (int i = 0; i < ((JSONArray) rows).size(); i++) {
        NotificationEntry entry = mapNotificationEntry(readContext, i, source);
        if (entry != null) {
            attachActions(request, entry);
            list.add(entry);
        }
    }
    // build the notification response...
    NotificationResponse notification = new NotificationResponse();
    if (!list.isEmpty()) {
        NotificationCategory category = getNotificationCategory(request);
        category.addEntries(list);
        notification.setCategories(Arrays.asList(category));
    }
    return notification;
}
Example 68
Project: spring-boot-master  File: BootCuriesHrefIntegrationTests.java View source code
private String getCurieHref(String uri) {
    ResponseEntity<String> response = new TestRestTemplate().getForEntity(uri, String.class);
    JSONArray bootCuriesHrefs = JsonPath.parse(response.getBody()).read("_links.curies[?(@.name == 'boot')].href");
    assertThat(bootCuriesHrefs).hasSize(1);
    return (String) bootCuriesHrefs.get(0);
}
Example 69
Project: spring-data-rest-tck-master  File: JpaTckTests.java View source code
/**
	 * Test whether the {@link org.springframework.data.rest.tck.jpa.repository.CustomerRepository} exposes a CREATE
	 * feature.
	 *
	 * @throws Exception
	 */
@Test
public void testCreate() throws Exception {
    for (Link l : linksToCustomers()) {
        MockHttpServletResponse response = request(l.getHref());
        String jsonBody = response.getContentAsString();
        assertThat("Customer is a Doe", JsonPath.read(jsonBody, "lastname").toString(), is("Doe"));
        assertThat("Entity contains self Link", links.findLinkWithRel(SELF_REL, jsonBody), notNullValue());
        assertThat("Entity maintains addresses as Links", links.findLinkWithRel(CUSTOMER_ADDRESSES_REL, jsonBody), notNullValue());
    }
}
Example 70
Project: Web-Karma-master  File: ConvertJSONLD.java View source code
@Override
public Boolean call(Tuple2<Text, Text> textTextTuple2) throws Exception {
    List<String> results = JsonPath.read(textTextTuple2._2.toString(), "$..dateCreated");
    for (String s : results) {
        String date = outputFormat.format(inputFormat.parse(s));
        if (date.contains(dateFilter)) {
            return true;
        }
    }
    if (results.isEmpty() && dateFilter.isEmpty()) {
        return true;
    }
    return false;
}
Example 71
Project: incubator-brooklyn-master  File: JsonFunctions.java View source code
/** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */
@SuppressWarnings("unused")
@Deprecated
private static <T> Function<JsonElement, T> getPathOld(final String path) {
    // TODO PERSISTENCE WORKAROUND
    return new Function<JsonElement, T>() {

        @SuppressWarnings("unchecked")
        @Override
        public T apply(JsonElement input) {
            String jsonString = input.toString();
            Object rawElement = JsonPath.read(jsonString, path);
            return (T) rawElement;
        }
    };
}
Example 72
Project: ambari-master  File: FileService.java View source code
protected String getJsonPathContentByUrl(String filePath) throws IOException {
    URL url = new URL(filePath.substring(JSON_PATH_FILE.length()));
    InputStream responseInputStream = context.getURLStreamProvider().readFrom(url.toString(), "GET", (String) null, new HashMap<String, String>());
    String response = IOUtils.toString(responseInputStream);
    for (String ref : url.getRef().split("!")) {
        response = JsonPath.read(response, ref);
    }
    return response;
}
Example 73
Project: camel-master  File: JsonPathEngine.java View source code
public Object read(Exchange exchange) throws Exception {
    if (path == null) {
        Expression exp = exchange.getContext().resolveLanguage("simple").createExpression(expression);
        String text = exp.evaluate(exchange, String.class);
        JsonPath path = JsonPath.compile(text);
        LOG.debug("Compiled dynamic JsonPath: {}", expression);
        return doRead(path, exchange);
    } else {
        return doRead(path, exchange);
    }
}
Example 74
Project: carbon-business-process-master  File: JsonNodeObject.java View source code
/**
     * Function to evaluate jsonpath over JsonNodeObject
     * @param jsonPathStr jsonpath
     * @return returns the evaluation result. The returned Object can be a
     *                      com.fasterxml.jackson.databind.JsonNode (in case the result is json object)
     *                      com.fasterxml.jackson.databind.node.ArrayNode (in case the result is json array)
     *                      Or main primitive data types (String, Integer, Byte, Character, Short, Long, Float, Double, Boolean)
     *                 This function returns new Object representing the evaluation results, no a reference to a node
     * @throws IOException
     * @throws BPMNJsonException is thrown if the the resulting data type cannot be identified
     */
public Object jsonPath(String jsonPathStr) throws IOException, BPMNJsonException {
    ObjectMapper mapper = new ObjectMapper();
    Map map = mapper.convertValue(jsonNode, Map.class);
    Object result = JsonPath.read(map, jsonPathStr);
    JsonBuilder builder = new JsonBuilder(mapper);
    if (result instanceof Map) {
        //If the result is a Map, then it should be a json object
        return builder.createJsonNodeFromMap((Map<String, Object>) result);
    } else if (result instanceof List) {
        //when result is a list, then it should be a json array
        return builder.createJsonArrayFromMap((List<Object>) result);
    } else if (result instanceof String || result instanceof Integer || result instanceof Byte || result instanceof Character || result instanceof Short || result instanceof Long || result instanceof Float || result instanceof Double || result instanceof Boolean) {
        //If result is primitive data type, then return it as it is
        return result;
    } else {
        //Un-filtered data type, considered as unknown types
        throw new BPMNJsonException("Unknown type data type: " + result.getClass().getName() + " resulted while evaluating json path");
    }
}
Example 75
Project: hibiscus.depotviewer-master  File: CortalConsorsMitHBCI.java View source code
@SuppressWarnings("unchecked")
public void runUmsaetze(Konto konto) throws ApplicationException {
    List<String> fehlerhafteOrder = new ArrayList<String>();
    String depotnummer = null;
    try {
        depotnummer = konto.getKontonummer();
    } catch (RemoteException e2) {
        throw new ApplicationException("Kontonummer nicht gefunden", e2);
    }
    ArrayList<String> seiten = new ArrayList<String>();
    try {
        String username = konto.getMeta(PROP_KUNDENNUMMER, null);
        if (username == null || username.length() == 0) {
            throw new ApplicationException("Bitte geben ihre Kundenummer in den Synchronisationsoptionen ein");
        }
        String password = konto.getMeta(PROP_PASSWORD, null);
        try {
            if (password == null || password.length() == 0) {
                password = Application.getCallback().askPassword(getName());
            }
        } catch (Exception e1) {
            e1.printStackTrace();
            throw new ApplicationException("Password-Eingabe:" + e1.getMessage());
        }
        final WebClient webClient = new WebClient();
        HtmlUtils.setProxyCfg(webClient, "https://webservices.consorsbank.de/");
        webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
        String url = "https://webservices.consorsbank.de/WebServicesDe/services/restful/login";
        // Login und "sessionID" speichern
        // TODO Password und Username entsprechend escapen
        String request = "{\"1\":{\"2\":\"" + password + "\",\"3\":\"" + username + "\",\"0\":{\"5\":\"MOOTWINA\",\"6\":\"0\",\"2\":\"DE\",\"1\":\"DE\",\"0\":\"CCLogin\",\"3\":\"\",\"4\":\"1\"}}}";
        String json = getRequest(webClient, url, request);
        seiten.add(json);
        // Prüfen, ob Login Fehlgeschlagen ist
        if (!"CCLogin".equals(jsonRead(json, "$.2.0.0"))) {
            Logger.debug(json);
            String msg = jsonRead(json, "$.20[0].1");
            if (msg == null || msg.isEmpty()) {
                msg = "Login aus unbekannten Grund nicht möglich!";
            }
            throw new ApplicationException(msg);
        }
        String sessionID = jsonRead(json, "$.2.0.3");
        // Request: Alle Order
        String allordersRequest = "{\"6\":{\"1\":\"" + depotnummer + "\",\"600\":{\"2\":\"30\",\"3\":\"orderNo DESC\",\"1\":\"1\",\"0\":\"Order\"},\"601\":\"Q\",\"0\":{\"5\":\"MOOTWINA\",\"6\":\"0\",\"2\":\"DE\",\"1\":\"DE\",\"0\":\"CCOrderAllInquiry\",\"3\":\"" + sessionID + "\",\"4\":\"1\"}}}";
        json = getRequest(webClient, "https://webservices.consorsbank.de/WebServicesDe/services/restful/getAllOrders", allordersRequest);
        seiten.add(json);
        // Für alle Order, die Detailinformationen requesten und Umsatz-Eintrag generieren
        try {
            Logger.debug("JSON für Order: " + json.replace(depotnummer, "000111222333"));
            Integer anzahlOrders = JsonPath.parse(json).read("$.7.602.2");
            List<Map<String, Object>> orders = null;
            if (anzahlOrders == 1) {
                orders = new ArrayList<Map<String, Object>>();
                orders.add(JsonPath.parse(json).read("$.7.2", Map.class));
            } else if (anzahlOrders > 1) {
                orders = JsonPath.parse(json).read("$.7.2", List.class);
            }
            if (orders == null) {
                Logger.info("Es wurden keine Order gefunden!");
            } else {
                Logger.info("Es wurden " + orders.size() + " Order gefunden!");
                for (Map<String, Object> orderinfo : orders) {
                    if (orderinfo.get("6").toString().equals("0")) {
                        Logger.info("Offene Order übersprungen!");
                        continue;
                    }
                    String orderRequest = "{\"101\":{\"1\":\"" + depotnummer + "\",\"2\":\"" + orderinfo.get("4").toString() + "\",\"0\":{\"5\":\"MOOTWINA\",\"6\":\"0\",\"2\":\"DE\",\"1\":\"DE\",\"0\":\"CCOrderDetailInquiry\",\"3\":\"" + sessionID + "\",\"4\":\"1\"}}}";
                    String order = getRequest(webClient, "https://webservices.consorsbank.de/WebServicesDe/services/restful/getOrderDetail", orderRequest);
                    seiten.add(order);
                    parseOrder(depotnummer, konto, fehlerhafteOrder, orderinfo, order);
                }
            }
        } catch (PathNotFoundException pnfe) {
            Logger.error("Fehler bei der Verarbeitung der JSON", pnfe);
            fehlerhafteOrder.add(pnfe + json.replace(depotnummer, "000111222333"));
        }
        // Logout
        String logoutRequest = "{\"17\":{\"0\":{\"5\":\"MOOTWINA\",\"6\":\"0\",\"2\":\"DE\",\"1\":\"DE\",\"0\":\"CCLogout\",\"3\":\"" + sessionID + "\",\"4\":\"1\"}}}";
        json = getRequest(webClient, "https://webservices.consorsbank.de/WebServicesDe/services/restful/logout", logoutRequest);
        seiten.add(json);
    // @TODO Anwort verifizieren
    } catch (IOException e) {
        throw new ApplicationException(e);
    } finally {
        try {
            debug(seiten, konto);
        } catch (RemoteException e) {
            throw new ApplicationException(e);
        }
    }
    try {
        if (fehlerhafteOrder.size() > 0) {
            DebugDialogWithTextarea dialog = new DebugDialogWithTextarea(DebugDialog.POSITION_CENTER, fehlerhafteOrder);
            dialog.open();
        }
    } catch (OperationCanceledException oce) {
    } catch (Exception e) {
        Logger.error("unable to display debug dialog", e);
    }
}
Example 76
Project: jvm-serializers-master  File: JsonPathDeserializerOnly.java View source code
private static Media readMedia(String mediaJsonInput) throws Exception {
    Media media = new Media();
    Object bitrate = JsonPath.read(mediaJsonInput, "$.bitrate");
    if (bitrate != null && bitrate instanceof Long) {
        media.bitrate = ((Long) bitrate).intValue();
        media.hasBitrate = true;
    }
    media.copyright = JsonPath.read(mediaJsonInput, "$.copyright");
    media.duration = (Long) JsonPath.read(mediaJsonInput, "$.duration");
    media.format = JsonPath.read(mediaJsonInput, "$.format");
    media.height = ((Long) JsonPath.read(mediaJsonInput, "$.height")).intValue();
    List<String> persons = JsonPath.read(mediaJsonInput, "$.persons[*]");
    media.persons = persons;
    media.player = Media.Player.valueOf((String) JsonPath.read(mediaJsonInput, "$.player"));
    media.size = (Long) JsonPath.read(mediaJsonInput, "$.size");
    media.title = JsonPath.read(mediaJsonInput, "$.title");
    media.uri = JsonPath.read(mediaJsonInput, "$.uri");
    media.width = ((Long) JsonPath.read(mediaJsonInput, "$.width")).intValue();
    return media;
}
Example 77
Project: mangooio-master  File: OAuthCallbackFilter.java View source code
/**
     * Executes an OAuth authentication to the Facebook API
     *
     * @param request The current request
     */
@SuppressWarnings("rawtypes")
private void facebookOAuth(Request request) {
    final String code = request.getParameter(CODE);
    final Optional<OAuthService> oAuthService = this.requestHelper.createOAuthService(OAuthProvider.FACEBOOK);
    if (StringUtils.isNotBlank(code) && oAuthService.isPresent()) {
        final OAuth20Service oAuth20Service = (OAuth20Service) oAuthService.get();
        OAuth2AccessToken oAuth2AccessToken = null;
        try {
            oAuth2AccessToken = oAuth20Service.getAccessToken(code);
        } catch (IOExceptionInterruptedException | ExecutionException |  e) {
            LOG.error("Failed to get facebook OAuth2 accesstoken", e);
        }
        if (oAuth2AccessToken != null) {
            com.github.scribejava.core.model.Response scribeResponse = null;
            String scribeResponseBody = null;
            try {
                scribeResponse = getResourceResponse(oAuth20Service, oAuth2AccessToken, OAuthResource.FACEBOOK.toString());
                scribeResponseBody = scribeResponse.getBody();
            } catch (IOExceptionInterruptedException | ExecutionException |  e) {
                LOG.error("Failed to get response body for facebook OAuth2", e);
            }
            if (scribeResponse != null && scribeResponse.isSuccessful() && StringUtils.isNotBlank(scribeResponseBody)) {
                final ReadContext readContext = JsonPath.parse(scribeResponseBody);
                request.getAuthentication().withOAuthUser(new OAuthUser(readContext.read(ID), scribeResponseBody, readContext.read(NAME), readContext.read(PICTURE_DATA_URL)));
            }
        }
    }
}
Example 78
Project: parallec-master  File: TargetHostsBuilder.java View source code
/**
     * TODO https://github.com/jayway/JsonPath
     *
     * @param jsonPath
     *            the json path
     * @param sourcePath
     *            the source path
     * @param sourceType
     *            the source type
     * @return the list
     * @throws TargetHostsLoadException
     *             the target hosts load exception
     */
@Override
public List<String> setTargetHostsFromJsonPath(String jsonPath, String sourcePath, HostsSourceType sourceType) throws TargetHostsLoadException {
    List<String> targetHosts = new ArrayList<String>();
    try {
        String content = getContentFromPath(sourcePath, sourceType);
        targetHosts = JsonPath.read(content, jsonPath);
    } catch (IOException e) {
        throw new TargetHostsLoadException("IEException when reading  " + sourcePath, e);
    }
    return targetHosts;
}
Example 79
Project: pentaho-kettle-master  File: FastJsonReader.java View source code
private List<Object[]> evalCombinedResult() throws JsonInputException {
    int lastSize = -1;
    String prevPath = null;
    List<List<?>> inputs = new ArrayList<>(paths.length);
    int i = 0;
    for (JsonPath path : paths) {
        List<Object> input = getReadContext().read(path);
        if (input.size() != lastSize && lastSize > 0 & input.size() != 0) {
            throw new JsonInputException(BaseMessages.getString(PKG, "JsonInput.Error.BadStructure", input.size(), fields[i].getPath(), prevPath, lastSize));
        }
        if ((isAllNull(input) || input.size() == 0) && !isIgnoreMissingPath()) {
            throw new JsonInputException(BaseMessages.getString(PKG, "JsonReader.Error.CanNotFindPath", fields[i].getPath()));
        }
        inputs.add(input);
        lastSize = input.size();
        prevPath = fields[i].getPath();
        i++;
    }
    List<Object[]> resultRows = convertInputsIntoResultRows(inputs);
    filterOutExcessRows(resultRows);
    if (!ignoreMissingPath & paths.length != 0) {
        raiseExceptionIfAnyMissingPath(resultRows);
    }
    return resultRows;
}
Example 80
Project: sputnik-master  File: StashFacade.java View source code
@NotNull
@Override
public List<ReviewFile> listFiles() {
    try {
        String response = stashConnector.listFiles();
        List<JSONObject> jsonList = JsonPath.read(response, "$.values[?(@.type != 'DELETE')].path");
        List<ReviewElement> containers = transform(jsonList, ReviewElement.class);
        List<ReviewFile> files = new ArrayList<>();
        for (ReviewElement container : containers) {
            String filePath = getFilePath(container);
            files.add(new ReviewFile(filePath));
        }
        return files;
    } catch (URISyntaxExceptionIOException |  e) {
        throw new StashException("Error when listing files", e);
    }
}
Example 81
Project: java-apikit-master  File: HDTest.java View source code
/**
	 * device vendors test
	 * @throws IOException 
	 * @depends test_cloudConfigExists
	 * @group cloud
	 **/
@Test
public void test_0cloud_1Vendors() throws IOException {
    hd = new HD(cloudConfig);
    result = hd.deviceVendors();
    reply = hd.getReply();
    assertTrue(result);
    assertEquals((Integer) 0, (Integer) JsonPath.read(gson.toJson(reply), "$.status"));
    assertEquals("OK", (String) (String) JsonPath.read(gson.toJson(reply), "$.message"));
    assertThat((List<String>) JsonPath.read(gson.toJson(reply), "$.vendor"), hasItem("Nokia"));
    assertThat((List<String>) JsonPath.read(gson.toJson(reply), "$.vendor"), hasItem("Samsung"));
}
Example 82
Project: carbon-analytics-master  File: JSONInputMapper.java View source code
private Event processSingleEvent(Object obj) throws EventReceiverProcessingException {
    Object[] outObjArray = null;
    StreamDefinition outStreamDefinition = this.streamDefinition;
    int metaDataCount = outStreamDefinition.getMetaData() != null ? outStreamDefinition.getMetaData().size() : 0;
    int correlationDataCount = outStreamDefinition.getCorrelationData() != null ? outStreamDefinition.getCorrelationData().size() : 0;
    int payloadDataCount = outStreamDefinition.getPayloadData() != null ? outStreamDefinition.getPayloadData().size() : 0;
    Object[] metaDataArray = new Object[metaDataCount];
    Object[] correlationDataArray = new Object[correlationDataCount];
    Object[] payloadDataArray = new Object[payloadDataCount];
    if (obj instanceof String) {
        String jsonString = (String) obj;
        List<Object> objList = new ArrayList<Object>();
        for (JsonPathData jsonPathData : attributeJsonPathDataList) {
            JsonPath jsonPath = jsonPathData.getJsonPath();
            AttributeType type = jsonPathData.getType();
            try {
                Object resultObject = null;
                Object returnedObj = null;
                try {
                    resultObject = jsonPath.read(jsonString);
                } catch (InvalidPathException e) {
                    log.debug(e.getMessage() + ". Could not find match for JSONPath : " + jsonPath.toString() + " for event: " + obj.toString());
                }
                if (resultObject == null) {
                    if (jsonPathData.getDefaultValue() != null && !jsonPathData.getDefaultValue().isEmpty()) {
                        returnedObj = getPropertyValue(jsonPathData.getDefaultValue(), type);
                        log.debug("Unable to parse JSONPath to retrieve required attribute. Sending defaults.");
                    } else if (!(AttributeType.STRING.equals(jsonPathData.getType()))) {
                        throw new InvalidPropertyValueException("Found Invalid property value null for attribute ");
                    }
                } else {
                    try {
                        returnedObj = getPropertyValue(resultObject, type);
                    } catch (NumberFormatException e) {
                        if ((!AttributeType.STRING.equals(type)) && jsonPathData.getDefaultValue() != null) {
                            returnedObj = getPropertyValue(jsonPathData.getDefaultValue(), type);
                        } else {
                            throw e;
                        }
                    }
                }
                objList.add(returnedObj);
            } catch (NumberFormatException e) {
                log.error("Unable to cast the input data to required type :" + type + " ,hence dropping the event " + obj.toString(), e);
                return null;
            } catch (InvalidPropertyValueException e) {
                log.error(e.getMessage() + " ,hence dropping the event : " + obj.toString());
                return null;
            }
        }
        outObjArray = objList.toArray(new Object[objList.size()]);
    }
    return EventReceiverUtil.getEventFromArray(outObjArray, outStreamDefinition, metaDataArray, correlationDataArray, payloadDataArray);
}
Example 83
Project: geoserver-master  File: GeoServerRestRoleService.java View source code
@Override
public Object executeWithContext(String json) throws Exception {
    try {
        List<String> rolesString = JsonPath.read(json, restRoleServiceConfig.getUsersJSONPath());
        for (String role : rolesString) {
            if (role.startsWith(rolePrefix)) {
                // remove standard role prefix
                role = role.substring(rolePrefix.length());
            }
            roles.add(createRoleObject(role));
        }
    } catch (PathNotFoundException ex) {
        Logger.getLogger(getClass().getName()).log(Level.WARNING, null, ex);
        roles.clear();
        roles.add(GeoServerRole.AUTHENTICATED_ROLE);
    }
    SortedSet<GeoServerRole> finalRoles = Collections.unmodifiableSortedSet(fixGeoServerRoles(roles));
    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine("Setting ROLES for User [" + username + "] to " + finalRoles);
    }
    return finalRoles;
}
Example 84
Project: presto-riak-master  File: CoverageRecordCursor.java View source code
private void fetchData() {
    totalBytes = 0;
    String tableName = split.getTableHandle().getTableName();
    try {
        String bucket = PRSubTable.bucketName(tableName);
        log.info("accessing bucket %s for table %s", bucket, tableName);
        DirectConnection conn = directConnection;
        // TODO: if tupleDomain indicates there is a predicate and
        //       the predicate matches to the 2i then fetch via 2i.
        //       if the predicate is on __pkey then also use 2i with <<"key">>.
        OtpErlangList objects = null;
        if (tupleDomain.isAll()) {
            log.info("using coverage query on %s, this may take a long time!!", split.getTableHandle().toString());
            objects = splitTask.fetchAllData(conn, split.getTableHandle().getSchemaName(), bucket);
        } else if (!tupleDomain.isNone()) {
            OtpErlangTuple query = buildQuery();
            log.info("2i query '%s' on %s", query, split.getTableHandle().toString());
            if (query == null) {
                log.warn("there are no matching index btw %s and %s", columnHandles, tupleDomain);
                objects = splitTask.fetchAllData(conn, split.getTableHandle().getSchemaName(), bucket);
            } else {
                objects = splitTask.fetchViaIndex(conn, split.getTableHandle().getSchemaName(), bucket, query);
            }
        }
        for (OtpErlangObject o : objects) {
            InternalRiakObject riakObject = new InternalRiakObject(o);
            totalBytes += riakObject.getValueAsString().length();
            PRSubTable subtable = split.getTable().getSubtable(tableName);
            if (subtable != null) {
                try {
                    // @doc depending on path and object structure, both Object and List may
                    // match path expression and be returned here. This if is to handle both.
                    Object records = JsonPath.read(riakObject.getValueAsString(), subtable.getPath());
                    if (records instanceof Map) {
                        //log.debug("instance of map; %s", records);
                        handleObject((Map) records, riakObject);
                    } else if (records instanceof List) {
                        //log.debug("instance of list; %s", records);
                        for (Map<String, Object> record : (List<Map<String, Object>>) records) {
                            handleObject(record, riakObject);
                        }
                    }
                } catch (IllegalArgumentException e) {
                    log.debug(e.getMessage() + " - JSONPath couldn't parse this string : " + riakObject.getValueAsString());
                } catch (com.jayway.jsonpath.PathNotFoundException e) {
                }
            } else {
                try {
                    ObjectMapper mapper = new ObjectMapper();
                    Map record = mapper.readValue(riakObject.getValueAsString(), HashMap.class);
                    handleObject(record, riakObject);
                    buffer.add(record);
                } catch (IOException e) {
                    log.warn(e.getMessage());
                }
            }
        }
        log.debug("%d key data fetched.", buffer.size());
    } catch (OtpErlangExit e) {
        log.error(e);
    } catch (OtpAuthException e) {
        log.error(e);
    } catch (OtpErlangDecodeException e) {
        log.error(e);
    }
}
Example 85
Project: siddhi-master  File: JsonSourceMapper.java View source code
/**
     * Convert the given JSON string to {@link Event}.
     *
     * @param eventObject JSON string
     * @return the constructed Event object
     */
private Object convertToEvent(Object eventObject) {
    if (!(eventObject instanceof String)) {
        log.error("Invalid JSON object received. Expected String, but found " + eventObject.getClass().getCanonicalName());
        return null;
    }
    if (!isJsonValid(eventObject.toString())) {
        log.error("Invalid Json String :" + eventObject.toString());
        return null;
    }
    Object jsonObj;
    ReadContext readContext = JsonPath.parse(eventObject.toString());
    if (isCustomMappingEnabled) {
        jsonObj = readContext.read(enclosingElement);
        if (jsonObj == null) {
            log.error("Enclosing element " + enclosingElement + " cannot be found in the json string " + eventObject.toString() + ".");
            return null;
        }
        if (jsonObj instanceof JSONArray) {
            JSONArray jsonArray = (JSONArray) jsonObj;
            List<Event> eventList = new ArrayList<Event>();
            for (Object eventObj : jsonArray) {
                Event event = processCustomEvent(JsonPath.parse(eventObj));
                if (event != null) {
                    eventList.add(event);
                }
            }
            Event[] eventArray = eventList.toArray(new Event[0]);
            return eventArray;
        } else {
            try {
                Event event = processCustomEvent(JsonPath.parse(jsonObj));
                return event;
            } catch (ExecutionPlanRuntimeException e) {
                log.error(e.getMessage());
                return null;
            }
        }
    } else {
        jsonObj = readContext.read(DEFAULT_ENCLOSING_ELEMENT);
        if (jsonObj instanceof JSONArray) {
            return convertToEventArrayForDefaultMapping(eventObject);
        } else {
            try {
                return convertToSingleEventForDefaultMapping(eventObject);
            } catch (IOException e) {
                log.error("Json string " + eventObject + " cannot be parsed to json object.");
                return null;
            }
        }
    }
}
Example 86
Project: H-Viewer-master  File: RuleParser.java View source code
public static List<Collection> getCollections(List<Collection> collections, String text, Rule rule, String sourceUrl, boolean noRegex) {
    try {
        Iterable items;
        if (!isJson(text)) {
            Document doc = Jsoup.parse(text);
            items = doc.select(rule.item.selector);
            for (Object item : items) {
                String itemStr;
                if (item instanceof Element) {
                    if ("attr".equals(rule.item.fun))
                        itemStr = ((Element) item).attr(rule.title.param);
                    else if ("html".equals(rule.item.fun))
                        itemStr = ((Element) item).html();
                    else if ("text".equals(rule.item.fun))
                        itemStr = ((Element) item).text();
                    else
                        itemStr = item.toString();
                } else
                    continue;
                if (!noRegex && rule.item.regex != null) {
                    Pattern pattern = Pattern.compile(rule.item.regex);
                    Matcher matcher = pattern.matcher(itemStr);
                    Logger.d("RuleParser", "beforeMatch");
                    if (!matcher.find()) {
                        continue;
                    } else if (matcher.groupCount() >= 1) {
                        Logger.d("RuleParser", "matcher.groupCount() >= 1");
                        if (rule.item.replacement != null) {
                            itemStr = rule.item.replacement;
                            for (int i = 1; i <= matcher.groupCount(); i++) {
                                String replace = matcher.group(i);
                                itemStr = itemStr.replaceAll("\\$" + i, (replace != null) ? replace : "");
                            }
                        } else {
                            itemStr = matcher.group(1);
                        }
                    }
                }
                if (rule.item.path != null && isJson(itemStr)) {
                    Logger.d("RuleParser", "isJson : true");
                    collections = getCollections(collections, itemStr, rule, sourceUrl, true);
                } else {
                    Collection collection = new Collection(collections.size() + 1);
                    collection = getCollectionDetail(collection, item, rule, sourceUrl);
                    collections.add(collection);
                }
            }
        } else {
            ReadContext ctx = JsonPath.parse(text);
            items = getJsonArray(ctx, rule.item.path);
            Logger.d("RuleParser", items.toString());
            for (Object item : items) {
                String itemStr;
                if (item instanceof JsonElement)
                    itemStr = item.toString();
                else
                    continue;
                if (!noRegex && rule.item.regex != null) {
                    Pattern pattern = Pattern.compile(rule.item.regex);
                    Matcher matcher = pattern.matcher(itemStr);
                    if (!matcher.find()) {
                        continue;
                    } else if (matcher.groupCount() >= 1) {
                        if (rule.item.replacement != null) {
                            itemStr = rule.item.replacement;
                            for (int i = 1; i <= matcher.groupCount(); i++) {
                                String replace = matcher.group(i);
                                itemStr = itemStr.replaceAll("\\$" + i, (replace != null) ? replace : "");
                            }
                        } else {
                            itemStr = matcher.group(1);
                        }
                    }
                }
                if (rule.item.selector != null && !isJson(itemStr)) {
                    Logger.d("RuleParser", "isJson : false");
                    collections = getCollections(collections, itemStr, rule, sourceUrl, true);
                } else {
                    Collection collection = new Collection(collections.size() + 1);
                    collection = getCollectionDetail(collection, item, rule, sourceUrl);
                    collections.add(collection);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return collections;
}
Example 87
Project: collectors-master  File: JsonPathSupport.java View source code
public static DocumentContext asDocumentContext(final TreeNode jsonDocument) {
    return JsonPath.parse(jsonDocument, JSON_PATH_CONFIGURATION);
}
Example 88
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 89
Project: knox-master  File: NewApp.java View source code
public String getAppId() throws IOException {
    return JsonPath.read(getString(), "$.application-id");
}
Example 90
Project: jmeter-maven-plugin-master  File: TestConfig.java View source code
public void setResultsFileLocations(List<String> resultFileLocations) {
    jsonData = JsonPath.parse(jsonData).set("$.resultFilesLocations", resultFileLocations).jsonString();
}
Example 91
Project: spydra-master  File: GcpUtils.java View source code
public String projectFromJsonCredential(String json) {
    return JsonPath.read(json, "$.project_id");
}
Example 92
Project: devoxx-2013-master  File: IntegrationTest.java View source code
private List<String> getDoors(String game) throws Exception {
    String content = this.mockMvc.perform(get(game)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
    return JsonPath.read(content, "$.links[?(@.rel==door)].href");
}
Example 93
Project: pdi-fastjsoninput-plugin-master  File: FastJsonReader.java View source code
private ParseContext getParseContext() {
    return JsonPath.using(jsonConfiguration);
}
Example 94
Project: RestIt-master  File: Condition.java View source code
/**
     * With Valid Json Path.
     * Check to see if incoming path has a valid string value selected via a <a href="https://github.com/jayway/JsonPath/">
     * JSONPath</a> expression.
     *
     * @param - Json Path
     * @param - value to check against
     * @return
     */
public static Condition withPostBodyContainingJsonPath(final String pattern, final Object value) {
    return new Condition( input -> value.equals(JsonPath.parse(input.getPostBody()).read(pattern)));
}
Example 95
Project: spring-one-2013-master  File: GamesControllerIntegrationTest.java View source code
private String getLinkedLocation(String location, String rel) throws Exception {
    String json = this.mockMvc.perform(get(location)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
    return JsonPath.read(json, String.format("$.links[?(@.rel==%s)].href[0]", rel));
}
Example 96
Project: spring-framework-master  File: JsonPathExpectationsHelper.java View source code
private Object evaluateJsonPath(String content, Class<?> targetType) {
    String message = "No value at JSON path \"" + this.expression + "\"";
    try {
        return JsonPath.parse(content).read(this.expression, targetType);
    } catch (Throwable ex) {
        throw new AssertionError(message, ex);
    }
}
Example 97
Project: av-sched-master  File: CronJobIT.java View source code
// ---------------------------------------------- Privates Methods ------------------------------------------------
private void assertJsonList(String json, String jsonPath, Object expected) throws Exception {
    List<Object> actual = JsonPath.parse(json).read(jsonPath);
    Assert.assertEquals(expected, actual.get(0));
}
Example 98
Project: spring-restdocs-master  File: GettingStartedDocumentation.java View source code
private String getLink(MvcResult result, String rel) throws UnsupportedEncodingException {
    return JsonPath.parse(result.getResponse().getContentAsString()).read("_links." + rel + ".href");
}
Example 99
Project: cucumber-common-steps-master  File: RestSteps.java View source code
@Then("^response json path list \"(.*?)\" should be:$")
public void response_json_path_list_should_be(final String jsonPath, final DataTable list) throws Throwable {
    final List<String> responseList = JsonPath.read(this.responseValue, jsonPath);
    assertThat(responseList).isEqualTo(list.asList(String.class));
}