com.github.fge.jsonpatch.JsonPatch Java Examples

The following examples show how to use com.github.fge.jsonpatch.JsonPatch. 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: TrafficControlIntegrationTest.java    From data-highway with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 20000)
public void inspect_updates_status_when_required() throws Exception {
  kafka.createTopic("test_topic2", 4, 1);
  JsonNode model = mapper
      .readTree(
          "{\"name\":\"test\",\"topicName\":\"test_topic2\",\"status\":{\"topicCreated\":true,\"partitions\":999,\"replicationFactor\":999}}");
  KafkaModelReader modelReader = context.getBean(KafkaModelReader.class);
  TrafficControl agent = context.getBean(TrafficControl.class);
  List<PatchOperation> operations = agent.inspectModel("test", modelReader.read(model));

  JsonNode message = mapper.convertValue(operations, JsonNode.class);
  model = JsonPatch.fromJson(message).apply(model);

  assertThat(model.get("status").get("topicCreated").asBoolean(), is(true));
  assertThat(model.get("status").get("partitions").asInt(), is(4));
  assertThat(model.get("status").get("replicationFactor").asInt(), is(1));
}
 
Example #2
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 #3
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 #4
Source File: CommandRestController.java    From genie with Apache License 2.0 6 votes vote down vote up
/**
 * Patch a command using JSON Patch.
 *
 * @param id    The id of the command to patch
 * @param patch The JSON Patch instructions
 * @throws NotFoundException           When no {@link Command} with the given {@literal id} exists
 * @throws PreconditionFailedException When {@literal id} and the {@literal updateCommand} id don't match
 * @throws GenieServerException        When the patch can't be applied
 */
@PatchMapping(value = "/{id}", consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.NO_CONTENT)
public void patchCommand(
    @PathVariable("id") final String id,
    @RequestBody final JsonPatch patch
) throws NotFoundException, PreconditionFailedException, GenieServerException {
    log.info("Called to patch command {} with patch {}", id, patch);

    final Command currentCommand = DtoConverters.toV3Command(this.persistenceService.getCommand(id));

    try {
        log.debug("Will patch cluster {}. Original state: {}", id, currentCommand);
        final JsonNode commandNode = GenieObjectMapper.getMapper().valueToTree(currentCommand);
        final JsonNode postPatchNode = patch.apply(commandNode);
        final Command patchedCommand = GenieObjectMapper.getMapper().treeToValue(postPatchNode, Command.class);
        log.debug("Finished patching command {}. New state: {}", id, patchedCommand);
        this.persistenceService.updateCommand(id, DtoConverters.toV4Command(patchedCommand));
    } catch (final JsonPatchException | IOException e) {
        log.error("Unable to patch command {} with patch {} due to exception.", id, patch, e);
        throw new GenieServerException(e.getLocalizedMessage(), e);
    }
}
 
Example #5
Source File: ClusterRestController.java    From genie with Apache License 2.0 6 votes vote down vote up
/**
 * Patch a cluster using JSON Patch.
 *
 * @param id    The id of the cluster to patch
 * @param patch The JSON Patch instructions
 * @throws NotFoundException           If no cluster with {@literal id} exists
 * @throws PreconditionFailedException If the ids don't match
 * @throws GenieServerException        If the patch can't be applied
 */
@PatchMapping(value = "/{id}", consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.NO_CONTENT)
public void patchCluster(
    @PathVariable("id") final String id,
    @RequestBody final JsonPatch patch
) throws NotFoundException, PreconditionFailedException, GenieServerException {
    log.info("[patchCluster] Called with id {} with patch {}", id, patch);

    final Cluster currentCluster = DtoConverters.toV3Cluster(this.persistenceService.getCluster(id));

    try {
        log.debug("Will patch cluster {}. Original state: {}", id, currentCluster);
        final JsonNode clusterNode = GenieObjectMapper.getMapper().valueToTree(currentCluster);
        final JsonNode postPatchNode = patch.apply(clusterNode);
        final Cluster patchedCluster = GenieObjectMapper.getMapper().treeToValue(postPatchNode, Cluster.class);
        log.debug("Finished patching cluster {}. New state: {}", id, patchedCluster);
        this.persistenceService.updateCluster(id, DtoConverters.toV4Cluster(patchedCluster));
    } catch (final JsonPatchException | IOException e) {
        log.error("Unable to patch cluster {} with patch {} due to exception.", id, patch, e);
        throw new GenieServerException(e.getLocalizedMessage(), e);
    }
}
 
Example #6
Source File: ApplicationRestController.java    From genie with Apache License 2.0 6 votes vote down vote up
/**
 * Patch an application using JSON Patch.
 *
 * @param id    The id of the application to patch
 * @param patch The JSON Patch instructions
 * @throws NotFoundException           If no application with the given id exists
 * @throws PreconditionFailedException When the id in the update doesn't match
 * @throws GenieServerException        If the patch can't be successfully applied
 */
@PatchMapping(value = "/{id}", consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.NO_CONTENT)
public void patchApplication(
    @PathVariable("id") final String id,
    @RequestBody final JsonPatch patch
) throws NotFoundException, PreconditionFailedException, GenieServerException {
    log.info("Called to patch application {} with patch {}", id, patch);
    final Application currentApp = DtoConverters.toV3Application(this.persistenceService.getApplication(id));

    try {
        log.debug("Will patch application {}. Original state: {}", id, currentApp);
        final JsonNode applicationNode = GenieObjectMapper.getMapper().valueToTree(currentApp);
        final JsonNode postPatchNode = patch.apply(applicationNode);
        final Application patchedApp = GenieObjectMapper.getMapper().treeToValue(postPatchNode, Application.class);
        log.debug("Finished patching application {}. New state: {}", id, patchedApp);
        this.persistenceService.updateApplication(id, DtoConverters.toV4Application(patchedApp));
    } catch (final JsonPatchException | IOException e) {
        log.error("Unable to patch application {} with patch {} due to exception.", id, patch, e);
        throw new GenieServerException(e.getLocalizedMessage(), e);
    }
}
 
Example #7
Source File: UserParams.java    From aerogear-unifiedpush-server with Apache License 2.0 6 votes vote down vote up
@Override
public JsonNode transform(JsonNode patched) throws IOException {
    Iterator<Map.Entry<String, JsonNode>> nodeIterator = patched.get("message").fields();
    while (nodeIterator.hasNext()) {
        Map.Entry<String, JsonNode> entry = nodeIterator.next();

        if (!KNOWN_KEYS.contains(entry.getKey())) {
            String json = format(MOVE_OP, entry.getKey());
            try {
                patched = JsonPatch.fromJson(JacksonUtils.getReader().readTree(json)).apply(patched);
            } catch (JsonPatchException e) {
                throw new RuntimeException("move operation could not be applied", e);
            }
        }
    }

    return patched;
}
 
Example #8
Source File: ApplicationClient.java    From genie with Apache License 2.0 5 votes vote down vote up
/**
 * Method to patch a application using json patch instructions.
 *
 * @param applicationId The id of the application.
 * @param patch         The patch object specifying all the instructions.
 * @throws GenieClientException For any other error.
 * @throws IOException          If the response received is not 2xx.
 */
public void patchApplication(final String applicationId, final JsonPatch patch)
    throws IOException, GenieClientException {
    if (StringUtils.isEmpty(applicationId)) {
        throw new IllegalArgumentException("Missing required parameter: applicationId.");
    }

    if (patch == null) {
        throw new IllegalArgumentException("Patch cannot be null");
    }

    this.applicationService.patchApplication(applicationId, patch).execute();
}
 
Example #9
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 #10
Source File: ClusterClient.java    From genie with Apache License 2.0 5 votes vote down vote up
/**
 * Method to patch a cluster using json patch instructions.
 *
 * @param clusterId The id of the cluster.
 * @param patch     The patch object specifying all the instructions.
 * @throws GenieClientException If the response received is not 2xx.
 * @throws IOException          For Network and other IO issues.
 */
public void patchCluster(final String clusterId, final JsonPatch patch) throws IOException, GenieClientException {
    if (StringUtils.isEmpty(clusterId)) {
        throw new IllegalArgumentException("Missing required parameter: clusterId.");
    }

    if (patch == null) {
        throw new IllegalArgumentException("Patch cannot be null");
    }

    clusterService.patchCluster(clusterId, patch).execute();
}
 
Example #11
Source File: CommandClient.java    From genie with Apache License 2.0 5 votes vote down vote up
/**
 * Method to patch a command using json patch instructions.
 *
 * @param commandId The id of the command.
 * @param patch     The patch object specifying all the instructions.
 * @throws GenieClientException If the response received is not 2xx.
 * @throws IOException          For Network and other IO issues.
 */
public void patchCommand(final String commandId, final JsonPatch patch) throws IOException, GenieClientException {
    if (StringUtils.isEmpty(commandId)) {
        throw new IllegalArgumentException("Missing required parameter: commandId.");
    }

    if (patch == null) {
        throw new IllegalArgumentException("Patch cannot be null");
    }

    commandService.patchCommand(commandId, patch).execute();
}
 
Example #12
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 #13
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 #14
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 #15
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 #16
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 #17
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 #18
Source File: UpdatePayload.java    From metacat with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new update payload.
 *
 * @param previous The previous version of the object that was updated
 * @param patch    The JSON patch to go from previous to current
 */
@JsonCreator
public UpdatePayload(
        @JsonProperty("previous") final T previous,
        @JsonProperty("patch") final JsonPatch patch
) {
    this.previous = previous;
    this.patch = patch;
}
 
Example #19
Source File: AbstractPersistenceManager.java    From FROST-Server with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public boolean update(PathElementEntity pathElement, JsonPatch patch) throws NoSuchEntityException, IncompleteEntityException {
    EntityChangedMessage result = doUpdate(pathElement, patch);
    if (result != null) {
        result.setEventType(EntityChangedMessage.Type.UPDATE);
        changedEntities.add(result);
    }
    return result != null;
}
 
Example #20
Source File: CustomerRestController.java    From tutorials with MIT License 4 votes vote down vote up
private Customer applyPatchToCustomer(JsonPatch patch, Customer targetCustomer) throws JsonPatchException, JsonProcessingException {
    JsonNode patched = patch.apply(objectMapper.convertValue(targetCustomer, JsonNode.class));
    return objectMapper.treeToValue(patched, Customer.class);
}
 
Example #21
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 #22
Source File: SNSNotificationServiceImpl.java    From metacat with Apache License 2.0 4 votes vote down vote up
private UpdateOrRenameTableMessageBase createUpdateorRenameTableMessage(
    final String id,
    final long timestamp,
    final String requestId,
    final QualifiedName name,
    final TableDto oldTable,
    final TableDto currentTable,
    final String exceptionMessage,
    final String metricName,
    final SNSMessageType messageType
) {
    try {
        final JsonPatch patch = JsonDiff.asJsonPatch(
            this.mapper.valueToTree(oldTable),
            this.mapper.valueToTree(currentTable)
        );
        if (messageType == SNSMessageType.TABLE_UPDATE) {
            return new UpdateTableMessage(
                id,
                timestamp,
                requestId,
                name.toString(),
                new UpdatePayload<>(oldTable, patch)
            );
        } else {
            return new RenameTableMessage(
                id,
                timestamp,
                requestId,
                name.toString(),
                new UpdatePayload<>(oldTable, patch)
            );
        }
    } catch (final Exception e) {
        this.notificationMetric.handleException(
            name,
            exceptionMessage,
            metricName,
            null,
            e
        );
    }
    return null;
}
 
Example #23
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);
}
 
Example #24
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 #25
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 #26
Source File: PersistenceManager.java    From FROST-Server with GNU Lesser General Public License v3.0 2 votes vote down vote up
/**
 * Update the given entity using the given (rfc6902) JSON Patch.
 *
 * @param pathElement The path to the entity.
 * @param patch The patch to apply to the entity.
 * @return True if the update was successful.
 * @throws NoSuchEntityException If the entity does not exist.
 * @throws IncompleteEntityException If the patch would cause the given
 * entity to lack required fields.
 */
public boolean update(PathElementEntity pathElement, JsonPatch patch) throws NoSuchEntityException, IncompleteEntityException;
 
Example #27
Source File: AbstractPersistenceManager.java    From FROST-Server with GNU Lesser General Public License v3.0 2 votes vote down vote up
/**
 * Update the given entity and return a message with the entity and fields
 * that were changed.
 *
 * @param pathElement The path to the entity to update.
 * @param patch The patch to apply to the entity.
 * @return A message with the entity and the fields that were changed.
 * @throws NoSuchEntityException If the entity does not exist.
 * @throws IncompleteEntityException If the entity does not have all the
 * required fields.
 */
public abstract EntityChangedMessage doUpdate(PathElementEntity pathElement, JsonPatch patch) throws NoSuchEntityException, IncompleteEntityException;
 
Example #28
Source File: ApplicationService.java    From genie with Apache License 2.0 2 votes vote down vote up
/**
 * Patch a application using JSON Patch.
 *
 * @param applicationId The id of the application to patch
 * @param patch         The JSON Patch instructions
 * @return A callable object.
 */
@PATCH(APPLICATION_URL_SUFFIX + "/{id}")
Call<Void> patchApplication(@Path("id") String applicationId, @Body JsonPatch patch);
 
Example #29
Source File: CommandService.java    From genie with Apache License 2.0 2 votes vote down vote up
/**
 * Patch a command using JSON Patch.
 *
 * @param commandId The id of the command to patch
 * @param patch     The JSON Patch instructions
 * @return A callable object.
 */
@PATCH(COMMAND_URL_SUFFIX + "/{id}")
Call<Void> patchCommand(@Path("id") String commandId, @Body JsonPatch patch);
 
Example #30
Source File: ClusterService.java    From genie with Apache License 2.0 2 votes vote down vote up
/**
 * Patch a cluster using JSON Patch.
 *
 * @param clusterId The id of the cluster to patch
 * @param patch     The JSON Patch instructions
 * @return A callable object.
 */
@PATCH(CLUSTER_URL_SUFFIX + "/{id}")
Call<Void> patchCluster(@Path("id") String clusterId, @Body JsonPatch patch);