org.springframework.hateoas.CollectionModel Java Examples

The following examples show how to use org.springframework.hateoas.CollectionModel. 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: CustomerController.java    From tutorials with MIT License 6 votes vote down vote up
@GetMapping(produces = { "application/hal+json" })
public CollectionModel<Customer> getAllCustomers() {
    final List<Customer> allCustomers = customerService.allCustomers();

    for (final Customer customer : allCustomers) {
        String customerId = customer.getCustomerId();
        Link selfLink = linkTo(CustomerController.class).slash(customerId)
            .withSelfRel();
        customer.add(selfLink);
        if (orderService.getAllOrdersForCustomer(customerId)
            .size() > 0) {
            final Link ordersLink = linkTo(methodOn(CustomerController.class).getOrdersForCustomer(customerId))
                .withRel("allOrders");
            customer.add(ordersLink);
        }
    }

    Link link = linkTo(CustomerController.class).withSelfRel();
    CollectionModel<Customer> result = new CollectionModel<>(allCustomers, link);
    return result;
}
 
Example #2
Source File: RuntimeStreamsController.java    From spring-cloud-dataflow with Apache License 2.0 6 votes vote down vote up
private StreamStatusResource toStreamStatus(String streamName, List<AppStatus> appStatuses) {
	StreamStatusResource streamStatusResource = new StreamStatusResource();
	streamStatusResource.setName(streamName);

	List<AppStatusResource> appStatusResources = new ArrayList<>();

	if (!CollectionUtils.isEmpty(appStatuses)) {
		for (AppStatus appStatus : appStatuses) {
			try {
				appStatusResources.add(new RuntimeAppsController.Assembler().toModel(appStatus));
			}
			catch (Throwable throwable) {
				logger.warn("Failed to retrieve runtime status for " + appStatus.getDeploymentId(), throwable);
			}
		}
	}
	streamStatusResource.setApplications(new CollectionModel<>(appStatusResources));
	return streamStatusResource;
}
 
Example #3
Source File: StreamStatusResource.java    From spring-cloud-dataflow with Apache License 2.0 6 votes vote down vote up
public String getVersion() {
	try {
		if (applications.iterator().hasNext()) {
			CollectionModel<AppInstanceStatusResource> instances = applications.iterator().next().getInstances();
			if (instances != null && instances.iterator().hasNext()) {
				AppInstanceStatusResource instance = instances.iterator().next();
				if (instance != null && instance.getAttributes() != null
						&& instance.getAttributes().containsKey(StreamRuntimePropertyKeys.ATTRIBUTE_SKIPPER_RELEASE_VERSION)) {
					String releaseVersion = instance.getAttributes().get(StreamRuntimePropertyKeys.ATTRIBUTE_SKIPPER_RELEASE_VERSION);
					if (releaseVersion != null) {
						return releaseVersion;
					}
				}
			}
		}
	}
	catch (Throwable t) {
		// do nothing
	}
	return NO_APPS;
}
 
Example #4
Source File: EmployeeController.java    From spring-hateoas-examples with Apache License 2.0 6 votes vote down vote up
@GetMapping("/employees")
ResponseEntity<CollectionModel<EntityModel<Employee>>> findAll() {

	List<EntityModel<Employee>> employeeResources = StreamSupport.stream(repository.findAll().spliterator(), false)
			.map(employee -> new EntityModel<>(employee,
					linkTo(methodOn(EmployeeController.class).findOne(employee.getId())).withSelfRel()
							.andAffordance(afford(methodOn(EmployeeController.class).updateEmployee(null, employee.getId())))
							.andAffordance(afford(methodOn(EmployeeController.class).deleteEmployee(employee.getId()))),
					linkTo(methodOn(EmployeeController.class).findAll()).withRel("employees")))
			.collect(Collectors.toList());

	return ResponseEntity.ok(new CollectionModel<>( //
			employeeResources, //
			linkTo(methodOn(EmployeeController.class).findAll()).withSelfRel()
					.andAffordance(afford(methodOn(EmployeeController.class).newEmployee(null)))));
}
 
Example #5
Source File: RestOperations.java    From bowman with Apache License 2.0 6 votes vote down vote up
public <T> CollectionModel<EntityModel<T>> getResources(URI uri, Class<T> entityType) {
	ObjectNode node;
	
	try {
		node = restTemplate.getForObject(uri, ObjectNode.class);
	}
	catch (HttpClientErrorException exception) {
		if (exception.getStatusCode() == HttpStatus.NOT_FOUND) {
			return CollectionModel.wrap(Collections.<T>emptyList());
		}
		
		throw exception;
	}
	
	JavaType innerType = objectMapper.getTypeFactory().constructParametricType(EntityModel.class, entityType);
	JavaType targetType = objectMapper.getTypeFactory().constructParametricType(CollectionModel.class, innerType);
	
	return objectMapper.convertValue(node, targetType);
}
 
Example #6
Source File: EmployeeWithManagerResourceAssembler.java    From spring-hateoas-examples with Apache License 2.0 5 votes vote down vote up
/**
 * Define links to add to the {@link CollectionModel} collection.
 *
 * @param resources
 */
@Override
public void addLinks(CollectionModel<EntityModel<EmployeeWithManager>> resources) {

	resources.add(linkTo(methodOn(EmployeeController.class).findAllDetailedEmployees()).withSelfRel());
	resources.add(linkTo(methodOn(EmployeeController.class).findAll()).withRel("employees"));
	resources.add(linkTo(methodOn(ManagerController.class).findAll()).withRel("managers"));
	resources.add(linkTo(methodOn(RootController.class).root()).withRel("root"));
}
 
Example #7
Source File: HomeController.java    From spring-hateoas-examples with Apache License 2.0 5 votes vote down vote up
/**
 * Get a listing of ALL {@link Employee}s by querying the remote services' root URI, and then "hopping" to the
 * {@literal employees} rel. NOTE: Also create a form-backed {@link Employee} object to allow creating a new entry
 * with the Thymeleaf template.
 *
 * @param model
 * @return
 * @throws URISyntaxException
 */
@GetMapping
public String index(Model model) throws URISyntaxException {

	Traverson client = new Traverson(new URI(REMOTE_SERVICE_ROOT_URI), MediaTypes.HAL_JSON);
	CollectionModel<EntityModel<Employee>> employees = client //
			.follow("employees") //
			.toObject(new CollectionModelType<EntityModel<Employee>>() {});

	model.addAttribute("employee", new Employee());
	model.addAttribute("employees", employees);

	return "index";
}
 
Example #8
Source File: ManagerRepresentationModelAssembler.java    From spring-hateoas-examples with Apache License 2.0 5 votes vote down vote up
/**
 * Retain default links for the entire collection, but add extra custom links for the {@link Manager} collection.
 *
 * @param resources
 */
@Override
public void addLinks(CollectionModel<EntityModel<Manager>> resources) {

	super.addLinks(resources);

	resources.add(linkTo(methodOn(EmployeeController.class).findAll()).withRel("employees"));
	resources.add(linkTo(methodOn(EmployeeController.class).findAllDetailedEmployees()).withRel("detailedEmployees"));
	resources.add(linkTo(methodOn(RootController.class).root()).withRel("root"));
}
 
Example #9
Source File: EmployeeRepresentationModelAssembler.java    From spring-hateoas-examples with Apache License 2.0 5 votes vote down vote up
/**
 * Define links to add to {@link CollectionModel} collection.
 *
 * @param resources
 */
@Override
public void addLinks(CollectionModel<EntityModel<Employee>> resources) {

	super.addLinks(resources);

	resources.add(linkTo(methodOn(EmployeeController.class).findAllDetailedEmployees()).withRel("detailedEmployees"));
	resources.add(linkTo(methodOn(ManagerController.class).findAll()).withRel("managers"));
	resources.add(linkTo(methodOn(RootController.class).root()).withRel("root"));
}
 
Example #10
Source File: EmployeeController.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * Look up all employees, and transform them into a REST collection resource. Then return them through Spring Web's
 * {@link ResponseEntity} fluent API.
 */
@GetMapping("/employees")
ResponseEntity<CollectionModel<EntityModel<Employee>>> findAll() {

	List<EntityModel<Employee>> employees = StreamSupport.stream(repository.findAll().spliterator(), false)
			.map(employee -> new EntityModel<>(employee, //
					linkTo(methodOn(EmployeeController.class).findOne(employee.getId())).withSelfRel(), //
					linkTo(methodOn(EmployeeController.class).findAll()).withRel("employees"))) //
			.collect(Collectors.toList());

	return ResponseEntity.ok( //
			new CollectionModel<>(employees, //
					linkTo(methodOn(EmployeeController.class).findAll()).withSelfRel()));
}
 
Example #11
Source File: HomeController.java    From spring-hateoas-examples with Apache License 2.0 5 votes vote down vote up
/**
 * Get a listing of ALL {@link Employee}s by querying the remote services' root URI, and then "hopping" to the
 * {@literal employees} rel. NOTE: Also create a form-backed {@link Employee} object to allow creating a new entry
 * with the Thymeleaf template.
 *
 * @param model
 * @return
 * @throws URISyntaxException
 */
@GetMapping
public String index(Model model) throws URISyntaxException {

	Traverson client = new Traverson(new URI(REMOTE_SERVICE_ROOT_URI), MediaTypes.HAL_JSON);

	CollectionModel<EntityModel<Employee>> employees = client //
			.follow("employees") //
			.toObject(new CollectionModelType<EntityModel<Employee>>() {});

	model.addAttribute("employee", new Employee());
	model.addAttribute("employees", employees);

	return "index";
}
 
Example #12
Source File: FooResourceAssembler.java    From friendly-id with Apache License 2.0 5 votes vote down vote up
@Override
public FooResource toModel(Foo entity) {
	BarResourceAssembler barResourceAssembler = new BarResourceAssembler();
	List<Bar> bars = Arrays.asList(new Bar(UUID.randomUUID(), "bar one", entity),
			new Bar(UUID.randomUUID(), "bar two", entity));
	CollectionModel<BarResource> barResources = barResourceAssembler.toCollectionModel(bars);
	WebMvcLinkBuilderFactory factory = new WebMvcLinkBuilderFactory();
	FooResource resource = new FooResource(entity.getId(), entity.getName(), barResources);

	resource.add(factory.linkTo(FooController.class).slash(toFriendlyId(entity.getId())).withSelfRel());
	return resource;
}
 
Example #13
Source File: LinkedResourceMethodHandler.java    From bowman with Apache License 2.0 5 votes vote down vote up
private <F> Collection<F> resolveCollectionLinkedResource(CollectionModel<EntityModel<F>> resources,
	Object contextEntity,
	Method originalMethod) throws IllegalAccessException, InvocationTargetException {

	@SuppressWarnings("unchecked")
	Collection<F> collection = (Collection<F>) originalMethod.invoke(contextEntity);

	if (collection == null) {
		collection = createCollectionForMethod(originalMethod);
	}
	else {
		collection.clear();
	}
	return updateCollectionWithLinkedResources(collection, resources);
}
 
Example #14
Source File: LinkedResourceMethodHandler.java    From bowman with Apache License 2.0 5 votes vote down vote up
private <F> Collection<F> updateCollectionWithLinkedResources(Collection<F> collection,
	CollectionModel<EntityModel<F>> resources) {
	for (EntityModel<F> fResource : resources) {
		collection.add(proxyFactory.create(fResource, restOperations));
	}

	return collection;
}
 
Example #15
Source File: Client.java    From bowman with Apache License 2.0 5 votes vote down vote up
/**
 * GET a collection of entities from the given URI.
 * 
 * @param uri the URI from which to retrieve the entities
 * @return the entities retrieved
 */
public Iterable<T> getAll(URI uri) {
	List<T> result = new ArrayList<>();

	CollectionModel<EntityModel<T>> resources = restOperations.getResources(uri, entityType);

	for (EntityModel<T> resource : resources) {
		result.add(proxyFactory.create(resource, restOperations));
	}

	return result;
}
 
Example #16
Source File: ClientTest.java    From bowman with Apache License 2.0 5 votes vote down vote up
@Test
public void getAllWithNoArgumentsReturnsProxyIterable() {
	Entity expected = new Entity();
	
	EntityModel<Entity> resource = new EntityModel<>(new Entity());
	when(restOperations.getResources(URI.create(BASE_URI + "/entities"), Entity.class)).thenReturn(
			new CollectionModel<>(asList(resource)));
	when(proxyFactory.create(resource, restOperations)).thenReturn(expected);
	
	Iterable<Entity> proxies = client.getAll();
	
	assertThat(proxies, contains(expected));
}
 
Example #17
Source File: RestOperationsTest.java    From bowman with Apache License 2.0 5 votes vote down vote up
@Test
public void getResourcesReturnsResources() throws Exception {
	when(restTemplate.getForObject(URI.create("http://example.com"), ObjectNode.class))
		.thenReturn(createObjectNode("{\"_embedded\":{\"entities\":[{\"field\":\"value\"}]}}"));
	
	CollectionModel<EntityModel<Entity>> resources = restOperations.getResources(URI.create("http://example.com"),
		Entity.class);
	
	assertThat(resources.getContent().iterator().next().getContent().getField(), is("value"));
}
 
Example #18
Source File: RestOperationsTest.java    From bowman with Apache License 2.0 5 votes vote down vote up
@Test
public void getResourcesOnNotFoundHttpClientExceptionReturnsEmpty() {
	when(restTemplate.getForObject(URI.create("http://example.com"), ObjectNode.class))
		.thenThrow(new HttpClientErrorException(NOT_FOUND));
	
	CollectionModel<EntityModel<Entity>> resources = restOperations.getResources(URI.create("http://example.com"),
		Entity.class);
	
	assertThat(resources.getContent(), is(empty()));
}
 
Example #19
Source File: JavassistClientProxyFactoryTest.java    From bowman with Apache License 2.0 5 votes vote down vote up
@Test
public void createReturnsProxyWithLinkedResources() {
	EntityModel<Entity> resource = new EntityModel<>(new Entity(),
			new Link("http://www.example.com/association/linked", "linkedCollection"));
	
	when(restOperations.getResources(URI.create("http://www.example.com/association/linked"),
			Entity.class)).thenReturn(new CollectionModel<>(asList(new EntityModel<>(new Entity(),
					new Link("http://www.example.com/1", IanaLinkRelations.SELF)))));
	
	Entity proxy = proxyFactory.create(resource, restOperations);
	
	assertThat(proxy.getLinkedCollection().get(0).getId(), is(URI.create("http://www.example.com/1")));
}
 
Example #20
Source File: JavassistClientProxyFactoryTest.java    From bowman with Apache License 2.0 5 votes vote down vote up
@Test
public void createWithNullLinkedCollectionReturnsProxyWithLinkedResources() {
	EntityModel<Entity> resource = new EntityModel<>(new Entity(),
			new Link("http://www.example.com/association/linked", "nullLinkedCollection"));
	
	when(restOperations.getResources(URI.create("http://www.example.com/association/linked"),
			Entity.class)).thenReturn(new CollectionModel<>(asList(new EntityModel<>(new Entity(),
					new Link("http://www.example.com/1", IanaLinkRelations.SELF)))));
	
	Entity proxy = proxyFactory.create(resource, restOperations);
	
	assertThat(proxy.getNullLinkedCollection().get(0).getId(), is(URI.create("http://www.example.com/1")));
}
 
Example #21
Source File: JavassistClientProxyFactoryTest.java    From bowman with Apache License 2.0 5 votes vote down vote up
@Test
public void createWithResourceWithProxiedInterfaceContentReturnsProxyWithLinkedResources() throws Exception {
	InterfaceTypeResource content = instantiateProxyOfInterfaceType(InterfaceTypeResource.class);
	
	when(restOperations.getResources(URI.create("http://www.example.com/association/linked"),
		Entity.class)).thenReturn(new CollectionModel<>(asList(new EntityModel<>(new Entity(),
		new Link("http://www.example.com/1", IanaLinkRelations.SELF)))));
	
	InterfaceTypeResource resource = proxyFactory.create(new EntityModel<>(content,
		new Link("http://www.example.com/association/linked", "linked")), restOperations);
	
	assertThat(resource.linked().get(0).getId(), is(URI.create("http://www.example.com/1")));
}
 
Example #22
Source File: RuntimeAppsController.java    From spring-cloud-dataflow with Apache License 2.0 5 votes vote down vote up
@Override
protected AppStatusResource instantiateModel(AppStatus entity) {
	AppStatusResource resource = new AppStatusResource(entity.getDeploymentId(),
			ControllerUtils.mapState(entity.getState()).getKey());
	List<AppInstanceStatusResource> instanceStatusResources = new ArrayList<>();
	RuntimeAppInstanceController.InstanceAssembler instanceAssembler = new RuntimeAppInstanceController.InstanceAssembler(
			entity);
	List<AppInstanceStatus> instanceStatuses = new ArrayList<>(entity.getInstances().values());
	Collections.sort(instanceStatuses, INSTANCE_SORTER);
	for (AppInstanceStatus appInstanceStatus : instanceStatuses) {
		instanceStatusResources.add(instanceAssembler.toModel(appInstanceStatus));
	}
	resource.setInstances(new CollectionModel<>(instanceStatusResources));
	return resource;
}
 
Example #23
Source File: CustomerController.java    From tutorials with MIT License 5 votes vote down vote up
@GetMapping(value = "/{customerId}/orders", produces = { "application/hal+json" })
public CollectionModel<Order> getOrdersForCustomer(@PathVariable final String customerId) {
    final List<Order> orders = orderService.getAllOrdersForCustomer(customerId);
    for (final Order order : orders) {
        final Link selfLink = linkTo(
            methodOn(CustomerController.class).getOrderById(customerId, order.getOrderId())).withSelfRel();
        order.add(selfLink);
    }

    Link link = linkTo(methodOn(CustomerController.class).getOrdersForCustomer(customerId)).withSelfRel();
    CollectionModel<Order> result = new CollectionModel<>(orders, link);
    return result;
}
 
Example #24
Source File: JobDetailController.java    From spring-batch-rest with Apache License 2.0 5 votes vote down vote up
@Operation(summary = "Get all Quartz job details")
@GetMapping
public CollectionModel<JobDetailResource> all(@RequestParam(value = "enabled", required = false) Boolean enabled,
                                        @RequestParam(value = "springBatchJobName", required = false) String springBatchJobName) {
    return new CollectionModel<>(jobDetailService.all(Optional.ofNullable(enabled), Optional.ofNullable(springBatchJobName)).stream()
            .map(JobDetailResource::new).collect(toList()),
            WebMvcLinkBuilder.linkTo(methodOn(JobDetailController.class).all(enabled, springBatchJobName)).withSelfRel().expand());
}
 
Example #25
Source File: DataRestResponseBuilder.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * Find search return type type.
 *
 * @param handlerMethod the handler method
 * @param methodResourceMapping the method resource mapping
 * @param domainType the domain type
 * @return the type
 */
private Type findSearchReturnType(HandlerMethod handlerMethod, MethodResourceMapping methodResourceMapping, Class<?> domainType) {
	Type returnType = null;
	Type returnRepoType = ReturnTypeParser.resolveType(methodResourceMapping.getMethod().getGenericReturnType(), methodResourceMapping.getMethod().getDeclaringClass());
	if (methodResourceMapping.isPagingResource()) {
		returnType = ResolvableType.forClassWithGenerics(PagedModel.class, domainType).getType();
	}
	else if (Iterable.class.isAssignableFrom(ResolvableType.forType(returnRepoType).getRawClass())) {
		returnType = ResolvableType.forClassWithGenerics(CollectionModel.class, domainType).getType();
	}
	else if (!ClassUtils.isPrimitiveOrWrapper(domainType)) {
		returnType = ResolvableType.forClassWithGenerics(EntityModel.class, domainType).getType();
	}
	if (returnType == null) {
		returnType = ReturnTypeParser.resolveType(handlerMethod.getMethod().getGenericReturnType(), handlerMethod.getBeanType());
		returnType = getType(returnType, domainType);
	}
	return returnType;
}
 
Example #26
Source File: EmployeeController.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * Look up all employees, and transform them into a REST collection resource. Then return them through Spring Web's
 * {@link ResponseEntity} fluent API.
 */
@GetMapping("/employees")
ResponseEntity<CollectionModel<EntityModel<Employee>>> findAll() {

	List<EntityModel<Employee>> employees = StreamSupport.stream(repository.findAll().spliterator(), false)
			.map(employee -> new EntityModel<>(employee, //
					linkTo(methodOn(EmployeeController.class).findOne(employee.getId())).withSelfRel(), //
					linkTo(methodOn(EmployeeController.class).findAll()).withRel("employees"))) //
			.collect(Collectors.toList());

	return ResponseEntity.ok( //
			new CollectionModel<>(employees, //
					linkTo(methodOn(EmployeeController.class).findAll()).withSelfRel()));
}
 
Example #27
Source File: PatronProfileController.java    From library with MIT License 5 votes vote down vote up
@GetMapping("/profiles/{patronId}/holds/")
ResponseEntity<CollectionModel<EntityModel<Hold>>> findHolds(@PathVariable UUID patronId) {
    List<EntityModel<Hold>> holds = patronProfiles.fetchFor(new PatronId(patronId))
            .getHoldsView()
            .getCurrentHolds()
            .toStream()
            .map(hold -> resourceWithLinkToHoldSelf(patronId, hold))
            .collect(toList());
    return ResponseEntity.ok(new CollectionModel<>(holds, linkTo(methodOn(PatronProfileController.class).findHolds(patronId)).withSelfRel()));

}
 
Example #28
Source File: PatronProfileController.java    From library with MIT License 5 votes vote down vote up
@GetMapping("/profiles/{patronId}/checkouts/")
ResponseEntity<CollectionModel<EntityModel<Checkout>>> findCheckouts(@PathVariable UUID patronId) {
    List<EntityModel<Checkout>> checkouts = patronProfiles.fetchFor(new PatronId(patronId))
            .getCurrentCheckouts()
            .getCurrentCheckouts()
            .toStream()
            .map(checkout -> resourceWithLinkToCheckoutSelf(patronId, checkout))
            .collect(toList());
    return ResponseEntity.ok(new CollectionModel<>(checkouts, linkTo(methodOn(PatronProfileController.class).findHolds(patronId)).withSelfRel()));
}
 
Example #29
Source File: FeignHalController.java    From spring-cloud-openfeign with Apache License 2.0 5 votes vote down vote up
@GetMapping("/collection")
public CollectionModel<MarsRover> getCollection() {
	MarsRover marsRover = new MarsRover();
	marsRover.setName("Opportunity");
	Link link = new Link("/collection", "self");
	return new CollectionModel<>(Collections.singleton(marsRover), link);
}
 
Example #30
Source File: FeignHalController.java    From spring-cloud-openfeign with Apache License 2.0 5 votes vote down vote up
@GetMapping("/paged")
public CollectionModel<MarsRover> getPaged() {
	MarsRover marsRover = new MarsRover();
	marsRover.setName("Curiosity");
	Link link = new Link("/paged", "self");
	PagedModel.PageMetadata metadata = new PagedModel.PageMetadata(1, 1, 1);
	return new PagedModel<>(Collections.singleton(marsRover), metadata, link);
}