Java Code Examples for org.springframework.hateoas.Link

The following are top voted examples for showing how to use org.springframework.hateoas.Link. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: spring-data-examples   File: StarbucksClient.java   View source code 9 votes vote down vote up
@Test
public void accessServiceUsingRestTemplate() {

	// Access root resource

	URI uri = URI.create(String.format(SERVICE_URI, port));
	RequestEntity<Void> request = RequestEntity.get(uri).accept(HAL_JSON).build();
	Resource<Object> rootLinks = restOperations.exchange(request, new ResourceType<Object>() {}).getBody();
	Links links = new Links(rootLinks.getLinks());

	// Follow stores link

	Link storesLink = links.getLink("stores").expand();
	request = RequestEntity.get(URI.create(storesLink.getHref())).accept(HAL_JSON).build();
	Resources<Store> stores = restOperations.exchange(request, new ResourcesType<Store>() {}).getBody();

	stores.getContent().forEach(store -> log.info("{} - {}", store.name, store.address));
}
 
Example 2
Project: spring-hateoas-examples   File: EmployeeController.java   View source code 7 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 Resource<>(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")
	).getId()
		.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 3
Project: REST-Web-Services   File: MovieContributionRestController.java   View source code 6 votes vote down vote up
@ApiOperation(value = "Get the contribution of titles")
@ApiResponses(value = { @ApiResponse(code = 404, message = "No contribution found") })
@GetMapping(value = "/contributions/{id}/othertitles", produces = MediaTypes.HAL_JSON_VALUE)
@ResponseStatus(HttpStatus.OK)
public
ContributionResource<OtherTitle> getOtherTitleContribution(
        @ApiParam(value = "The contribution ID", required = true)
        @PathVariable("id") final Long id
) {
    log.info("Called with id {}", id);

    final Contribution<OtherTitle> otherTitleContribution = this.movieContributionSearchService.getOtherTitleContribution(id);

    final Link self = linkTo(
            methodOn(MovieContributionRestController.class).getOtherTitleContribution(id)
    ).withSelfRel();

    return new ContributionResource<>(otherTitleContribution, self);
}
 
Example 4
Project: REST-Web-Services   File: MovieContributionRestController.java   View source code 6 votes vote down vote up
@ApiOperation(value = "Get the contribution of release dates")
@ApiResponses(value = { @ApiResponse(code = 404, message = "No contribution found") })
@GetMapping(value = "/contributions/{id}/releasedates", produces = MediaTypes.HAL_JSON_VALUE)
@ResponseStatus(HttpStatus.OK)
public
ContributionResource<ReleaseDate> getReleaseDateContribution(
        @ApiParam(value = "The contribution ID", required = true) @PathVariable("id") final Long id
) {
    log.info("Called with id {}", id);

    final Contribution<ReleaseDate> releaseDateContribution = this.movieContributionSearchService.getReleaseDateContribution(id);

    final Link self = linkTo(
            methodOn(MovieContributionRestController.class).getReleaseDateContribution(id)
    ).withSelfRel();

    return new ContributionResource<>(releaseDateContribution, self);
}
 
Example 5
Project: REST-Web-Services   File: MovieContributionRestController.java   View source code 6 votes vote down vote up
@ApiOperation(value = "Get the contribution of storylines")
@ApiResponses(value = { @ApiResponse(code = 404, message = "No contribution found") })
@GetMapping(value = "/contributions/{id}/storylines", produces = MediaTypes.HAL_JSON_VALUE)
@ResponseStatus(HttpStatus.OK)
public
ContributionResource<Storyline> getStorylineContribution(
        @ApiParam(value = "The contribution ID", required = true)
        @PathVariable("id") final Long id
) {
    log.info("Called with id {}", id);

    final Contribution<Storyline> storylineContribution = this.movieContributionSearchService.getStorylineContribution(id);

    final Link self = linkTo(
            methodOn(MovieContributionRestController.class).getStorylineContribution(id)
    ).withSelfRel();

    return new ContributionResource<>(storylineContribution, self);
}
 
Example 6
Project: REST-Web-Services   File: MovieContributionRestController.java   View source code 6 votes vote down vote up
@ApiOperation(value = "Get the contribution of box offices")
@ApiResponses(value = { @ApiResponse(code = 404, message = "No contribution found") })
@GetMapping(value = "/contributions/{id}/boxoffices", produces = MediaTypes.HAL_JSON_VALUE)
@ResponseStatus(HttpStatus.OK)
public
ContributionResource<BoxOffice> getBoxOfficeContribution(
        @ApiParam(value = "The contribution ID", required = true)
        @PathVariable("id") final Long id
) {
    log.info("Called with id {}", id);

    final Contribution<BoxOffice> boxOfficeContribution = this.movieContributionSearchService.getBoxOfficeContribution(id);

    final Link self = linkTo(
            methodOn(MovieContributionRestController.class).getBoxOfficeContribution(id)
    ).withSelfRel();

    return new ContributionResource<>(boxOfficeContribution, self);
}
 
Example 7
Project: REST-Web-Services   File: MovieContributionRestController.java   View source code 6 votes vote down vote up
@ApiOperation(value = "Get the contribution of sites")
@ApiResponses(value = { @ApiResponse(code = 404, message = "No contribution found") })
@GetMapping(value = "/contributions/{id}/sites", produces = MediaTypes.HAL_JSON_VALUE)
@ResponseStatus(HttpStatus.OK)
public
ContributionResource<Site> getSiteContribution(
        @ApiParam(value = "The contribution ID", required = true)
        @PathVariable("id") final Long id
) {
    log.info("Called with id {}", id);

    final Contribution<Site> siteContribution = this.movieContributionSearchService.getSiteContribution(id);

    final Link self = linkTo(
            methodOn(MovieContributionRestController.class).getSiteContribution(id)
    ).withSelfRel();

    return new ContributionResource<>(siteContribution, self);
}
 
Example 8
Project: REST-Web-Services   File: MovieContributionRestController.java   View source code 6 votes vote down vote up
@ApiOperation(value = "Get the contribution of countries")
@ApiResponses(value = { @ApiResponse(code = 404, message = "No contribution found") })
@GetMapping(value = "/contributions/{id}/countries", produces = MediaTypes.HAL_JSON_VALUE)
@ResponseStatus(HttpStatus.OK)
public
ContributionResource<Country> getCountryContribution(
        @ApiParam(value = "The contribution ID", required = true)
        @PathVariable("id") final Long id
) {
    log.info("Called with id {}", id);

    final Contribution<Country> countryContribution = this.movieContributionSearchService.getCountryContribution(id);

    final Link self = linkTo(
            methodOn(MovieContributionRestController.class).getCountryContribution(id)
    ).withSelfRel();

    return new ContributionResource<>(countryContribution, self);
}
 
Example 9
Project: REST-Web-Services   File: MovieContributionRestController.java   View source code 6 votes vote down vote up
@ApiOperation(value = "Get the contribution of languages")
@ApiResponses(value = { @ApiResponse(code = 404, message = "No contribution found") })
@GetMapping(value = "/contributions/{id}/languages", produces = MediaTypes.HAL_JSON_VALUE)
@ResponseStatus(HttpStatus.OK)
public
ContributionResource<Language> getLanguageContribution(
        @ApiParam(value = "The contribution ID", required = true)
        @PathVariable("id") final Long id
) {
    log.info("Called with id {}", id);

    final Contribution<Language> languageContribution = this.movieContributionSearchService.getLanguageContribution(id);

    final Link self = linkTo(
            methodOn(MovieContributionRestController.class).getLanguageContribution(id)
    ).withSelfRel();

    return new ContributionResource<>(languageContribution, self);
}
 
Example 10
Project: REST-Web-Services   File: MovieContributionRestController.java   View source code 6 votes vote down vote up
@ApiOperation(value = "Get the contribution of genres")
@ApiResponses(value = { @ApiResponse(code = 404, message = "No contribution found") })
@GetMapping(value = "/contributions/{id}/genres", produces = MediaTypes.HAL_JSON_VALUE)
@ResponseStatus(HttpStatus.OK)
public
ContributionResource<Genre> getGenreContribution(
        @ApiParam(value = "The contribution ID", required = true)
        @PathVariable("id") final Long id
) {
    log.info("Called with id {}", id);

    final Contribution<Genre> genreContribution = this.movieContributionSearchService.getGenreContribution(id);

    final Link self = linkTo(
            methodOn(MovieContributionRestController.class).getGenreContribution(id)
    ).withSelfRel();

    return new ContributionResource<>(genreContribution, self);
}
 
Example 11
Project: REST-Web-Services   File: MovieContributionRestController.java   View source code 6 votes vote down vote up
@ApiOperation(value = "Get the contribution of reviews")
@ApiResponses(value = { @ApiResponse(code = 404, message = "No contribution found") })
@GetMapping(value = "/contributions/{id}/reviews", produces = MediaTypes.HAL_JSON_VALUE)
@ResponseStatus(HttpStatus.OK)
public
ContributionResource<Review> getReviewContribution(
        @ApiParam(value = "The contribution ID", required = true)
        @PathVariable("id") final Long id
) {
    log.info("Called with id {}", id);

    final Contribution<Review> reviewContribution = this.movieContributionSearchService.getReviewContribution(id);

    final Link self = linkTo(
            methodOn(MovieContributionRestController.class).getReviewContribution(id)
    ).withSelfRel();

    return new ContributionResource<>(reviewContribution, self);
}
 
Example 12
Project: REST-Web-Services   File: MovieContributionRestController.java   View source code 6 votes vote down vote up
@ApiOperation(value = "Get the contribution of photos")
@ApiResponses(value = { @ApiResponse(code = 404, message = "No contribution found") })
@GetMapping(value = "/contributions/{id}/photos", produces = MediaTypes.HAL_JSON_VALUE)
@ResponseStatus(HttpStatus.OK)
public
ContributionResource<ImageResponse> getPhotoContribution(
        @ApiParam(value = "The contribution ID", required = true)
        @PathVariable("id") final Long id
) {
    log.info("Called with id {}", id);

    final Contribution<ImageResponse> photoContribution = this.movieContributionSearchService.getPhotoContribution(id);

    final Link self = linkTo(
            methodOn(MovieContributionRestController.class).getPhotoContribution(id)
    ).withSelfRel();

    return new ContributionResource<>(photoContribution, self);
}
 
Example 13
Project: REST-Web-Services   File: MovieContributionRestController.java   View source code 6 votes vote down vote up
@ApiOperation(value = "Get the contribution of posters")
@ApiResponses(value = { @ApiResponse(code = 404, message = "No contribution found") })
@GetMapping(value = "/contributions/{id}/posters", produces = MediaTypes.HAL_JSON_VALUE)
@ResponseStatus(HttpStatus.OK)
public
ContributionResource<ImageResponse> getPosterContribution(
        @ApiParam(value = "The contribution ID", required = true)
        @PathVariable("id") final Long id
) {
    log.info("Called with id {}", id);

    final Contribution<ImageResponse> posterContribution = this.movieContributionSearchService.getPosterContribution(id);

    final Link self = linkTo(
            methodOn(MovieContributionRestController.class).getPosterContribution(id)
    ).withSelfRel();

    return new ContributionResource<>(posterContribution, self);
}
 
Example 14
Project: composed-task-runner   File: TaskLauncherTaskletTests.java   View source code 6 votes vote down vote up
@Test
@DirtiesContext
public void testInvalidTaskName() throws Exception {
	String exceptionMessage = null;
	final String ERROR_MESSAGE =
			"Could not find task definition named " + TASK_NAME;
	VndErrors errors = new VndErrors("message", ERROR_MESSAGE, new Link("ref"));
	Mockito.doThrow(new DataFlowClientException(errors))
			.when(this.taskOperations)
			.launch(Matchers.anyString(),
					(Map<String, String>) Matchers.any(),
					(List<String>) Matchers.any());
	TaskLauncherTasklet taskLauncherTasklet = getTaskExecutionTasklet();
	ChunkContext chunkContext = chunkContext();
	try {
		taskLauncherTasklet.execute(null, chunkContext);
	}
	catch (DataFlowClientException dfce) {
		exceptionMessage = dfce.getMessage();
	}
	assertEquals(ERROR_MESSAGE+"\n", exceptionMessage);
}
 
Example 15
Project: catpeds   File: PedigreeResourceFactoryTest.java   View source code 6 votes vote down vote up
/**
 * Check that {@link PedigreeResourceFactory#create(Pedigree)} instantiates the
 * {@link PedigreeResource} with the {@link Pedigree} and Link.
 */
@Test
public void testCreate() {
	// Given
	Link link = mock(Link.class);
	when(hateoasFactory.createResourceLink(pedigree)).thenReturn(link);

	// When
	PedigreeResource resource = pedigreeResourceFactory.create(pedigree);

	// Then
	assertNotNull("Expecting an instance", resource);
	assertSame("Expecting the pedigree passed as argument", pedigree, resource.getPedigree());
	assertEquals("Expecting one link", 1, resource.getLinks().size());
	assertSame("Expecting the Link instance for the Link factory", link, resource.getLinks().get(0));
}
 
Example 16
Project: TOSCAna   File: CommonController.java   View source code 6 votes vote down vote up
@RequestMapping(
    value = {"/status/", "/status"},
    method = RequestMethod.GET,
    produces = "application/hal+json"
)
@ApiOperation(
    value = "Hypermedia endpoint to get all supported Status operations",
    notes = "Status operations are based on Spring Boot Actuator",
    produces = "application/hal+json",
    response = ResourceSupport.class
)
public ResourceSupport getStatusIndex(HttpServletRequest request) throws Exception {
    String baseURL = request.getRequestURL().toString()
        .replace("/api/status", "").replace("/api/status/", "");
    ResourceSupport support = new HiddenResourceSupport();
    support.add(new Link(baseURL + actuatorHealthPath, "health"));
    support.add(new Link(baseURL + actuatorMetricsPath, "metrics"));
    if (actuatorMappingsActive)
        support.add(new Link(baseURL + actuatorMappingsPath, "mappings"));
    support.add(linkTo(methodOn(CommonController.class).getStatusIndex(null)).withSelfRel());
    return support;
}
 
Example 17
Project: TOSCAna   File: CsarController.java   View source code 6 votes vote down vote up
/**
 Responds with a list of csars stored on the transformer.
 <p>
 This always responds with HTTP-Code 200 (application/hal+json)
 */
@ApiOperation(
    value = "List all CSARs stored on the server",
    notes = "Returns a Hypermedia Resource containing all CSARs" +
        " that have been uploaded to the server and did not get removed",
    response = CsarResources.class,
    produces = "application/hal+json"
)
@RequestMapping(
    path = "",
    method = RequestMethod.GET,
    produces = "application/hal+json"
)
public ResponseEntity<Resources<CsarResponse>> listCSARs() {
    Link selfLink = linkTo(methodOn(CsarController.class).listCSARs()).withSelfRel();
    List<CsarResponse> responses = new ArrayList<>();
    for (Csar csar : csarService.getCsars()) {
        responses.add(new CsarResponse(csar.getIdentifier()));
    }
    Resources<CsarResponse> csarResources = new HiddenResources<>(responses, selfLink);
    return ResponseEntity.ok().body(csarResources);
}
 
Example 18
Project: TOSCAna   File: PlatformController.java   View source code 6 votes vote down vote up
/**
 Lists all Supported Platforms (HTTP Response Method).
 <p>
 It handles the <code>/platforms</code> Request
 <p>
 Always responds with HTTP-Code 200 (application/hal+json)
 */
@ApiOperation(
    value = "List all supported Platforms",
    notes = "Returns a HAL resource (_embedded) containing all " +
        "Platforms supported by this transformer",
    code = 200,
    response = PlatformResources.class
)
@RequestMapping(
    path = "",
    method = RequestMethod.GET,
    produces = "application/hal+json"
)
public ResponseEntity<Resources<PlatformResponse>> getPlatforms() {
    Link selfLink = linkTo(methodOn(PlatformController.class).getPlatforms()).withSelfRel();
    ArrayList<PlatformResponse> responses = new ArrayList<>();
    for (Platform platform : platformService.getSupportedPlatforms()) {
        logger.info("Adding Platform {} to response ", platform.id);
        PlatformResponse res = getPlatformResource(platform);
        responses.add(res);
    }
    Resources<PlatformResponse> resources = new HiddenResources<>(responses, selfLink);

    return ResponseEntity.ok(resources);
}
 
Example 19
Project: spring-hateoas-examples   File: EmployeeController.java   View source code 6 votes vote down vote up
@PostMapping("/employees")
ResponseEntity<?> newEmployee(@RequestBody Employee employee) {

	Employee savedEmployee = repository.save(employee);

	return new Resource<>(savedEmployee,
		linkTo(methodOn(EmployeeController.class).findOne(savedEmployee.getId())).withSelfRel()
			.andAffordance(afford(methodOn(EmployeeController.class).updateEmployee(null, savedEmployee.getId())))
			.andAffordance(afford(methodOn(EmployeeController.class).deleteEmployee(savedEmployee.getId()))),
		linkTo(methodOn(EmployeeController.class).findAll()).withRel("employees")
	).getId()
		.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 create " + employee));
}
 
Example 20
Project: spring-hateoas-examples   File: HomeController.java   View source code 6 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 21
Project: spring-hateoas-examples   File: HomeController.java   View source code 6 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 22
Project: ingest-core   File: SubmissionEnvelopeResourceProcessor.java   View source code 6 votes vote down vote up
private Optional<Link> getStateTransitionLink(SubmissionEnvelope submissionEnvelope, SubmissionState targetState) {
    Optional<String> transitionResourceName = getSubresourceNameForSubmissionState(targetState);
    if (transitionResourceName.isPresent()) {
        Optional<String> rel = getRelNameForSubmissionState(targetState);
        if (rel.isPresent()) {
            return Optional.of(entityLinks.linkForSingleResource(submissionEnvelope)
                    .slash(transitionResourceName.get())
                    .withRel(rel.get()));
        } else {
            throw new RuntimeException(String.format("Unexpected link/rel mismatch exception (link = '%s', rel = " +
                    "'%s')", transitionResourceName.toString(), rel.toString()));
        }
    } else {
        return Optional.empty();
    }
}
 
Example 23
Project: ingest-core   File: MetadataDocumentResourceProcessor.java   View source code 6 votes vote down vote up
private Optional<Link> getStateTransitionLink(MetadataDocument metadataDocument, ValidationState targetState) {
    Optional<String> transitionResourceName = getSubresourceNameForValidationState(targetState);
    if (transitionResourceName.isPresent()) {
        Optional<String> rel = getRelNameForValidationState(targetState);
        if (rel.isPresent()) {
            return Optional.of(entityLinks.linkForSingleResource(metadataDocument)
                                       .slash(transitionResourceName.get())
                                       .withRel(rel.get()));
        }
        else {
            throw new RuntimeException(String.format("Unexpected link/rel mismatch exception (link = '%s', rel = " +
                                                             "'%s')",
                                                     transitionResourceName.toString(),
                                                     rel.toString()));
        }
    }
    else {
        return Optional.empty();
    }
}
 
Example 24
Project: spring-cloud-dashboard   File: RootController.java   View source code 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 25
Project: microservice-dojo   File: ProfilesServiceApplication.java   View source code 6 votes vote down vote up
@RequestMapping(method = RequestMethod.GET)
Collection<Resource<String>> readPhotos(@PathVariable String key) {

    Profile profile = this.profilesRepository.findOne(key);

    Collection<Resource<String>> coll = new LinkedList<>();

    profile.photosList().forEach(photoId -> {
        Resource<String> resource = new Resource<>(photoId);
        resource.add(new Link(ServletUriComponentsBuilder.fromCurrentRequest()
                .path("/{id}/photo").buildAndExpand(photoId).toString(), photoId));

        coll.add(resource);
    });

    return coll;
}
 
Example 26
Project: microservice-dojo   File: AccountsServiceApplication.java   View source code 6 votes vote down vote up
@Override
public Resource<Account> process(Resource<Account> accountResource) {

    Account account = accountResource.getContent();

    URI profileUri = this.profilesClient.getProfileUri(account);

    if (null != profileUri) {
        Link profileLink = new Link(profileUri.toString(), "profile");
        accountResource.add(profileLink);
    }

    ResponseEntity<Profile> profile = profilesServiceProxy.getProfile(account.getUsername());
    if (null != profile)
        accountResource.getContent().updateWithProfileData(profile.getBody());

    return accountResource;
}
 
Example 27
Project: microservice-dojo   File: AccountsServiceApplication.java   View source code 6 votes vote down vote up
@Override
public Resource<Account> process(Resource<Account> accountResource) {

    Account account = accountResource.getContent();

    URI profileUri = this.profilesClient.getProfileUri(account);

    if (null != profileUri) {
        Link profileLink = new Link(profileUri.toString(), "profile");
        accountResource.add(profileLink);
    }

    ResponseEntity<Profile> profile = profilesServiceProxy.getProfile(account.getUsername());
    if (null != profile)
        accountResource.getContent().updateWithProfileData(profile.getBody());

    return accountResource;
}
 
Example 28
Project: microservice-dojo   File: ProfilesServiceApplication.java   View source code 6 votes vote down vote up
@RequestMapping(method = RequestMethod.GET)
Collection<Resource<String>> readPhotos(@PathVariable String key) {

    Profile profile = this.profilesRepository.findOne(key);

    Collection<Resource<String>> coll = new LinkedList<>();

    profile.photosList().forEach(photoId -> {
        Resource<String> resource = new Resource<>(photoId);
        resource.add(new Link(ServletUriComponentsBuilder.fromCurrentRequest()
                .path("/{id}/photo").buildAndExpand(photoId).toString(), photoId));

        coll.add(resource);
    });

    return coll;
}
 
Example 29
Project: microservice-dojo   File: AccountsServiceApplication.java   View source code 6 votes vote down vote up
@Override
    public Resource<Account> process(Resource<Account> accountResource) {

        Account account = accountResource.getContent();

        URI profileUri = this.profilesClient.getProfileUri(account);

        if (null != profileUri) {
            Link profileLink = new Link(profileUri.toString(), "profile");
            accountResource.add(profileLink);
        }

// tag::feign-using[]
        ResponseEntity<Profile> profile = profilesServiceProxy.getProfile(account.getUsername());
        if (null != profile)
            accountResource.getContent().updateWithProfileData(profile.getBody());
// end::feign-using[]

        return accountResource;
    }
 
Example 30
Project: microservice-dojo   File: ProfilesServiceApplication.java   View source code 6 votes vote down vote up
@RequestMapping(method = RequestMethod.GET)
Collection<Resource<String>> readPhotos(@PathVariable String key) {

    Profile profile = this.profilesRepository.findOne(key);

    Collection<Resource<String>> coll = new LinkedList<>();

    profile.photosList().forEach(photoId -> {
        Resource<String> resource = new Resource<>(photoId);
        resource.add(new Link(ServletUriComponentsBuilder.fromCurrentRequest()
                .path("/{id}/photo").buildAndExpand(photoId).toString(), photoId));

        coll.add(resource);
    });

    return coll;
}
 
Example 31
Project: microservice-dojo   File: AccountsServiceApplication.java   View source code 6 votes vote down vote up
@Override
    public Resource<Account> process(Resource<Account> accountResource) {

        Account account = accountResource.getContent();

        URI profileUri = this.profilesClient.getProfileUri(account);

        if (null != profileUri) {
            Link profileLink = new Link(profileUri.toString(), "profile");
            accountResource.add(profileLink);
        }
// end::account-resource[]
// tag::updateAccountWithProfileInfo[]
        ResponseEntity<Profile> profile = this.profilesClient.getProfile(profileUri);
        if (null != profile)
            accountResource.getContent().updateWithProfileData(profile.getBody());
// end::updateAccountWithProfileInfo[]
// tag::account-resource[]
        return accountResource;
    }
 
Example 32
Project: coordinated-entry   File: EligibleClientsControllerV2.java   View source code 6 votes vote down vote up
@Override
public Resource<EligibleClientModel> toResource(EligibleClient arg0) {
	EligibleClientModel model = eligibleClientsTranslator.translate(arg0);
	if(arg0.getClient()!=null) {
		ClientModel clientModel = new ClientModel();
		if(arg0.getClient()!=null) {
			if(arg0.getClient().getDob()!=null) clientModel.setDob(Date.from( arg0.getClient().getDob().atZone(ZoneId.systemDefault()).toInstant()));
			clientModel.setEmailAddress(arg0.getClient().getEmailAddress());
			clientModel.setFirstName(arg0.getClient().getFirstName());
			clientModel.setLastName(arg0.getClient().getLastName());
			clientModel.setMiddleName(arg0.getClient().getMiddleName());
			clientModel.setPhoneNumber(arg0.getClient().getPhoneNumber());
			clientModel.setId(arg0.getClient().getId());
		}
		model.setClient(clientModel);
	}
	Resource<EligibleClientModel> resource = new Resource<EligibleClientModel>(model);
	if(arg0.getClientLink()!=null)
		resource.add(new Link(arg0.getClientLink()).withRel("client"));
	return resource;
}
 
Example 33
Project: service-integration-sdk   File: SubscriptionOrderEventParser.java   View source code 6 votes vote down vote up
@Override
public SubscriptionOrder parse(EventInfo eventInfo, EventHandlingContext eventContext) {
	String samlIdpUrl = eventInfo.getLinks().stream().filter(link -> link.getRel().equals("samlIdp")).findFirst().map(Link::getHref).orElse(null);

	return new SubscriptionOrder(
			eventContext.getConsumerKeyUsedByTheRequest(),
			eventInfo.getFlag(),
			eventInfo.getCreator(),
			eventInfo.getPayload().getConfiguration(),
			eventInfo.getPayload().getCompany(),
			eventInfo.getPayload().getAccount(),
			eventInfo.getPayload().getOrder(),
			eventInfo.getMarketplace().getPartner(),
			eventInfo.getApplicationUuid(),
			eventContext.getQueryParameters(),
			eventInfo.getId(),
			eventInfo.getMarketplace().getBaseUrl(),
			samlIdpUrl
	);
}
 
Example 34
Project: micro-ecommerce   File: Application.java   View source code 6 votes vote down vote up
@RequestMapping("/")
public HttpEntity<RootResource> getRootResource() {
	RootResource resource = new RootResource();
	String baseUri = BasicLinkBuilder.linkToCurrentMapping().toString();

	Link catalogServiceLink = new Link(new UriTemplate(baseUri + "/catalog"), RootResource.LINK_NAME_CATALOG);
	resource.add(catalogServiceLink);

	Link reviewServiceLink = new Link(new UriTemplate(baseUri + "/reviews"), RootResource.LINK_NAME_REVIEW);
	resource.add(reviewServiceLink);

	Link recommendationServiceLink = new Link(new UriTemplate(baseUri + "/recommendations"),
			RootResource.LINK_NAME_RECOMMENDATIONS);
	resource.add(recommendationServiceLink);

	Link orderServiceLink = new Link(new UriTemplate(baseUri + "/orders"), RootResource.LINK_NAME_ORDERS);
	resource.add(orderServiceLink);

	Link productLink = new Link(new UriTemplate(baseUri + "/product/{id}"), RootResource.LINK_NAME_PRODUCT_DETAIL);
	resource.add(productLink);

	return new ResponseEntity<>(resource, HttpStatus.OK);
}
 
Example 35
Project: workflow-catalog-old   File: WorkflowRevisionServiceTest.java   View source code 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);

    workflowRevisionService = Mockito.spy(workflowRevisionService);

    Mockito.doReturn(new Link("test"))
           .when(workflowRevisionService)
           .createLink(Matchers.any(Long.class), Matchers.any(Long.class), Matchers.any(WorkflowRevision.class));

    Long revCnt = EXISTING_ID;
    mockedBucket = newMockedBucket(EXISTING_ID);
    revisions = new TreeSet<>();
    revisions.add(newWorkflowRevision(mockedBucket.getId(), revCnt++, LocalDateTime.now().minusHours(1)));
    revisions.add(newWorkflowRevision(mockedBucket.getId(), revCnt, LocalDateTime.now()));

    workflow2Rev = newMockedWorkflow(EXISTING_ID, mockedBucket, revisions, 2L);
}
 
Example 36
Project: Showcase   File: PageLinksAspect.java   View source code 6 votes vote down vote up
@Around("@annotation(org.educama.common.api.resource.PageLinks) && execution(org.springframework.hateoas.ResourceSupport+ *(..)) && args(page, ..)")
public Object pageLinksAdvice(ProceedingJoinPoint joinPoint, Page<?> page) throws Throwable {
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
    PageLinks pageLinks = method.getAnnotation(PageLinks.class);
    Class<?> controller = pageLinks.value();
    UriComponentsBuilder original = originalUri(controller, request);
    ResourceSupport resourceSupport = (ResourceSupport) joinPoint.proceed();
    if (page.hasNext()) {
        UriComponentsBuilder nextBuilder = replacePageParams(original, page.nextPageable());
        resourceSupport.add(new Link(nextBuilder.toUriString()).withRel("next"));
    }
    if (page.hasPrevious()) {
        UriComponentsBuilder prevBuilder = replacePageParams(original, page.previousPageable());
        resourceSupport.add(new Link(prevBuilder.toUriString()).withRel("prev"));
    }
    return resourceSupport;
}
 
Example 37
Project: spring-data-rest-android   File: JsonPathLinkDiscoverer.java   View source code 6 votes vote down vote up
/**
 * Creates {@link Link} instances from the given parse result.
 * 
 * @param parseResult the result originating from parsing the source content using the JSON path expression.
 * @param rel the relation type that was parsed for.
 * @return
 */
private List<Link> createLinksFrom(Object parseResult, String rel) {

	if (parseResult instanceof JSONArray) {

		List<Link> links = new ArrayList<Link>();
		JSONArray array = (JSONArray) parseResult;

		for (Object element : array) {
			links.add(new Link(element.toString(), rel));
		}

		return Collections.unmodifiableList(links);
	}

	return Collections.unmodifiableList(Arrays.asList(new Link(parseResult.toString(), rel)));
}
 
Example 38
Project: subs   File: RootEndpointLinkProcessor.java   View source code 6 votes vote down vote up
private void addStatusDescriptions(List<Link> links) {
    links.add(
            linkTo(
                    methodOn(StatusDescriptionController.class)
                            .allProcessingStatus(null))
                    .withRel("processingStatusDescriptions")
    );
    links.add(
            linkTo(
                    methodOn(StatusDescriptionController.class)
                            .allReleaseStatus(null))
                    .withRel("releaseStatusDescriptions")
    );
    links.add(
            linkTo(
                    methodOn(StatusDescriptionController.class)
                            .allSubmissionStatus(null))
                    .withRel("submissionStatusDescriptions")
    );
}
 
Example 39
Project: sw360rest   File: AttachmentController.java   View source code 6 votes vote down vote up
private HalResource<Attachment> createHalAttachment(
        Attachment sw360Attachment,
        Release sw360Release,
        User sw360User) {

    HalResource<Attachment> halAttachment = new HalResource<>(sw360Attachment);
    String componentUUID = sw360Attachment.getAttachmentContentId();

    Link releaseLink = linkTo(AttachmentController.class).slash("api/releases/" + sw360Release.getId()).withRel("release");
    halAttachment.add(releaseLink);

    restControllerHelper.addEmbeddedRelease(halAttachment, sw360Release, "release");
    restControllerHelper.addEmbeddedUser(halAttachment, sw360User, "createdBy");

    return halAttachment;
}
 
Example 40
Project: sw360rest   File: RestControllerHelper.java   View source code 6 votes vote down vote up
private void addEmbeddedAttachments(
        HalResource halResource,
        Set<Attachment> attachments) {
    for (Attachment attachment : attachments) {
        attachment.setCreatedTeam(null);
        attachment.setCreatedComment(null);
        attachment.setCreatedOn(null);
        attachment.setCheckedBy(null);
        attachment.setCheckedOn(null);
        attachment.setCheckedTeam(null);
        attachment.setCheckedComment(null);
        attachment.setCheckStatus(null);

        HalResource<Attachment> halAttachmentResource = new HalResource<>(attachment);
        try {
            Link attachmentLink = linkTo(AttachmentController.class)
                    .slash("api/attachments/" + attachment.getAttachmentContentId()).withSelfRel();
            halAttachmentResource.add(attachmentLink);
        } catch (Exception e) {
            log.error("cannot create embedded attachment with content id: " + attachment.getAttachmentContentId());
        }

        halResource.addEmbeddedResource("attachments", halAttachmentResource);
    }
}