org.springframework.hateoas.EntityModel Java Examples
The following examples show how to use
org.springframework.hateoas.EntityModel.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JacksonClientModule.java From bowman with Apache License 2.0 | 6 votes |
public JacksonClientModule() { setSerializerModifier(new BeanSerializerModifier() { @Override public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc, List<BeanPropertyWriter> beanProperties) { for (BeanPropertyWriter writer : beanProperties) { if (writer.getAnnotation(LinkedResource.class) != null) { writer.assignSerializer(new LinkedResourceUriSerializer()); } } return beanProperties; } }); setMixInAnnotation(EntityModel.class, ResourceMixin.class); setMixInAnnotation(MethodHandler.class, MethodHandlerMixin.class); }
Example #2
Source File: ApplicationRestController.java From genie with Apache License 2.0 | 6 votes |
/** * Get all the commands this application is associated with. * * @param id The id of the application to get the commands for. Not * NULL/empty/blank. * @param statuses The various statuses of the commands to retrieve * @return The set of commands. * @throws NotFoundException If no application with the given ID exists * @throws GeniePreconditionException When the statuses can't be parsed successfully */ @GetMapping(value = "/{id}/commands", produces = MediaTypes.HAL_JSON_VALUE) public Set<EntityModel<Command>> getCommandsForApplication( @PathVariable("id") final String id, @RequestParam(value = "status", required = false) @Nullable final Set<String> statuses ) throws NotFoundException, GeniePreconditionException { log.info("Called with id {} and statuses {}", id, statuses); Set<CommandStatus> enumStatuses = null; if (statuses != null) { enumStatuses = EnumSet.noneOf(CommandStatus.class); for (final String status : statuses) { enumStatuses.add( DtoConverters.toV4CommandStatus(com.netflix.genie.common.dto.CommandStatus.parse(status)) ); } } return this.persistenceService.getCommandsForApplication(id, enumStatuses) .stream() .map(DtoConverters::toV3Command) .map(this.commandModelAssembler::toModel) .collect(Collectors.toSet()); }
Example #3
Source File: JobSearchResultModelAssembler.java From genie with Apache License 2.0 | 6 votes |
/** * {@inheritDoc} */ @Override @Nonnull public EntityModel<JobSearchResult> toModel(final JobSearchResult job) { final EntityModel<JobSearchResult> jobSearchResultModel = new EntityModel<>(job); try { jobSearchResultModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(JobRestController.class) .getJob(job.getId()) ).withSelfRel() ); } catch (final GenieException ge) { // If we can't convert it we might as well force a server exception throw new RuntimeException(ge); } return jobSearchResultModel; }
Example #4
Source File: EmployeeController.java From spring-hateoas-examples with Apache License 2.0 | 6 votes |
@GetMapping("/employees") ResponseEntity<CollectionModel<EntityModel<Employee>>> findAll() { List<EntityModel<Employee>> employeeResources = StreamSupport.stream(repository.findAll().spliterator(), false) .map(employee -> new EntityModel<>(employee, linkTo(methodOn(EmployeeController.class).findOne(employee.getId())).withSelfRel() .andAffordance(afford(methodOn(EmployeeController.class).updateEmployee(null, employee.getId()))) .andAffordance(afford(methodOn(EmployeeController.class).deleteEmployee(employee.getId()))), linkTo(methodOn(EmployeeController.class).findAll()).withRel("employees"))) .collect(Collectors.toList()); return ResponseEntity.ok(new CollectionModel<>( // employeeResources, // linkTo(methodOn(EmployeeController.class).findAll()).withSelfRel() .andAffordance(afford(methodOn(EmployeeController.class).newEmployee(null))))); }
Example #5
Source File: EmployeeController.java From springdoc-openapi with Apache License 2.0 | 6 votes |
@PostMapping("/employees") ResponseEntity<EntityModel<Employee>> newEmployee(@RequestBody Employee employee) { try { Employee savedEmployee = repository.save(employee); EntityModel<Employee> employeeResource = new EntityModel<>(savedEmployee, // linkTo(methodOn(EmployeeController.class).findOne(savedEmployee.getId())).withSelfRel()); return ResponseEntity // .created(new URI(employeeResource.getRequiredLink(IanaLinkRelations.SELF).getHref())) // .body(employeeResource); } catch (URISyntaxException e) { return ResponseEntity.badRequest().body(null); } }
Example #6
Source File: EmployeeController.java From spring-hateoas-examples with Apache License 2.0 | 6 votes |
@PostMapping("/employees") ResponseEntity<?> newEmployee(@RequestBody Employee employee) { Employee savedEmployee = repository.save(employee); return new EntityModel<>(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")).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 create " + employee)); }
Example #7
Source File: EmployeeRepresentationModelAssembler.java From spring-hateoas-examples with Apache License 2.0 | 6 votes |
/** * Define links to add to every {@link EntityModel}. * * @param resource */ @Override public void addLinks(EntityModel<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 #8
Source File: RestOperations.java From bowman with Apache License 2.0 | 6 votes |
public <T> CollectionModel<EntityModel<T>> getResources(URI uri, Class<T> entityType) { ObjectNode node; try { node = restTemplate.getForObject(uri, ObjectNode.class); } catch (HttpClientErrorException exception) { if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { return CollectionModel.wrap(Collections.<T>emptyList()); } throw exception; } JavaType innerType = objectMapper.getTypeFactory().constructParametricType(EntityModel.class, entityType); JavaType targetType = objectMapper.getTypeFactory().constructParametricType(CollectionModel.class, innerType); return objectMapper.convertValue(node, targetType); }
Example #9
Source File: EmployeeController.java From spring-hateoas-examples with Apache License 2.0 | 5 votes |
@GetMapping("/employees/detailed") public ResponseEntity<CollectionModel<EntityModel<EmployeeWithManager>>> findAllDetailedEmployees() { return ResponseEntity.ok( // employeeWithManagerResourceAssembler.toCollectionModel( // StreamSupport.stream(repository.findAll().spliterator(), false) // .map(EmployeeWithManager::new) // .collect(Collectors.toList()))); }
Example #10
Source File: EmployeeController.java From spring-hateoas-examples with Apache License 2.0 | 5 votes |
@GetMapping("/employees/{id}/detailed") public ResponseEntity<EntityModel<EmployeeWithManager>> findDetailedEmployee(@PathVariable Long id) { return repository.findById(id) // .map(EmployeeWithManager::new) // .map(employeeWithManagerResourceAssembler::toModel) // .map(ResponseEntity::ok) // .orElse(ResponseEntity.notFound().build()); }
Example #11
Source File: EmployeeController.java From spring-hateoas-examples with Apache License 2.0 | 5 votes |
/** * Look up all employees, and transform them into a REST collection resource using * {@link EmployeeRepresentationModelAssembler#toCollectionModel(Iterable)}. Then return them through Spring Web's * {@link ResponseEntity} fluent API. */ @GetMapping("/employees") public ResponseEntity<CollectionModel<EntityModel<Employee>>> findAll() { return ResponseEntity.ok( // this.assembler.toCollectionModel(this.repository.findAll())); }
Example #12
Source File: JavassistClientProxyFactoryTest.java From bowman with Apache License 2.0 | 5 votes |
@Test public void createWithLinkedResourceTargetNotPresentReturnsProxyReturningNull() { EntityModel<Entity> resource = new EntityModel<>(new Entity(), new Link("http://www.example.com/association/linked", "linked")); when(restOperations.getResource(URI.create("http://www.example.com/association/linked"), Entity.class)).thenReturn(null); Entity proxy = proxyFactory.create(resource, restOperations); assertThat(proxy.linked(), is(nullValue())); }
Example #13
Source File: EmployeeWithManagerResourceAssembler.java From spring-hateoas-examples with Apache License 2.0 | 5 votes |
/** * Define links to add to the {@link CollectionModel} collection. * * @param resources */ @Override public void addLinks(CollectionModel<EntityModel<EmployeeWithManager>> resources) { resources.add(linkTo(methodOn(EmployeeController.class).findAllDetailedEmployees()).withSelfRel()); resources.add(linkTo(methodOn(EmployeeController.class).findAll()).withRel("employees")); resources.add(linkTo(methodOn(ManagerController.class).findAll()).withRel("managers")); resources.add(linkTo(methodOn(RootController.class).root()).withRel("root")); }
Example #14
Source File: ClusterRestController.java From genie with Apache License 2.0 | 5 votes |
/** * Get cluster configuration from unique id. * * @param id id for the cluster * @return the cluster * @throws NotFoundException If no cluster with {@literal id} exists */ @GetMapping(value = "/{id}", produces = MediaTypes.HAL_JSON_VALUE) @ResponseStatus(HttpStatus.OK) public EntityModel<Cluster> getCluster(@PathVariable("id") final String id) throws NotFoundException { log.info("[getCluster] Called with id: {}", id); return this.clusterModelAssembler.toModel( DtoConverters.toV3Cluster(this.persistenceService.getCluster(id)) ); }
Example #15
Source File: HomeController.java From spring-hateoas-examples with Apache License 2.0 | 5 votes |
/** * Get a listing of ALL {@link Employee}s by querying the remote services' root URI, and then "hopping" to the * {@literal employees} rel. NOTE: Also create a form-backed {@link Employee} object to allow creating a new entry * with the Thymeleaf template. * * @param model * @return * @throws URISyntaxException */ @GetMapping public String index(Model model) throws URISyntaxException { Traverson client = new Traverson(new URI(REMOTE_SERVICE_ROOT_URI), MediaTypes.HAL_JSON); CollectionModel<EntityModel<Employee>> employees = client // .follow("employees") // .toObject(new CollectionModelType<EntityModel<Employee>>() {}); model.addAttribute("employee", new Employee()); model.addAttribute("employees", employees); return "index"; }
Example #16
Source File: EmployeeController.java From spring-hateoas-examples with Apache License 2.0 | 5 votes |
/** * Look up a single {@link Employee} and transform it into a REST resource using * {@link EmployeeRepresentationModelAssembler#toModel(Object)}. Then return it through Spring Web's * {@link ResponseEntity} fluent API. * * @param id */ @GetMapping("/employees/{id}") public ResponseEntity<EntityModel<Employee>> findOne(@PathVariable long id) { return repository.findById(id) // .map(assembler::toModel) // .map(ResponseEntity::ok) // .orElse(ResponseEntity.notFound().build()); }
Example #17
Source File: ApplicationRestController.java From genie with Apache License 2.0 | 5 votes |
/** * Get Application for given id. * * @param id unique id for application configuration * @return The application configuration * @throws NotFoundException If no application exists with the given id */ @GetMapping(value = "/{id}", produces = MediaTypes.HAL_JSON_VALUE) @ResponseStatus(HttpStatus.OK) public EntityModel<Application> getApplication(@PathVariable("id") final String id) throws NotFoundException { log.info("Called to get Application for id {}", id); return this.applicationModelAssembler.toModel( DtoConverters.toV3Application(this.persistenceService.getApplication(id)) ); }
Example #18
Source File: RestOperationsTest.java From bowman with Apache License 2.0 | 5 votes |
@Test public void getResourceReturnsResource() throws Exception { when(restTemplate.getForObject(URI.create("http://example.com"), ObjectNode.class)) .thenReturn(createObjectNode("{\"field\":\"value\"}")); EntityModel<Entity> resource = restOperations.getResource(URI.create("http://example.com"), Entity.class); assertThat(resource.getContent().getField(), is("value")); }
Example #19
Source File: StarbucksClient.java From spring-data-examples with Apache License 2.0 | 5 votes |
@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"); PagedModel<EntityModel<Store>> resources = builder.// withTemplateParameters(parameters).// toObject(new PagedModelType<EntityModel<Store>>() {}); PageMetadata metadata = resources.getMetadata(); log.info("Got {} of {} stores: ", resources.getContent().size(), metadata.getTotalElements()); StreamSupport.stream(resources.spliterator(), false).// map(EntityModel::getContent).// forEach(store -> log.info("{} - {}", store.name, store.address)); }
Example #20
Source File: PackageMetadataResourceProcessor.java From spring-cloud-skipper with Apache License 2.0 | 5 votes |
@Override public EntityModel<PackageMetadata> process(EntityModel<PackageMetadata> packageMetadataResource) { Link installLink = linkTo( methodOn(PackageController.class).install(packageMetadataResource.getContent().getId(), null)) .withRel("install"); packageMetadataResource.add(installLink); return packageMetadataResource; }
Example #21
Source File: RestOperationsTest.java From bowman with Apache License 2.0 | 5 votes |
@Test public void patchForResourceReturnsResource() throws Exception { Map<String, String> patch = new HashMap<>(); patch.put("field", "patchedValue"); when(restTemplate.patchForObject(URI.create("http://example.com"), patch, ObjectNode.class)) .thenReturn(createObjectNode("{\"field\":\"patchedValue\"}")); EntityModel<Entity> resource = restOperations.patchForResource(URI.create("http://example.com"), patch, Entity.class); assertThat(resource.getContent().getField(), is("patchedValue")); }
Example #22
Source File: MethodLinkUriResolverTest.java From bowman with Apache License 2.0 | 5 votes |
@Test public void resolveForMethodWithNoMatchingLinkThrowsException() { EntityModel<Object> resource = new EntityModel<>(new Object(), Links.of(new Link("http://www.example.com", "other"))); thrown.expect(NoSuchLinkException.class); thrown.expect(hasProperty("linkName", is("link1"))); new MethodLinkUriResolver().resolveForMethod(resource, "link1", new Object[0]); }
Example #23
Source File: OptionalLinksEntitiesAbsentLinksController.java From bowman with Apache License 2.0 | 5 votes |
@GetMapping("/{id}") public EntityModel<OptionalLinksEntity> get(@PathVariable("id") Integer id) { OptionalLinksEntity entity = repository.findById(id) .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND)); return new EntityModel<>(entity, Links.of(new Link( String.format("http://localhost:8080/optional-links-entities/%s", id)))); }
Example #24
Source File: LinkedResourceMethodHandler.java From bowman with Apache License 2.0 | 5 votes |
LinkedResourceMethodHandler(EntityModel resource, RestOperations restOperations, ClientProxyFactory proxyFactory, PropertyValueFactory propertyValueFactory, MethodLinkAttributesResolver methodLinkAttributesResolver, MethodLinkUriResolver methodLinkUriResolver) { super(resource.getContent().getClass()); this.resource = resource; this.restOperations = restOperations; this.proxyFactory = proxyFactory; this.propertyValueFactory = propertyValueFactory; this.methodLinkAttributesResolver = methodLinkAttributesResolver; this.methodLinkUriResolver = methodLinkUriResolver; }
Example #25
Source File: HomeController.java From spring-hateoas-examples with Apache License 2.0 | 5 votes |
/** * Get a listing of ALL {@link Employee}s by querying the remote services' root URI, and then "hopping" to the * {@literal employees} rel. NOTE: Also create a form-backed {@link Employee} object to allow creating a new entry * with the Thymeleaf template. * * @param model * @return * @throws URISyntaxException */ @GetMapping public String index(Model model) throws URISyntaxException { Traverson client = new Traverson(new URI(REMOTE_SERVICE_ROOT_URI), MediaTypes.HAL_JSON); CollectionModel<EntityModel<Employee>> employees = client // .follow("employees") // .toObject(new CollectionModelType<EntityModel<Employee>>() {}); model.addAttribute("employee", new Employee()); model.addAttribute("employees", employees); return "index"; }
Example #26
Source File: RestOperations.java From bowman with Apache License 2.0 | 5 votes |
public <T> EntityModel<T> patchForResource(URI uri, Object patch, Class<T> entityType) { ObjectNode node; node = restTemplate.patchForObject(uri, patch, ObjectNode.class); if (node == null) { return null; } JavaType targetType = objectMapper.getTypeFactory().constructParametricType(EntityModel.class, entityType); return objectMapper.convertValue(node, targetType); }
Example #27
Source File: ResourceDeserializer.java From bowman with Apache License 2.0 | 5 votes |
@Override public EntityModel<?> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { ObjectNode node = p.readValueAs(ObjectNode.class); ObjectMapper mapper = (ObjectMapper) p.getCodec(); RepresentationModel resource = mapper.convertValue(node, RepresentationModel.class); Links links = Links.of(resource.getLinks()); Object content = mapper.convertValue(node, getResourceDeserializationType(links)); return new EntityModel<>(content, links); }
Example #28
Source File: ClusterModelAssemblerTest.java From genie with Apache License 2.0 | 5 votes |
@Test void canConvertToModel() { final EntityModel<Cluster> model = this.assembler.toModel(this.cluster); Assertions.assertThat(model.getLinks()).hasSize(2); Assertions.assertThat(model.getLink("self")).isPresent(); Assertions.assertThat(model.getLink("commands")).isPresent(); }
Example #29
Source File: RestOperationsTest.java From bowman with Apache License 2.0 | 5 votes |
@Test public void getResourcesOnNotFoundHttpClientExceptionReturnsEmpty() { when(restTemplate.getForObject(URI.create("http://example.com"), ObjectNode.class)) .thenThrow(new HttpClientErrorException(NOT_FOUND)); CollectionModel<EntityModel<Entity>> resources = restOperations.getResources(URI.create("http://example.com"), Entity.class); assertThat(resources.getContent(), is(empty())); }
Example #30
Source File: RestOperationsTest.java From bowman with Apache License 2.0 | 5 votes |
@Test public void patchForResourceReturnsNull() { Map<String, String> patch = new HashMap<>(); when(restTemplate.patchForObject(URI.create("http://example.com"), patch, ObjectNode.class)) .thenReturn(null); EntityModel<Entity> resource = restOperations.patchForResource(URI.create("http://example.com"), patch, Entity.class); assertThat(resource, is(nullValue())); }