/** * Converts the given entity into a {@link Resource}. * * @param entity * @return */ default Resource<T> toResource(T entity) { Resource<T> resource = new Resource<>(entity); addLinks(resource); return resource; }
/** * Creates a new {@link Resources} instance by wrapping the given domain class instances into a {@link Resource}. * * @param content must not be {@literal null}. * @return */ @SuppressWarnings("unchecked") public static <T extends Resource<S>, S> Resources<T> wrap(Iterable<S> content) { Assert.notNull(content, "Content must not be null!"); ArrayList<T> resources = new ArrayList<>(); for (S element : content) { resources.add((T) new Resource<>(element)); } return new Resources<>(resources); }
/** * Factory method to easily create a {@link PagedResources} instance from a set of entities and pagination metadata. * * @param content must not be {@literal null}. * @param metadata * @return */ @SuppressWarnings("unchecked") public static <T extends Resource<S>, S> PagedResources<T> wrap(Iterable<S> content, PageMetadata metadata) { Assert.notNull(content, "Content must not be null!"); ArrayList<T> resources = new ArrayList<>(); for (S element : content) { resources.add((T) new Resource<>(element)); } return new PagedResources<>(resources, metadata); }
@NotNull private Resource<Object> convertToResource(UberData uberData, List<Link> links) { // Primitive type List<UberData> data = uberData.getData(); if (isPrimitiveType(data)) { Object scalarValue = data.get(0).getValue(); return new Resource<>(scalarValue, links); } Map<String, Object> properties; if (data == null) { properties = new HashMap<>(); } else { properties = data.stream().collect(Collectors.toMap(UberData::getName, UberData::getValue)); } JavaType rootType = JacksonHelper.findRootType(this.contentType); Object value = PropertyUtils.createObjectFromProperties(rootType.getRawClass(), properties); return new Resource<>(value, links); }
/** * Extract links and content from an object of any type. */ private static List<UberData> doExtractLinksAndContent(Object item) { if (item instanceof Resource) { return extractLinksAndContent((Resource<?>) item); } if (item instanceof ResourceSupport) { return extractLinksAndContent((ResourceSupport) item); } return extractLinksAndContent(new Resource<>(item)); }
@Override public Resource<?> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { JavaType rootType = JacksonHelper.findRootType(this.contentType); JavaType wrappedType = ctxt.getTypeFactory().constructParametricType(CollectionJsonDocument.class, rootType); CollectionJsonDocument<?> document = jp.getCodec().readValue(jp, wrappedType); List<? extends CollectionJsonItem<?>> items = Optional.ofNullable(document.getCollection().getItems()).orElse(new ArrayList<>()); List<Link> links = Optional.ofNullable(document.getCollection().getLinks()).orElse(new ArrayList<>()); if (items.size() == 0 && document.getCollection().getTemplate() != null) { Map<String, Object> properties = document.getCollection().getTemplate().getData().stream() .collect(Collectors.toMap(CollectionJsonData::getName, CollectionJsonData::getValue)); Object obj = PropertyUtils.createObjectFromProperties(rootType.getRawClass(), properties); return new Resource<>(obj, potentiallyAddSelfLink(links, document.getCollection().getHref())); } else { items.stream() .flatMap(item -> Optional.ofNullable(item.getLinks()) .map(Collection::stream) .orElse(Stream.empty())) .forEach(link -> { if (!links.contains(link)) links.add(link); }); return new Resource<>(items.get(0).toRawData(rootType), potentiallyAddSelfLink(links, items.get(0).getHref())); } }
@RequestMapping(value = BASE_MAPPING, method = GET) public ResponseEntity<ResourceSupport> followPropertyReference(final RootResourceInformation repoRequest, @BackendId Serializable id, final @PathVariable String property, final PersistentEntityResourceAssembler assembler) throws Exception { HttpHeaders headers = new HttpHeaders(); Function<ReferencedProperty, ResourceSupport> handler = prop -> prop.mapValue(it -> { if (prop.property.isCollectionLike()) { return toResources((Iterable<?>) it, assembler, prop.propertyType, Optional.empty()); } else if (prop.property.isMap()) { Map<Object, Resource<?>> resources = new HashMap<Object, Resource<?>>(); for (Map.Entry<Object, Object> entry : ((Map<Object, Object>) it).entrySet()) { resources.put(entry.getKey(), assembler.toResource(entry.getValue())); } return new Resource<Object>(resources); } else { PersistentEntityResource resource = assembler.toResource(it); headers.set("Content-Location", resource.getId().getHref()); return resource; } }).orElseThrow(() -> new ResourceNotFoundException()); return ControllerUtils.toResponseEntity(HttpStatus.OK, headers, // doWithReferencedProperty(repoRequest, id, property, handler, HttpMethod.GET)); }
return new Resource<Object>(prop.propertyValue);
return ControllerUtils.toResponseEntity(HttpStatus.OK, null, new Resource<Object>(EMPTY_RESOURCE_LIST, links));
/** * Renders the given {@link Receipt} including links to the associated {@link Order} as well as a self link in case * the {@link Receipt} is still available. * * @param receipt * @return */ private HttpEntity<Resource<Receipt>> createReceiptResponse(Receipt receipt) { Order order = receipt.getOrder(); Resource<Receipt> resource = new Resource<>(receipt); resource.add(entityLinks.linkToSingleResource(order)); if (!order.isTaken()) { resource.add(entityLinks.linkForSingleResource(order).slash("receipt").withSelfRel()); } return ResponseEntity.ok(resource); }
@Override public PagedResources deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { JavaType rootType = JacksonHelper.findRootType(this.contentType); JavaType wrappedType = ctxt.getTypeFactory().constructParametricType(CollectionJsonDocument.class, rootType); CollectionJsonDocument<?> document = jp.getCodec().readValue(jp, wrappedType); List<Object> items = new ArrayList<>(); document.getCollection().getItems().forEach(item -> { Object data = item.toRawData(rootType); List<Link> links = item.getLinks() == null ? Collections.EMPTY_LIST : item.getLinks(); if (this.contentType.hasGenericTypes()) { if (this.contentType.containedType(0).hasRawClass(Resource.class)) { items.add(new Resource<>(data, potentiallyAddSelfLink(links, item.getHref()))); } else { items.add(data); } } }); PagedResources.PageMetadata pageMetadata = null; return new PagedResources(items, pageMetadata, potentiallyAddSelfLink(document.getCollection().getLinks(), document.getCollection().getHref())); }
@Override public Resources deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { JavaType rootType = JacksonHelper.findRootType(this.contentType); JavaType wrappedType = ctxt.getTypeFactory().constructParametricType(CollectionJsonDocument.class, rootType); CollectionJsonDocument<?> document = jp.getCodec().readValue(jp, wrappedType); List<Object> contentList = new ArrayList<>(); if (document.getCollection().getItems() != null) { for (CollectionJsonItem<?> item : document.getCollection().getItems()) { Object data = item.toRawData(rootType); if (this.contentType.hasGenericTypes()) { if (isResource(this.contentType)) { contentList.add(new Resource<>(data, potentiallyAddSelfLink(item.getLinks(), item.getHref()))); } else { contentList.add(data); } } } } return new Resources(contentList, potentiallyAddSelfLink(document.getCollection().getLinks(), document.getCollection().getHref())); }
/** * Creates a {@link ProjectionResource} for the given {@link TargetAware}. * * @param value must not be {@literal null}. * @return */ private ProjectionResource toResource(TargetAware value) { Object target = value.getTarget(); ResourceMetadata metadata = associations.getMetadataFor(value.getTargetClass()); Links links = metadata.isExported() ? collector.getLinksFor(target) : new Links(); Resource<TargetAware> resource = invoker.invokeProcessorsFor(new Resource<TargetAware>(value, links)); return new ProjectionResource(resource.getContent(), resource.getLinks()); } }
@JsonCreator public Event(@JsonProperty("performer") String performer, @JsonProperty("workPerformed") CreativeWork workPerformed, @JsonProperty("location") String location, @JsonProperty("eventStatus") @Select() EventStatusType eventStatus) { this.id = 0; this.performer = performer; this.location = location; this.workPerformed = new Resource<CreativeWork>(workPerformed); this.eventStatus = eventStatus; }
@GetMapping(value = "/supervisors/{id}", produces = MediaTypes.HAL_JSON_VALUE) public ResponseEntity<Resource<Supervisor>> findOne(@PathVariable Long id) { Resource<Manager> managerResource = controller.findOne(id).getBody(); Resource<Supervisor> supervisorResource = new Resource<>( new Supervisor(managerResource.getContent()), managerResource.getLinks()); return ResponseEntity.ok(supervisorResource); } }
@GetMapping("/students/{id}") @ApiOperation(value = "Find student by id", notes = "Also returns a link to retrieve all students with rel - all-students") public Resource<Student> retrieveStudent(@PathVariable long id) { Optional<Student> student = studentRepository.findById(id); if (!student.isPresent()) throw new StudentNotFoundException("id-" + id); Resource<Student> resource = new Resource<Student>(student.get()); ControllerLinkBuilder linkTo = linkTo(methodOn(this.getClass()).retrieveAllStudents()); resource.add(linkTo.withRel("all-students")); return resource; }
@GetMapping("/students/{id}") public Resource<Student> retrieveStudent(@PathVariable long id) { Optional<Student> student = studentRepository.findById(id); if (!student.isPresent()) throw new StudentNotFoundException("id-" + id); Resource<Student> resource = new Resource<Student>(student.get()); ControllerLinkBuilder linkTo = linkTo(methodOn(this.getClass()).retrieveAllStudents()); resource.add(linkTo.withRel("all-students")); return resource; }
@GetMapping("/students/{id}") public Resource<Student> retrieveStudent(@PathVariable long id) { Optional<Student> student = studentRepository.findById(id); if (!student.isPresent()) throw new StudentNotFoundException("id-" + id); Resource<Student> resource = new Resource<Student>(student.get()); ControllerLinkBuilder linkTo = linkTo(methodOn(this.getClass()).retrieveAllStudents()); resource.add(linkTo.withRel("all-students")); return resource; }
@RequestMapping(method = RequestMethod.GET) public List<Resource<S3ObjectSummary>> getBucketResources() { ObjectListing objectListing = amazonS3Template.getAmazonS3Client() .listObjects(new ListObjectsRequest() .withBucketName(bucketName)); return objectListing.getObjectSummaries() .stream() .map(a -> new Resource<>(a, new Link(String.format("https://s3.amazonaws.com/%s/%s", a.getBucketName(), a.getKey())).withRel("url"))) .collect(Collectors.toList()); }