org.springframework.hateoas.Resource.<init>()方法的使用及代码示例

x33g5p2x  于2022-01-28 转载在 其他  
字(12.1k)|赞(0)|评价(0)|浏览(84)

本文整理了Java中org.springframework.hateoas.Resource.<init>方法的一些代码示例,展示了Resource.<init>的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Resource.<init>方法的具体详情如下:
包路径:org.springframework.hateoas.Resource
类名称:Resource
方法名:<init>

Resource.<init>介绍

[英]Creates an empty Resource.
[中]创建一个空资源。

代码示例

代码示例来源:origin: spring-projects/spring-hateoas

/**
 * 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;
}

代码示例来源:origin: spring-projects/spring-hateoas

/**
 * 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);
}

代码示例来源:origin: spring-projects/spring-hateoas

/**
 * 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);
}

代码示例来源:origin: spring-projects/spring-hateoas

@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);
}

代码示例来源:origin: spring-projects/spring-hateoas

/**
 * 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));
}

代码示例来源:origin: spring-projects/spring-hateoas

@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()));
  }
}

代码示例来源:origin: spring-projects/spring-data-rest

@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));
}

代码示例来源:origin: spring-projects/spring-data-rest

return new Resource<Object>(prop.propertyValue);

代码示例来源:origin: spring-projects/spring-data-rest

return ControllerUtils.toResponseEntity(HttpStatus.OK, null, new Resource<Object>(EMPTY_RESOURCE_LIST, links));

代码示例来源:origin: spring-projects/spring-hateoas

resource = new Resource<>(scalarValue, uberData.getLinks());
} else {
  resource = new Resource<>(obj, uberData.getLinks());

代码示例来源:origin: odrotbohm/spring-restbucks

/**
 * 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);
}

代码示例来源:origin: spring-projects/spring-hateoas

@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()));
}

代码示例来源:origin: spring-projects/spring-hateoas

@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()));
}

代码示例来源:origin: spring-projects/spring-data-rest

/**
   * 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());
  }
}

代码示例来源:origin: de.escalon.hypermedia/hydra-service

@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;
}

代码示例来源:origin: spring-projects/spring-hateoas-examples

@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);
  }
}

代码示例来源:origin: in28minutes/spring-boot-examples

@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;
}

代码示例来源:origin: in28minutes/spring-boot-examples

@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;
}

代码示例来源:origin: in28minutes/spring-boot-examples

@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;
}

代码示例来源:origin: kbastani/spring-boot-starter-amazon-s3

@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());
}

相关文章

微信公众号

最新文章

更多