protected ExampleServiceState updateState(Operation update) { // A DCP service handler is state-less: Everything it needs is provided as part of the // of the operation. The body and latest state associated with the service are retrieved // below. ExampleServiceState body = getBody(update); ExampleServiceState currentState = getState(update); // use helper that will merge automatically current state, with state supplied in body. // Note the usage option PropertyUsageOption.AUTO_MERGE_IF_NOT_NULL has been set on the // "name" field. boolean hasStateChanged = Utils.mergeWithState(getStateDescription(), currentState, body); updateCounter(body, currentState, hasStateChanged); if (body.documentExpirationTimeMicros != currentState.documentExpirationTimeMicros) { currentState.documentExpirationTimeMicros = body.documentExpirationTimeMicros; } // response has latest, updated state update.setBody(currentState); return currentState; }
private void handlePatchForStrictUpdate(Operation patch) { ExampleServiceState currentState = getState(patch); StrictUpdateRequest body = patch.getBody(StrictUpdateRequest.class); if (body.kind == null || !body.kind.equals(Utils.buildKind(StrictUpdateRequest.class))) { patch.fail(new IllegalArgumentException("invalid kind: %s" + body.kind)); return; } if (body.name == null) { patch.fail(new IllegalArgumentException("name is required")); return; } if (body.documentVersion != currentState.documentVersion) { String errorString = String .format("Current version %d. Request version %d", currentState.documentVersion, body.documentVersion); patch.fail(new IllegalArgumentException(errorString)); return; } currentState.name = body.name; patch.setBody(currentState); patch.complete(); }
@Override public void handleDelete(Operation delete) { if (!delete.hasBody()) { delete.complete(); return; } // A DELETE can be used to both stop the service, mark it deleted in the index // so its excluded from queries, but it can also set its expiration so its state // history is permanently removed ExampleServiceState currentState = getState(delete); ExampleServiceState st = delete.getBody(ExampleServiceState.class); if (st.documentExpirationTimeMicros > 0) { currentState.documentExpirationTimeMicros = st.documentExpirationTimeMicros; } delete.complete(); }
@Override @RouteDocumentation(description = "@PUT") public void handlePut(Operation put) { ExampleServiceState newState = getBody(put); ExampleServiceState currentState = getState(put); // example of structural validation: check if the new state is acceptable if (currentState.name != null && newState.name == null) { put.fail(new IllegalArgumentException("name must be set")); return; } updateCounter(newState, currentState, false); // replace current state, with the body of the request, in one step setState(put, newState); put.complete(); }