org.springframework.hateoas.Link Java Examples

The following examples show how to use org.springframework.hateoas.Link. 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: LockingAndVersioningRestController.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 #2
Source File: ActuatorEndpointsDiscovererServiceTests.java    From microservices-dashboard with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnMergedMapOfDiscoveredEndpointsWithHalTakingPrecedence() {
	when(this.otherActuatorEndpointsDiscoverer.findActuatorEndpoints(this.applicationInstance))
			.thenReturn(Mono.just(new Links(new Link("http://localhost:8081/actuator/health", "health"),
					new Link("http://localhost:8081/actuator/info", "info"))));
	when(this.halActuatorEndpointsDiscoverer.findActuatorEndpoints(this.applicationInstance))
			.thenReturn(Mono.just(new Links(new Link("http://localhost:8080/actuator/health", "health"))));

	this.service.findActuatorEndpoints(this.applicationInstance)
			.subscribe(actuatorEndpoints -> {

				verify(this.otherActuatorEndpointsDiscoverer).findActuatorEndpoints(this.applicationInstance);
				verifyNoMoreInteractions(this.otherActuatorEndpointsDiscoverer);

				verify(this.halActuatorEndpointsDiscoverer).findActuatorEndpoints(this.applicationInstance);
				verifyNoMoreInteractions(this.halActuatorEndpointsDiscoverer);

				assertThat(actuatorEndpoints).isNotEmpty();
				assertThat(actuatorEndpoints).hasSize(2);
				assertThat(actuatorEndpoints.hasLink("info")).isTrue();
				assertThat(actuatorEndpoints.getLink("info").getHref()).isEqualTo("http://localhost:8081/actuator/info");
				assertThat(actuatorEndpoints.hasLink("health")).isTrue();
				assertThat(actuatorEndpoints.getLink("health").getHref()).isEqualTo("http://localhost:8080/actuator/health");
			});
}
 
Example #3
Source File: ApplicationInstanceHealthWatcherTests.java    From microservices-dashboard with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldOnlyRetrieveHealthDataForInstancesWithAHealthActuatorEndpoint() {
	ApplicationInstance firstInstance = ApplicationInstanceMother.instance("a-1", "a");
	ApplicationInstance secondInstance = ApplicationInstanceMother.instance("a-2", "a",
			URI.create("http://localhost:8080"),
			new Links(new Link("http://localhost:8080/actuator/health", "health")));
	List<ApplicationInstance> applicationInstances = Arrays.asList(firstInstance, secondInstance);

	when(this.applicationInstanceService.getApplicationInstances()).thenReturn(applicationInstances);
	when(this.responseSpec.bodyToMono(ApplicationInstanceHealthWatcher.HealthWrapper.class))
			.thenReturn(Mono.just(new ApplicationInstanceHealthWatcher.HealthWrapper(Status.UP, new HashMap<>())));

	this.healthWatcher.retrieveHealthDataForAllApplicationInstances();

	assertHealthInfoRetrievalSucceeded(Collections.singletonList(secondInstance));
}
 
Example #4
Source File: FeignHalTests.java    From spring-cloud-openfeign with Apache License 2.0 6 votes vote down vote up
@Test
public void testPagedModel() {
	PagedModel<MarsRover> paged = feignHalClient.paged();
	assertThat(paged).isNotNull();
	assertThat(paged).isNotEmpty();

	assertThat(paged.hasLinks()).isTrue();
	assertThat(paged.hasLink("self")).isTrue();

	assertThat(paged.getLink("self")).map(Link::getHref).contains("/paged");

	Collection<MarsRover> collection = paged.getContent();
	assertThat(collection).isNotEmpty();

	MarsRover marsRover = collection.stream().findAny().orElse(null);
	assertThat(marsRover).isNotNull();
	assertThat(marsRover.getName()).isEqualTo("Curiosity");
}
 
Example #5
Source File: EmployeeController.java    From spring-hateoas-examples with Apache License 2.0 6 votes vote down vote up
/**
 * Update existing employee then return a Location header.
 * 
 * @param employee
 * @param id
 * @return
 */
@PutMapping("/employees/{id}")
ResponseEntity<?> updateEmployee(@RequestBody Employee employee, @PathVariable long id) {

	Employee employeeToUpdate = employee;
	employeeToUpdate.setId(id);
	repository.save(employeeToUpdate);

	Link newlyCreatedLink = linkTo(methodOn(EmployeeController.class).findOne(id)).withSelfRel();

	try {
		return ResponseEntity.noContent().location(new URI(newlyCreatedLink.getHref())).build();
	} catch (URISyntaxException e) {
		return ResponseEntity.badRequest().body("Unable to update " + employeeToUpdate);
	}
}
 
Example #6
Source File: EmployeeController.java    From spring-hateoas-examples with Apache License 2.0 6 votes vote down vote up
@PutMapping("/employees/{id}")
ResponseEntity<?> updateEmployee(@RequestBody Employee employee, @PathVariable long id) {

	Employee employeeToUpdate = employee;
	employeeToUpdate.setId(id);

	Employee updatedEmployee = repository.save(employeeToUpdate);

	return new EntityModel<>(updatedEmployee,
			linkTo(methodOn(EmployeeController.class).findOne(updatedEmployee.getId())).withSelfRel()
					.andAffordance(afford(methodOn(EmployeeController.class).updateEmployee(null, updatedEmployee.getId())))
					.andAffordance(afford(methodOn(EmployeeController.class).deleteEmployee(updatedEmployee.getId()))),
			linkTo(methodOn(EmployeeController.class).findAll()).withRel("employees")).getLink(IanaLinkRelations.SELF)
					.map(Link::getHref).map(href -> {
						try {
							return new URI(href);
						} catch (URISyntaxException e) {
							throw new RuntimeException(e);
						}
					}) //
					.map(uri -> ResponseEntity.noContent().location(uri).build()) //
					.orElse(ResponseEntity.badRequest().body("Unable to update " + employeeToUpdate));
}
 
Example #7
Source File: ApplicationInstanceHealthWatcherTests.java    From microservices-dashboard with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldOnlyRetrieveHealthDataForInstancesThatAreNotDeleted() {
	ApplicationInstance firstInstance = ApplicationInstanceMother.instance("a-1", "a");
	firstInstance.delete();
	ApplicationInstance secondInstance = ApplicationInstanceMother.instance("a-2", "a",
			URI.create("http://localhost:8080"),
			new Links(new Link("http://localhost:8080/actuator/health", "health")));
	List<ApplicationInstance> applicationInstances = Arrays.asList(firstInstance, secondInstance);

	when(this.applicationInstanceService.getApplicationInstances()).thenReturn(applicationInstances);
	when(this.responseSpec.bodyToMono(ApplicationInstanceHealthWatcher.HealthWrapper.class))
			.thenReturn(Mono.just(new ApplicationInstanceHealthWatcher.HealthWrapper(Status.UP, new HashMap<>())));

	this.healthWatcher.retrieveHealthDataForAllApplicationInstances();

	assertHealthInfoRetrievalSucceeded(Collections.singletonList(secondInstance));
}
 
Example #8
Source File: AbstractRessourcesAssembler.java    From taskana with Apache License 2.0 6 votes vote down vote up
protected PagedResources<?> addPageLinks(
    PagedResources<?> pagedResources, PageMetadata pageMetadata) {
  UriComponentsBuilder original = getBuilderForOriginalUri();
  pagedResources.add(
      (Link.of(original.replaceQueryParam("page", 1).toUriString())).withRel("first"));
  pagedResources.add(
      (Link.of(original.replaceQueryParam("page", pageMetadata.getTotalPages()).toUriString()))
          .withRel("last"));
  if (pageMetadata.getNumber() > 1L) {
    pagedResources.add(
        (Link.of(original.replaceQueryParam("page", pageMetadata.getNumber() - 1L).toUriString()))
            .withRel("prev"));
  }

  if (pageMetadata.getNumber() < pageMetadata.getTotalPages()) {
    pagedResources.add(
        (Link.of(original.replaceQueryParam("page", pageMetadata.getNumber() + 1L).toUriString()))
            .withRel("next"));
  }

  return pagedResources;
}
 
Example #9
Source File: RootController.java    From spring-cloud-dashboard with Apache License 2.0 6 votes vote down vote up
/**
 * Return a {@link ResourceSupport} object containing the resources
 * served by the Data Flow server.
 *
 * @return {@code ResourceSupport} object containing the Data Flow server's resources
 */
@RequestMapping("/")
public ResourceSupport info() {
	ResourceSupport resourceSupport = new ResourceSupport();
	resourceSupport.add(new Link(dashboard(""), "dashboard"));
	resourceSupport.add(entityLinks.linkToCollectionResource(AppRegistrationResource.class).withRel("apps"));

	resourceSupport.add(entityLinks.linkToCollectionResource(AppStatusResource.class).withRel("runtime/apps"));
	resourceSupport.add(unescapeTemplateVariables(entityLinks.linkForSingleResource(AppStatusResource.class, "{appId}").withRel("runtime/apps/app")));
	resourceSupport.add(unescapeTemplateVariables(entityLinks.linkFor(AppInstanceStatusResource.class, UriComponents.UriTemplateVariables.SKIP_VALUE).withRel("runtime/apps/instances")));

	resourceSupport.add(entityLinks.linkToCollectionResource(ApplicationDefinitionResource.class).withRel("applications/definitions"));
	resourceSupport.add(unescapeTemplateVariables(entityLinks.linkToSingleResource(ApplicationDefinitionResource.class, "{name}").withRel("applications/definitions/definition")));
	resourceSupport.add(entityLinks.linkToCollectionResource(ApplicationDeploymentResource.class).withRel("applications/deployments"));
	resourceSupport.add(unescapeTemplateVariables(entityLinks.linkToSingleResource(ApplicationDeploymentResource.class, "{name}").withRel("applications/deployments/deployment")));

	String completionStreamTemplated = entityLinks.linkFor(CompletionProposalsResource.class).withSelfRel().getHref() + ("/stream{?start,detailLevel}");
	resourceSupport.add(new Link(completionStreamTemplated).withRel("completions/stream"));
	String completionTaskTemplated = entityLinks.linkFor(CompletionProposalsResource.class).withSelfRel().getHref() + ("/task{?start,detailLevel}");
	resourceSupport.add(new Link(completionTaskTemplated).withRel("completions/task"));
	return resourceSupport;
}
 
Example #10
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 #11
Source File: SpringDocHateoasConfiguration.java    From springdoc-openapi with Apache License 2.0 6 votes vote down vote up
/**
 * Registers an OpenApiCustomiser and a jackson mixin to ensure the definition of `Links` matches the serialized
 * output. This is done because the customer serializer converts the data to a map before serializing it.
 *
 * @param halProvider the hal provider
 * @return the open api customiser
 * @see org.springframework.hateoas.mediatype.hal.Jackson2HalModule.HalLinkListSerializer#serialize(Links, JsonGenerator, SerializerProvider) org.springframework.hateoas.mediatype.hal.Jackson2HalModule.HalLinkListSerializer#serialize(Links, JsonGenerator, SerializerProvider)
 */
@Bean
@ConditionalOnMissingBean
@Lazy(false)
OpenApiCustomiser linksSchemaCustomiser(HateoasHalProvider halProvider) {
	if (!halProvider.isHalEnabled()) {
		return openApi -> {
		};
	}
	Json.mapper().addMixIn(RepresentationModel.class, RepresentationModelLinksOASMixin.class);

	ResolvedSchema resolvedLinkSchema = ModelConverters.getInstance()
			.resolveAsResolvedSchema(new AnnotatedType(Link.class));

	return openApi -> openApi
			.schema("Link", resolvedLinkSchema.schema)
			.schema("Links", new MapSchema()
					.additionalProperties(new StringSchema())
					.additionalProperties(new ObjectSchema().$ref(AnnotationsUtils.COMPONENTS_REF +"Link")));
}
 
Example #12
Source File: ActuatorEndpointsDiscovererServiceTests.java    From microservices-dashboard with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnAnEmptyMonoWhenSomethingGoesWrong() {
	when(this.otherActuatorEndpointsDiscoverer.findActuatorEndpoints(this.applicationInstance))
			.thenReturn(Mono.just(new Links(new Link("http://localhost:8081/actuator/health", "health"),
					new Link("http://localhost:8081/actuator/info", "info"))));
	when(this.halActuatorEndpointsDiscoverer.findActuatorEndpoints(this.applicationInstance))
			.thenReturn(Mono.error(new RuntimeException("OOPSIE")));

	this.service.findActuatorEndpoints(this.applicationInstance)
			.subscribe(actuatorEndpoints -> {

				verify(this.otherActuatorEndpointsDiscoverer).findActuatorEndpoints(this.applicationInstance);
				verifyNoMoreInteractions(this.otherActuatorEndpointsDiscoverer);

				verify(this.halActuatorEndpointsDiscoverer).findActuatorEndpoints(this.applicationInstance);
				verifyNoMoreInteractions(this.halActuatorEndpointsDiscoverer);

				assertThat(actuatorEndpoints).isEmpty();
			});
}
 
Example #13
Source File: SpeakerController.java    From springrestdoc with MIT License 5 votes vote down vote up
@PostMapping
public ResponseEntity<SpeakerResource> createSpeaker(@Validated @RequestBody SpeakerDto speakerDto) {
    if (!speakerRepository.findByName(speakerDto.getName()).isPresent()) {
        Speaker savedSpeaker = speakerRepository.save(speakerDto.createSpeaker());
        Link linkToSpeaker = new SpeakerResource(savedSpeaker).getLink(Link.REL_SELF);
        return ResponseEntity.created(URI.create(linkToSpeaker.getHref())).build();
    } else {
        throw new DuplicateEntityException(Speaker.class, speakerDto.getName());
    }
}
 
Example #14
Source File: JavassistClientProxyFactoryTest.java    From bowman with Apache License 2.0 5 votes vote down vote up
@Test
public void createReturnsProxyWithLinkedResourceWithCustomRel() {
	EntityModel<Entity> resource = new EntityModel<>(new Entity(),
			new Link("http://www.example.com/association/linked", "a:b"));
	
	when(restOperations.getResource(URI.create("http://www.example.com/association/linked"),
			Entity.class)).thenReturn(new EntityModel<>(new Entity(),
					new Link("http://www.example.com/1", IanaLinkRelations.SELF)));
	
	Entity proxy = proxyFactory.create(resource, restOperations);
	
	assertThat(proxy.getLinkedWithCustomRel().getId(), is(URI.create("http://www.example.com/1")));
}
 
Example #15
Source File: SpeakerController.java    From springrestdoc with MIT License 5 votes vote down vote up
@PostMapping
public ResponseEntity<SpeakerResource> createSpeaker(@Validated @RequestBody SpeakerDto speakerDto) {
    if (!speakerRepository.findByName(speakerDto.getName()).isPresent()) {
        Speaker savedSpeaker = speakerRepository.save(speakerDto.createSpeaker());
        Link linkToSpeaker = new SpeakerResource(savedSpeaker).getLink(Link.REL_SELF);
        return ResponseEntity.created(URI.create(linkToSpeaker.getHref())).build();
    } else {
        throw new DuplicateEntityException(Speaker.class, speakerDto.getName());
    }
}
 
Example #16
Source File: HomeController.java    From spring-hateoas-examples with Apache License 2.0 5 votes vote down vote up
/**
 * Instead of putting the creation link from the remote service in the template (a security concern), have a local
 * route for {@literal POST} requests. Gather up the information, and form a remote call, using {@link Traverson} to
 * fetch the {@literal employees} {@link Link}. Once a new employee is created, redirect back to the root URL.
 *
 * @param employee
 * @return
 * @throws URISyntaxException
 */
@PostMapping("/employees")
public String newEmployee(@ModelAttribute Employee employee) throws URISyntaxException {

	Traverson client = new Traverson(new URI(REMOTE_SERVICE_ROOT_URI), MediaTypes.HAL_JSON);
	Link employeesLink = client.follow("employees").asLink();

	this.rest.postForEntity(employeesLink.expand().getHref(), employee, Employee.class);

	return "redirect:/";
}
 
Example #17
Source File: SelfLinkTypeResolver.java    From bowman with Apache License 2.0 5 votes vote down vote up
@Override
public <T> Class<? extends T> resolveType(Class<T> declaredType, Links resourceLinks, Configuration configuration) {

	Optional<Link> self = resourceLinks.getLink(IanaLinkRelations.SELF);
	
	if (!self.isPresent()) {
		return declaredType;
	}
	
	for (Class<?> candidateClass : subtypes) {
		RemoteResource candidateClassInfo = AnnotationUtils.findAnnotation(candidateClass, RemoteResource.class);
		
		if (candidateClassInfo == null) {
			throw new ClientProxyException(String.format("%s is not annotated with @%s", candidateClass.getName(),
				RemoteResource.class.getSimpleName()));
		}
		
		String resourcePath = candidateClassInfo.value();
		
		String resourceBaseUriString = UriComponentsBuilder.fromUri(configuration.getBaseUri())
			.path(resourcePath)
			.toUriString();
		
		String selfLinkUriString = toAbsoluteUriString(self.get().getHref(), configuration.getBaseUri());
		
		if (selfLinkUriString.startsWith(resourceBaseUriString + "/")) {
			if (!declaredType.isAssignableFrom(candidateClass)) {
				throw new ClientProxyException(String.format("%s is not a subtype of %s", candidateClass.getName(),
					declaredType.getName()));
			}
			
			@SuppressWarnings("unchecked")
			Class<? extends T> result = (Class<? extends T>) candidateClass;
			
			return result;
		}
	}
	
	return declaredType;
}
 
Example #18
Source File: ResourceDeserializerTest.java    From bowman with Apache License 2.0 5 votes vote down vote up
@Test
public void deserializeResolvesType() throws Exception {
	mapper.readValue("{\"_links\":{\"self\":{\"href\":\"http://x.com/1\"}}}",
		new TypeReference<EntityModel<DeclaredType>>() { /* generic type reference */ });
	
	verify(typeResolver).resolveType(DeclaredType.class,
		Links.of(new Link("http://x.com/1", IanaLinkRelations.SELF)), configuration);
}
 
Example #19
Source File: PageLinksAspect.java    From taskana with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Around("@annotation(pro.taskana.resource.rest.PageLinks) && args(data, page, ..)")
public <T extends RepresentationModel<? extends T> & ProceedingJoinPoint>
    RepresentationModel<T> addLinksToPageResource(
        ProceedingJoinPoint joinPoint, List<?> data, PageMetadata page) throws Throwable {
  HttpServletRequest request =
      ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
  Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
  PageLinks pageLinks = method.getAnnotation(PageLinks.class);
  String relativeUrl = pageLinks.value();
  UriComponentsBuilder original = originalUri(relativeUrl, request);
  RepresentationModel<T> resourceSupport = (RepresentationModel<T>) joinPoint.proceed();
  resourceSupport.add(Link.of(original.toUriString()).withSelfRel());
  if (page != null) {
    resourceSupport.add(
        Link.of(original.replaceQueryParam("page", 1).toUriString())
            .withRel(IanaLinkRelations.FIRST));
    resourceSupport.add(
        Link.of(original.replaceQueryParam("page", page.getTotalPages()).toUriString())
            .withRel(IanaLinkRelations.LAST));
    if (page.getNumber() > 1) {
      resourceSupport.add(
          Link.of(original.replaceQueryParam("page", page.getNumber() - 1).toUriString())
              .withRel(IanaLinkRelations.PREV));
    }
    if (page.getNumber() < page.getTotalPages()) {
      resourceSupport.add(
          Link.of(original.replaceQueryParam("page", page.getNumber() + 1).toUriString())
              .withRel(IanaLinkRelations.NEXT));
    }
  }
  return resourceSupport;
}
 
Example #20
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 #21
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 #22
Source File: DataFlowTemplate.java    From spring-cloud-dashboard with Apache License 2.0 5 votes vote down vote up
public Link getLink(ResourceSupport resourceSupport, String rel) {
	Link link = resourceSupport.getLink(rel);
	if (link == null) {
		throw new DataFlowServerException("Server did not return a link for '" + rel + "', links: '"
				+ resourceSupport + "'");
	}
	return link;
}
 
Example #23
Source File: PackageMetadataResourceProcessor.java    From spring-cloud-skipper with Apache License 2.0 5 votes vote down vote up
@Override
public EntityModel<PackageMetadata> process(EntityModel<PackageMetadata> packageMetadataResource) {
	Link installLink = linkTo(
			methodOn(PackageController.class).install(packageMetadataResource.getContent().getId(), null))
			.withRel("install");
	packageMetadataResource.add(installLink);
	return packageMetadataResource;
}
 
Example #24
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 #25
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 #26
Source File: ContentPropertyCollectionRestController.java    From spring-content with Apache License 2.0 5 votes vote down vote up
Resource<?> toResource(final HttpServletRequest request, Object newContent)
		throws SecurityException, BeansException {
	Link self = new Link(
			StringUtils.trimTrailingCharacter(request.getRequestURL().toString(), '/')
					+ "/"
					+ BeanUtils.getFieldWithAnnotation(newContent, ContentId.class));
	Resource<?> contentResource = new Resource<Object>(newContent,
			Collections.singletonList(self));
	return contentResource;
}
 
Example #27
Source File: JavassistClientProxyFactoryTest.java    From bowman with Apache License 2.0 5 votes vote down vote up
@Test
public void createWithLinkedResourceTargetNotPresentReturnsProxyReturningNull() {
	EntityModel<Entity> resource = new EntityModel<>(new Entity(),
		new Link("http://www.example.com/association/linked", "linked"));

	when(restOperations.getResource(URI.create("http://www.example.com/association/linked"),
			Entity.class)).thenReturn(null);
	
	Entity proxy = proxyFactory.create(resource, restOperations);
	
	assertThat(proxy.linked(), is(nullValue()));
}
 
Example #28
Source File: AcctController.java    From Spring5Tutorial with GNU Lesser General Public License v3.0 5 votes vote down vote up
@PostMapping("tryCreateUser")
public Resource<Optional<Account>> tryCreateUser(
		@RequestParam("email") String email, 
		@RequestParam("username") String username, 
		@RequestParam("password") String password) {
	
	Optional<Account> acct = accountService.tryCreateUser(email, username, password);

	String uri = String.format("%s/tryCreateUser?email=%s&username=%s&password=%s", linkTo(AcctController.class), email, username, password);
	return new Resource<>(acct, new Link(uri));
}
 
Example #29
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 #30
Source File: DefaultTypeResolverTest.java    From bowman with Apache License 2.0 5 votes vote down vote up
@Test
public void resolveTypeWithNoResourceTypeInfoReturnsDeclaredType() {
	Class<?> type = resolver.resolveType(TypeWithoutInfo.class,
		Links.of(new Link("http://x", IanaLinkRelations.SELF)), Configuration.build());
	
	assertThat(type, Matchers.<Class<?>>equalTo(TypeWithoutInfo.class));
}