Java Code Examples for com.github.fge.jsonpatch.JsonPatch#fromJson()

The following examples show how to use com.github.fge.jsonpatch.JsonPatch#fromJson() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TollBoothHiveDestinationAdminClientTest.java    From data-highway with Apache License 2.0 6 votes vote down vote up
@Before
public void before() {
  PatchSetEmitter modificationEmitter = new PatchSetEmitter() {
    @Override
    public void emit(PatchSet roadPatch) {
      try {
        JsonNode roadJson = Optional
            .ofNullable(store.get(roadPatch.getDocumentId()))
            .map(r -> mapper.convertValue(r, JsonNode.class))
            .orElse(NullNode.instance);
        JsonNode patchJson = mapper.convertValue(roadPatch.getOperations(), JsonNode.class);
        JsonPatch jsonPatch = JsonPatch.fromJson(patchJson);
        JsonNode newRoadJson = jsonPatch.apply(roadJson);
        Road nnewRoad = mapper.convertValue(newRoadJson, Road.class);
        store.put(roadPatch.getDocumentId(), nnewRoad);
      } catch (IOException | JsonPatchException e) {
        throw new RuntimeException(e);
      }
    }
  };
  underTest = new TollBoothHiveDestinationAdminClient(store, modificationEmitter);

}
 
Example 2
Source File: ApplicationClientIntegrationTest.java    From genie with Apache License 2.0 6 votes vote down vote up
@Test
void testApplicationPatchMethod() throws Exception {
    final ObjectMapper mapper = GenieObjectMapper.getMapper();
    final String newName = UUID.randomUUID().toString();
    final String patchString = "[{ \"op\": \"replace\", \"path\": \"/name\", \"value\": \"" + newName + "\" }]";
    final JsonPatch patch = JsonPatch.fromJson(mapper.readTree(patchString));

    final Application application = this.constructApplicationDTO("application1");

    final String appId = this.applicationClient.createApplication(application);
    this.applicationClient.patchApplication(appId, patch);

    Assertions
        .assertThat(this.applicationClient.getApplication(appId))
        .extracting(Application::getName)
        .isEqualTo(newName);
}
 
Example 3
Source File: JsonPatchApplier.java    From data-highway with Apache License 2.0 5 votes vote down vote up
public JsonNode apply(JsonNode document, List<PatchOperation> patchOperations) throws PatchApplicationException {
  try {
    JsonNode patch = mapper.convertValue(patchOperations, JsonNode.class);
    JsonPatch jsonPatch = JsonPatch.fromJson(patch);

    return jsonPatch.apply(document);
  } catch (IOException | JsonPatchException e) {
    String message = String.format("Unable to apply patch to document. document: %s, patch: %s", document,
        patchOperations);
    throw new PatchApplicationException(message, e);
  }
}
 
Example 4
Source File: MemoryRoadAdminClient.java    From data-highway with Apache License 2.0 5 votes vote down vote up
JsonNode applyPatch(JsonNode road, PatchSet patch) {
  try {
    JsonNode jsonNodePatch = mapper.convertValue(patch.getOperations(), JsonNode.class);
    JsonPatch jsonPatch = JsonPatch.fromJson(jsonNodePatch);
    return jsonPatch.apply(road);
  } catch (IOException | JsonPatchException e) {
    throw new ServiceException(e);
  }
}
 
Example 5
Source File: TollboothRoadAdminClientTest.java    From data-highway with Apache License 2.0 5 votes vote down vote up
@Before
public void before() {
  road1 = new Road();
  road1.setName("road1");
  road1.setTopicName("road1");
  road1.setDescription("description");
  road1.setContactEmail("contactEmail");
  road1.setEnabled(false);
  status = new KafkaStatus();
  status.setTopicCreated(false);
  road1.setStatus(status);
  road1.setDeleted(false);

  PatchSetEmitter patchSetEmitter = new PatchSetEmitter() {

    @Override
    public void emit(PatchSet patchSet) {
      try {
        JsonNode roadJson = Optional
            .ofNullable(store.get(patchSet.getDocumentId()))
            .map(r -> mapper.convertValue(r, JsonNode.class))
            .orElse(NullNode.instance);
        JsonNode patchJson = mapper.convertValue(patchSet.getOperations(), JsonNode.class);
        JsonPatch jsonPatch = JsonPatch.fromJson(patchJson);
        JsonNode newRoadJson = jsonPatch.apply(roadJson);
        Road nnewRoad = mapper.convertValue(newRoadJson, Road.class);
        store.put(patchSet.getDocumentId(), nnewRoad);
      } catch (IOException | JsonPatchException e) {
        throw new RuntimeException(e);
      }
    }
  };

  store = new HashMap<>();
  client = new TollboothRoadAdminClient(Collections.unmodifiableMap(store), patchSetEmitter);
}
 
Example 6
Source File: BuildConfigurationPatchTest.java    From pnc with Apache License 2.0 5 votes vote down vote up
private BuildConfiguration applyPatch(BuildConfiguration buildConfiguration, String patchString)
        throws IOException, JsonPatchException {
    logger.info("Original: " + mapper.writeValueAsString(buildConfiguration));
    logger.info("Json patch:" + patchString);
    JsonPatch patch = JsonPatch.fromJson(mapper.readValue(patchString, JsonNode.class));
    JsonNode result = patch.apply(mapper.valueToTree(buildConfiguration));
    logger.info("Patched: " + mapper.writeValueAsString(result));
    return mapper.treeToValue(result, BuildConfiguration.class);
}
 
Example 7
Source File: BuildConfigurationSerializationTest.java    From pnc with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldPatchBuildConfiguration() throws PatchBuilderException, IOException, JsonPatchException {
    ObjectMapper mapper = ObjectMapperProvider.getInstance();

    // given
    Instant now = Instant.now();
    Map<String, String> initialParameters = Collections.singletonMap("KEY", "VALUE");
    BuildConfiguration buildConfiguration = BuildConfiguration.builder()
            .id("1")
            .name("name")
            .creationTime(now)
            .parameters(initialParameters)
            .build();

    // when
    BuildConfigurationPatchBuilder patchBuilder = new BuildConfigurationPatchBuilder();
    patchBuilder.replaceName("new name");
    Map<String, String> newParameter = Collections.singletonMap("KEY 2", "VALUE 2");
    patchBuilder.addParameters(newParameter);

    JsonNode targetJson = mapper.valueToTree(buildConfiguration);
    JsonPatch patch = JsonPatch.fromJson(mapper.readValue(patchBuilder.getJsonPatch(), JsonNode.class));
    JsonNode result = patch.apply(targetJson);

    // then
    BuildConfiguration deserialized = mapper.treeToValue(result, BuildConfiguration.class);
    Assert.assertEquals(now, deserialized.getCreationTime());
    Assert.assertEquals("new name", deserialized.getName());

    Map<String, String> finalParameters = new HashMap<>(initialParameters);
    finalParameters.putAll(newParameter);
    assertThat(deserialized.getParameters()).containsAllEntriesOf(finalParameters);
}
 
Example 8
Source File: CommandClientIntegrationTest.java    From genie with Apache License 2.0 5 votes vote down vote up
@Test
void testCommandPatchMethod() throws Exception {
    final ObjectMapper mapper = GenieObjectMapper.getMapper();
    final String newName = UUID.randomUUID().toString();
    final String patchString = "[{ \"op\": \"replace\", \"path\": \"/name\", \"value\": \"" + newName + "\" }]";
    final JsonPatch patch = JsonPatch.fromJson(mapper.readTree(patchString));

    final Command command = this.constructCommandDTO(null);

    final String commandId = this.commandClient.createCommand(command);
    this.commandClient.patchCommand(commandId, patch);

    Assertions.assertThat(this.commandClient.getCommand(commandId).getName()).isEqualTo(newName);
}
 
Example 9
Source File: ClusterClientIntegrationTest.java    From genie with Apache License 2.0 5 votes vote down vote up
@Test
void testClusterPatchMethod() throws Exception {
    final ObjectMapper mapper = GenieObjectMapper.getMapper();
    final String newName = UUID.randomUUID().toString();
    final String patchString = "[{ \"op\": \"replace\", \"path\": \"/name\", \"value\": \"" + newName + "\" }]";
    final JsonPatch patch = JsonPatch.fromJson(mapper.readTree(patchString));

    final Cluster cluster = new Cluster.Builder("name", "user", "1.0", ClusterStatus.UP).build();

    final String clusterId = this.clusterClient.createCluster(cluster);
    this.clusterClient.patchCluster(clusterId, patch);

    Assertions.assertThat(this.clusterClient.getCluster(clusterId).getName()).isEqualTo(newName);
}
 
Example 10
Source File: TollboothSchemaStoreClientTest.java    From data-highway with Apache License 2.0 4 votes vote down vote up
@Before
public void before() {
  mapper.registerModule(new SchemaSerializationModule());

  road1 = new Road();
  road1.setName("road1");
  road1.setTopicName("road1");
  road1.setDescription("description");
  road1.setContactEmail("contactEmail");
  road1.setEnabled(false);
  status = new KafkaStatus();
  status.setTopicCreated(false);
  road1.setStatus(status);
  road1.setSchemas(Collections.emptyMap());
  road1.setDeleted(false);

  schema1 = SchemaBuilder.builder().record("a").fields().name("v").type().booleanType().noDefault().endRecord();
  schema2 = SchemaBuilder
      .builder()
      .record("a")
      .fields()
      .name("v")
      .type()
      .booleanType()
      .booleanDefault(false)
      .endRecord();
  schema3 = SchemaBuilder
      .builder()
      .record("a")
      .fields()
      .name("v")
      .type()
      .booleanType()
      .booleanDefault(false)
      .optionalString("u")
      .endRecord();
  schema4 = SchemaBuilder
      .builder()
      .record("a")
      .fields()
      .name("v")
      .type()
      .booleanType()
      .booleanDefault(false)
      .requiredString("u")
      .endRecord();

  schemaVersion1 = new SchemaVersion(schema1, 1, false);
  schemaVersion2 = new SchemaVersion(schema2, 2, false);
  schemaVersion3 = new SchemaVersion(schema3, 3, false);

  schemaVersionsMap = ImmutableMap.of(schemaVersion1.getVersion(), schemaVersion1, schemaVersion2.getVersion(),
      schemaVersion2, schemaVersion3.getVersion(), schemaVersion3);

  PatchSetEmitter patchSetEmitter = new PatchSetEmitter() {

    @Override
    public void emit(PatchSet patchSet) {
      try {
        JsonNode roadJson = Optional
            .ofNullable(store.get(patchSet.getDocumentId()))
            .map(r -> mapper.convertValue(r, JsonNode.class))
            .orElse(NullNode.instance);
        JsonNode patchJson = mapper.convertValue(patchSet.getOperations(), JsonNode.class);
        JsonPatch jsonPatch = JsonPatch.fromJson(patchJson);
        JsonNode newRoadJson = jsonPatch.apply(roadJson);
        Road nnewRoad = mapper.convertValue(newRoadJson, Road.class);
        store.put(patchSet.getDocumentId(), nnewRoad);
      } catch (IOException | JsonPatchException e) {
        throw new RuntimeException(e);
      }
    }
  };

  store = new HashMap<>();
  store.put("road1", road1);

  client = new TollboothSchemaStoreClient(Collections.unmodifiableMap(store), patchSetEmitter);
}
 
Example 11
Source File: ApplicationRestControllerIntegrationTest.java    From genie with Apache License 2.0 4 votes vote down vote up
@Test
void canPatchApplication() throws Exception {
    final String id = this.createConfigResource(
        new Application.Builder(NAME, USER, VERSION, ApplicationStatus.ACTIVE).withId(ID).build(),
        null
    );
    final String applicationResource = APPLICATIONS_API + "/{id}";
    RestAssured
        .given(this.getRequestSpecification())
        .when()
        .port(this.port)
        .get(applicationResource, id)
        .then()
        .statusCode(Matchers.is(HttpStatus.OK.value()))
        .contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
        .body(USER_PATH, Matchers.is(USER));

    final String newUser = UUID.randomUUID().toString();
    final String patchString = "[{ \"op\": \"replace\", \"path\": \"/user\", \"value\": \"" + newUser + "\" }]";
    final JsonPatch patch = JsonPatch.fromJson(GenieObjectMapper.getMapper().readTree(patchString));

    final RestDocumentationFilter patchFilter = RestAssuredRestDocumentation.document(
        "{class-name}/{method-name}/{step}/",
        Snippets.CONTENT_TYPE_HEADER, // request headers
        Snippets.ID_PATH_PARAM, // path params
        Snippets.PATCH_FIELDS // request payload
    );

    RestAssured
        .given(this.getRequestSpecification())
        .filter(patchFilter)
        .contentType(MediaType.APPLICATION_JSON_VALUE)
        .body(GenieObjectMapper.getMapper().writeValueAsBytes(patch))
        .when()
        .port(this.port)
        .patch(applicationResource, id)
        .then()
        .statusCode(Matchers.is(HttpStatus.NO_CONTENT.value()));

    RestAssured
        .given(this.getRequestSpecification())
        .when()
        .port(this.port)
        .get(applicationResource, id)
        .then()
        .statusCode(Matchers.is(HttpStatus.OK.value()))
        .contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
        .body(USER_PATH, Matchers.is(newUser));

    Assertions.assertThat(this.applicationRepository.count()).isEqualTo(1L);
}
 
Example 12
Source File: CommandRestControllerIntegrationTest.java    From genie with Apache License 2.0 4 votes vote down vote up
@Test
void canPatchCommand() throws Exception {
    final String id = this.createConfigResource(
        new Command
            .Builder(NAME, USER, VERSION, CommandStatus.ACTIVE, EXECUTABLE_AND_ARGS, CHECK_DELAY)
            .withId(ID)
            .build(),
        null
    );
    final String commandResource = COMMANDS_API + "/{id}";
    RestAssured
        .given(this.getRequestSpecification())
        .when()
        .port(this.port)
        .get(commandResource, id)
        .then()
        .statusCode(Matchers.is(HttpStatus.OK.value()))
        .contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
        .body(NAME_PATH, Matchers.is(NAME));

    final String newName = UUID.randomUUID().toString();
    final String patchString = "[{ \"op\": \"replace\", \"path\": \"/name\", \"value\": \"" + newName + "\" }]";
    final JsonPatch patch = JsonPatch.fromJson(GenieObjectMapper.getMapper().readTree(patchString));

    final RestDocumentationFilter patchFilter = RestAssuredRestDocumentation.document(
        "{class-name}/{method-name}/{step}/",
        Snippets.CONTENT_TYPE_HEADER, // request headers
        Snippets.ID_PATH_PARAM, // path params
        Snippets.PATCH_FIELDS // request payload
    );

    RestAssured
        .given(this.getRequestSpecification())
        .filter(patchFilter)
        .contentType(MediaType.APPLICATION_JSON_VALUE)
        .body(GenieObjectMapper.getMapper().writeValueAsBytes(patch))
        .when()
        .port(this.port)
        .patch(commandResource, id)
        .then()
        .statusCode(Matchers.is(HttpStatus.NO_CONTENT.value()));

    RestAssured
        .given(this.getRequestSpecification())
        .when()
        .port(this.port)
        .get(commandResource, id)
        .then()
        .statusCode(Matchers.is(HttpStatus.OK.value()))
        .contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
        .body(NAME_PATH, Matchers.is(newName));

    Assertions.assertThat(this.commandRepository.count()).isEqualTo(1L);
}
 
Example 13
Source File: ClusterRestControllerIntegrationTest.java    From genie with Apache License 2.0 4 votes vote down vote up
@Test
void canPatchCluster() throws Exception {
    final String id = this.createConfigResource(
        new Cluster.Builder(NAME, USER, VERSION, ClusterStatus.UP).withId(ID).build(),
        null
    );
    final String clusterResource = CLUSTERS_API + "/{id}";

    RestAssured
        .given(this.getRequestSpecification())
        .when()
        .port(this.port)
        .get(clusterResource, id)
        .then()
        .statusCode(Matchers.is(HttpStatus.OK.value()))
        .contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
        .body(NAME_PATH, Matchers.is(NAME));

    final String newName = UUID.randomUUID().toString();
    final String patchString = "[{ \"op\": \"replace\", \"path\": \"/name\", \"value\": \"" + newName + "\" }]";
    final JsonPatch patch = JsonPatch.fromJson(GenieObjectMapper.getMapper().readTree(patchString));

    final RestDocumentationFilter patchFilter = RestAssuredRestDocumentation.document(
        "{class-name}/{method-name}/{step}/",
        Snippets.CONTENT_TYPE_HEADER, // request headers
        Snippets.ID_PATH_PARAM, // path params
        Snippets.PATCH_FIELDS // request payload
    );

    RestAssured
        .given(this.getRequestSpecification())
        .filter(patchFilter)
        .contentType(MediaType.APPLICATION_JSON_VALUE)
        .body(GenieObjectMapper.getMapper().writeValueAsBytes(patch))
        .when()
        .port(this.port)
        .patch(clusterResource, id)
        .then()
        .statusCode(Matchers.is(HttpStatus.NO_CONTENT.value()));

    RestAssured
        .given(this.getRequestSpecification())
        .when()
        .port(this.port)
        .get(clusterResource, id)
        .then()
        .statusCode(Matchers.is(HttpStatus.OK.value()))
        .contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
        .body(NAME_PATH, Matchers.is(newName));

    Assertions.assertThat(this.clusterRepository.count()).isEqualTo(1L);
}