Java Code Examples for org.springframework.hateoas.Resource

The following are top voted examples for showing how to use org.springframework.hateoas.Resource. 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: sos   File: EventController.java   View source code 7 votes vote down vote up
@GetMapping("events")
HttpEntity<Resources<?>> events(PagedResourcesAssembler<AbstractEvent<?>> assembler,
		@SortDefault("publicationDate") Pageable pageable,
		@RequestParam(required = false) @DateTimeFormat(iso = ISO.DATE_TIME) LocalDateTime since,
		@RequestParam(required = false) String type) {

	QAbstractEvent $ = QAbstractEvent.abstractEvent;

	BooleanBuilder builder = new BooleanBuilder();

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

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

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

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

	return ResponseEntity.ok(resource);
}
 
Example 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: 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 4
Project: spring-hateoas-examples   File: EmployeeResourceAssembler.java   View source code 6 votes vote down vote up
/**
 * Define links to add to every {@link Resource}.
 *
 * @param resource
 */
@Override
protected void addLinks(Resource<Employee> resource) {

	/**
	 * Add some custom links to the default ones provided.
	 *
	 * NOTE: To replace default links, don't invoke {@literal super.addLinks()}.
	 */
	super.addLinks(resource);

	resource.getContent().getId()
		.ifPresent(id -> {
			// Add additional links
			resource.add(linkTo(methodOn(ManagerController.class).findManager(id)).withRel("manager"));
			resource.add(linkTo(methodOn(EmployeeController.class).findDetailedEmployee(id)).withRel("detailed"));

			// Maintain a legacy link to support older clients not yet adjusted to the switch from "supervisor" to "manager".
			resource.add(linkTo(methodOn(SupervisorController.class).findOne(id)).withRel("supervisor"));
		});
}
 
Example 5
Project: service-block-samples   File: AccountController.java   View source code 6 votes vote down vote up
/**
 * Appends an {@link AccountEvent} domain event to the event log of the {@link Account}
 * aggregate with the specified accountId.
 *
 * @param accountId is the unique identifier for the {@link Account}
 * @param event     is the {@link AccountEvent} that attempts to alter the state of the {@link Account}
 * @return a hypermedia resource for the newly appended {@link AccountEvent}
 */
private Resource<AccountEvent> appendEventResource(Long accountId, AccountEvent event) {
    Assert.notNull(event, "Event body must be provided");

    Account account = accountRepository.findOne(accountId);
    Assert.notNull(account, "Account could not be found");

    event.setAccountId(account.getIdentity());
    eventService.apply(event);

    return new Resource<>(event,
            linkTo(AccountController.class)
                    .slash("accounts")
                    .slash(accountId)
                    .slash("events")
                    .slash(event.getEventId())
                    .withSelfRel(),
            linkTo(AccountController.class)
                    .slash("accounts")
                    .slash(accountId)
                    .withRel("account")
    );
}
 
Example 6
Project: service-block-samples   File: AccountController.java   View source code 6 votes vote down vote up
/**
 * Get a hypermedia enriched {@link Account} entity.
 *
 * @param account is the {@link Account} to enrich with hypermedia links
 * @return is a hypermedia enriched resource for the supplied {@link Account} entity
 */
private Resource<Account> getAccountResource(Account account) {
    Assert.notNull(account, "Account must not be null");

    if (!account.hasLink("commands")) {
        // Add command link
        account.add(linkBuilder("getCommands", account.getIdentity()).withRel("commands"));
    }

    if (!account.hasLink("events")) {
        // Add get events link
        account.add(linkBuilder("getAccountEvents", account.getIdentity()).withRel("events"));
    }

    return new Resource<>(account);
}
 
Example 7
Project: service-block-samples   File: AccountController.java   View source code 6 votes vote down vote up
private ResourceSupport getCommandsResource(Long id) {
    Account account = new Account();
    account.setIdentity(id);

    CommandResources commandResources = new CommandResources();

    // Add activate command link
    commandResources.add(linkTo(AccountController.class)
            .slash("accounts")
            .slash(id)
            .slash("commands")
            .slash("activate")
            .withRel("activate"));

    // Add suspend command link
    commandResources.add(linkTo(AccountController.class)
            .slash("accounts")
            .slash(id)
            .slash("commands")
            .slash("suspend")
            .withRel("suspend"));

    return new Resource<>(commandResources);
}
 
Example 8
Project: service-block-samples   File: ProjectController.java   View source code 6 votes vote down vote up
/**
 * Get a hypermedia enriched {@link Project} entity.
 *
 * @param project is the {@link Project} to enrich with hypermedia links
 * @return is a hypermedia enriched resource for the supplied {@link Project} entity
 */
private Resource<Project> getProjectResource(Project project) {
    Assert.notNull(project, "Project must not be null");

    if (!project.hasLink("commands")) {
        // Add command link
        project.add(linkBuilder("getCommands", project.getIdentity()).withRel("commands"));
    }

    if (!project.hasLink("events")) {
        // Add get events link
        project.add(linkBuilder("getProjectEvents", project.getIdentity()).withRel("events"));
    }

    if (!project.hasLink("commits")) {
        // Add get events link
        project.add(linkBuilder("getProjectCommits", project.getIdentity()).withRel("commits"));
    }

    return new Resource<>(project);
}
 
Example 9
Project: service-block-samples   File: ProjectController.java   View source code 6 votes vote down vote up
private ResourceSupport getCommandsResource(Long id) {
    Project project = new Project();
    project.setIdentity(id);

    CommandResources commandResources = new CommandResources();

    // Add suspend command link
    commandResources.add(linkTo(ProjectController.class)
            .slash("projects")
            .slash(id)
            .slash("commands")
            .slash("commit")
            .withRel("commit"));

    return new Resource<>(commandResources);
}
 
Example 10
Project: ingest-core   File: SubmissionEnvelopeResourceProcessor.java   View source code 6 votes vote down vote up
public Resource<SubmissionEnvelope> process(Resource<SubmissionEnvelope> resource) {
    SubmissionEnvelope submissionEnvelope = resource.getContent();

    // add subresource links for each type of metadata document in a submission envelope
    resource.add(getAnalysesLink(submissionEnvelope));
    resource.add(getAssaysLink(submissionEnvelope));
    resource.add(getFilesLink(submissionEnvelope));
    resource.add(getProjectsLink(submissionEnvelope));
    resource.add(getProtocolsLink(submissionEnvelope));
    resource.add(getSamplesLink(submissionEnvelope));

    // add subresource links for events that occur in response to state transitions
    submissionEnvelope.allowedStateTransitions().stream()
            .map(submissionState -> getStateTransitionLink(submissionEnvelope, submissionState))
            .filter(Optional::isPresent)
            .map(Optional::get)
            .forEach(resource::add);

    return resource;
}
 
Example 11
Project: spring-cloud-skipper   File: DefaultSkipperClient.java   View source code 5 votes vote down vote up
@Override
public Info status(String releaseName) {
	ParameterizedTypeReference<Resource<Info>> typeReference =
			new ParameterizedTypeReference<Resource<Info>>() {	};
	Map<String, String> uriVariables = new HashMap<String, String>();
	uriVariables.put("releaseName", releaseName);

	ResponseEntity<Resource<Info>> resourceResponseEntity =
			restTemplate.exchange(baseUri + "/release/status/{releaseName}",
					HttpMethod.GET,
					null,
					typeReference,
					uriVariables);
	return resourceResponseEntity.getBody().getContent();
}
 
Example 12
Project: spring-cloud-skipper   File: DefaultSkipperClient.java   View source code 5 votes vote down vote up
@Override
public Info status(String releaseName, int releaseVersion) {
	ParameterizedTypeReference<Resource<Info>> typeReference =
			new ParameterizedTypeReference<Resource<Info>>() {	};
	Map<String, String> uriVariables = new HashMap<String, String>();
	uriVariables.put("releaseName", releaseName);
	uriVariables.put("releaseVersion", Integer.toString(releaseVersion));
	ResponseEntity<Resource<Info>> resourceResponseEntity =
			restTemplate.exchange(baseUri + "/release/status/{releaseName}/{releaseVersion}",
					HttpMethod.GET,
					null,
					typeReference,
					uriVariables);
	return resourceResponseEntity.getBody().getContent();
}
 
Example 13
Project: spring-cloud-skipper   File: DefaultSkipperClient.java   View source code 5 votes vote down vote up
@Override
public String manifest(String releaseName) {
	ParameterizedTypeReference<Resource<Manifest>> typeReference =
			new ParameterizedTypeReference<Resource<Manifest>>() {	};
	Map<String, String> uriVariables = new HashMap<String, String>();
	uriVariables.put("releaseName", releaseName);
	ResponseEntity<Resource<Manifest>> resourceResponseEntity =
			restTemplate.exchange(baseUri + "/release/manifest/{releaseName}",
					HttpMethod.GET,
					null,
					typeReference,
					uriVariables);
	return resourceResponseEntity.getBody().getContent().getData();
}
 
Example 14
Project: spring-cloud-skipper   File: DefaultSkipperClient.java   View source code 5 votes vote down vote up
@Override
public String manifest(String releaseName, int releaseVersion) {
	ParameterizedTypeReference<Resource<Manifest>> typeReference =
			new ParameterizedTypeReference<Resource<Manifest>>() {	};
	Map<String, String> uriVariables = new HashMap<String, String>();
	uriVariables.put("releaseName", releaseName);
	uriVariables.put("releaseVersion", Integer.toString(releaseVersion));
	ResponseEntity<Resource<Manifest>> resourceResponseEntity =
			restTemplate.exchange(baseUri + "/release/manifest/{releaseName}/{releaseVersion}",
					HttpMethod.GET,
					null,
					typeReference,
					uriVariables);
	return resourceResponseEntity.getBody().getContent().getData();
}
 
Example 15
Project: spring-cloud-skipper   File: DefaultSkipperClient.java   View source code 5 votes vote down vote up
public Release install(InstallRequest installRequest) {
	ParameterizedTypeReference<Resource<Release>> typeReference =
			new ParameterizedTypeReference<Resource<Release>>() { };
	String url = String.format("%s/%s/%s", baseUri, "package", "install");

	HttpEntity<InstallRequest> httpEntity = new HttpEntity<>(installRequest);
	ResponseEntity<Resource<Release>> resourceResponseEntity =
			restTemplate.exchange(url, HttpMethod.POST, httpEntity,	typeReference);
	return resourceResponseEntity.getBody().getContent();
}
 
Example 16
Project: spring-cloud-skipper   File: DefaultSkipperClient.java   View source code 5 votes vote down vote up
@Override
public void deleteRepository(String name) {
	ParameterizedTypeReference<Resource<Repository>> typeReference = new ParameterizedTypeReference<Resource<Repository>>() {
	};
	Traverson.TraversalBuilder traversalBuilder = this.traverson.follow("repositories", "search", "findByName");
	Map<String, Object> parameters = new HashMap<>();
	parameters.put("name", name);
	Resource<Repository> repositoryResource = traversalBuilder.withTemplateParameters(parameters)
			.toObject(typeReference);
	if (repositoryResource != null) {
		this.restTemplate.delete(repositoryResource.getId().getHref());
	}
	else {
		throw new IllegalStateException("The Repository with the " + name + " doesn't exist.");
	}
}
 
Example 17
Project: spring-cloud-skipper   File: DefaultSkipperClient.java   View source code 5 votes vote down vote up
@Override
public PackageMetadata upload(UploadRequest uploadRequest) {
	ParameterizedTypeReference<Resource<PackageMetadata>> typeReference =
			new ParameterizedTypeReference<Resource<PackageMetadata>>() { };
	String url = String.format("%s/%s/%s", baseUri, "package", "upload");
	log.debug("Uploading package {}-{} to repository {}.", uploadRequest.getName(), uploadRequest.getVersion(),
			uploadRequest.getRepoName());
	HttpEntity<UploadRequest> httpEntity = new HttpEntity<>(uploadRequest);
	ResponseEntity<Resource<PackageMetadata>> resourceResponseEntity =
			restTemplate.exchange(url, HttpMethod.POST, httpEntity,	typeReference);
	PackageMetadata packageMetadata = resourceResponseEntity.getBody().getContent();
	return packageMetadata;
}
 
Example 18
Project: spring-cloud-skipper   File: ReleaseController.java   View source code 5 votes vote down vote up
@RequestMapping(path = "/rollback/{name}/{version}", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public Resource<Release> rollback(@PathVariable("name") String releaseName,
		@PathVariable("version") int rollbackVersion) {
	Release release = this.skipperStateMachineService.rollbackRelease(releaseName, rollbackVersion);
	return this.releaseResourceAssembler.toResource(release);
}
 
Example 19
Project: spring-cloud-skipper   File: ReleaseController.java   View source code 5 votes vote down vote up
@RequestMapping(path = "/{name}/{deletePackage}", method = RequestMethod.DELETE)
@ResponseStatus(HttpStatus.OK)
public Resource<Release> delete(@PathVariable("name") String releaseName,
		@PathVariable("deletePackage") boolean deletePackage) {
	DeleteProperties deleteProperties = new DeleteProperties();
	deleteProperties.setDeletePackage(deletePackage);
	Release release = this.skipperStateMachineService.deleteRelease(releaseName, deleteProperties);
	return this.releaseResourceAssembler.toResource(release);
}
 
Example 20
Project: spring-cloud-skipper   File: ReleaseController.java   View source code 5 votes vote down vote up
@RequestMapping(path = "/list", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public Resources<Resource<Release>> list() {
	List<Release> releaseList = this.releaseService.list();
	Resources<Resource<Release>> resources = this.releaseResourceAssembler.toResources(releaseList);
	return resources;
}
 
Example 21
Project: spring-cloud-skipper   File: ReleaseController.java   View source code 5 votes vote down vote up
@RequestMapping(path = "/list/{name}", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public Resources<Resource<Release>> list(@PathVariable("name") String releaseName) {
	List<Release> releaseList = this.releaseService.list(releaseName);
	Resources<Resource<Release>> resources = this.releaseResourceAssembler.toResources(releaseList);
	return resources;
}
 
Example 22
Project: spring-cloud-skipper   File: PackageController.java   View source code 5 votes vote down vote up
@RequestMapping(path = "/upload", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public Resource<PackageMetadata> upload(@RequestBody UploadRequest uploadRequest) {
	return this.packageMetadataResourceAssembler.toResource(this.packageService.upload(uploadRequest));
}
 
Example 23
Project: spring-cloud-skipper   File: PackageMetadataResourceProcessor.java   View source code 5 votes vote down vote up
@Override
public Resource<PackageMetadata> process(Resource<PackageMetadata> packageMetadataResource) {
	Link installLink = linkTo(
			methodOn(PackageController.class).install(packageMetadataResource.getContent().getId(), null))
					.withRel("install");
	packageMetadataResource.add(installLink);
	return packageMetadataResource;
}
 
Example 24
Project: spring-cloud-skipper   File: PackageSummaryResourceProcessor.java   View source code 5 votes vote down vote up
@Override
public Resource<PackageSummary> process(Resource<PackageSummary> packageSummaryResource) {
	Link link = linkTo(
			methodOn(PackageController.class).install(Long.valueOf(packageSummaryResource.getContent().getId()),
					null))
							.withRel("install");
	packageSummaryResource.add(link);
	return packageSummaryResource;
}
 
Example 25
Project: spring-cloud-microservices-docker   File: Application.java   View source code 5 votes vote down vote up
@Bean
public ResourceProcessor<Resource<User>> movieProcessor() {
    return new ResourceProcessor<Resource<User>>() {
        @Override
        public Resource<User> process(Resource<User> resource) {

            resource.add(new Link("/movie/movies", "movies"));
            return resource;
        }
    };
}
 
Example 26
Project: spring-data-examples   File: StarbucksClient.java   View source code 5 votes vote down vote up
@Test
public void discoverStoreSearch() {

	Traverson traverson = new Traverson(URI.create(String.format(SERVICE_URI, port)), MediaTypes.HAL_JSON);

	// Set up path traversal
	TraversalBuilder builder = traverson. //
			follow("stores", "search", "by-location");

	// Log discovered
	log.info("");
	log.info("Discovered link: {}", builder.asTemplatedLink());
	log.info("");

	Map<String, Object> parameters = new HashMap<>();
	parameters.put("location", "40.740337,-73.995146");
	parameters.put("distance", "0.5miles");

	PagedResources<Resource<Store>> resources = builder.//
			withTemplateParameters(parameters).//
			toObject(new PagedResourcesType<Resource<Store>>() {});

	PageMetadata metadata = resources.getMetadata();

	log.info("Got {} of {} stores: ", resources.getContent().size(), metadata.getTotalElements());

	StreamSupport.stream(resources.spliterator(), false).//
			map(Resource::getContent).//
			forEach(store -> log.info("{} - {}", store.name, store.address));
}
 
Example 27
Project: ingest-core   File: MetadataDocumentResourceProcessor.java   View source code 5 votes vote down vote up
@Override public Resource<MetadataDocument> process(Resource<MetadataDocument> resource) {
    MetadataDocument metadataDocument = resource.getContent();

    metadataDocument.allowedStateTransitions().stream()
            .map(validationState -> getStateTransitionLink(metadataDocument, validationState))
            .filter(Optional::isPresent)
            .map(Optional::get)
            .forEach(resource::add);

    return resource;
}
 
Example 28
Project: ingest-core   File: AnalysisController.java   View source code 5 votes vote down vote up
@RequestMapping(path = "/analyses/{analysis_id}/" + Links.BUNDLE_REF_URL,
                method = RequestMethod.PUT)
ResponseEntity<Resource<?>> addBundleReference(@PathVariable("analysis_id") Analysis analysis,
                                               @RequestBody BundleReference bundleReference,
                                               final PersistentEntityResourceAssembler assembler) {
    Analysis entity = getAnalysisService().resolveBundleReferencesForAnalysis(analysis, bundleReference);
    PersistentEntityResource resource = assembler.toFullResource(entity);
    return ResponseEntity.accepted().body(resource);
}
 
Example 29
Project: sos   File: CatalogIntegration.java   View source code 5 votes vote down vote up
private void initializeInventory(Resources<Resource<ProductAdded>> resources) {

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

		resources.forEach(resource -> {

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

			log.info("Successful catalog update. New reference time: {}.",
					integration.getCatalogUpdate().map(it -> it.format(DateTimeFormatter.ISO_DATE_TIME)) //
							.orElseThrow(() -> new IllegalStateException()));
		});
	}
 
Example 30
Project: sos   File: CatalogIntegration.java   View source code 5 votes vote down vote up
private void initProductInfos(Resources<Resource<ProductAdded>> resources) {

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

		resources.forEach(resource -> {

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

			log.info("Successful catalog update. New reference time: {}.",
					integration.getCatalogUpdate().map(it -> it.format(DateTimeFormatter.ISO_DATE_TIME)) //
							.orElseThrow(() -> new IllegalStateException()));
		});
	}
 
Example 31
Project: sos   File: CatalogIntegration.java   View source code 5 votes vote down vote up
private void initProductInfo(Resource<ProductAdded> resource) {

		ProductId productId = ProductId.of(resource.getLink("product").getHref());
		ProductAdded event = resource.getContent();
		Product product = event.getProduct();

		log.info("Creating inventory item for product {}.", product.getDescription());

		productInfos.findByProductId(productId) //
				.orElseGet(() -> productInfos.save(ProductInfo.of(productId, product.getDescription(), product.getPrice())));
	}
 
Example 32
Project: spring-web-services   File: UserResource.java   View source code 5 votes vote down vote up
@GetMapping("/users/{id}")
public Resource<User> retrieveUser(@PathVariable int id) {
	User user = service.findOne(id);
	
	if(user==null)
		throw new UserNotFoundException("id-"+ id);
	
	
	//"all-users", SERVER_PATH + "/users"
	//retrieveAllUsers
	Resource<User> resource = new Resource<User>(user);
	
	ControllerLinkBuilder linkTo = 
			linkTo(methodOn(this.getClass()).retrieveAllUsers());
	
	resource.add(linkTo.withRel("all-users"));
	
	//HATEOAS
	
	return resource;
}
 
Example 33
Project: Mastering-Spring-5.0   File: TodoController.java   View source code 5 votes vote down vote up
@GetMapping(path = "/users/{name}/todos/{id}")
public Resource<Todo> retrieveTodo(@PathVariable String name, @PathVariable int id) {
	Todo todo = todoService.retrieveTodo(id);
	if (todo == null) {
		throw new TodoNotFoundException("Todo Not Found");
	}
	
	Resource<com.mastering.spring.springboot.bean.Todo> todoResource = new Resource<com.mastering.spring.springboot.bean.Todo>(todo);
	ControllerLinkBuilder linkTo = linkTo(methodOn(this.getClass()).retrieveTodos(name));
	todoResource.add(linkTo.withRel("parent"));
	return todoResource;
}
 
Example 34
Project: ingest-core   File: AnalysisController.java   View source code 5 votes vote down vote up
@RequestMapping(path = "/analyses/{analysis_id}/" + Links.FILE_REF_URL,
                method = RequestMethod.PUT)
ResponseEntity<Resource<?>> addFileReference(@PathVariable("analysis_id") Analysis analysis,
                                             @RequestBody File file,
                                             final PersistentEntityResourceAssembler assembler) {
    SubmissionEnvelope submissionEnvelope = analysis.getOpenSubmissionEnvelope();
    file.addToSubmissionEnvelope(submissionEnvelope);
    File entity = getFileRepository().save(file);
    Analysis result = getAnalysisService().getAnalysisRepository().save(analysis.addFile(entity));
    PersistentEntityResource resource = assembler.toFullResource(result);
    return ResponseEntity.accepted().body(resource);
}
 
Example 35
Project: spring-hateoas-examples   File: EmployeeController.java   View source code 5 votes vote down vote up
@GetMapping("/employees/{id}")
ResponseEntity<Resource<Employee>> findOne(@PathVariable long id) {

	return repository.findById(id)
		.map(employee -> new Resource<>(employee,
			linkTo(methodOn(EmployeeController.class).findOne(employee.getId())).withSelfRel()
				.andAffordance(afford(methodOn(EmployeeController.class).updateEmployee(null, employee.getId())))
				.andAffordance(afford(methodOn(EmployeeController.class).deleteEmployee(employee.getId()))),
			linkTo(methodOn(EmployeeController.class).findAll()).withRel("employees")
		))
		.map(ResponseEntity::ok)
		.orElse(ResponseEntity.notFound().build());
}
 
Example 36
Project: spring-hateoas-examples   File: SupervisorController.java   View source code 5 votes vote down vote up
@GetMapping(value = "/supervisors/{id}", produces = MediaTypes.HAL_JSON_VALUE)
public ResponseEntity<Resource<Supervisor>> findOne(@PathVariable Long id) {

	Resource<Manager> managerResource = controller.findOne(id).getBody();
	Resource<Supervisor> supervisorResource = new Resource<>(
		new Supervisor(managerResource.getContent()),
		managerResource.getLinks());

	return ResponseEntity.ok(supervisorResource);
}
 
Example 37
Project: spring-hateoas-examples   File: ManagerResourceAssembler.java   View source code 5 votes vote down vote up
/**
 * Retain default links provided by {@link SimpleIdentifiableResourceAssembler}, but add extra ones to each {@link Manager}.
 *
 * @param resource
 */
@Override
protected void addLinks(Resource<Manager> resource) {
	/**
	 * Retain default links.
	 */
	super.addLinks(resource);

	resource.getContent().getId()
		.ifPresent(id -> {
			// Add custom link to find all managed employees
			resource.add(linkTo(methodOn(EmployeeController.class).findEmployees(id)).withRel("employees"));
		});
}
 
Example 38
Project: spring-hateoas-examples   File: ManagerResourceAssembler.java   View source code 5 votes vote down vote up
/**
 * Retain default links for the entire collection, but add extra custom links for the {@link Manager} collection.
 *
 * @param resources
 */
@Override
protected void addLinks(Resources<Resource<Manager>> resources) {

	super.addLinks(resources);

	resources.add(linkTo(methodOn(EmployeeController.class).findAll()).withRel("employees"));
	resources.add(linkTo(methodOn(EmployeeController.class).findAllDetailedEmployees()).withRel("detailedEmployees"));
	resources.add(linkTo(methodOn(RootController.class).root()).withRel("root"));
}
 
Example 39
Project: spring-hateoas-examples   File: EmployeeController.java   View source code 5 votes vote down vote up
@GetMapping(value = "/employees/detailed", produces = MediaTypes.HAL_JSON_VALUE)
public ResponseEntity<Resources<Resource<EmployeeWithManager>>> findAllDetailedEmployees() {

	return ResponseEntity.ok(
		employeeWithManagerResourceAssembler.toResources(
			StreamSupport.stream(repository.findAll().spliterator(), false)
				.map(EmployeeWithManager::new)
				.collect(Collectors.toList())));
}
 
Example 40
Project: spring-hateoas-examples   File: EmployeeController.java   View source code 5 votes vote down vote up
@GetMapping(value = "/employees/{id}/detailed", produces = MediaTypes.HAL_JSON_VALUE)
public ResponseEntity<Resource<EmployeeWithManager>> findDetailedEmployee(@PathVariable Long id) {

	return repository.findById(id)
		.map(EmployeeWithManager::new)
		.map(employeeWithManagerResourceAssembler::toResource)
		.map(ResponseEntity::ok)
		.orElse(ResponseEntity.notFound().build());
}