public String getCollectionPath() { return "/"+Kind.from(getType()).getModelName()+"s"; }
@Override public Class<T> getType() { return model.getKind().getModelClass(); } };
public void clearCache() { for (Kind kind : Kind.values()) { caches.getCache(kind.modelName).clear(); } }
public <T extends WithId<T>> void update(T entity) { Optional<String> id = entity.getId(); if (!id.isPresent()) { throw new EntityNotFoundException("Setting the id on the entity is required for updates"); } String idVal = id.get(); Kind kind = entity.getKind(); T previous = this.<T, T>doWithDataAccessObject(kind.getModelClass(), d -> d.update(entity)); Map<String, T> cache = caches.getCache(kind.getModelName()); if (!cache.containsKey(idVal) && previous==null) { throw new EntityNotFoundException("Can not find " + kind + " with id " + idVal); } cache.put(idVal, entity); broadcast("updated", kind.getModelName(), idVal); //TODO 1. properly merge the data ? + add data validation in the REST Resource }
private <T extends WithId<T>> void importModels(JsonDbDao<T> export, ArrayList<ChangeEvent> result) { for (T item : export.fetchAll().getItems()) { Kind kind = item.getKind(); String id = item.getId().get(); if (dataManager.fetch(export.getType(), id) == null) { dataManager.create(item); if( kind == Kind.Connection ) { connectionHandler.updateBulletinBoard(id); } result.add(ChangeEvent.of("created", kind.getModelName(), id)); } } }
public <T extends WithId<T>> T create(final T entity) { Kind kind = entity.getKind(); Map<String, T> cache = caches.getCache(kind.getModelName()); Optional<String> id = entity.getId(); String idVal; final T entityToCreate; if (!id.isPresent()) { idVal = KeyGenerator.createKey(); entityToCreate = entity.withId(idVal); } else { idVal = id.get(); if (cache.containsKey(idVal)) { throw new EntityExistsException("There already exists a " + kind + " with id " + idVal); } entityToCreate = entity; } this.<T, T>doWithDataAccessObject(kind.getModelClass(), d -> d.create(entityToCreate)); cache.put(idVal, entityToCreate); broadcast("created", kind.getModelName(), idVal); return entityToCreate; }
private void importIntegrations(SecurityContext sec, JsonDbDao<Integration> export, ArrayList<ChangeEvent> result) { for (Integration integration : export.fetchAll().getItems()) { Integration.Builder builder = new Integration.Builder() .createFrom(integration) .isDeleted(false) .updatedAt(System.currentTimeMillis()); // Do we need to create it? String id = integration.getId().get(); Integration previous = dataManager.fetch(Integration.class, id); if (previous == null) { LOG.info("Creating integration: {}", integration.getName()); integrationHandler.create(sec, builder.build()); result.add(ChangeEvent.of("created", integration.getKind().getModelName(), id)); } else { LOG.info("Updating integration: {}", integration.getName()); integrationHandler.update(id, builder.version(previous.getVersion()+1).build()); result.add(ChangeEvent.of("updated", integration.getKind().getModelName(), id)); } integrationHandler.updateBulletinBoard(id); break; } }
public String getCollectionPath() { return "/"+Kind.from(getType()).getModelName()+"s"; }
@DELETE @Consumes("application/json") @Path(value = "/{id}") default void delete(@NotNull @PathParam("id") @ApiParam(required = true) String id) { Class<T> modelClass = resourceKind().getModelClass(); getDataManager().delete(modelClass, id); }
public <T extends WithId<T>> T fetch(Class<T> model, String id) { Kind kind = Kind.from(model); Map<String, T> cache = caches.getCache(kind.getModelName()); T value = cache.get(id); if ( value == null) { value = doWithDataAccessObject(model, d -> d.fetch(id)); if (value != null) { cache.put(id, value); } } return value; }
@GET @Produces(MediaType.APPLICATION_JSON) @Path(value = "/{id}") default T get(@NotNull @PathParam("id") @ApiParam(required = true) String id) { Class<T> modelClass = resourceKind().getModelClass(); T result = getDataManager().fetch(modelClass, id); if( result == null ) { throw new EntityNotFoundException(); } return result; }
public <T extends WithId<T>> void deleteAll(Class<T> model) { Kind kind = Kind.from(model); Map<String, WithId<T>> cache = caches.getCache(kind.getModelName()); cache.clear(); doWithDataAccessObject(model, d -> { d.deleteAll(); return null; }); }
public <T extends WithId<T>> void store(ModelData<T> modelData) { try { final Kind kind = modelData.getKind(); final T entity = modelData.getData(); LOGGER.debug("{}:{}", kind, modelData.getDataAsJson()); store(entity, kind.getModelClass()); } catch (@SuppressWarnings("PMD.AvoidCatchingGenericException") Exception e) { LOGGER.warn("Cannot load entity from file: ", e); throw SyndesisServerException.launderThrowable(e); } }
public <T extends WithId<T>> boolean delete(Class<T> model, String id) { if (id == null || id.equals("")) { throw new EntityNotFoundException("Setting the id on the entity is required for updates"); } Kind kind = Kind.from(model); Map<String, WithId<T>> cache = caches.getCache(kind.getModelName()); // Remove it out of the cache WithId<T> entity = cache.remove(id); boolean deletedInCache = entity != null; // And out of the DAO boolean deletedFromDAO = Boolean.TRUE.equals(doWithDataAccessObject(model, d -> d.delete(id))); // Return true if the entity was found in any of the two. if ( deletedInCache || deletedFromDAO ) { broadcast("deleted", kind.getModelName(), id); return true; } return false; }
@PATCH @Path(value = "/{id}") @Consumes(MediaType.APPLICATION_JSON) default void patch(@NotNull @PathParam("id") @ApiParam(required = true) String id, @NotNull JsonNode patchJson) throws IOException { Class<T> modelClass = resourceKind().getModelClass(); final T existing = getDataManager().fetch(modelClass, id); if( existing == null ) { throw new EntityNotFoundException(); } JsonNode document = Json.reader().readTree(Json.writer().writeValueAsString(existing)); // Attempt to apply the patch... final JsonMergePatch patch; try { patch = JsonMergePatch.fromJson(patchJson); document = patch.apply(document); } catch (JsonPatchException e) { throw new WebApplicationException(e, Response.Status.BAD_REQUEST); } // Convert the Json back to an entity. T obj = Json.reader().forType(modelClass).readValue(Json.writer().writeValueAsBytes(document)); if (this instanceof Validating) { final Validator validator = ((Validating<?>) this).getValidator(); final Set<ConstraintViolation<T>> violations = validator.validate(obj, AllValidations.class); if (!violations.isEmpty()) { throw new ConstraintViolationException(violations); } } getDataManager().update(obj); }
@SafeVarargs @SuppressWarnings({"unchecked", "varargs"}) public final <T extends WithId<T>> ListResult<T> fetchAll(Class<T> model, Function<ListResult<T>, ListResult<T>>... operators) { ListResult<T> result; if (getDataAccessObject(model) != null) { return doWithDataAccessObject(model, d -> d.fetchAll(operators)); } else { Kind kind = Kind.from(model); Map<String, T> cache = caches.getCache(kind.getModelName()); result = ListResult.of(cache.values()); if (operators == null) { return result; } for (Function<ListResult<T>, ListResult<T>> operator : operators) { result = operator.apply(result); } return result; } }
@Override public ListResult<Integration> list(UriInfo uriInfo) { Class<Integration> clazz = resourceKind().getModelClass(); return getDataManager().fetchAll(Integration.class, new DeletedFilter(), new ReflectiveSorter<>(clazz, new SortOptionsFromQueryParams(uriInfo)), new PaginationFilter<>(new PaginationOptionsFromQueryParams(uriInfo)) ); }
@GET @Produces(MediaType.APPLICATION_JSON) @ApiImplicitParams({ @ApiImplicitParam( name = "sort", value = "Sort the result list according to the given field value", paramType = "query", dataType = "string"), @ApiImplicitParam( name = "direction", value = "Sorting direction when a 'sort' field is provided. Can be 'asc' " + "(ascending) or 'desc' (descending)", paramType = "query", dataType = "string"), @ApiImplicitParam( name = "page", value = "Page number to return", paramType = "query", dataType = "integer", defaultValue = "1"), @ApiImplicitParam( name = "per_page", value = "Number of records per page", paramType = "query", dataType = "integer", defaultValue = "20"), @ApiImplicitParam( name = "query", value = "The search query to filter results on", paramType = "query", dataType = "string"), }) default ListResult<T> list(@Context UriInfo uriInfo) { Class<T> clazz = resourceKind().getModelClass(); return getDataManager().fetchAll( clazz, new ReflectiveFilterer<>(clazz, new FilterOptionsFromQueryParams(uriInfo).getFilters()), new ReflectiveSorter<>(clazz, new SortOptionsFromQueryParams(uriInfo)), new PaginationFilter<>(new PaginationOptionsFromQueryParams(uriInfo)) ); }