Java Code Examples for org.springframework.hateoas.Resource

The following examples show how to use org.springframework.hateoas.Resource. 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: service-block-samples   Source File: ProjectController.java    License: Apache License 2.0 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 2
Source Project: steady   Source File: BugController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Deletes the {@link Bug} with the given external ID. This ID is provided by the user when creating a bug, e.g., a CVE identifier.
 *
 * @return 404 {@link HttpStatus#NOT_FOUND} if bug with given bug ID does not exist, 200 {@link HttpStatus#OK} if the bug was successfully deleted
 * @param bugid a {@link java.lang.String} object.
 */
@RequestMapping(value = "/{bugid}", method = RequestMethod.DELETE)
@CacheEvict(value = "bug")
public ResponseEntity<Resource<Bug>> deleteBug(@PathVariable String bugid) {
	try {
		final Bug b = BugRepository.FILTER.findOne(this.bugRepository.findByBugId(bugid));
		
		// Ensure that no affected libs for bug exist
		final List<AffectedLibrary> aff_libs = this.afflibRepository.findByBug(b);
		if(aff_libs!=null && aff_libs.size()>0) 
			return new ResponseEntity<Resource<Bug>>(HttpStatus.UNPROCESSABLE_ENTITY);
		this.bugRepository.delete(b);
		return new ResponseEntity<Resource<Bug>>(HttpStatus.OK);
	}
	catch(EntityNotFoundException enfe) {
		return new ResponseEntity<Resource<Bug>>(HttpStatus.NOT_FOUND);
	}
}
 
Example 3
Source Project: sakai   Source File: RubricsServiceImpl.java    License: Educational Community License v2.0 6 votes vote down vote up
protected Collection<Resource<Evaluation>> getRubricEvaluationsByAssociation(Long associationId) throws Exception {
    TypeReferences.ResourcesType<Resource<Evaluation>> resourceParameterizedTypeReference = new TypeReferences.ResourcesType<Resource<Evaluation>>() {};

    URI apiBaseUrl = new URI(serverConfigurationService.getServerUrl() + RBCS_SERVICE_URL_PREFIX);
    Traverson traverson = new Traverson(apiBaseUrl, MediaTypes.HAL_JSON);
    Traverson.TraversalBuilder builder = traverson.follow("evaluations", "search", "by-association-id");

    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", String.format("Bearer %s", generateJsonWebToken(RubricsConstants.RBCS_TOOL)));
    builder.withHeaders(headers);

    Map<String, Object> parameters = new HashMap<>();
    parameters.put("toolItemRubricAssociationId", associationId);
    Resources<Resource<Evaluation>> evaluationResources = builder.withTemplateParameters(parameters).toObject(resourceParameterizedTypeReference);

    return evaluationResources.getContent();
}
 
Example 4
@Test
public void getServiceDocument() throws Exception {
    String result = mvc.perform(
            MockMvcRequestBuilders.get("/")
            .accept("application/hal+json;charset=UTF-8")
    ).andDo(print())
            .andExpect(content()
                    .contentTypeCompatibleWith("application/hal+json;charset=UTF-8"))
            .andReturn().getResponse().getContentAsString();

    Resource<String> value = mapper.readValue(result, new TypeReference<Resource<String>>() {
    });

    List<String> linkRels = value.getLinks().stream().map(link -> link.getRel()).collect(Collectors.toList());
    assertThat(linkRels, Matchers.hasItem("self"));
    assertEquals(value.getLink("self"), value.getId());

    assertTrue(value.hasLink("bookmarks"));
}
 
Example 5
@Test
public void updateABookmark() throws Exception {
    Bookmark input = getSimpleBookmark();
    String location = addBookmark(input);

    Resource<Bookmark> output = getBookmark(location);

    String result = mvc.perform(
            put(output.getId().getHref())
                    .contentType(MediaType.APPLICATION_JSON_UTF8)
                    .accept("application/hal+json;charset=UTF-8", "application/json;charset=UTF-8")
                    .content(objectMapper.writeValueAsString(output.getContent().withUrl("http://kulinariweb.de")))
                    .with(csrf())
    ).andDo(print()).andExpect(status().isOk())
            .andReturn().getResponse().getContentAsString();
    output = objectMapper.readValue(result, new TypeReference<Resource<Bookmark>>() {
    });

    assertEquals("http://kulinariweb.de", output.getContent().getUrl());
}
 
Example 6
Source Project: sakai   Source File: RubricsServiceImpl.java    License: Educational Community License v2.0 6 votes vote down vote up
public void restoreRubricAssociation(String toolId, String itemId) {
    try{
        Optional<Resource<ToolItemRubricAssociation>> associationResource = getRubricAssociationResource(toolId, itemId, null);
        if (associationResource.isPresent()) {
            String associationHref = associationResource.get().getLink(Link.REL_SELF).getHref();
            ToolItemRubricAssociation association = associationResource.get().getContent();
            String created = association.getMetadata().getCreated().toString();
            String owner = association.getMetadata().getOwnerId();
            String ownerType = association.getMetadata().getOwnerType();
            String creatorId = association.getMetadata().getCreatorId();
            Map <String,Boolean> oldParams = association.getParameters();
            oldParams.put(RubricsConstants.RBCS_SOFT_DELETED, false);
            String input = "{\"toolId\" : \""+toolId+"\",\"itemId\" : \"" + association.getItemId() + "\",\"rubricId\" : " + association.getRubricId() + ",\"metadata\" : {\"created\" : \"" + created + "\",\"ownerId\" : \"" + owner +
            "\",\"ownerType\" : \"" + ownerType + "\",\"creatorId\" : \"" + creatorId + "\"},\"parameters\" : {" + setConfigurationParametersForDuplication(oldParams) + "}}";
            log.debug("Restoring association {}", input);
            String resultPut = putRubricResource(associationHref, input, toolId, null);
            log.debug("resultPUT: {}",  resultPut);
        }
    } catch (Exception e) {
        log.warn("Error restoring rubric association for item id prefix {} : {}", itemId, e.getMessage());
    }
}
 
Example 7
Source Project: service-block-samples   Source File: ProjectController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Appends an {@link ProjectEvent} domain event to the event log of the {@link Project}
 * aggregate with the specified projectId.
 *
 * @param projectId is the unique identifier for the {@link Project}
 * @param event     is the {@link ProjectEvent} that attempts to alter the state of the {@link Project}
 * @return a hypermedia resource for the newly appended {@link ProjectEvent}
 */
private Resource<ProjectEvent> appendEventResource(Long projectId, ProjectEvent event) {
    Assert.notNull(event, "Event body must be provided");

    Project project = projectRepository.findById(projectId).get();
    Assert.notNull(project, "Project could not be found");

    event.setProjectId(project.getIdentity());
    projectEventService.apply(event, projectService);

    return new Resource<>(event,
            linkTo(ProjectController.class)
                    .slash("projects")
                    .slash(projectId)
                    .slash("events")
                    .slash(event.getEventId())
                    .withSelfRel(),
            linkTo(ProjectController.class)
                    .slash("projects")
                    .slash(projectId)
                    .withRel("project")
    );
}
 
Example 8
@ResponseBody
@RequestMapping(value = ENTITY_VERSION_MAPPING, method = RequestMethod.PUT)
public ResponseEntity<Resource<?>> version(RootResourceInformation repoInfo,
										   @PathVariable String repository,
										   @PathVariable String id,
										   @RequestBody VersionInfo info,
										   Principal principal,
										   PersistentEntityResourceAssembler assembler)
		throws ResourceNotFoundException, HttpRequestMethodNotSupportedException {

	Object domainObj = repoInfo.getInvoker().invokeFindById(id).get();

	domainObj = ReflectionUtils.invokeMethod(VERSION_METHOD, repositories.getRepositoryFor(domainObj.getClass()).get(), domainObj, info);

	if (domainObj != null) {
		return new ResponseEntity(assembler.toResource(domainObj), HttpStatus.OK);
	} else {
		return ResponseEntity.status(HttpStatus.CONFLICT).build();
	}
}
 
Example 9
Source Project: sos   Source File: EventController.java    License: Apache License 2.0 6 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 10
@ResponseBody
@RequestMapping(value = ENTITY_LOCK_MAPPING, method = RequestMethod.DELETE)
public ResponseEntity<Resource<?>> unlock(RootResourceInformation repoInfo,
										  @PathVariable String repository,
										  @PathVariable String id, Principal principal)
		throws ResourceNotFoundException, HttpRequestMethodNotSupportedException {

	Object domainObj = repoInfo.getInvoker().invokeFindById(id).get();

	domainObj = ReflectionUtils.invokeMethod(UNLOCK_METHOD, repositories.getRepositoryFor(domainObj.getClass()).get(), domainObj);

	if (domainObj != null) {
		return ResponseEntity.ok().build();
	} else {
		return ResponseEntity.status(HttpStatus.CONFLICT).build();
	}
}
 
Example 11
Source Project: microservices-dashboard   Source File: CatalogController.java    License: Apache License 2.0 6 votes vote down vote up
@GetMapping
public CatalogResource getCatalog() {
	Catalog catalog = this.service.getCatalog();
	List<Resource<String>> applicationInstanceResources = catalog.getApplications()
			.stream()
			.map(catalog::getApplicationInstancesForApplication)
			.flatMap(Collection::stream)
			.map(applicationInstance -> {
				Resource<String> resource = new Resource<>(applicationInstance);
				resource.add(linkTo(ApplicationInstanceController.class)
						.slash(applicationInstance)
						.withSelfRel());
				return resource;
			})
			.collect(Collectors.toList());
	return new CatalogResource(applicationInstanceResources);
}
 
Example 12
Source Project: sakai   Source File: RubricsServiceImpl.java    License: Educational Community License v2.0 5 votes vote down vote up
public void restoreRubricAssociationsByItemIdPrefix(String itemId, String toolId) {
    try{
        TypeReferences.ResourcesType<Resource<ToolItemRubricAssociation>> resourceParameterizedTypeReference =
                new TypeReferences.ResourcesType<Resource<ToolItemRubricAssociation>>() {};

        URI apiBaseUrl = new URI(serverConfigurationService.getServerUrl() + RBCS_SERVICE_URL_PREFIX);
        Traverson traverson = new Traverson(apiBaseUrl, MediaTypes.HAL_JSON);

        Traverson.TraversalBuilder builder = traverson.follow("rubric-associations", "search", "by-item-id-prefix");

        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", String.format("Bearer %s", generateJsonWebToken(toolId)));
        builder.withHeaders(headers);

        Map<String, Object> parameters = new HashMap<>();
        parameters.put("toolId", toolId);
        parameters.put("itemId", itemId);

        Resources<Resource<ToolItemRubricAssociation>> associationResources = builder.withTemplateParameters(parameters).toObject(resourceParameterizedTypeReference);
        for (Resource<ToolItemRubricAssociation> associationResource : associationResources) {
            String associationHref = associationResource.getLink(Link.REL_SELF).getHref();
            ToolItemRubricAssociation association = associationResource.getContent();
            String created = association.getMetadata().getCreated().toString();
            String owner = association.getMetadata().getOwnerId();
            String ownerType = association.getMetadata().getOwnerType();
            String creatorId = association.getMetadata().getCreatorId();
            Map <String,Boolean> oldParams = association.getParameters();
            oldParams.put(RubricsConstants.RBCS_SOFT_DELETED, false);
            String input = "{\"toolId\" : \""+toolId+"\",\"itemId\" : \"" + association.getItemId() + "\",\"rubricId\" : " + association.getRubricId() + ",\"metadata\" : {\"created\" : \"" + created + "\",\"ownerId\" : \"" + owner +
            "\",\"ownerType\" : \"" + ownerType + "\",\"creatorId\" : \"" + creatorId + "\"},\"parameters\" : {" + setConfigurationParametersForDuplication(oldParams) + "}}";
            log.debug("Restoring association {}", input);
            String resultPut = putRubricResource(associationHref, input, toolId, null);
            log.debug("resultPUT: {}",  resultPut);
        }
    } catch (Exception e) {
        log.warn("Error restoring rubric association for id {} : {}", itemId, e.getMessage());
    }
}
 
Example 13
Source Project: Mastering-Spring-5.1   Source File: TodoController.java    License: MIT License 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<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 14
Source Project: Mastering-Spring-5.1   Source File: TodoController.java    License: MIT License 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<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 15
@GetMapping("messagesBy")
public Resources<Resource<Message>> messagesBy(@RequestParam("username") String username) {
	List<Message> messages = messageService.messages(username);
	
	List<Resource<Message>> result = 
			IntStream.range(0, messages.size())
			         .mapToObj(idx -> new Resource<>(messages.get(idx)))
			         .collect(toList());

	String uri = String.format("%s/messagesBy?username=%s", linkTo(MsgController.class), username);
	return new Resources<>(result, new Link(uri));
}
 
Example 16
@Override
public PagedResources<Resource<Taco>> process(PagedResources<Resource<Taco>> resources) {
  resources
    .add(entityLinks
        .linkFor(Taco.class)
        .slash("recent")
        .withRel("recents"));
  
  return resources;
}
 
Example 17
Source Project: myfeed   Source File: FeedItemInitializer.java    License: Apache License 2.0 5 votes vote down vote up
Single<String> getRandomUsername(String defaultUsername) {
	List<String> usernames = userService.getUsers()
			.map(Resource::getContent)
			.map(User::getUsername)
			.toList().toBlocking().first();

	if (usernames.isEmpty()) {
		return Single.just(defaultUsername);
	}
	return Single.just(usernames.get(random.nextInt(usernames.size())));
}
 
Example 18
Source Project: sakai   Source File: RubricsServiceImpl.java    License: Educational Community License v2.0 5 votes vote down vote up
public void deleteRubricAssociation(String tool, String id){
    try{
        Optional<Resource<ToolItemRubricAssociation>> associationResource = getRubricAssociationResource(tool, id, null);
        if (associationResource.isPresent()) {
            String associationHref = associationResource.get().getLink(Link.REL_SELF).getHref();
            deleteRubricEvaluationsForAssociation(associationHref, tool);
            deleteRubricResource(associationHref, tool, null);
            ToolItemRubricAssociation association = associationResource.get().getContent();
            hasAssociatedRubricCache.remove(association.getToolId() + "#" + association.getItemId());
        }
    } catch (Exception e) {
        log.warn("Error deleting rubric association for tool {} and id {} : {}", tool, id, e.getMessage());
    }
}
 
Example 19
@Override
public Resource<Bookmark> toResource(Bookmark entity) {
    Resource<Bookmark> resource = new Resource<>(entity,
            linkTo(methodOn(BookmarkController.class).getBookmark(entity.getUuid())).withSelfRel());
    if(request.isUserInRole("ADMIN")){
        resource.add(
                linkTo(methodOn(BookmarkController.class).getBookmark(entity.getUuid())).withRel("update"),
                linkTo(methodOn(BookmarkController.class).getBookmark(entity.getUuid())).withRel("delete")
        );
    }
    return resource;
}
 
Example 20
Source Project: sakai   Source File: RubricsServiceImpl.java    License: Educational Community License v2.0 5 votes vote down vote up
private void deleteRubricEvaluationsForAssociation(String associationHref, String tool){
    try{
        String [] assocSplitted = associationHref.split("/");
        Long associationId = Long.valueOf(assocSplitted[assocSplitted.length-1]);
        log.debug("Deleting evaluations for association {}", associationId);
        Collection<Resource<Evaluation>> evaluations = getRubricEvaluationsByAssociation(Long.valueOf(associationId));
        for(Resource<Evaluation> eval : evaluations){
            deleteRubricResource(eval.getLink(Link.REL_SELF).getHref(), tool, null);
        }
    } catch (Exception e) {
        log.warn("Error deleting rubric association for tool {} and association {} : {}", tool, associationHref, e.getMessage());
    }
}
 
Example 21
Source Project: chaos-lemur   Source File: TaskResourceAssembler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Resource<Task> toResource(Task task) {
    Resource<Task> resource = new Resource<>(task);

    resource.add(getTaskLinkBuilder(task).withSelfRel());

    return resource;
}
 
Example 22
Source Project: service-block-samples   Source File: ProjectController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Appends an {@link Commit} domain commit to the commit log of the {@link Project}
 * aggregate with the specified projectId.
 *
 * @param projectId is the unique identifier for the {@link Project}
 * @param commit    is the {@link Commit} that attempts to alter the state of the {@link Project}
 * @return a hypermedia resource for the newly appended {@link Commit}
 */
private Resource<Commit> appendCommitResource(Long projectId, Commit commit) {
    Assert.notNull(commit, "Commit body must be provided");

    Project project = projectRepository.findById(projectId).get();
    Assert.notNull(project, "Project could not be found");

    commit.setProjectId(project.getIdentity());
    commit = commitRepository.save(commit);
    project.getCommits().add(commit);
    projectRepository.save(project);

    Map<String, Object> payload = new HashMap<>();
    payload.put("commit", commit);

    // Generate commit event
    projectEventService.apply(new ProjectEvent(ProjectEventType.COMMIT_EVENT, project, payload), projectService);

    return new Resource<>(commit,
            linkTo(CommitController.class)
                    .slash("commits")
                    .slash(commit.getIdentity())
                    .withSelfRel(),
            linkTo(ProjectController.class)
                    .slash("projects")
                    .slash(projectId)
                    .withRel("project")
    );
}
 
Example 23
Source Project: Mastering-Spring-5.0   Source File: TodoController.java    License: MIT License 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 24
private Resource<Bookmark> getBookmark(String location) throws Exception {
    String result = mvc.perform(
            get(location)
                    .accept("application/hal+json;charset=UTF-8", "application/json;charset=UTF-8")
    ).andDo(print())
            .andReturn().getResponse().getContentAsString();
    return objectMapper.readValue(result, new TypeReference<Resource<Bookmark>>() {
    });
}
 
Example 25
Source Project: sos   Source File: CatalogIntegration.java    License: Apache License 2.0 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 26
Source Project: Mastering-Spring-5.0   Source File: TodoController.java    License: MIT License 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 27
@RequestMapping(method = RequestMethod.GET)
public List<Resource<S3ObjectSummary>> getBucketResources() {

    ObjectListing objectListing = amazonS3Template.getAmazonS3Client()
            .listObjects(new ListObjectsRequest()
                    .withBucketName(bucketName));

    return objectListing.getObjectSummaries()
            .stream()
            .map(a -> new Resource<>(a,
                    new Link(String.format("https://s3.amazonaws.com/%s/%s",
                            a.getBucketName(), a.getKey())).withRel("url")))
            .collect(Collectors.toList());
}
 
Example 28
Resource<?> toResource(final HttpServletRequest request, Object newContent)
		throws SecurityException, BeansException {
	Link self = new Link(
			StringUtils.trimTrailingCharacter(request.getRequestURL().toString(), '/')
					+ "/"
					+ BeanUtils.getFieldWithAnnotation(newContent, ContentId.class));
	Resource<?> contentResource = new Resource<Object>(newContent,
			Collections.singletonList(self));
	return contentResource;
}
 
Example 29
Source Project: sakai   Source File: RubricsServiceImpl.java    License: Educational Community License v2.0 5 votes vote down vote up
/**
 * Returns the ToolItemRubricAssociation resource for the given tool and associated item ID, wrapped as an Optional.
 * @param toolId the tool id, something like "sakai.assignment"
 * @param associatedToolItemId the id of the associated element within the tool
 * @return
 */
protected Optional<Resource<ToolItemRubricAssociation>> getRubricAssociationResource(String toolId, String associatedToolItemId, String siteId) throws Exception {

    TypeReferences.ResourcesType<Resource<ToolItemRubricAssociation>> resourceParameterizedTypeReference =
            new TypeReferences.ResourcesType<Resource<ToolItemRubricAssociation>>() {};

    URI apiBaseUrl = new URI(serverConfigurationService.getServerUrl() + RBCS_SERVICE_URL_PREFIX);
    Traverson traverson = new Traverson(apiBaseUrl, MediaTypes.HAL_JSON);

    Traverson.TraversalBuilder builder = traverson.follow("rubric-associations", "search",
            "by-tool-item-ids");

    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", String.format("Bearer %s", generateJsonWebToken(toolId, siteId)));
    builder.withHeaders(headers);

    Map<String, Object> parameters = new HashMap<>();
    parameters.put("toolId", toolId);
    parameters.put("itemId", associatedToolItemId);

    Resources<Resource<ToolItemRubricAssociation>> associationResources = builder.withTemplateParameters(
            parameters).toObject(resourceParameterizedTypeReference);

    // Should only be one matching this search criterion
    if (associationResources.getContent().size() > 1) {
        throw new IllegalStateException(String.format(
                "Number of rubric association resources greater than one for request: %s",
                associationResources.getLink(Link.REL_SELF).toString()));
    }

    Optional<Resource<ToolItemRubricAssociation>> associationResource = associationResources.getContent().stream().findFirst();

    return associationResource;
}
 
Example 30
Source Project: JiwhizBlogWeb   Source File: WebsiteRestController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get current user info. If not authenticated, return 401.
 * @return
 */
@RequestMapping(method = RequestMethod.GET, value = ApiUrls.URL_SITE_CURRENT_USER)
public HttpEntity<Resource<UserAccount>> getCurrentUserAccount() {
    UserAccount currentUser = this.userAccountService.getCurrentUser();
    Resource<UserAccount> resource = (currentUser == null)? null : new Resource<UserAccount>(currentUser);
    return new ResponseEntity<>(resource, HttpStatus.OK);
}