Java Code Examples for org.springframework.hateoas.Link

The following examples show how to use org.springframework.hateoas.Link. These examples are extracted from open source projects. 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 Project: springdoc-openapi   Author: springdoc   File: SpringDocHateoasConfiguration.java    License: 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 #2
Source Project: microservices-dashboard   Author: ordina-jworks   File: ApplicationInstanceHealthWatcherTests.java    License: 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 #3
Source Project: spring-cloud-openfeign   Author: spring-cloud   File: FeignHalTests.java    License: 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 #4
Source Project: microservices-dashboard   Author: ordina-jworks   File: ActuatorEndpointsDiscovererServiceTests.java    License: 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 #5
Source Project: microservices-dashboard   Author: ordina-jworks   File: ApplicationInstanceHealthWatcherTests.java    License: 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 #6
Source Project: taskana   Author: Taskana   File: AbstractRessourcesAssembler.java    License: 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 #7
Source Project: spring-hateoas-examples   Author: spring-projects   File: EmployeeController.java    License: 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 #8
Source Project: spring-hateoas-examples   Author: spring-projects   File: EmployeeController.java    License: 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 #9
Source Project: microservices-dashboard   Author: ordina-jworks   File: ActuatorEndpointsDiscovererServiceTests.java    License: 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 #10
Source Project: spring-cloud-dashboard   Author: spring-cloud   File: RootController.java    License: 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 #11
Source Project: spring-content   Author: paulcwarren   File: LockingAndVersioningRestController.java    License: 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 #12
Source Project: spring-content   Author: paulcwarren   File: ContentSearchRestController.java    License: 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 #13
Source Project: bowman   Author: BlackPepperSoftware   File: DefaultTypeResolverTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void resolveTypeWithSubtypesAndMatchingAbsolutePathReferenceUriSubtypeReturnsSubtype() {
	Configuration config = Configuration.builder().setBaseUri("http://x.com").build();
	
	Class<?> type = resolver.resolveType(TypeWithSubtypes.class,
		Links.of(new Link("/2/1", IanaLinkRelations.SELF)), config);
	
	assertThat(type, Matchers.<Class<?>>equalTo(TypeWithSubtypesSubtype2.class));
}
 
Example #14
Source Project: microservices-dashboard   Author: ordina-jworks   File: ApplicationInstanceHealthWatcherTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotRetrieveTheHealthDataAfterActuatorEndpointsHaveBeenUpdatedWithoutHealthLink() {
	ActuatorEndpointsUpdated event =
			ApplicationInstanceEventMother.actuatorEndpointsUpdated("a-1", "a",
					new Links(new Link("http://localhost:8080/actuator/info", "info")));

	this.healthWatcher.retrieveHealthData(event);

	verifyZeroInteractions(this.webClient);
	verifyZeroInteractions(this.requestHeadersUriSpec);
	verifyZeroInteractions(this.requestHeadersSpec);
	verifyZeroInteractions(this.responseSpec);
	verifyZeroInteractions(this.applicationInstanceService);
}
 
Example #15
Source Project: microservices-dashboard   Author: ordina-jworks   File: HalActuatorEndpointsDiscovererTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnListWithDiscoveredEndpointsFromResponse() {
	String body = "{\"_links\":{\"self\":{\"href\":\"http://localhost:8080/actuator\",\"templated\":false},\"health-component-instance\":{\"href\":\"http://localhost:8080/actuator/health/{component}/{instance}\",\"templated\":true},\"health-component\":{\"href\":\"http://localhost:8080/actuator/health/{component}\",\"templated\":true},\"health\":{\"href\":\"http://localhost:8080/actuator/health\",\"templated\":false},\"info\":{\"href\":\"http://localhost:8080/actuator/info\",\"templated\":false}}}";
	when(this.clientResponse.toEntity(String.class))
			.thenReturn(Mono.just(ResponseEntity.ok(body)));
	when(this.linkDiscoverers.getLinkDiscovererFor(MediaTypes.HAL_JSON_UTF8))
			.thenReturn(this.linkDiscoverer);
	when(this.linkDiscoverer.findLinkWithRel("self", body))
			.thenReturn(new Link("http://localhost:8080/actuator", "self"));
	when(this.linkDiscoverer.findLinkWithRel("health-component-instance", body))
			.thenReturn(new Link("http://localhost:8080/actuator/health/{component}/instance/{instance}", "health-component-instance"));
	when(this.linkDiscoverer.findLinkWithRel("health-component", body))
			.thenReturn(new Link("http://localhost:8080/actuator/health/{component}", "health-component"));
	when(this.linkDiscoverer.findLinkWithRel("health", body))
			.thenReturn(new Link("http://localhost:8080/actuator/health", "health"));
	when(this.linkDiscoverer.findLinkWithRel("info", body))
			.thenReturn(new Link("http://localhost:8080/actuator/info", "info"));

	this.discoverer.findActuatorEndpoints(this.applicationInstance)
			.subscribe(actuatorEndpoints -> {
				assertThat(actuatorEndpoints).hasSize(5);

				verify(this.webClient).get();
				verifyNoMoreInteractions(this.webClient);
				verify(this.requestHeadersSpec).exchange();
				verifyNoMoreInteractions(this.requestHeadersSpec);
				verify(this.requestHeadersUriSpec).uri(URI.create("http://localhost:8080/actuator"));
				verifyNoMoreInteractions(this.requestHeadersUriSpec);
				verify(this.clientResponse).toEntity(String.class);
				verifyNoMoreInteractions(this.clientResponse);
				verify(this.linkDiscoverers, times(5)).getLinkDiscovererFor(MediaTypes.HAL_JSON_UTF8);
				verifyNoMoreInteractions(this.linkDiscoverers);
				verify(this.linkDiscoverer).findLinkWithRel("self", body);
				verify(this.linkDiscoverer).findLinkWithRel("health-component-instance", body);
				verify(this.linkDiscoverer).findLinkWithRel("health-component", body);
				verify(this.linkDiscoverer).findLinkWithRel("health", body);
				verify(this.linkDiscoverer).findLinkWithRel("info", body);
				verifyNoMoreInteractions(this.linkDiscoverer);
			});
}
 
Example #16
Source Project: spring-cloud-openfeign   Author: spring-cloud   File: FeignHalController.java    License: 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);
}
 
Example #17
Source Project: Spring5Tutorial   Author: JustinSDK   File: AcctController.java    License: 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 #18
Source Project: microservices-dashboard   Author: ordina-jworks   File: ApplicationInstanceTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void sameActuatorEndpointsWillNotBeMarkedAsChanged() {
	Links newLinks = new Links(new Link("http://localhost:8080/actuator/health", "health"));
	ApplicationInstance applicationInstance = ApplicationInstanceMother.instance("a-1", "a",
			URI.create("http://localhost:8080"),
			new Links(new Link("http://localhost:8080/actuator/health", "health")));
	applicationInstance.markChangesAsCommitted();

	applicationInstance.updateActuatorEndpoints(newLinks);

	assertThat(applicationInstance.getUncommittedChanges()).isEmpty();
}
 
Example #19
Source Project: Spring5Tutorial   Author: JustinSDK   File: MsgController.java    License: 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 #20
Source Project: Spring5Tutorial   Author: JustinSDK   File: MsgController.java    License: 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 #21
Source Project: microservices-dashboard   Author: ordina-jworks   File: ActuatorEndpointsDiscovererServiceTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnMapOfDiscoveredEndpointsByAnotherDiscovererThanDefault() {
	when(this.otherActuatorEndpointsDiscoverer.findActuatorEndpoints(this.applicationInstance))
			.thenReturn(Mono.just(new Links(new Link("http://localhost:8081/actuator/health", "health"))));

	this.service.findActuatorEndpoints(this.applicationInstance)
			.subscribe(actuatorEndpoints -> {
				verify(this.halActuatorEndpointsDiscoverer).findActuatorEndpoints(this.applicationInstance);
				verifyNoMoreInteractions(this.halActuatorEndpointsDiscoverer);

				assertThat(actuatorEndpoints).isNotEmpty();
				assertThat(actuatorEndpoints.hasLink("health")).isTrue();
				assertThat(actuatorEndpoints.getLink("health").getHref()).isEqualTo("http://localhost:8081/actuator/health");
			});
}
 
Example #22
Source Project: Spring5Tutorial   Author: JustinSDK   File: AcctController.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
@PutMapping("verify")
public Resource<Optional<Account>> verify(
		@RequestParam("email") String email, 
		@RequestParam("token") String token) {
	
	Optional<Account> acct = accountService.verify(email, token);

	String uri = String.format("%s/verify?email=%s&token=%s", linkTo(AcctController.class), email, token);
	return new Resource<>(acct, new Link(uri));
}
 
Example #23
Source Project: bowman   Author: BlackPepperSoftware   File: MethodLinkUriResolverTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void resolveForMethodReturnsUriWithParamsExpanded() {
	EntityModel<Object> resource = new EntityModel<>(new Object(),
		Links.of(new Link("http://www.example.com/{?x,y}",
			"link1")));
	
	URI uri = new MethodLinkUriResolver().resolveForMethod(resource, "link1", new Object[] {"1", 2});
	
	assertThat(uri, is(URI.create("http://www.example.com/?x=1&y=2")));
}
 
Example #24
Source Project: Spring5Tutorial   Author: JustinSDK   File: MsgController.java    License: 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 #25
Source Project: Spring5Tutorial   Author: JustinSDK   File: MsgController.java    License: 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 #26
Source Project: microservices-dashboard   Author: ordina-jworks   File: ApplicationInstanceHealthWatcherTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHandleApplicationInstanceEventHandlesError() {
	URI healthActuatorEndpoint = URI.create("http://localhost:8080/actuator/health");
	ActuatorEndpointsUpdated event =
			ApplicationInstanceEventMother.actuatorEndpointsUpdated("a-1", "a",
			new Links(new Link(healthActuatorEndpoint.toString(), "health")));

	when(this.responseSpec.bodyToMono(ApplicationInstanceHealthWatcher.HealthWrapper.class))
			.thenReturn(Mono.error(new RuntimeException("OOPSIE!")));

	this.healthWatcher.retrieveHealthData(event);

	assertHealthInfoRetrievalFailed((ApplicationInstance) event.getSource(), healthActuatorEndpoint);
}
 
Example #27
Source Project: Spring5Tutorial   Author: JustinSDK   File: AcctController.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
@PutMapping("verify")
public Resource<Optional<Account>> verify(
		@RequestParam("email") String email, 
		@RequestParam("token") String token) {
	
	Optional<Account> acct = accountService.verify(email, token);

	String uri = String.format("%s/verify?email=%s&token=%s", linkTo(AcctController.class), email, token);
	return new Resource<>(acct, new Link(uri));
}
 
Example #28
Source Project: Spring5Tutorial   Author: JustinSDK   File: MsgController.java    License: 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 #29
Source Project: Spring5Tutorial   Author: JustinSDK   File: MsgController.java    License: 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 Project: Spring5Tutorial   Author: JustinSDK   File: AcctController.java    License: 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));
}