Example usage for org.springframework.hateoas MediaTypes HAL_JSON

List of usage examples for org.springframework.hateoas MediaTypes HAL_JSON

Introduction

In this page you can find the example usage for org.springframework.hateoas MediaTypes HAL_JSON.

Prototype

MediaType HAL_JSON

To view the source code for org.springframework.hateoas MediaTypes HAL_JSON.

Click Source Link

Document

Public constant media type for application/hal+json .

Usage

From source file:example.springdata.rest.stores.StarbucksClient.java

@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>>() {
            });//from   ww w  . j a  v  a2 s . co  m

    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));
}

From source file:com.jiwhiz.rest.admin.CommentRestControllerTest.java

@Test
public void getCommentPosts_ShouldReturnAllCommentPosts() throws Exception {
    Page<CommentPost> page = new PageImpl<CommentPost>(getTestApprovedCommentPostList(), new PageRequest(0, 10),
            2);/*from  w  w w . j  ava  2s.co m*/

    when(commentPostRepositoryMock.findAll(any(Pageable.class))).thenReturn(page);

    mockMvc.perform(get(API_ROOT + URL_ADMIN_COMMENTS + "?page=1&size=10")).andExpect(status().isOk())
            .andExpect(content().contentType(MediaTypes.HAL_JSON))
            .andExpect(jsonPath("$._embedded.commentPostList", hasSize(2)))
            .andExpect(jsonPath("$._embedded.commentPostList[0].id", is(COMMENTS_1_ID)))
            .andExpect(jsonPath("$._embedded.commentPostList[0].content", is(COMMENTS_1_CONTENT)))
            .andExpect(jsonPath("$._embedded.commentPostList[1].id", is(COMMENTS_2_ID)))
            .andExpect(jsonPath("$._embedded.commentPostList[1].content", is(COMMENTS_2_CONTENT)))
            .andExpect(jsonPath("$._links.self.href", endsWith(URL_ADMIN_COMMENTS + "{?page,size,sort}")));
}

From source file:example.company.UrlLevelSecurityTests.java

@Test
public void rejectsPostAccessToCollectionResource() throws Exception {

    mvc.perform(post("/employees").//
            content(PAYLOAD).//
            accept(MediaTypes.HAL_JSON)).//
            andExpect(status().isUnauthorized()).//
            andDo(print());/*ww w .  j  a  v a2 s. com*/
}

From source file:com.jiwhiz.rest.author.AuthorBlogRestControllerTest.java

@Test
public void getBlogPosts_ShouldReturnAllBlogPostsForCurrentUser() throws Exception {
    UserAccount user = getTestLoggedInUserWithAuthorRole();
    when(userAccountServiceMock.getCurrentUser()).thenReturn(user);

    when(blogPostRepositoryMock.findByAuthorOrderByCreatedTimeDesc(eq(user), any(Pageable.class)))
            .thenReturn(new PageImpl<BlogPost>(getTestPublishedBlogPostList(), new PageRequest(0, 10), 1));

    mockMvc.perform(get(API_ROOT + URL_AUTHOR_BLOGS)).andExpect(status().isOk())
            .andExpect(content().contentType(MediaTypes.HAL_JSON))
            .andExpect(jsonPath("$._embedded.blogPostList", hasSize(2)))
            .andExpect(jsonPath("$._embedded.blogPostList[0].id", is(BLOGS_1_ID)))
            .andExpect(jsonPath("$._embedded.blogPostList[0].title", is(BLOGS_1_TITLE)))
            .andExpect(jsonPath("$._embedded.blogPostList[1].id", is(BLOGS_2_ID)))
            .andExpect(jsonPath("$._embedded.blogPostList[1].title", is(BLOGS_2_TITLE)))
            .andExpect(jsonPath("$._links.self.templated", is(true)))
            .andExpect(jsonPath("$._links.self.href", endsWith(URL_AUTHOR_BLOGS + "{?page,size,sort}")));
}

From source file:com.jiwhiz.rest.user.UserCommentRestControllerTest.java

@Test
public void getCurrentUserComments_ShouldReturnAllCommentsByUser() throws Exception {
    UserAccount user = getTestLoggedInUserWithAdminRole();

    Page<CommentPost> page = new PageImpl<CommentPost>(getTestUserCommentPostList(), new PageRequest(0, 10), 2);

    when(userAccountServiceMock.getCurrentUser()).thenReturn(user);
    when(commentPostRepositoryMock.findByAuthorOrderByCreatedTimeDesc(any(UserAccount.class),
            any(Pageable.class))).thenReturn(page);
    mockMvc.perform(get(API_ROOT + URL_USER_COMMENTS)).andExpect(status().isOk())
            .andExpect(content().contentType(MediaTypes.HAL_JSON))
            .andExpect(jsonPath("$._embedded.commentPostList", hasSize(2)))
            .andExpect(jsonPath("$._embedded.commentPostList[0].id", is(COMMENTS_1_ID)))
            .andExpect(jsonPath("$._embedded.commentPostList[1].id", is(COMMENTS_2_ID)));
}

From source file:com.example.AuthzApp.java

private MappingJackson2HttpMessageConverter halJsonMappingJackson2HttpMessageConverter() {
    final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(
            halJsonObjectMapperBuilder().build());
    converter.setSupportedMediaTypes(/*from  w w  w.ja  v a2 s .co m*/
            Arrays.asList(MediaTypes.HAL_JSON, MediaType.APPLICATION_JSON_UTF8, MediaType.APPLICATION_JSON));
    return converter;
}

From source file:com.jiwhiz.rest.site.PublicBlogRestControllerTest.java

@Test
public void getPublicBlogPosts_ShouldReturnAllPublicBlogPosts() throws Exception {
    Pageable pageable = new PageRequest(0, 10);
    when(blogPostRepositoryMock.findByPublishedIsTrueOrderByPublishedTimeDesc(any(Pageable.class)))
            .thenReturn(new PageImpl<BlogPost>(getTestPublishedBlogPostList(), pageable, 2));

    mockMvc.perform(get(API_ROOT + URL_SITE_BLOGS)).andExpect(status().isOk())
            .andExpect(content().contentType(MediaTypes.HAL_JSON))
            .andExpect(jsonPath("$._embedded.blogPostList", hasSize(2)))
            .andExpect(jsonPath("$._embedded.blogPostList[0].id", is(BLOGS_1_ID)))
            .andExpect(jsonPath("$._embedded.blogPostList[0].title", is(BLOGS_1_TITLE)))
            .andExpect(jsonPath("$._embedded.blogPostList[1].id", is(BLOGS_2_ID)))
            .andExpect(jsonPath("$._embedded.blogPostList[1].title", is(BLOGS_2_TITLE)))
            //check links
            .andExpect(jsonPath("$._links.self.templated", is(true)))
            .andExpect(jsonPath("$._links.self.href", endsWith("public/blogs{?page,size,sort}")))
            //check page
            .andExpect(jsonPath("$.page.size", is(10))).andExpect(jsonPath("$.page.totalElements", is(2)))
            .andExpect(jsonPath("$.page.totalPages", is(1))).andExpect(jsonPath("$.page.number", is(0)));

    verify(blogPostRepositoryMock, times(1)).findByPublishedIsTrueOrderByPublishedTimeDesc(pageable);
    verifyNoMoreInteractions(blogPostRepositoryMock);
}

From source file:com.jiwhiz.rest.user.UserAccountRestControllerTest.java

@Test
public void getCurrentUserAccount_ShouldReturnCurrentUserAccountWithSocialConnections() throws Exception {
    UserAccount user = getTestLoggedInUserWithAdminRole();
    UserSocialConnection socialConnection1 = new UserSocialConnection();
    socialConnection1.setProviderId("google");
    socialConnection1.setProviderUserId("googleUser");
    UserSocialConnection socialConnection2 = new UserSocialConnection();
    socialConnection2.setProviderId("facebook");
    socialConnection2.setProviderUserId("facebookUser");

    when(userAccountServiceMock.getCurrentUser()).thenReturn(user);
    when(userSocialConnectionRepositoryMock.findByUserId(user.getUserId()))
            .thenReturn(Arrays.asList(socialConnection1, socialConnection2));

    mockMvc.perform(get(API_ROOT + URL_USER)).andExpect(status().isOk())
            .andExpect(content().contentType(MediaTypes.HAL_JSON))
            .andExpect(jsonPath("$.id", is(ADMIN_USER_ID)))
            .andExpect(jsonPath("$.userId", is(ADMIN_USER_USERNAME)))
            .andExpect(jsonPath("$.displayName", is(USER_DISPLAY_NAME)))
            .andExpect(jsonPath("$.admin", is(true))).andExpect(jsonPath("$.author", is(false)))
            .andExpect(jsonPath("$.socialConnections.google.providerId", is("google")))
            .andExpect(jsonPath("$.socialConnections.google.providerUserId", is("googleUser")))
            .andExpect(jsonPath("$.socialConnections.facebook.providerId", is("facebook")))
            .andExpect(jsonPath("$.socialConnections.facebook.providerUserId", is("facebookUser")))
            //validate links
            .andExpect(jsonPath("$._links.self.href", endsWith(URL_USER)))
            .andExpect(jsonPath("$._links.profile.href", endsWith(URL_USER_PROFILE)))
            .andExpect(jsonPath("$._links.comments.templated", is(true)))
            .andExpect(jsonPath("$._links.comments.href", endsWith(URL_USER_COMMENTS + "{?page,size,sort}")));
}

From source file:example.company.UrlLevelSecurityTests.java

@Test
public void allowsGetRequestsButRejectsPostForUser() throws Exception {

    HttpHeaders headers = new HttpHeaders();
    headers.add(HttpHeaders.ACCEPT, MediaTypes.HAL_JSON.toString());
    headers.add(HttpHeaders.AUTHORIZATION, "Basic " + new String(Base64.encode(("greg:turnquist").getBytes())));

    mvc.perform(get("/employees").//
            headers(headers)).//
            andExpect(content().contentType(MediaTypes.HAL_JSON)).//
            andExpect(status().isOk()).//
            andDo(print());//from   ww  w . j  a v a  2 s  . c o m

    mvc.perform(post("/employees").//
            headers(headers)).//
            andExpect(status().isForbidden()).//
            andDo(print());
}

From source file:com.jiwhiz.rest.admin.BlogRestControllerTest.java

@Test
public void getBlogPostById_ShouldReturnBlogPost() throws Exception {
    BlogPost blog = getTestSinglePublishedBlogPost();
    blog.setId(BLOG_ID);//w  w w .jav a2  s.  com

    when(blogPostRepositoryMock.findOne(BLOG_ID)).thenReturn(blog);
    mockMvc.perform(get(API_ROOT + URL_ADMIN_BLOGS_BLOG, BLOG_ID)).andExpect(status().isOk())
            .andExpect(content().contentType(MediaTypes.HAL_JSON)).andExpect(jsonPath("$.id", is(BLOG_ID)))
            .andExpect(jsonPath("$.title", is(BLOG_TITLE)))
            .andExpect(jsonPath("$._links.self.href", endsWith(URL_ADMIN_BLOGS + "/" + BLOG_ID)));
}