Java Code Examples for org.springframework.hateoas.server.mvc.WebMvcLinkBuilder

The following examples show how to use org.springframework.hateoas.server.mvc.WebMvcLinkBuilder. 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: spring-cloud-skipper   Source File: ReleaseController.java    License: Apache License 2.0 6 votes vote down vote up
@RequestMapping(method = RequestMethod.GET)
public ReleaseControllerLinksResource resourceLinks() {
	ReleaseControllerLinksResource resource = new ReleaseControllerLinksResource();
	resource.add(WebMvcLinkBuilder.linkTo(methodOn(ReleaseController.class).status(null))
			.withRel("status/name"));
	resource.add(WebMvcLinkBuilder.linkTo(methodOn(ReleaseController.class).status(null, null))
			.withRel("status/name/version"));
	resource.add(
			WebMvcLinkBuilder.linkTo(methodOn(ReleaseController.class).manifest(null))
					.withRel("manifest"));
	resource.add(WebMvcLinkBuilder.linkTo(methodOn(ReleaseController.class).manifest(null, null))
			.withRel("manifest/name/version"));
	resource.add(WebMvcLinkBuilder.linkTo(methodOn(ReleaseController.class).upgrade(null))
			.withRel("upgrade"));
	resource.add(
			WebMvcLinkBuilder.linkTo(methodOn(ReleaseController.class).rollbackWithNamedVersion(null, 123))
					.withRel("rollback"));
	resource.add(WebMvcLinkBuilder.linkTo(methodOn(ReleaseController.class).list())
			.withRel("list"));
	resource.add(WebMvcLinkBuilder.linkTo(methodOn(ReleaseController.class).list(null))
			.withRel("list/name"));
	return resource;
}
 
Example 2
Source Project: genie   Source File: JobSearchResultModelAssembler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * {@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 3
Source Project: spring-batch-rest   Source File: JobDetailController.java    License: Apache License 2.0 5 votes vote down vote up
@Operation(summary = "Get all Quartz job details")
@GetMapping
public CollectionModel<JobDetailResource> all(@RequestParam(value = "enabled", required = false) Boolean enabled,
                                        @RequestParam(value = "springBatchJobName", required = false) String springBatchJobName) {
    return new CollectionModel<>(jobDetailService.all(Optional.ofNullable(enabled), Optional.ofNullable(springBatchJobName)).stream()
            .map(JobDetailResource::new).collect(toList()),
            WebMvcLinkBuilder.linkTo(methodOn(JobDetailController.class).all(enabled, springBatchJobName)).withSelfRel().expand());
}
 
Example 4
Source Project: spring-cloud-skipper   Source File: PackageController.java    License: Apache License 2.0 5 votes vote down vote up
@RequestMapping(method = RequestMethod.GET)
public PackageControllerLinksResource resourceLinks() {
	PackageControllerLinksResource resource = new PackageControllerLinksResource();
	resource.add(
			WebMvcLinkBuilder.linkTo(methodOn(PackageController.class).upload(null))
					.withRel("upload"));
	resource.add(WebMvcLinkBuilder.linkTo(methodOn(PackageController.class).install(null))
			.withRel("install"));
	resource.add(WebMvcLinkBuilder.linkTo(methodOn(PackageController.class).install(null, null))
			.withRel("install/id"));
	return resource;
}
 
Example 5
@Override
public RepositoryLinksResource process(RepositoryLinksResource resource) {
	resource.add(WebMvcLinkBuilder.linkTo(methodOn(AboutController.class).getAboutResource()).withRel("about"));
	resource.add(WebMvcLinkBuilder.linkTo(ReleaseController.class).withRel("release"));
	resource.add(WebMvcLinkBuilder.linkTo(PackageController.class).withRel("package"));
	return resource;
}
 
Example 6
@NonNull
@Override
public ClassificationRepresentationModel toModel(@NonNull Classification classification) {
  ClassificationRepresentationModel repModel = new ClassificationRepresentationModel();
  repModel.setClassificationId(classification.getId());
  repModel.setApplicationEntryPoint(classification.getApplicationEntryPoint());
  repModel.setCategory(classification.getCategory());
  repModel.setDomain(classification.getDomain());
  repModel.setKey(classification.getKey());
  repModel.setName(classification.getName());
  repModel.setParentId(classification.getParentId());
  repModel.setParentKey(classification.getParentKey());
  repModel.setPriority(classification.getPriority());
  repModel.setServiceLevel(classification.getServiceLevel());
  repModel.setType(classification.getType());
  repModel.setCustom1(classification.getCustom1());
  repModel.setCustom2(classification.getCustom2());
  repModel.setCustom3(classification.getCustom3());
  repModel.setCustom4(classification.getCustom4());
  repModel.setCustom5(classification.getCustom5());
  repModel.setCustom6(classification.getCustom6());
  repModel.setCustom7(classification.getCustom7());
  repModel.setCustom8(classification.getCustom8());
  repModel.setIsValidInDomain(classification.getIsValidInDomain());
  repModel.setCreated(classification.getCreated());
  repModel.setModified(classification.getModified());
  repModel.setDescription(classification.getDescription());
  try {
    repModel.add(
        WebMvcLinkBuilder.linkTo(
                methodOn(ClassificationController.class)
                    .getClassification(classification.getId()))
            .withSelfRel());
  } catch (ClassificationNotFoundException e) {
    throw new SystemException("caught unexpected Exception.", e.getCause());
  }
  return repModel;
}
 
Example 7
Source Project: spring-web-services   Source File: UserResource.java    License: MIT License 5 votes vote down vote up
@GetMapping("/users/{id}")
public EntityModel<User> retrieveUser(@PathVariable int id) {
	User user = service.findOne(id);
	
	if(user==null)
		throw new UserNotFoundException("id-"+ id);
	
	
	//"all-users", SERVER_PATH + "/users"
	//retrieveAllUsers
	EntityModel<User> resource = EntityModel.of(user);
	
	WebMvcLinkBuilder linkTo = 
			linkTo(methodOn(this.getClass()).retrieveAllUsers());
	
	resource.add(linkTo.withRel("all-users"));
	
	//HATEOAS
	
	return resource;
}
 
Example 8
/**
 * Build up a URI for the collection using the Spring web controller followed by the resource type transformed by the
 * {@link LinkRelationProvider}. Assumption is that an {@literal EmployeeController} serving up {@literal Employee}
 * objects will be serving resources at {@code /employees} and {@code /employees/1}. If this is not the case, simply
 * override this method in your concrete instance, or resort to overriding {@link #addLinks(EntityModel)} and
 * {@link #addLinks(CollectionModel)} where you have full control over exactly what links are put in the individual
 * and collection resources.
 *
 * @return
 */
protected LinkBuilder getCollectionLinkBuilder() {

	WebMvcLinkBuilder linkBuilder = linkTo(this.controllerClass);

	for (String pathComponent : (getPrefix() + this.relProvider.getCollectionResourceRelFor(this.resourceType))
			.split("/")) {
		if (!pathComponent.isEmpty()) {
			linkBuilder = linkBuilder.slash(pathComponent);
		}
	}

	return linkBuilder;
}
 
Example 9
Source Project: spring-cloud-dataflow   Source File: SecurityController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Return security information. E.g. is security enabled? Which user do you represent?
 *
 * @return the security info
 */
@ResponseBody
@RequestMapping(method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public SecurityInfoResource getSecurityInfo() {

	final boolean authenticationEnabled = securityStateBean.isAuthenticationEnabled();

	final SecurityInfoResource securityInfo = new SecurityInfoResource();
	securityInfo.setAuthenticationEnabled(authenticationEnabled);
	securityInfo.add(WebMvcLinkBuilder.linkTo(SecurityController.class).withSelfRel());

	if (authenticationEnabled && SecurityContextHolder.getContext() != null) {
		final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if (!(authentication instanceof AnonymousAuthenticationToken)) {
			securityInfo.setAuthenticated(authentication.isAuthenticated());
			securityInfo.setUsername(authentication.getName());

			for (Object authority : authentication.getAuthorities()) {
				final GrantedAuthority grantedAuthority = (GrantedAuthority) authority;
				securityInfo.addRole(grantedAuthority.getAuthority());
			}

		}
	}

	return securityInfo;
}
 
Example 10
Source Project: POC   Source File: PostController.java    License: Apache License 2.0 5 votes vote down vote up
@GetMapping("/{user_name}/posts/{title}")
public ResponseEntity<PostDTO> getPostByUserNameAndTitle(@PathVariable("user_name") String userName,
		@PathVariable("title") String title) {
	PostDTO postDTO = this.addLinkToPostBiFunction.apply(userName,
			this.postService.fetchPostByUserNameAndTitle(userName, title));

	Link getAllPostsLink = WebMvcLinkBuilder
			.linkTo(WebMvcLinkBuilder.methodOn(this.getClass()).getPostsByUserName(userName))
			.withRel("get-all-posts-by-username");
	postDTO.add(getAllPostsLink);

	return ResponseEntity.of(Optional.of(postDTO));
}
 
Example 11
Source Project: genie   Source File: ClusterModelAssembler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
@Nonnull
public EntityModel<Cluster> toModel(final Cluster cluster) {
    final String id = cluster.getId().orElseThrow(IllegalArgumentException::new);
    final EntityModel<Cluster> clusterModel = new EntityModel<>(cluster);

    try {
        clusterModel.add(
            WebMvcLinkBuilder.linkTo(
                WebMvcLinkBuilder
                    .methodOn(ClusterRestController.class)
                    .getCluster(id)
            ).withSelfRel()
        );

        clusterModel.add(
            WebMvcLinkBuilder.linkTo(
                WebMvcLinkBuilder
                    .methodOn(ClusterRestController.class)
                    .getCommandsForCluster(id, null)
            ).withRel(COMMANDS_LINK)
        );
    } catch (final NotFoundException ge) {
        // If we can't convert it we might as well force a server exception
        throw new RuntimeException(ge);
    }

    return clusterModel;
}
 
Example 12
Source Project: genie   Source File: ApplicationModelAssembler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
@Nonnull
public EntityModel<Application> toModel(final Application application) {
    final String id = application.getId().orElseThrow(IllegalArgumentException::new);
    final EntityModel<Application> applicationModel = new EntityModel<>(application);

    try {
        applicationModel.add(
            WebMvcLinkBuilder.linkTo(
                WebMvcLinkBuilder
                    .methodOn(ApplicationRestController.class)
                    .getApplication(id)
            ).withSelfRel()
        );

        applicationModel.add(
            WebMvcLinkBuilder.linkTo(
                WebMvcLinkBuilder
                    .methodOn(ApplicationRestController.class)
                    .getCommandsForApplication(id, null)
            ).withRel(COMMANDS_LINK)
        );
    } catch (final GenieException | NotFoundException ge) {
        // If we can't convert it we might as well force a server exception
        throw new RuntimeException(ge);
    }

    return applicationModel;
}
 
Example 13
Source Project: genie   Source File: CommandModelAssembler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
@Nonnull
public EntityModel<Command> toModel(final Command command) {
    final String id = command.getId().orElseThrow(IllegalArgumentException::new);
    final EntityModel<Command> commandModel = new EntityModel<>(command);

    try {
        commandModel.add(
            WebMvcLinkBuilder.linkTo(
                WebMvcLinkBuilder
                    .methodOn(CommandRestController.class)
                    .getCommand(id)
            ).withSelfRel()
        );

        commandModel.add(
            WebMvcLinkBuilder.linkTo(
                WebMvcLinkBuilder
                    .methodOn(CommandRestController.class)
                    .getApplicationsForCommand(id)
            ).withRel(APPLICATIONS_LINK)
        );

        commandModel.add(
            WebMvcLinkBuilder.linkTo(
                WebMvcLinkBuilder
                    .methodOn(CommandRestController.class)
                    .getClustersForCommand(id, null)
            ).withRel(CLUSTERS_LINK)
        );
    } catch (final GenieException | GenieCheckedException ge) {
        // If we can't convert it we might as well force a server exception
        throw new RuntimeException(ge);
    }

    return commandModel;
}
 
Example 14
Source Project: spring-web-services   Source File: UserJPAResource.java    License: MIT License 4 votes vote down vote up
@GetMapping("/jpa/users/{id}")
public EntityModel<User> retrieveUser(@PathVariable int id) {
	Optional<User> user = userRepository.findById(id);

	if (!user.isPresent())
		throw new UserNotFoundException("id-" + id);

	// "all-users", SERVER_PATH + "/users"
	// retrieveAllUsers
	EntityModel<User> resource = EntityModel.of(user.get());//new EntityModel<User>(user.get());

	WebMvcLinkBuilder linkTo = linkTo(methodOn(this.getClass()).retrieveAllUsers());

	resource.add(linkTo.withRel("all-users"));

	// HATEOAS

	return resource;
}
 
Example 15
Source Project: spring-microservices   Source File: UserResource.java    License: MIT License 4 votes vote down vote up
@GetMapping("/users/{id}")
public EntityModel<User> retrieveUser(@PathVariable int id) {
	User user = service.findOne(id);
	
	if(user==null)
		throw new UserNotFoundException("id-"+ id);
	
	
	//"all-users", SERVER_PATH + "/users"
	//retrieveAllUsers
	EntityModel<User> resource = EntityModel.of(user);
	
	WebMvcLinkBuilder linkTo = 
			linkTo(methodOn(this.getClass()).retrieveAllUsers());
	
	resource.add(linkTo.withRel("all-users"));
	
	//HATEOAS
	
	return resource;
}
 
Example 16
Source Project: genie   Source File: JobExecutionModelAssembler.java    License: Apache License 2.0 4 votes vote down vote up
/**
     * {@inheritDoc}
     */
    @Override
    @Nonnull
    public EntityModel<JobExecution> toModel(final JobExecution jobExecution) {
        final String id = jobExecution.getId().orElseThrow(IllegalArgumentException::new);
        final EntityModel<JobExecution> jobExecutionModel = new EntityModel<>(jobExecution);

        try {
            jobExecutionModel.add(
                WebMvcLinkBuilder.linkTo(
                    WebMvcLinkBuilder
                        .methodOn(JobRestController.class)
                        .getJobExecution(id)
                ).withSelfRel()
            );

            jobExecutionModel.add(
                WebMvcLinkBuilder.linkTo(
                    WebMvcLinkBuilder
                        .methodOn(JobRestController.class)
                        .getJob(id)
                ).withRel(JOB_LINK)
            );

            jobExecutionModel.add(
                WebMvcLinkBuilder.linkTo(
                    WebMvcLinkBuilder
                        .methodOn(JobRestController.class)
                        .getJobRequest(id)
                ).withRel(REQUEST_LINK)
            );

            // TODO: https://github.com/spring-projects/spring-hateoas/issues/186 should be fixed in .20 currently .19
//            jobExecutionResource.add(
//                ControllerLinkBuilder.linkTo(
//                    JobRestController.class,
//                    JobRestController.class.getMethod(
//                        "getJobOutput",
//                        String.class,
//                        String.class,
//                        HttpServletRequest.class,
//                        HttpServletResponse.class
//                    ),
//                    id,
//                    null,
//                    null,
//                    null
//                ).withRel("output")
//            );

            jobExecutionModel.add(
                WebMvcLinkBuilder
                    .linkTo(JobRestController.class)
                    .slash(id)
                    .slash(OUTPUT_LINK)
                    .withRel(OUTPUT_LINK)
            );

            jobExecutionModel.add(
                WebMvcLinkBuilder.linkTo(
                    WebMvcLinkBuilder
                        .methodOn(JobRestController.class)
                        .getJobStatus(id)
                ).withRel(STATUS_LINK)
            );

            jobExecutionModel.add(
                WebMvcLinkBuilder.linkTo(
                    WebMvcLinkBuilder
                        .methodOn(JobRestController.class)
                        .getJobMetadata(id)
                ).withRel(METADATA_LINK)
            );
        } catch (final GenieException | GenieCheckedException ge) {
            // If we can't convert it we might as well force a server exception
            throw new RuntimeException(ge);
        }

        return jobExecutionModel;
    }
 
Example 17
Source Project: genie   Source File: JobMetadataModelAssembler.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
@Nonnull
public EntityModel<JobMetadata> toModel(final JobMetadata jobMetadata) {
    final String id = jobMetadata.getId().orElseThrow(IllegalArgumentException::new);
    final EntityModel<JobMetadata> jobMetadataModel = new EntityModel<>(jobMetadata);

    try {
        jobMetadataModel.add(
            WebMvcLinkBuilder.linkTo(
                WebMvcLinkBuilder
                    .methodOn(JobRestController.class)
                    .getJobMetadata(id)
            ).withSelfRel()
        );

        jobMetadataModel.add(
            WebMvcLinkBuilder.linkTo(
                WebMvcLinkBuilder
                    .methodOn(JobRestController.class)
                    .getJob(id)
            ).withRel(JOB_LINK)
        );

        jobMetadataModel.add(
            WebMvcLinkBuilder.linkTo(
                WebMvcLinkBuilder
                    .methodOn(JobRestController.class)
                    .getJobRequest(id)
            ).withRel(REQUEST_LINK)
        );

        jobMetadataModel.add(
            WebMvcLinkBuilder
                .linkTo(JobRestController.class)
                .slash(id)
                .slash(OUTPUT_LINK)
                .withRel(OUTPUT_LINK)
        );

        jobMetadataModel.add(
            WebMvcLinkBuilder.linkTo(
                WebMvcLinkBuilder
                    .methodOn(JobRestController.class)
                    .getJobStatus(id)
            ).withRel(STATUS_LINK)
        );

        jobMetadataModel.add(
            WebMvcLinkBuilder.linkTo(
                WebMvcLinkBuilder
                    .methodOn(JobRestController.class)
                    .getJobExecution(id)
            ).withRel(EXECUTION_LINK)
        );
    } catch (final GenieException | GenieCheckedException ge) {
        // If we can't convert it we might as well force a server exception
        throw new RuntimeException(ge);
    }

    return jobMetadataModel;
}
 
Example 18
Source Project: genie   Source File: JobRequestModelAssembler.java    License: Apache License 2.0 4 votes vote down vote up
/**
     * {@inheritDoc}
     */
    @Override
    @Nonnull
    public EntityModel<JobRequest> toModel(final JobRequest jobRequest) {
        final String id = jobRequest.getId().orElseThrow(IllegalArgumentException::new);
        final EntityModel<JobRequest> jobRequestModel = new EntityModel<>(jobRequest);

        try {
            jobRequestModel.add(
                WebMvcLinkBuilder.linkTo(
                    WebMvcLinkBuilder
                        .methodOn(JobRestController.class)
                        .getJobRequest(id)
                ).withSelfRel()
            );

            jobRequestModel.add(
                WebMvcLinkBuilder.linkTo(
                    WebMvcLinkBuilder
                        .methodOn(JobRestController.class)
                        .getJob(id)
                ).withRel(JOB_LINK)
            );

            jobRequestModel.add(
                WebMvcLinkBuilder.linkTo(
                    WebMvcLinkBuilder
                        .methodOn(JobRestController.class)
                        .getJobExecution(id)
                ).withRel(EXECUTION_LINK)
            );

            // TODO: https://github.com/spring-projects/spring-hateoas/issues/186 should be fixed in .20 currently .19
//            jobRequestResource.add(
//                ControllerLinkBuilder.linkTo(
//                    JobRestController.class,
//                    JobRestController.class.getMethod(
//                        "getJobOutput",
//                        String.class,
//                        String.class,
//                        HttpServletRequest.class,
//                        HttpServletResponse.class
//                    ),
//                    id,
//                    null,
//                    null,
//                    null
//                ).withRel("output")
//            );

            jobRequestModel.add(
                WebMvcLinkBuilder
                    .linkTo(JobRestController.class)
                    .slash(id)
                    .slash(OUTPUT_LINK)
                    .withRel(OUTPUT_LINK)
            );

            jobRequestModel.add(
                WebMvcLinkBuilder.linkTo(
                    WebMvcLinkBuilder
                        .methodOn(JobRestController.class)
                        .getJobStatus(id)
                ).withRel(STATUS_LINK)
            );

            jobRequestModel.add(
                WebMvcLinkBuilder.linkTo(
                    WebMvcLinkBuilder
                        .methodOn(JobRestController.class)
                        .getJobMetadata(id)
                ).withRel(METADATA_LINK)
            );
        } catch (final GenieException | GenieCheckedException ge) {
            // If we can't convert it we might as well force a server exception
            throw new RuntimeException(ge);
        }

        return jobRequestModel;
    }
 
Example 19
Source Project: genie   Source File: RootModelAssembler.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
@SuppressFBWarnings("NP_NULL_PARAM_DEREF_ALL_TARGETS_DANGEROUS")
@Nonnull
public EntityModel<JsonNode> toModel(final JsonNode metadata) {
    final EntityModel<JsonNode> rootResource = new EntityModel<>(metadata);

    try {
        rootResource.add(
            WebMvcLinkBuilder.linkTo(
                WebMvcLinkBuilder
                    .methodOn(RootRestController.class)
                    .getRoot()
            ).withSelfRel()
        );

        rootResource.add(
            WebMvcLinkBuilder.linkTo(
                WebMvcLinkBuilder
                    .methodOn(ApplicationRestController.class)
                    .createApplication(null)
            ).withRel(APPLICATIONS_LINK)
        );

        rootResource.add(
            WebMvcLinkBuilder.linkTo(
                WebMvcLinkBuilder
                    .methodOn(CommandRestController.class)
                    .createCommand(null)
            ).withRel(COMMANDS_LINK)
        );

        rootResource.add(
            WebMvcLinkBuilder.linkTo(
                WebMvcLinkBuilder
                    .methodOn(ClusterRestController.class)
                    .createCluster(null)
            ).withRel(CLUSTERS_LINK)
        );

        rootResource.add(
            WebMvcLinkBuilder.linkTo(
                WebMvcLinkBuilder
                    .methodOn(JobRestController.class)
                    .submitJob(null, null, null, null)
            ).withRel(JOBS_LINK)
        );
    } catch (final GenieException | GenieCheckedException ge) {
        // If we can't convert it we might as well force a server exception
        throw new RuntimeException(ge);
    }

    return rootResource;
}
 
Example 20
Source Project: spring-microservices   Source File: UserJPAResource.java    License: MIT License 3 votes vote down vote up
@GetMapping("/jpa/users/{id}")
public EntityModel<User> retrieveUser(@PathVariable int id) {
	Optional<User> user = userRepository.findById(id);

	if (!user.isPresent())
		throw new UserNotFoundException("id-" + id);

	// "all-users", SERVER_PATH + "/users"
	// retrieveAllUsers
	EntityModel<User> resource = EntityModel.of(user.get());//new EntityModel<User>(user.get());

	WebMvcLinkBuilder linkTo = linkTo(methodOn(this.getClass()).retrieveAllUsers());

	resource.add(linkTo.withRel("all-users"));

	// HATEOAS

	return resource;
}