org.springframework.hateoas.Resources Java Examples

The following examples show how to use org.springframework.hateoas.Resources. 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: RecentTacosController.java    From spring-in-action-5-samples with Apache License 2.0 6 votes vote down vote up
@GetMapping(path="/tacos/recent", produces="application/hal+json")
public Mono<ResponseEntity<Resources<TacoResource>>> recentTacos() {
  return tacoRepo.findAll()
      .take(12)
      .collectList()
      .map(tacos -> {
        List<TacoResource> tacoResources = 
            new TacoResourceAssembler().toResources(tacos);
        Resources<TacoResource> recentResources = 
                new Resources<TacoResource>(tacoResources);
        
        recentResources.add(
            linkTo(methodOn(RecentTacosController.class).recentTacos())
                .withRel("recents"));
        return new ResponseEntity<>(recentResources, HttpStatus.OK);
      });
}
 
Example #2
Source File: TacoCloudClient.java    From spring-in-action-5-samples with Apache License 2.0 6 votes vote down vote up
public Iterable<Taco> getRecentTacosWithTraverson() {
    ParameterizedTypeReference<Resources<Taco>> tacoType =
        new ParameterizedTypeReference<Resources<Taco>>() {};

    Resources<Taco> tacoRes =
        traverson
          .follow("tacos")
          .follow("recents")
          .toObject(tacoType);

      // Alternatively, list the two paths in the same call to follow()
//    Resources<Taco> tacoRes =
//        traverson
//          .follow("tacos", "recents")
//          .toObject(tacoType);

    return tacoRes.getContent();
  }
 
Example #3
Source File: RecentTacosController.java    From spring-in-action-5-samples with Apache License 2.0 6 votes vote down vote up
@GetMapping(path="/tacos/recent", produces="application/hal+json")
public ResponseEntity<Resources<TacoResource>> recentTacos() {
  PageRequest page = PageRequest.of(
                        0, 12, Sort.by("createdAt").descending());
  List<Taco> tacos = tacoRepo.findAll(page).getContent();

  List<TacoResource> tacoResources = 
      new TacoResourceAssembler().toResources(tacos);
  Resources<TacoResource> recentResources = 
          new Resources<TacoResource>(tacoResources);
  
  recentResources.add(
      linkTo(methodOn(RecentTacosController.class).recentTacos())
          .withRel("recents"));
  return new ResponseEntity<>(recentResources, HttpStatus.OK);
}
 
Example #4
Source File: InventoryController.java    From moserp with Apache License 2.0 6 votes vote down vote up
@RequestMapping(method = RequestMethod.GET, value = "/inventoryItems/search/findByProductIdOrFacilityId")
public Resources<Resource<InventoryItem>> findByProductIdOrFacilityId(@RequestParam(required = false) String productId,
                                                                      @RequestParam(required = false) String facilityId) {
    List<InventoryItem> items;
    RestUri facilityBaseUri = moduleRegistry.getBaseUriForResource(OtherResources.FACILITIES);
    RestUri facilityUri = facilityBaseUri.slash(facilityId);
    RestUri productsBaseUri = moduleRegistry.getBaseUriForResource(OtherResources.PRODUCTS);
    RestUri productUri = productsBaseUri.slash(productId);
    if (productId == null) {
        items = repository.findByFacility(facilityUri);
    } else if (facilityId == null) {
        items =  repository.findByProductInstanceProduct(productUri);
    } else {
        Query query = query(where("productInstance.product").is(productUri.getUri()).and("facility").is(facilityUri.getUri()));
        items =  mongoTemplate.find(query, InventoryItem.class);
    }
    Stream<Resource<InventoryItem>> resourceStream = items.stream().map(inventoryItem -> new Resource<>(inventoryItem));
    List<Resource<InventoryItem>> inventoryItemResources = resourceStream.collect(Collectors.toList());
    inventoryItemResources.forEach(inventoryItemLinks::addLinks);
    return new Resources<>(inventoryItemResources);
}
 
Example #5
Source File: RecentTacosController.java    From spring-in-action-5-samples with Apache License 2.0 6 votes vote down vote up
@GetMapping(path="/tacos/recent", produces="application/hal+json")
public ResponseEntity<Resources<TacoResource>> recentTacos() {
  PageRequest page = PageRequest.of(
                        0, 12, Sort.by("createdAt").descending());
  List<Taco> tacos = tacoRepo.findAll(page).getContent();

  List<TacoResource> tacoResources = 
      new TacoResourceAssembler().toResources(tacos);
  Resources<TacoResource> recentResources = 
          new Resources<TacoResource>(tacoResources);
  
  recentResources.add(
      linkTo(methodOn(RecentTacosController.class).recentTacos())
          .withRel("recents"));
  return new ResponseEntity<>(recentResources, HttpStatus.OK);
}
 
Example #6
Source File: EventController.java    From sos with Apache License 2.0 6 votes vote down vote up
@GetMapping("events")
HttpEntity<Resources<?>> events(PagedResourcesAssembler<AbstractEvent<?>> assembler,
		@SortDefault("publicationDate") Pageable pageable,
		@RequestParam(required = false) @DateTimeFormat(iso = ISO.DATE_TIME) LocalDateTime since,
		@RequestParam(required = false) String type) {

	QAbstractEvent $ = QAbstractEvent.abstractEvent;

	BooleanBuilder builder = new BooleanBuilder();

	// Apply date
	Optional.ofNullable(since).ifPresent(it -> builder.and($.publicationDate.after(it)));

	// Apply type
	Optional.ofNullable(type) //
			.flatMap(events::findEventTypeByName) //
			.ifPresent(it -> builder.and($.instanceOf(it)));

	Page<AbstractEvent<?>> result = events.findAll(builder, pageable);

	PagedResources<Resource<AbstractEvent<?>>> resource = assembler.toResource(result, event -> toResource(event));
	resource
			.add(links.linkTo(methodOn(EventController.class).events(assembler, pageable, since, type)).withRel("events"));

	return ResponseEntity.ok(resource);
}
 
Example #7
Source File: ContentSearchRestController.java    From spring-content with Apache License 2.0 6 votes vote down vote up
public static Resources<?> toResources(Iterable<?> source,
									   PersistentEntityResourceAssembler assembler,
									   PagedResourcesAssembler resourcesAssembler,
									   Class<?> domainType,
									   Link baseLink) {

	if (source instanceof Page) {
		Page<Object> page = (Page<Object>) source;
		return entitiesToResources(page, assembler, resourcesAssembler, domainType, baseLink);
	}
	else if (source instanceof Iterable) {
		return entitiesToResources((Iterable<Object>) source, assembler, domainType);
	}
	else {
		return new Resources(EMPTY_RESOURCE_LIST);
	}
}
 
Example #8
Source File: RecentTacosController.java    From spring-in-action-5-samples with Apache License 2.0 6 votes vote down vote up
@GetMapping(path="/tacos/recent", produces="application/hal+json")
public ResponseEntity<Resources<TacoResource>> recentTacos() {
  PageRequest page = PageRequest.of(
                        0, 12, Sort.by("createdAt").descending());
  List<Taco> tacos = tacoRepo.findAll(page).getContent();

  List<TacoResource> tacoResources = 
      new TacoResourceAssembler().toResources(tacos);
  Resources<TacoResource> recentResources = 
          new Resources<TacoResource>(tacoResources);
  
  recentResources.add(
      linkTo(methodOn(RecentTacosController.class).recentTacos())
          .withRel("recents"));
  return new ResponseEntity<>(recentResources, HttpStatus.OK);
}
 
Example #9
Source File: RubricsServiceImpl.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
protected Collection<Resource<ToolItemRubricAssociation>> getRubricAssociationByRubric(String rubricId, String toSite) throws Exception {
    TypeReferences.ResourcesType<Resource<ToolItemRubricAssociation>> resourceParameterizedTypeReference = new TypeReferences.ResourcesType<Resource<ToolItemRubricAssociation>>() {};

    URI apiBaseUrl = new URI(serverConfigurationService.getServerUrl() + RBCS_SERVICE_URL_PREFIX);
    Traverson traverson = new Traverson(apiBaseUrl, MediaTypes.HAL_JSON);
    Traverson.TraversalBuilder builder = traverson.follow("rubric-associations", "search", "by-rubric-id");

    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", String.format("Bearer %s", generateJsonWebToken(RubricsConstants.RBCS_TOOL, toSite)));
    builder.withHeaders(headers);

    Map<String, Object> parameters = new HashMap<>();
    parameters.put("rubricId", Long.valueOf(rubricId));
    Resources<Resource<ToolItemRubricAssociation>> associationResources = builder.withTemplateParameters(parameters).toObject(resourceParameterizedTypeReference);

    return associationResources.getContent();
}
 
Example #10
Source File: ResourcesMapper.java    From mobilecloud-15 with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(Resources value, JsonGenerator jgen,
		SerializerProvider provider) throws IOException,
		JsonProcessingException {
	// Extracted the actual data inside of the Resources object
	// that we care about (e.g., the list of Video objects)
	Object content = value.getContent();
	// Instead of all of the Resources member variables, etc.
	// Just mashall the actual content (Videos) into the JSON
	JsonSerializer<Object> s = provider.findValueSerializer(
			content.getClass(), null);
	s.serialize(content, jgen, provider);
}
 
Example #11
Source File: WebsiteRestController.java    From JiwhizBlogWeb with Apache License 2.0 5 votes vote down vote up
@RequestMapping(method = RequestMethod.GET, value = ApiUrls.URL_SITE_RECENT_BLOGS)
public HttpEntity<Resources<PublicBlogResource>> getRecentPublicBlogPosts() {
    PageRequest request = new PageRequest(0, MOST_RECENT_NUMBER);
    Collection<PublicBlogResource> blogPostResourceCollection = new ArrayList<PublicBlogResource>();
    Page<BlogPost> blogPosts = this.blogPostRepository.findByPublishedIsTrueOrderByPublishedTimeDesc(request);
    for (BlogPost blogPost : blogPosts) {
        PublicBlogResource resource = publicBlogResourceAssembler.toResource(blogPost);
        blogPostResourceCollection.add(resource);
    }
    
    Resources<PublicBlogResource> resources = new Resources<>(blogPostResourceCollection);
    resources.add(linkTo(methodOn(WebsiteRestController.class).getRecentPublicBlogPosts())
            .withSelfRel());
    return new ResponseEntity<>(resources, HttpStatus.OK);
}
 
Example #12
Source File: BaseWebInventoryTest.java    From moserp with Apache License 2.0 5 votes vote down vote up
protected void checkInventory(RestUri product, RestUri facility, int quantity) {
        String restUri = facility + "/inventoryItems?productId=" + getProductIdFromUri(product.getUri());
        ParameterizedTypeReference<Resources<InventoryItem>> responseType = new ParameterizedTypeReference<Resources<InventoryItem>>() {
        };
        Resources<InventoryItem> inventories = restTemplate.exchange(restUri, HttpMethod.GET, null, responseType).getBody();
        InventoryItem inventory = inventories.getContent().iterator().next();
        assertNotNull("environment", inventory);
//        assertNotNull("Inventory facility", environment.getFacility());
//        assertNotNull("Inventory productInstance", environment.getProductInstance());
        assertEquals("Inventory quantity", quantity, inventory.getQuantityOnHand().intValue());
    }
 
Example #13
Source File: MsgController.java    From Spring5Tutorial with GNU Lesser General Public License v3.0 5 votes vote down vote up
@GetMapping("messagesBy")
public Resources<Resource<Message>> messagesBy(@RequestParam("username") String username) {
	List<Message> messages = messageService.messages(username);
	
	List<Resource<Message>> result = 
			IntStream.range(0, messages.size())
			         .mapToObj(idx -> new Resource<>(messages.get(idx)))
			         .collect(toList());

	String uri = String.format("%s/messagesBy?username=%s", linkTo(MsgController.class), username);
	return new Resources<>(result, new Link(uri));
}
 
Example #14
Source File: ValueListController.java    From moserp with Apache License 2.0 5 votes vote down vote up
@RequestMapping(method = RequestMethod.GET, value = "/valueLists/{key}/values")
public Resources<Resource<ValueListItem>> getValuesForKey(@PathVariable String key) {
    ValueList valueList = valueListRepository.findByKey(key);
    if(valueList == null) {
        valueList = new ValueList(key);
        valueList = valueListRepository.save(valueList);
    }
    List<ValueListItem> values = valueList.getValues();

    Stream<Resource<ValueListItem>> resourceStream = values.stream().map(item -> new Resource<>(item));
    List<Resource<ValueListItem>> resources = resourceStream.collect(Collectors.toList());
    return new Resources<>(resources);
}
 
Example #15
Source File: ReservationApiGatewayRestController.java    From spring-cloud-in-action with MIT License 5 votes vote down vote up
@RequestMapping("/names")
@HystrixCommand(fallbackMethod = "getReservationNamesFallback")
public Collection<String> getReservationNames() {
  logger.info("Get reservation names via rest template!");

  ParameterizedTypeReference<Resources<Reservation>> parameterizedTypeReference =
          new ParameterizedTypeReference<Resources<Reservation>>() {
          };

  ResponseEntity<Resources<Reservation>> exchange = rt.exchange(
          "http://reservation-service/reservations",
          HttpMethod.GET, null, parameterizedTypeReference);

  return exchange.getBody().getContent().stream().map(Reservation::getReservationName).collect(Collectors.toList());
}
 
Example #16
Source File: UserService.java    From myfeed with Apache License 2.0 5 votes vote down vote up
public Observable<Resource<User>> getFollowing(String userid) {
	Resources<Resource<User>> users = traverson.create("myfeed-user")
			.follow("users", "search", "findByFollowing")
			.withTemplateParameters(Collections.singletonMap("userId", userid))
			.toObject(TYPE_USERS);

	return Observable.from(users.getContent());
}
 
Example #17
Source File: ReservationApiGatewayRestController.java    From spring-cloud-in-action with MIT License 5 votes vote down vote up
@RequestMapping("/names-feign")
public Collection<String> getReservationNamesViaFeign() {
  logger.info("Get reservation names via feign!");

  Resources<Reservation> reservations = reservationService.queryReservations();

  return reservations.getContent().stream().map(Reservation::getReservationName).collect(Collectors.toList());
}
 
Example #18
Source File: ResourcesMapper.java    From mobilecloud-15 with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(Resources value, JsonGenerator jgen,
		SerializerProvider provider) throws IOException,
		JsonProcessingException {
	// Extracted the actual data inside of the Resources object
	// that we care about (e.g., the list of Video objects)
	Object content = value.getContent();
	// Instead of all of the Resources member variables, etc.
	// Just mashall the actual content (Videos) into the JSON
	JsonSerializer<Object> s = provider.findValueSerializer(
			content.getClass(), null);
	s.serialize(content, jgen, provider);
}
 
Example #19
Source File: RubricsServiceImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public void deleteSiteRubrics(String siteId) {
    try {
        TypeReferences.ResourcesType<Resource<Rubric>> resourceParameterizedTypeReference = new TypeReferences.ResourcesType<Resource<Rubric>>() {};
        URI apiBaseUrl = new URI(serverConfigurationService.getServerUrl() + RBCS_SERVICE_URL_PREFIX);
        Traverson traverson = new Traverson(apiBaseUrl, MediaTypes.HAL_JSON);
        Traverson.TraversalBuilder builder = traverson.follow("rubrics", "search", "rubrics-from-site");

        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", String.format("Bearer %s", generateJsonWebToken(RubricsConstants.RBCS_TOOL, siteId)));
        builder.withHeaders(headers);

        Map<String, Object> parameters = new HashMap<>();
        parameters.put("siteId", siteId);
        Resources<Resource<Rubric>> rubricResources = builder.withTemplateParameters(parameters).toObject(resourceParameterizedTypeReference);
        for (Resource<Rubric> rubricResource : rubricResources) {
            String [] rubricSplitted = rubricResource.getLink(Link.REL_SELF).getHref().split("/");
            Collection<Resource<ToolItemRubricAssociation>> assocs = getRubricAssociationByRubric(rubricSplitted[rubricSplitted.length-1],siteId);
            for(Resource<ToolItemRubricAssociation> associationResource : assocs){
                String associationHref = associationResource.getLink(Link.REL_SELF).getHref();
                deleteRubricResource(associationHref, RubricsConstants.RBCS_TOOL, siteId);
            }
            deleteRubricResource(rubricResource.getLink(Link.REL_SELF).getHref(), RubricsConstants.RBCS_TOOL, siteId);
        }
    } catch(Exception e){
        log.error("Rubrics: error trying to delete rubric -> {}" , e.getMessage());
    }
}
 
Example #20
Source File: RestTmplApplicationTests.java    From Spring5Tutorial with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void index() {
	RequestEntity<Void> request = RequestEntity
			.get(URI.create(String.format("%s/messages", serviceUri)))
			.build();
	
	ResponseEntity<Resources<Message>> response = 
			restTemplate.exchange(request, new TypeReferences.ResourcesType<Message>() {});

	assertTrue(response.getBody().getContent().size() > 0);
}
 
Example #21
Source File: MessageServiceRest.java    From Spring5Tutorial with GNU Lesser General Public License v3.0 5 votes vote down vote up
public List<Message> messages(String username) {
RequestEntity<Void> request = RequestEntity
		.get(URI.create(String.format("http://localhost:8083/messagesBy?username=%s", username)))
		.build();

ResponseEntity<Resources<Message>> response = 
		restTemplate.exchange(request, new TypeReferences.ResourcesType<Message>() {});
  	
      return new ArrayList<>(response.getBody().getContent());
  }
 
Example #22
Source File: MessageServiceRest.java    From Spring5Tutorial with GNU Lesser General Public License v3.0 5 votes vote down vote up
public List<Message> newestMessages(int n) {
RequestEntity<Void> request = RequestEntity
		.get(URI.create(String.format("http://localhost:8083/newestMessages?n=%d", n)))
		.build();

ResponseEntity<Resources<Message>> response = 
		restTemplate.exchange(request, new TypeReferences.ResourcesType<Message>() {});
  	
      return new ArrayList<>(response.getBody().getContent());
  }
 
Example #23
Source File: MsgController.java    From Spring5Tutorial with GNU Lesser General Public License v3.0 5 votes vote down vote up
@GetMapping("messagesBy")
public Resources<Resource<Message>> messagesBy(@RequestParam("username") String username) {
	List<Message> messages = messageService.messages(username);
	
	List<Resource<Message>> result = 
			IntStream.range(0, messages.size())
			         .mapToObj(idx -> new Resource<>(messages.get(idx)))
			         .collect(toList());

	String uri = String.format("%s/messagesBy?username=%s", linkTo(MsgController.class), username);
	return new Resources<>(result, new Link(uri));
}
 
Example #24
Source File: SpeakerController.java    From springrestdoc with MIT License 5 votes vote down vote up
@GetMapping("/{id}/topics")
public Resources<TopicResource> getSpeakerTopics(@PathVariable long id) {
    Optional<Speaker> speaker = speakerRepository.findOne(id);
    List<Topic> topics = speaker.get().getTopics();
    List<TopicResource> topicResources = topics.stream()
            .map(TopicResource::new)
            .collect(toList());
    return new Resources(topicResources);
}
 
Example #25
Source File: SpeakerController.java    From springrestdoc with MIT License 5 votes vote down vote up
@ExceptionHandler(value = {MethodArgumentNotValidException.class})
@ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY)
public Resources<ValidationErrorResource> handleMethodArgumentNotValid(MethodArgumentNotValidException ex) {
    List<ValidationErrorResource> validationErrors = ex.getBindingResult().getFieldErrors()
            .stream()
            .map(ValidationErrorResource::new)
            .collect(toList());

    return new Resources<>(validationErrors);
}
 
Example #26
Source File: WebsiteRestController.java    From JiwhizBlogWeb with Apache License 2.0 5 votes vote down vote up
@RequestMapping(method = RequestMethod.GET, value = ApiUrls.URL_SITE_RECENT_COMMENTS)
public HttpEntity<Resources<Resource<CommentPost>>> getRecentPublicCommentPosts() {
    PageRequest request = new PageRequest(0, MOST_RECENT_NUMBER);
    Collection<Resource<CommentPost>> resourceCollection = new ArrayList<Resource<CommentPost>>();
    Page<CommentPost> commentPosts = this.commentPostRepository.findByStatusOrderByCreatedTimeDesc(CommentStatusType.APPROVED, request);
    for (CommentPost comment : commentPosts) {
        Resource<CommentPost> resource = publicCommentResourceAssembler.toResource(comment);
        resourceCollection.add(resource);
    }
    
    Resources<Resource<CommentPost>> resources = new Resources<Resource<CommentPost>>(resourceCollection);
    resources.add(linkTo(methodOn(WebsiteRestController.class).getRecentPublicCommentPosts())
            .withSelfRel());
    return new ResponseEntity<>(resources, HttpStatus.OK);
}
 
Example #27
Source File: MsgController.java    From Spring5Tutorial with GNU Lesser General Public License v3.0 5 votes vote down vote up
@GetMapping("newestMessages")
public Resources<Resource<Message>> newestMessages(@RequestParam("n") int n) {
	List<Message> messages = messageService.newestMessages(n);
	
	List<Resource<Message>> result = 
			IntStream.range(0, messages.size())
			         .mapToObj(idx -> new Resource<>(messages.get(idx)))
			         .collect(toList());

	String uri = String.format("%s/newestMessages?n=%d", linkTo(MsgController.class), n);
	return new Resources<>(result, new Link(uri));
}
 
Example #28
Source File: CatalogIntegration.java    From sos with Apache License 2.0 5 votes vote down vote up
private void initializeInventory(Resources<Resource<ProductAdded>> resources) {

		log.info("Processing {} new events…", resources.getContent().size());

		resources.forEach(resource -> {

			Integration integration = repository.apply(() -> initInventory(resource),
					it -> it.withCatalogUpdate(resource.getContent().getPublicationDate()));

			log.info("Successful catalog update. New reference time: {}.",
					integration.getCatalogUpdate().map(it -> it.format(DateTimeFormatter.ISO_DATE_TIME)) //
							.orElseThrow(() -> new IllegalStateException()));
		});
	}
 
Example #29
Source File: CatalogIntegration.java    From sos with Apache License 2.0 5 votes vote down vote up
private void initProductInfos(Resources<Resource<ProductAdded>> resources) {

		log.info("Processing {} new events…", resources.getContent().size());

		resources.forEach(resource -> {

			Integration integration = repository.apply(() -> initProductInfo(resource),
					it -> it.withCatalogUpdate(resource.getContent().getPublicationDate()));

			log.info("Successful catalog update. New reference time: {}.",
					integration.getCatalogUpdate().map(it -> it.format(DateTimeFormatter.ISO_DATE_TIME)) //
							.orElseThrow(() -> new IllegalStateException()));
		});
	}
 
Example #30
Source File: SpeakerController.java    From springrestdoc with MIT License 5 votes vote down vote up
@GetMapping("/{id}/topics")
public Resources<TopicResource> getSpeakerTopics(@PathVariable long id) {
    Optional<Speaker> speaker = speakerRepository.findOne(id);
    List<Topic> topics = speaker.get().getTopics();
    List<TopicResource> topicResources = topics.stream()
            .map(TopicResource::new)
            .collect(toList());
    return new Resources(topicResources);
}