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.WebsiteRestControllerTest.java

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

    when(blogPostRepositoryMock.findByPublishedIsTrueOrderByPublishedTimeDesc(any(Pageable.class)))
            .thenReturn(new PageImpl<BlogPost>(Arrays.asList(blog), new PageRequest(0, 1), 1));

    mockMvc.perform(get(API_ROOT + URL_SITE_LATEST_BLOG)).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_SITE_BLOGS + "/" + BLOG_ID)))
            .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())));
}

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

/**
 * Test creating an application with an ID.
 *
 * @throws Exception When issue in creation
 *//* w  w  w.ja v a 2 s.  co m*/
@Test
public void canCreateApplicationWithId() throws Exception {
    Assert.assertThat(this.jpaApplicationRepository.count(), Matchers.is(0L));

    this.createConfigResource(
            new Application.Builder(NAME, USER, VERSION, ApplicationStatus.ACTIVE).withId(ID).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(),
            null);

    this.mvc.perform(MockMvcRequestBuilders.get(APPLICATIONS_API + "/" + 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)));

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

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

@Test
public void getRecentPublicBlogPosts_ShouldReturnRecentBlogPosts() throws Exception {
    Pageable pageable = new PageRequest(0, 4);

    when(blogPostRepositoryMock.findByPublishedIsTrueOrderByPublishedTimeDesc(any(Pageable.class)))
            .thenReturn(new PageImpl<BlogPost>(getTestPublishedBlogPostList(), pageable, 2));

    mockMvc.perform(get(API_ROOT + URL_SITE_RECENT_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.href", endsWith(URL_SITE_RECENT_BLOGS)));

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

}

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

/**
 * Test creating a Command with an ID./* ww w  . j  a va 2  s  .c o m*/
 *
 * @throws Exception When issue in creation
 */
@Test
public void canCreateCommandWithId() throws Exception {
    Assert.assertThat(this.jpaCommandRepository.count(), Matchers.is(0L));
    this.createConfigResource(
            new Command.Builder(NAME, USER, VERSION, CommandStatus.ACTIVE, EXECUTABLE, CHECK_DELAY).withId(ID)
                    .withDescription(DESCRIPTION).withMemory(MEMORY).withConfigs(CONFIGS)
                    .withDependencies(DEPENDENCIES).withTags(TAGS).build(),
            null);

    this.mvc.perform(MockMvcRequestBuilders.get(COMMANDS_API + "/" + 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(STATUS_PATH, Matchers.is(CommandStatus.ACTIVE.toString())))
            .andExpect(MockMvcResultMatchers.jsonPath(EXECUTABLE_PATH, Matchers.is(EXECUTABLE)))
            .andExpect(MockMvcResultMatchers.jsonPath(CHECK_DELAY_PATH, Matchers.is((int) CHECK_DELAY)))
            .andExpect(MockMvcResultMatchers.jsonPath(DESCRIPTION_PATH, Matchers.is(DESCRIPTION)))
            .andExpect(MockMvcResultMatchers.jsonPath(MEMORY_PATH, Matchers.is(MEMORY)))
            .andExpect(MockMvcResultMatchers.jsonPath(CONFIGS_PATH, Matchers.hasSize(2)))
            .andExpect(MockMvcResultMatchers.jsonPath(CONFIGS_PATH, Matchers.hasItems(CONFIG_1, CONFIG_2)))
            .andExpect(MockMvcResultMatchers.jsonPath(DEPENDENCIES_PATH, Matchers.hasSize(2)))
            .andExpect(MockMvcResultMatchers.jsonPath(DEPENDENCIES_PATH, Matchers.hasItems(DEP_1, DEP_2)))
            .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.hasItems(TAG_1, TAG_2)))
            .andExpect(MockMvcResultMatchers.jsonPath(LINKS_PATH + ".*", Matchers.hasSize(3)))
            .andExpect(MockMvcResultMatchers.jsonPath(LINKS_PATH, Matchers.hasKey(SELF_LINK_KEY)))
            .andExpect(MockMvcResultMatchers.jsonPath(LINKS_PATH, Matchers.hasKey(CLUSTERS_LINK_KEY)))
            .andExpect(MockMvcResultMatchers.jsonPath(LINKS_PATH, Matchers.hasKey(APPLICATIONS_LINK_KEY)))
            .andExpect(MockMvcResultMatchers.jsonPath(COMMAND_CLUSTERS_LINK_PATH,
                    EntityLinkMatcher.matchUri(COMMANDS_API, CLUSTERS_LINK_KEY,
                            CLUSTERS_OPTIONAL_HAL_LINK_PARAMETERS, ID)))
            .andExpect(MockMvcResultMatchers.jsonPath(COMMAND_APPS_LINK_PATH,
                    EntityLinkMatcher.matchUri(COMMANDS_API, APPLICATIONS_LINK_KEY, null, ID)));

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

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

@Test
public void tagsCreateExample() throws Exception {
    Map<String, String> tag = new HashMap<String, String>();
    tag.put("name", "REST");

    ConstrainedFields fields = new ConstrainedFields(TagInput.class);

    this.mockMvc//  w  w  w .  j a va  2 s .  c  o  m
            .perform(post("/tags").contentType(MediaTypes.HAL_JSON)
                    .content(this.objectMapper.writeValueAsString(tag)))
            .andExpect(status().isCreated()).andDo(this.documentationHandler
                    .document(requestFields(fields.withPath("name").description("The name of the tag"))));
}

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

@Test
public void getRecentPublicCommentPosts_ShouldReturnRecentCommentPosts() throws Exception {
    Pageable pageable = new PageRequest(0, 4);

    when(commentPostRepositoryMock.findByStatusOrderByCreatedTimeDesc(eq(CommentStatusType.APPROVED),
            any(Pageable.class)))
                    .thenReturn(new PageImpl<CommentPost>(getTestApprovedCommentPostList(), pageable, 2));

    mockMvc.perform(get(API_ROOT + URL_SITE_RECENT_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[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)))
            //check links
            .andExpect(jsonPath("$._links.self.href", endsWith(URL_SITE_RECENT_COMMENTS)));

    verify(commentPostRepositoryMock, times(1)).findByStatusOrderByCreatedTimeDesc(CommentStatusType.APPROVED,
            pageable);/* w  w  w.  ja v  a 2  s. com*/
    verifyNoMoreInteractions(commentPostRepositoryMock);

}

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

@Test
public void noteUpdateExample() throws Exception {
    Map<String, Object> note = new HashMap<String, Object>();
    note.put("title", "REST maturity model");
    note.put("body", "http://martinfowler.com/articles/richardsonMaturityModel.html");

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

    this.mockMvc.perform(get(noteLocation)).andExpect(status().isOk())
            .andExpect(jsonPath("title", is(note.get("title"))))
            .andExpect(jsonPath("body", is(note.get("body"))))
            .andExpect(jsonPath("_links.self.href", is(noteLocation)))
            .andExpect(jsonPath("_links.note-tags", is(notNullValue())));

    Map<String, String> tag = new HashMap<String, String>();
    tag.put("name", "REST");

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

    Map<String, Object> noteUpdate = new HashMap<String, Object>();
    noteUpdate.put("tags", Arrays.asList(tagLocation));

    ConstrainedFields fields = new ConstrainedFields(NotePatchInput.class);

    this.mockMvc/*w w w  . j  a  v a  2s.c  o  m*/
            .perform(patch(noteLocation).contentType(MediaTypes.HAL_JSON)
                    .content(this.objectMapper.writeValueAsString(noteUpdate)))
            .andExpect(status().isNoContent())
            .andDo(this.documentationHandler.document(requestFields(
                    fields.withPath("title").description("The title of the note").type(JsonFieldType.STRING)
                            .optional(),
                    fields.withPath("body").description("The body of the note").type(JsonFieldType.STRING)
                            .optional(),
                    fields.withPath("tags").description("An array of tag resource URIs"))));
}

From source file:org.springsource.restbucks.payment.web.PaymentProcessIntegrationTest.java

/**
 * Concludes the {@link Order} by looking up the {@code receipt} link from the response and follows it. Triggers a
 * {@code DELETE} request susequently.//from   www  .  jav a 2s  .c  o  m
 * 
 * @param response
 * @return
 * @throws Exception
 */
private MockHttpServletResponse takeReceipt(MockHttpServletResponse response) throws Exception {

    Link receiptLink = getDiscovererFor(response).findLinkWithRel(RECEIPT_REL, response.getContentAsString());

    MockHttpServletResponse receiptResponse = mvc.perform(get(receiptLink.getHref())). //
            andExpect(status().isOk()). //
            andReturn().getResponse();

    LOG.info("Accessing receipt, got:" + receiptResponse.getContentAsString());
    LOG.info("Taking receipt");

    return mvc.perform( //
            delete(receiptLink.getHref()).//
                    accept(MediaTypes.HAL_JSON))
            . //
            andExpect(status().isOk()). //
            andReturn().getResponse();
}

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

/**
 * Test to make sure that you can search for clusters by various parameters.
 *
 * @throws Exception on configuration error
 *///from   w w w .  j a  v a2 s . com
@Test
public void canFindClusters() throws Exception {
    Assert.assertThat(this.jpaClusterRepository.count(), Matchers.is(0L));
    final String id1 = UUID.randomUUID().toString();
    final String id2 = UUID.randomUUID().toString();
    final String id3 = UUID.randomUUID().toString();
    final String name1 = UUID.randomUUID().toString();
    final String name2 = UUID.randomUUID().toString();
    final String name3 = UUID.randomUUID().toString();
    final String user1 = UUID.randomUUID().toString();
    final String user2 = UUID.randomUUID().toString();
    final String user3 = UUID.randomUUID().toString();
    final String version1 = UUID.randomUUID().toString();
    final String version2 = UUID.randomUUID().toString();
    final String version3 = UUID.randomUUID().toString();

    this.createConfigResource(new Cluster.Builder(name1, user1, version1, ClusterStatus.UP).withId(id1).build(),
            null);
    Thread.sleep(1000);
    this.createConfigResource(
            new Cluster.Builder(name2, user2, version2, ClusterStatus.OUT_OF_SERVICE).withId(id2).build(),
            null);
    Thread.sleep(1000);
    this.createConfigResource(
            new Cluster.Builder(name3, user3, version3, ClusterStatus.TERMINATED).withId(id3).build(), null);

    final RestDocumentationResultHandler findResultHandler = MockMvcRestDocumentation.document(
            "{class-name}/{method-name}/{step}/", Preprocessors.preprocessRequest(Preprocessors.prettyPrint()),
            Preprocessors.preprocessResponse(Preprocessors.prettyPrint()),
            Snippets.CLUSTER_SEARCH_QUERY_PARAMETERS, // Request query parameters
            Snippets.HAL_CONTENT_TYPE_HEADER, // Response headers
            Snippets.CLUSTER_SEARCH_RESULT_FIELDS, // Result fields
            Snippets.SEARCH_LINKS // HAL Links
    );

    // Test finding all clusters
    this.mvc.perform(MockMvcRequestBuilders.get(CLUSTERS_API)).andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(MockMvcResultMatchers.content().contentTypeCompatibleWith(MediaTypes.HAL_JSON))
            .andExpect(MockMvcResultMatchers.jsonPath(CLUSTERS_LIST_PATH, Matchers.hasSize(3)))
            .andExpect(MockMvcResultMatchers.jsonPath(CLUSTERS_ID_LIST_PATH,
                    Matchers.containsInAnyOrder(id1, id2, id3)))
            .andExpect(MockMvcResultMatchers.jsonPath(CLUSTERS_COMMANDS_LINK_PATH,
                    EntitiesLinksMatcher.matchUrisAnyOrder(CLUSTERS_API, COMMANDS_LINK_KEY,
                            COMMANDS_OPTIONAL_HAL_LINK_PARAMETERS, Lists.newArrayList(id1, id2, id3))))
            .andDo(findResultHandler);

    // Try to limit the number of results
    this.mvc.perform(MockMvcRequestBuilders.get(CLUSTERS_API).param("size", "2"))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(MockMvcResultMatchers.content().contentTypeCompatibleWith(MediaTypes.HAL_JSON))
            .andExpect(MockMvcResultMatchers.jsonPath(CLUSTERS_LIST_PATH, Matchers.hasSize(2)))
            .andDo(findResultHandler);

    // Query by name
    this.mvc.perform(MockMvcRequestBuilders.get(CLUSTERS_API).param("name", name2))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(MockMvcResultMatchers.content().contentTypeCompatibleWith(MediaTypes.HAL_JSON))
            .andExpect(MockMvcResultMatchers.jsonPath(CLUSTERS_LIST_PATH, Matchers.hasSize(1)))
            .andExpect(MockMvcResultMatchers.jsonPath(CLUSTERS_LIST_PATH + "[0].id", Matchers.is(id2)))
            .andDo(findResultHandler);

    // Query by statuses
    this.mvc.perform(MockMvcRequestBuilders.get(CLUSTERS_API).param("status", ClusterStatus.UP.toString(),
            ClusterStatus.TERMINATED.toString())).andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(MockMvcResultMatchers.content().contentTypeCompatibleWith(MediaTypes.HAL_JSON))
            .andExpect(MockMvcResultMatchers.jsonPath(CLUSTERS_LIST_PATH, Matchers.hasSize(2)))
            .andExpect(MockMvcResultMatchers.jsonPath(CLUSTERS_LIST_PATH + "[0].id", Matchers.is(id3)))
            .andExpect(MockMvcResultMatchers.jsonPath(CLUSTERS_LIST_PATH + "[1].id", Matchers.is(id1)))
            .andDo(findResultHandler);

    // Query by tags
    this.mvc.perform(MockMvcRequestBuilders.get(CLUSTERS_API).param("tag", "genie.id:" + id1))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(MockMvcResultMatchers.content().contentTypeCompatibleWith(MediaTypes.HAL_JSON))
            .andExpect(MockMvcResultMatchers.jsonPath(CLUSTERS_LIST_PATH, Matchers.hasSize(1)))
            .andExpect(MockMvcResultMatchers.jsonPath(CLUSTERS_LIST_PATH + "[0].id", Matchers.is(id1)))
            .andDo(findResultHandler);

    //TODO: Add tests for searching by min and max update time as those are available parameters
    //TODO: Add tests for sort, orderBy etc

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

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

@Test
public void tagGetExample() throws Exception {
    Map<String, String> tag = new HashMap<String, String>();
    tag.put("name", "REST");

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

    this.mockMvc.perform(get(tagLocation)).andExpect(status().isOk())
            .andExpect(jsonPath("name", is(tag.get("name"))))
            .andDo(this.documentationHandler.document(
                    links(linkWithRel("self").description("This <<resources-tag,tag>>"),
                            linkWithRel("tagged-notes")
                                    .description("The <<resources-tagged-notes,notes>> that have this tag")),
                    responseFields(fieldWithPath("name").description("The name of the tag"),
                            fieldWithPath("_links")
                                    .description("<<resources-tag-links,Links>> to other resources"))));
}