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:com.jiwhiz.rest.site.PublicBlogRestControllerTest.java

@Test
public void getPublicBlogPostById_ShouldReturnBlogPost() throws Exception {
    BlogPost blog = getTestSinglePublishedBlogPost();

    when(blogPostRepositoryMock.findOne(BLOG_ID)).thenReturn(blog);

    mockMvc.perform(get(API_ROOT + URL_SITE_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(BLOG_ID.toString())))
            .andExpect(jsonPath("$._links.comments.templated", is(true)))
            .andExpect(jsonPath("$._links.comments.href",
                    endsWith(URL_SITE_BLOGS + "/" + BLOG_ID + "/comments{?page,size,sort}")))
            .andExpect(jsonPath("$._links.author.href",
                    endsWith(URL_SITE_PROFILES + "/" + blog.getAuthor().getUserId())));

    verify(blogPostRepositoryMock, times(1)).findOne(BLOG_ID);
    verifyNoMoreInteractions(blogPostRepositoryMock);
}

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

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

    BlogPost blogPost = getTestSinglePublishedBlogPost();
    when(blogPostRepositoryMock.findOne(BLOG_ID)).thenReturn(blogPost);

    CommentPost commentPost = getTestApprovedCommentPost();
    when(commentPostRepositoryMock.findOne(COMMENT_ID)).thenReturn(commentPost);

    mockMvc.perform(get(API_ROOT + URL_AUTHOR_BLOGS_BLOG_COMMENTS_COMMENT, BLOG_ID, COMMENT_ID))
            .andExpect(status().isOk()).andExpect(content().contentType(MediaTypes.HAL_JSON))
            .andExpect(jsonPath("$.id", is(COMMENT_ID))).andExpect(jsonPath("$.content", is(COMMENT_CONTENT)))
            .andExpect(jsonPath("$._links.self.href", endsWith(BLOG_ID + "/comments/" + COMMENT_ID)))
            .andExpect(jsonPath("$._links.blog.href", endsWith(BLOG_ID.toString())))
            .andExpect(jsonPath("$._links.author.href", endsWith(AUTHOR_USER_USERNAME)));
}

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

@Test
public void getPublicWebsiteResource_ShouldReturnWebsiteResourceWithoutAuthenticatedUser() throws Exception {
    when(userAccountServiceMock.getCurrentUser()).thenReturn(null);

    mockMvc.perform(get(API_ROOT + URL_SITE)).andExpect(status().isOk())
            .andExpect(content().contentType(MediaTypes.HAL_JSON))
            //check links
            .andExpect(jsonPath("$._links.self.href", endsWith(URL_SITE)))
            .andExpect(jsonPath("$._links.blogs.templated", is(true)))
            .andExpect(jsonPath("$._links.blogs.href", endsWith(URL_SITE_BLOGS + "{?page,size,sort}")))
            .andExpect(jsonPath("$._links.blog.templated", is(true)))
            .andExpect(jsonPath("$._links.blog.href", endsWith(URL_SITE_BLOGS_BLOG)))
            .andExpect(jsonPath("$._links.profile.templated", is(true)))
            .andExpect(jsonPath("$._links.profile.href", endsWith(URL_SITE_PROFILES_USER)))
            .andExpect(jsonPath("$._links.latestBlog.href", endsWith(URL_SITE_LATEST_BLOG)))
            .andExpect(jsonPath("$._links.recentBlogs.href", endsWith(URL_SITE_RECENT_BLOGS)))
            .andExpect(jsonPath("$._links.recentComments.href", endsWith(URL_SITE_RECENT_COMMENTS)))
            .andExpect(jsonPath("$._links.tagCloud.href", endsWith(URL_SITE_TAG_CLOUDS)));
}

From source file:io.github.howiefh.jeews.modules.oauth2.controller.OAuthTest.java

@Test
public void testCodeAuth() throws Exception {
    MvcResult result = mockMvc//from ww  w .  j av a 2s. co m
            .perform(get("/authentication").param("client_id", clientID).param("response_type", responseType)
                    .param("redirect_uri", redirectUri).param("state", "public").accept(MediaTypes.HAL_JSON))
            .andExpect(status().isFound()) // 302
            .andReturn();
    String redirect = result.getResponse().getRedirectedUrl();
    assertTrue(redirect.matches(".*code=.*"));

    Pattern pattern = Pattern.compile(".*code=([^&]*)");
    Matcher matcher = pattern.matcher(redirect);
    String code = null;
    if (matcher.find()) {
        code = matcher.group(1);
    }

    result = mockMvc
            .perform(post("/accessToken").param("code", code).param("client_id", clientID)
                    .param("client_secret", clientSecret).param("grant_type", grantType)
                    .param("redirect_uri", redirectUri).contentType("application/x-www-form-urlencoded")
                    .accept(MediaTypes.HAL_JSON))
            .andExpect(status().isOk()) // 200
            .andExpect(jsonPath("$.expires_in").value(3600)).andReturn();

    String content = result.getResponse().getContentAsString();
    JSONObject json = new JSONObject(content);
    String accessToken = json.get("access_token").toString();
    mockMvc.perform(
            get("/users/1").header("Authorization", "Bearer " + accessToken).accept(MediaTypes.HAL_JSON))
            .andExpect(status().isOk()) // 200
            .andExpect(content().contentType(MediaTypes.HAL_JSON)) // ??contentType
            .andReturn();
    mockMvc.perform(get("/users/1")).andExpect(status().isUnauthorized()) // 401
            .andReturn();
}

From source file:com.example.notes.GettingStartedDocumentation.java

String createTag() throws Exception, JsonProcessingException {
    Map<String, String> tag = new HashMap<String, String>();
    tag.put("name", "getting-started");

    String tagLocation = this.mockMvc
            .perform(post("/tags").contentType(MediaTypes.HAL_JSON)
                    .content(objectMapper.writeValueAsString(tag)))
            .andExpect(status().isCreated()).andExpect(header().string("Location", notNullValue())).andReturn()
            .getResponse().getHeader("Location");
    return tagLocation;
}

From source file:com.netflix.genie.web.controllers.ClusterRestControllerIntegrationTests.java

/**
 * Test creating a cluster without an ID.
 *
 * @throws Exception on configuration issue
 */// www  .j a va 2 s . c  o  m
@Test
public void canCreateClusterWithoutId() throws Exception {
    Assert.assertThat(this.jpaClusterRepository.count(), Matchers.is(0L));

    final RestDocumentationResultHandler creationResultHandler = MockMvcRestDocumentation.document(
            "{class-name}/{method-name}/{step}/", Preprocessors.preprocessRequest(Preprocessors.prettyPrint()),
            Preprocessors.preprocessResponse(Preprocessors.prettyPrint()), Snippets.CONTENT_TYPE_HEADER, // Request headers
            Snippets.getClusterRequestPayload(), // Request fields
            Snippets.LOCATION_HEADER // Response headers
    );

    final String id = this.createConfigResource(
            new Cluster.Builder(NAME, USER, VERSION, ClusterStatus.UP).build(), creationResultHandler);

    final RestDocumentationResultHandler getResultHandler = MockMvcRestDocumentation.document(
            "{class-name}/{method-name}/{step}/", Preprocessors.preprocessRequest(Preprocessors.prettyPrint()),
            Preprocessors.preprocessResponse(Preprocessors.prettyPrint()), Snippets.ID_PATH_PARAM, // path parameters
            Snippets.HAL_CONTENT_TYPE_HEADER, // response headers
            Snippets.getClusterResponsePayload(), // response payload
            Snippets.CLUSTER_LINKS // response links
    );

    this.mvc.perform(RestDocumentationRequestBuilders.get(CLUSTERS_API + "/{id}", id))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(MockMvcResultMatchers.content().contentTypeCompatibleWith(MediaTypes.HAL_JSON))
            .andExpect(MockMvcResultMatchers.jsonPath(ID_PATH, Matchers.is(id)))
            .andExpect(MockMvcResultMatchers.jsonPath(CREATED_PATH, Matchers.notNullValue()))
            .andExpect(MockMvcResultMatchers.jsonPath(UPDATED_PATH, Matchers.notNullValue()))
            .andExpect(MockMvcResultMatchers.jsonPath(NAME_PATH, Matchers.is(NAME)))
            .andExpect(MockMvcResultMatchers.jsonPath(USER_PATH, Matchers.is(USER)))
            .andExpect(MockMvcResultMatchers.jsonPath(VERSION_PATH, Matchers.is(VERSION)))
            .andExpect(MockMvcResultMatchers.jsonPath(TAGS_PATH, Matchers.hasItem("genie.id:" + id)))
            .andExpect(MockMvcResultMatchers.jsonPath(TAGS_PATH, Matchers.hasItem("genie.name:" + NAME)))
            .andExpect(MockMvcResultMatchers.jsonPath(SETUP_FILE_PATH, Matchers.nullValue()))
            .andExpect(MockMvcResultMatchers.jsonPath(STATUS_PATH, Matchers.is(ClusterStatus.UP.toString())))
            .andExpect(MockMvcResultMatchers.jsonPath(CONFIGS_PATH, Matchers.hasSize(0)))
            .andExpect(MockMvcResultMatchers.jsonPath(DEPENDENCIES_PATH, Matchers.hasSize(0)))
            .andExpect(MockMvcResultMatchers.jsonPath(LINKS_PATH + ".*", Matchers.hasSize(2)))
            .andExpect(MockMvcResultMatchers.jsonPath(LINKS_PATH, Matchers.hasKey(SELF_LINK_KEY)))
            .andExpect(MockMvcResultMatchers.jsonPath(LINKS_PATH, Matchers.hasKey(COMMANDS_LINK_KEY)))
            .andExpect(MockMvcResultMatchers.jsonPath(CLUSTER_COMMANDS_LINK_PATH, EntityLinkMatcher
                    .matchUri(CLUSTERS_API, COMMANDS_LINK_KEY, COMMANDS_OPTIONAL_HAL_LINK_PARAMETERS, id)))
            .andDo(getResultHandler);

    Assert.assertThat(this.jpaClusterRepository.count(), Matchers.is(1L));
}

From source file:com.netflix.genie.web.controllers.ApplicationRestControllerIntegrationTests.java

/**
 * Test creating an application without an ID.
 *
 * @throws Exception on configuration issue
 *//*from  w  w  w .j a v a  2 s  .co  m*/
@Test
public void canCreateApplicationWithoutId() throws Exception {
    Assert.assertThat(this.jpaApplicationRepository.count(), Matchers.is(0L));

    final RestDocumentationResultHandler creationResultHandler = MockMvcRestDocumentation.document(
            "{class-name}/{method-name}/{step}/", Preprocessors.preprocessRequest(Preprocessors.prettyPrint()),
            Preprocessors.preprocessResponse(Preprocessors.prettyPrint()), Snippets.CONTENT_TYPE_HEADER, // Request headers
            Snippets.getApplicationRequestPayload(), // Request fields
            Snippets.LOCATION_HEADER // Response headers
    );

    final String id = this
            .createConfigResource(
                    new Application.Builder(NAME, USER, VERSION, ApplicationStatus.ACTIVE).withType(TYPE)
                            .withDependencies(
                                    Sets.newHashSet("s3://mybucket/spark/" + VERSION + "/spark.tar.gz"))
                            .withSetupFile("s3://mybucket/spark/" + VERSION + "/setup-spark.sh")
                            .withConfigs(Sets.newHashSet("s3://mybucket/spark/" + VERSION + "/spark-env.sh"))
                            .withDescription("Spark for Genie")
                            .withTags(Sets.newHashSet("type:" + TYPE, "ver:" + VERSION)).build(),
                    creationResultHandler);

    final RestDocumentationResultHandler getResultHandler = MockMvcRestDocumentation.document(
            "{class-name}/{method-name}/{step}/", Preprocessors.preprocessRequest(Preprocessors.prettyPrint()),
            Preprocessors.preprocessResponse(Preprocessors.prettyPrint()), Snippets.ID_PATH_PARAM, // path parameters
            Snippets.HAL_CONTENT_TYPE_HEADER, // response headers
            Snippets.getApplicationResponsePayload(), // response payload
            Snippets.APPLICATION_LINKS // response links
    );

    this.mvc.perform(RestDocumentationRequestBuilders.get(APPLICATIONS_API + "/{id}", id))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(MockMvcResultMatchers.content().contentTypeCompatibleWith(MediaTypes.HAL_JSON))
            .andExpect(MockMvcResultMatchers.jsonPath(ID_PATH, Matchers.is(id)))
            .andExpect(MockMvcResultMatchers.jsonPath(UPDATED_PATH, Matchers.notNullValue()))
            .andExpect(MockMvcResultMatchers.jsonPath(CREATED_PATH, Matchers.notNullValue()))
            .andExpect(MockMvcResultMatchers.jsonPath(NAME_PATH, Matchers.is(NAME)))
            .andExpect(MockMvcResultMatchers.jsonPath(VERSION_PATH, Matchers.is(VERSION)))
            .andExpect(MockMvcResultMatchers.jsonPath(USER_PATH, Matchers.is(USER)))
            .andExpect(MockMvcResultMatchers.jsonPath(DESCRIPTION_PATH, Matchers.is("Spark for Genie")))
            .andExpect(MockMvcResultMatchers.jsonPath(SETUP_FILE_PATH,
                    Matchers.is("s3://mybucket/spark/" + VERSION + "/setup-spark.sh")))
            .andExpect(MockMvcResultMatchers.jsonPath(CONFIGS_PATH,
                    Matchers.hasItem("s3://mybucket/spark/" + VERSION + "/spark-env.sh")))
            .andExpect(MockMvcResultMatchers.jsonPath(TAGS_PATH, Matchers.hasSize(4)))
            .andExpect(MockMvcResultMatchers.jsonPath(TAGS_PATH, Matchers.hasItem("genie.id:" + id)))
            .andExpect(MockMvcResultMatchers.jsonPath(TAGS_PATH, Matchers.hasItem("genie.name:" + NAME)))
            .andExpect(MockMvcResultMatchers.jsonPath(TAGS_PATH, Matchers.hasItem("ver:" + VERSION)))
            .andExpect(MockMvcResultMatchers.jsonPath(TAGS_PATH, Matchers.hasItem("type:" + TYPE)))
            .andExpect(MockMvcResultMatchers.jsonPath(STATUS_PATH,
                    Matchers.is(ApplicationStatus.ACTIVE.toString())))
            .andExpect(MockMvcResultMatchers.jsonPath(DEPENDENCIES_PATH,
                    Matchers.hasItem("s3://mybucket/spark/" + VERSION + "/spark.tar.gz")))
            .andExpect(MockMvcResultMatchers.jsonPath(TYPE_PATH, Matchers.is(TYPE)))
            .andExpect(MockMvcResultMatchers.jsonPath(LINKS_PATH + ".*", Matchers.hasSize(2)))
            .andExpect(MockMvcResultMatchers.jsonPath(LINKS_PATH, Matchers.hasKey(SELF_LINK_KEY)))
            .andExpect(MockMvcResultMatchers.jsonPath(LINKS_PATH, Matchers.hasKey(COMMANDS_LINK_KEY)))
            .andExpect(MockMvcResultMatchers.jsonPath(APPLICATION_COMMANDS_LINK_PATH, EntityLinkMatcher
                    .matchUri(APPLICATIONS_API, COMMANDS_LINK_KEY, COMMANDS_OPTIONAL_HAL_LINK_PARAMETERS, id)))
            .andDo(getResultHandler);

    Assert.assertThat(this.jpaApplicationRepository.count(), Matchers.is(1L));
}

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

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

    when(userAccountRepositoryMock.findOne(ADMIN_USER_ID)).thenReturn(user);

    mockMvc.perform(get(API_ROOT + URL_SITE_PROFILES_USER, ADMIN_USER_USERNAME)).andExpect(status().isOk())
            .andExpect(content().contentType(MediaTypes.HAL_JSON))
            .andExpect(jsonPath("$.displayName", is(USER_DISPLAY_NAME)))
            .andExpect(jsonPath("$.admin", is(true))).andExpect(jsonPath("$.author", is(false)))
            //check links
            .andExpect(jsonPath("$._links.self.href", endsWith(URL_SITE_PROFILES + "/" + ADMIN_USER_USERNAME)))
            .andExpect(jsonPath("$._links.comments.templated", is(true)))
            .andExpect(jsonPath("$._links.comments.href",
                    endsWith(URL_SITE_PROFILES + "/" + ADMIN_USER_USERNAME + "/comments{?page,size,sort}")));
}

From source file:com.example.notes.GettingStartedDocumentation.java

String createTaggedNote(String tag) throws Exception {
    Map<String, Object> note = new HashMap<String, Object>();
    note.put("title", "Tagged note creation with cURL");
    note.put("body", "An example of how to create a tagged note using cURL");
    note.put("tags", Arrays.asList(tag));

    String noteLocation = this.mockMvc
            .perform(post("/notes").contentType(MediaTypes.HAL_JSON)
                    .content(objectMapper.writeValueAsString(note)))
            .andExpect(status().isCreated()).andExpect(header().string("Location", notNullValue())).andReturn()
            .getResponse().getHeader("Location");
    return noteLocation;
}

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

@Test
public void getBlogApprovedCommentPosts_ShouldReturnApprovedComments() throws Exception {
    BlogPost blog = getTestSinglePublishedBlogPost();
    Page<CommentPost> page = new PageImpl<CommentPost>(getTestApprovedCommentPostList(), new PageRequest(0, 10),
            2);// ww  w  .  j a va 2  s .  c om

    when(blogPostRepositoryMock.findOne(BLOG_ID)).thenReturn(blog);
    when(commentPostRepositoryMock.findByBlogPostAndStatusOrderByCreatedTimeAsc(any(BlogPost.class),
            eq(CommentStatusType.APPROVED), any(Pageable.class))).thenReturn(page);

    mockMvc.perform(get(API_ROOT + URL_SITE_BLOGS_BLOG_COMMENTS, BLOG_ID)).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.templated", is(true)))
            .andExpect(jsonPath("$._links.self.href", endsWith("/comments{?page,size,sort}")));

    verify(blogPostRepositoryMock, times(1)).findOne(BLOG_ID);
    verifyNoMoreInteractions(blogPostRepositoryMock);

    verify(commentPostRepositoryMock, times(1)).findByBlogPostAndStatusOrderByCreatedTimeAsc(
            any(BlogPost.class), eq(CommentStatusType.APPROVED), any(Pageable.class));
    verifyNoMoreInteractions(commentPostRepositoryMock);

}