Exemple #1
0
  @Test
  public void issue_97() throws Exception {
    String json =
        "{ \"books\": [ "
            + "{ \"category\": \"fiction\" }, "
            + "{ \"category\": \"reference\" }, "
            + "{ \"category\": \"fiction\" }, "
            + "{ \"category\": \"fiction\" }, "
            + "{ \"category\": \"reference\" }, "
            + "{ \"category\": \"fiction\" }, "
            + "{ \"category\": \"reference\" }, "
            + "{ \"category\": \"reference\" }, "
            + "{ \"category\": \"reference\" }, "
            + "{ \"category\": \"reference\" }, "
            + "{ \"category\": \"reference\" } ]  }";

    Configuration conf =
        Configuration.builder()
            .jsonProvider(new GsonJsonProvider())
            .mappingProvider(new GsonMappingProvider())
            .build();

    DocumentContext context = JsonPath.using(conf).parse(json);
    context.delete("$.books[?(@.category == 'reference')]");

    List<String> categories = context.read("$..category", List.class);

    Assertions.assertThat(categories).containsOnly("fiction");
  }
  public void save(
      @NotNull SchemaFormContentAware newEntity,
      SchemaFormContentAware oldEntity,
      String entityPath) {
    Assert.notNull(newEntity, "New content cannot be null");

    Object json = defaultConfiguration().jsonProvider().parse(newEntity.getContent());
    DocumentContext newContext =
        JsonPath.using(defaultConfiguration().addOptions(Option.AS_PATH_LIST)).parse(json);
    Map<String, JSONArray> newPaths = getPathFilesMap(newContext, json);
    if (newPaths == null) return; // content does not have any file field

    if (oldEntity != null) {
      Object oldJson = defaultConfiguration().jsonProvider().parse(oldEntity.getContent());
      DocumentContext oldContext =
          JsonPath.using(defaultConfiguration().addOptions(Option.AS_PATH_LIST)).parse(oldJson);
      Map<String, JSONArray> oldPaths = getPathFilesMap(oldContext, oldJson);
      if (oldPaths != null) {
        saveAndDelete(oldPaths, newPaths, entityPath);
      } else {
        // schema and definition now have files
        newPaths.values().stream().forEach(v -> saveFiles(v, entityPath));
      }

    } else {
      newPaths.values().stream().forEach(v -> saveFiles(v, entityPath));
    }

    cleanup(newPaths, newContext);
    newEntity.setContent(newContext.jsonString());
  }
Exemple #3
0
  @Test
  public void issue_76() throws Exception {
    /*
    String json = "{\n" +
            "    \"cpus\": -8.88178419700125e-16,\n" +
            "    \"disk\": 0,\n" +
            "    \"mem\": 0\n" +
            "}";

    JSONParser parser = new JSONParser(JSONParser.MODE_PERMISSIVE);
    JSONAware jsonModel = (JSONAware)parser.parse(json);

    jsonModel.toJSONString(); //java.lang.RuntimeException: no Getter for field scale in class java.math.BigDecimal
    */

    DocumentContext doc = JsonPath.parse(this.getClass().getResourceAsStream("/issue_76.json"));

    Object o;
    o = doc.read("$.frameworks");

    // Bug filed  in json-smart
    // https://code.google.com/p/json-smart/issues/detail?id=55&thanks=55&ts=1427547500
    try {
      System.out.println(JSON_SMART_CONFIGURATION.jsonProvider().toJson(o));
      Assert.assertTrue(false);
    } catch (RuntimeException e) {
    }
  }
Exemple #4
0
 private static void printUsedConfig() {
   String config = System.getProperty("config.resource", "application.conf");
   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());
 }
 @Then("^the user should receive a specified JSON content$")
 public void jsonResponse() throws Exception {
   assertThat(response.getHeaders("Content-Type"))
       .extracting(Header::getValue)
       .containsExactly(org.apache.http.entity.ContentType.APPLICATION_JSON.toString());
   DocumentContext jsonPath = JsonPath.parse(response.getEntity().getContent());
   assertThat(jsonPath.<String>read("blobId")).isEqualTo(_1M_ZEROED_FILE_BLOB_ID);
   assertThat(jsonPath.<String>read("type")).isEqualTo("application/octet-stream");
   assertThat(jsonPath.<Integer>read("size")).isEqualTo(_1M);
 }
Exemple #6
0
  @Test
  public void issue_170() {

    String json = "{\n" + "  \"array\": [\n" + "    0,\n" + "    1,\n" + "    2\n" + "  ]\n" + "}";

    DocumentContext context = using(JACKSON_JSON_NODE_CONFIGURATION).parse(json);
    context = context.set("$.array[0]", null);
    context = context.set("$.array[2]", null);

    List<Integer> list = context.read("$.array", List.class);

    assertThat(list).containsExactly(null, 1, null);
  }
Exemple #7
0
  @Test
  public void issue_171() {

    String json = "{\n" + "  \"can delete\": \"this\",\n" + "  \"can't delete\": \"this\"\n" + "}";

    DocumentContext context = using(JACKSON_JSON_NODE_CONFIGURATION).parse(json);
    context.set("$.['can delete']", null);
    context.set("$.['can\\'t delete']", null);

    ObjectNode objectNode = context.read("$");

    assertThat(objectNode.get("can delete").isNull());
    assertThat(objectNode.get("can't delete").isNull());
  }
  private Map<String, JSONArray> getPathFilesMap(DocumentContext context, Object json) {
    DocumentContext reader =
        new JsonReader(defaultConfiguration().addOptions(Option.REQUIRE_PROPERTIES)).parse(json);

    JSONArray paths = null;
    try {
      paths = context.read("$..obibaFiles");
    } catch (PathNotFoundException e) {
      return null;
    }

    return paths
        .stream()
        .collect(Collectors.toMap(Object::toString, p -> (JSONArray) reader.read(p.toString())));
  }
  public void deleteFiles(SchemaFormContentAware entity) {
    Object json = defaultConfiguration().jsonProvider().parse(entity.getContent());
    DocumentContext context =
        JsonPath.using(defaultConfiguration().addOptions(Option.AS_PATH_LIST)).parse(json);
    DocumentContext reader =
        new JsonReader(defaultConfiguration().addOptions(Option.REQUIRE_PROPERTIES)).parse(json);

    try {
      ((JSONArray) context.read("$..obibaFiles"))
          .stream()
          .map(p -> (JSONArray) reader.read(p.toString()))
          .flatMap(Collection::stream)
          .forEach(file -> fileStoreService.delete(((LinkedHashMap) file).get("id").toString()));
    } catch (PathNotFoundException e) {
    }
  }
 /**
  * Removes the fields with empty obibaFiles from content.
  *
  * @param newPaths
  * @param newContext
  */
 private void cleanup(Map<String, JSONArray> newPaths, DocumentContext newContext) {
   newPaths
       .keySet()
       .stream()
       .forEach(
           p -> {
             if (newPaths.get(p).isEmpty()) {
               newContext.delete(p.replace("['obibaFiles']", ""));
             }
           });
 }
  @SuppressWarnings("unchecked")
  @Override
  public boolean apply(PredicateContext ctx) {
    final Map<String, Object> items = ctx.item(Map.class);

    if (items != null) {
      for (Map.Entry<String, Object> entry : items.entrySet()) {

        final String value = entry.getValue().toString();

        if (isVariable(value)) {

          final String variable = extractVariable(value);
          final Object newValue = lookupContext.read(variable);

          entry.setValue(newValue);
        }
      }

      return isRootElement(items);
    }

    return false;
  }