org.springframework.hateoas.MediaTypes Java Examples

The following examples show how to use org.springframework.hateoas.MediaTypes. 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 File: RestHelper.java    From taskana with Apache License 2.0 6 votes vote down vote up
/**
 * Return a REST template which is capable of dealing with responses in HAL format.
 *
 * @return RestTemplate
 */
private static RestTemplate getRestTemplate() {
  ObjectMapper mapper = new ObjectMapper();
  mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
  mapper.registerModule(new Jackson2HalModule());
  mapper
      .registerModule(new ParameterNamesModule())
      .registerModule(new Jdk8Module())
      .registerModule(new JavaTimeModule());

  MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
  converter.setSupportedMediaTypes(Collections.singletonList(MediaTypes.HAL_JSON));
  converter.setObjectMapper(mapper);

  RestTemplate template = new RestTemplate();
  // important to add first to ensure priority
  template.getMessageConverters().add(0, converter);
  return template;
}
 
Example #2
Source File: RubricsServiceImpl.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
protected Collection<Resource<ToolItemRubricAssociation>> getRubricAssociationByRubric(String rubricId, String toSite) 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-rubric-id");

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

    Map<String, Object> parameters = new HashMap<>();
    parameters.put("rubricId", Long.valueOf(rubricId));
    Resources<Resource<ToolItemRubricAssociation>> associationResources = builder.withTemplateParameters(parameters).toObject(resourceParameterizedTypeReference);

    return associationResources.getContent();
}
 
Example #3
Source File: RubricsServiceImpl.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
public String getRubricEvaluationObjectId(String associationId, String userId, String toolId) {
    try {
        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-and-user");

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

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

        String response = builder.withTemplateParameters(parameters).toObject(String.class);
        if (StringUtils.isNotEmpty(response)){
            return response.replace("\"", "");
        }
    } catch (Exception e) {
        log.warn("Error {} while getting a rubric evaluation in assignment {} for user {}", e.getMessage(), associationId, userId);
    }
    return null;
}
 
Example #4
Source File: SpeakerControllerTest.java    From springrestdoc with MIT License 6 votes vote down vote up
@Test
public void testGetAllSpeakers() throws Exception {
    //Given
    Speaker josh = given.speaker("Josh Long").company("Pivotal").save();
    Speaker venkat = given.speaker("Venkat Subramaniam").company("Agile").save();

    //When
    ResultActions action = mockMvc.perform(
            get("/speakers").accept(MediaTypes.HAL_JSON));

    //Then
    action.andDo(print()).andExpect(status().isOk());
    action.andDo(document("{class-name}/{method-name}",
            responseFields(
                    fieldWithPath("_embedded").description("'speakers' array with Speakers resources."),
                    fieldWithPath("_embedded.speakers").description("Array with returned Speaker resources."),
                    fieldWithPath("_embedded.speakers[].name").description("Speaker's name."),
                    fieldWithPath("_embedded.speakers[].company").description("Speaker's company."),
                    fieldWithPath("_embedded.speakers[].status").description("Speaker's status name."),
                    fieldWithPath("_embedded.speakers[]._links").description("Link section."),
                    subsectionWithPath("_embedded.speakers[]._links").description("<<resources-tags-links, " +
                            "HATEOAS Links>> to Speaker actions")
            )

    ));
}
 
Example #5
Source File: DeptRepositoryTest.java    From spring-data-jpa-demo with Apache License 2.0 6 votes vote down vote up
/**
 * Create.
 *
 * @throws Exception the exception
 * @see DeptRepository#save(Object)
 */
@Test
void create() throws Exception {

    JSONObject params = new JSONObject();
    params.put("name", "This is a test dept.");

    this.mockMvc.perform(
            post(basePath + "/" + RESOURCE_NAME)
                    .contentType(MediaTypes.HAL_JSON)
                    .content(params.toJSONString()))
            .andExpect(status().isCreated())
            .andExpect(header().string("Location", notNullValue()))
            .andDo(document(RESOURCE_NAME + "-create",
                    selfLinksSnippet,
                    requestFields(
                            fieldWithPath("name").description("部门名称")
                    ),
                    responseFields
            ));
}
 
Example #6
Source File: RolloutResourceDocumentationTest.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
@Test
@Description("Handles the GET request of retrieving a all targets of a specific deploy group of a rollout. Required Permission: "
        + SpPermission.READ_ROLLOUT + ", " + SpPermission.READ_TARGET)
public void getRolloutDeployGroupTargetsWithParameters() throws Exception {
    final Rollout rollout = createRolloutEntity();
    final RolloutGroup firstRolloutGroup = rolloutGroupManagement
            .findByRollout(PageRequest.of(0, 1), rollout.getId()).getContent().get(0);

    mockMvc.perform(
            get(MgmtRestConstants.ROLLOUT_V1_REQUEST_MAPPING + "/{rolloutId}/deploygroups/{deployGroupId}/targets",
                    rollout.getId(), firstRolloutGroup.getId()).param("offset", "0").param("limit", "2")
                            .param("sort", "name:ASC").param("q", "controllerId==exampleTarget0")
                            .accept(MediaTypes.HAL_JSON_VALUE))
            .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
            .andExpect(content().contentType(MediaTypes.HAL_JSON_UTF8))
            .andDo(this.document.document(
                    pathParameters(parameterWithName("rolloutId").description(ApiModelPropertiesGeneric.ITEM_ID),
                            parameterWithName("deployGroupId").description(ApiModelPropertiesGeneric.ITEM_ID)),
                    getFilterRequestParamter()));
}
 
Example #7
Source File: WorkbasketController.java    From taskana with Apache License 2.0 6 votes vote down vote up
@GetMapping(path = Mapping.URL_WORKBASKET_ID_DISTRIBUTION, produces = MediaTypes.HAL_JSON_VALUE)
@Transactional(readOnly = true, rollbackFor = Exception.class)
public ResponseEntity<TaskanaPagedModel<WorkbasketSummaryRepresentationModel>>
    getDistributionTargets(@PathVariable(value = "workbasketId") String workbasketId)
        throws WorkbasketNotFoundException, NotAuthorizedException {

  LOGGER.debug("Entry to getDistributionTargets(workbasketId= {})", workbasketId);
  List<WorkbasketSummary> distributionTargets =
      workbasketService.getDistributionTargets(workbasketId);
  TaskanaPagedModel<WorkbasketSummaryRepresentationModel> distributionTargetListResource =
      workbasketSummaryRepresentationModelAssembler.toDistributionTargetPageModel(
          distributionTargets, null);
  ResponseEntity<TaskanaPagedModel<WorkbasketSummaryRepresentationModel>> result =
      ResponseEntity.ok(distributionTargetListResource);
  if (LOGGER.isDebugEnabled()) {
    LOGGER.debug("Exit from getDistributionTargets(), returning {}", result);
  }

  return result;
}
 
Example #8
Source File: DdiRootControllerTest.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
@Test
@Description("Ensures that the target state machine of a precomissioned target switches from "
        + "UNKNOWN to REGISTERED when the target polls for the first time.")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1),
        @Expect(type = TargetUpdatedEvent.class, count = 1), @Expect(type = TargetPollEvent.class, count = 1) })
public void rootRsPrecommissioned() throws Exception {
    testdataFactory.createTarget("4711");

    assertThat(targetManagement.getByControllerID("4711").get().getUpdateStatus())
            .isEqualTo(TargetUpdateStatus.UNKNOWN);

    final long current = System.currentTimeMillis();
    mvc.perform(get("/{tenant}/controller/v1/4711", tenantAware.getCurrentTenant()))
            .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
            .andExpect(content().contentType(MediaTypes.HAL_JSON_UTF8))
            .andExpect(jsonPath("$.config.polling.sleep", equalTo("00:01:00")));

    assertThat(targetManagement.getByControllerID("4711").get().getLastTargetQuery())
            .isLessThanOrEqualTo(System.currentTimeMillis());
    assertThat(targetManagement.getByControllerID("4711").get().getLastTargetQuery())
            .isGreaterThanOrEqualTo(current);

    assertThat(targetManagement.getByControllerID("4711").get().getUpdateStatus())
            .isEqualTo(TargetUpdateStatus.REGISTERED);
}
 
Example #9
Source File: SpeakerControllerTest.java    From springrestdoc with MIT License 5 votes vote down vote up
@Before
public void setUp() {
    this.mockMvc = MockMvcBuilders.webAppContextSetup(ctx)
            .defaultRequest(options("/")
                    .accept(MediaTypes.HAL_JSON)
                    .contentType("application/hal+json;charset=UTF-8"))
            .build();
}
 
Example #10
Source File: RolloutResourceDocumentationTest.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
@Test
@Description("Handles the GET request of retrieving all rollouts. Required Permission: "
        + SpPermission.READ_ROLLOUT)
public void getRolloutsWithParameters() throws Exception {
    createRolloutEntity();

    mockMvc.perform(get(MgmtRestConstants.ROLLOUT_V1_REQUEST_MAPPING).param("offset", "0").param("limit", "2")
            .param("sort", "id:DESC").param("q", "name==exampleRollout*").accept(MediaTypes.HAL_JSON_VALUE))
            .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
            .andExpect(content().contentType(MediaTypes.HAL_JSON_UTF8))
            .andDo(this.document.document(getFilterRequestParamter()));
}
 
Example #11
Source File: HalActuatorEndpointsDiscoverer.java    From microservices-dashboard with Apache License 2.0 5 votes vote down vote up
private Links discoverLinks(ResponseEntity<String> response) {
	Links links = new Links();
	if (!response.getStatusCode().isError()
			&& response.hasBody()
			&& !StringUtils.isEmpty(response.getBody())) {
		MediaType mediaType = Optional.ofNullable(response.getHeaders().getContentType())
				.orElse(MediaTypes.HAL_JSON_UTF8);
		links = createLinksFrom(response.getBody(), mediaType);
	}
	return links;
}
 
Example #12
Source File: RubricsServiceImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public void deleteSiteRubrics(String siteId) {
    try {
        TypeReferences.ResourcesType<Resource<Rubric>> resourceParameterizedTypeReference = new TypeReferences.ResourcesType<Resource<Rubric>>() {};
        URI apiBaseUrl = new URI(serverConfigurationService.getServerUrl() + RBCS_SERVICE_URL_PREFIX);
        Traverson traverson = new Traverson(apiBaseUrl, MediaTypes.HAL_JSON);
        Traverson.TraversalBuilder builder = traverson.follow("rubrics", "search", "rubrics-from-site");

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

        Map<String, Object> parameters = new HashMap<>();
        parameters.put("siteId", siteId);
        Resources<Resource<Rubric>> rubricResources = builder.withTemplateParameters(parameters).toObject(resourceParameterizedTypeReference);
        for (Resource<Rubric> rubricResource : rubricResources) {
            String [] rubricSplitted = rubricResource.getLink(Link.REL_SELF).getHref().split("/");
            Collection<Resource<ToolItemRubricAssociation>> assocs = getRubricAssociationByRubric(rubricSplitted[rubricSplitted.length-1],siteId);
            for(Resource<ToolItemRubricAssociation> associationResource : assocs){
                String associationHref = associationResource.getLink(Link.REL_SELF).getHref();
                deleteRubricResource(associationHref, RubricsConstants.RBCS_TOOL, siteId);
            }
            deleteRubricResource(rubricResource.getLink(Link.REL_SELF).getHref(), RubricsConstants.RBCS_TOOL, siteId);
        }
    } catch(Exception e){
        log.error("Rubrics: error trying to delete rubric -> {}" , e.getMessage());
    }
}
 
Example #13
Source File: HalActuatorEndpointsDiscovererTests.java    From microservices-dashboard with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnListWithDiscoveredEndpointsFromResponse() {
	String body = "{\"_links\":{\"self\":{\"href\":\"http://localhost:8080/actuator\",\"templated\":false},\"health-component-instance\":{\"href\":\"http://localhost:8080/actuator/health/{component}/{instance}\",\"templated\":true},\"health-component\":{\"href\":\"http://localhost:8080/actuator/health/{component}\",\"templated\":true},\"health\":{\"href\":\"http://localhost:8080/actuator/health\",\"templated\":false},\"info\":{\"href\":\"http://localhost:8080/actuator/info\",\"templated\":false}}}";
	when(this.clientResponse.toEntity(String.class))
			.thenReturn(Mono.just(ResponseEntity.ok(body)));
	when(this.linkDiscoverers.getLinkDiscovererFor(MediaTypes.HAL_JSON_UTF8))
			.thenReturn(this.linkDiscoverer);
	when(this.linkDiscoverer.findLinkWithRel("self", body))
			.thenReturn(new Link("http://localhost:8080/actuator", "self"));
	when(this.linkDiscoverer.findLinkWithRel("health-component-instance", body))
			.thenReturn(new Link("http://localhost:8080/actuator/health/{component}/instance/{instance}", "health-component-instance"));
	when(this.linkDiscoverer.findLinkWithRel("health-component", body))
			.thenReturn(new Link("http://localhost:8080/actuator/health/{component}", "health-component"));
	when(this.linkDiscoverer.findLinkWithRel("health", body))
			.thenReturn(new Link("http://localhost:8080/actuator/health", "health"));
	when(this.linkDiscoverer.findLinkWithRel("info", body))
			.thenReturn(new Link("http://localhost:8080/actuator/info", "info"));

	this.discoverer.findActuatorEndpoints(this.applicationInstance)
			.subscribe(actuatorEndpoints -> {
				assertThat(actuatorEndpoints).hasSize(5);

				verify(this.webClient).get();
				verifyNoMoreInteractions(this.webClient);
				verify(this.requestHeadersSpec).exchange();
				verifyNoMoreInteractions(this.requestHeadersSpec);
				verify(this.requestHeadersUriSpec).uri(URI.create("http://localhost:8080/actuator"));
				verifyNoMoreInteractions(this.requestHeadersUriSpec);
				verify(this.clientResponse).toEntity(String.class);
				verifyNoMoreInteractions(this.clientResponse);
				verify(this.linkDiscoverers, times(5)).getLinkDiscovererFor(MediaTypes.HAL_JSON_UTF8);
				verifyNoMoreInteractions(this.linkDiscoverers);
				verify(this.linkDiscoverer).findLinkWithRel("self", body);
				verify(this.linkDiscoverer).findLinkWithRel("health-component-instance", body);
				verify(this.linkDiscoverer).findLinkWithRel("health-component", body);
				verify(this.linkDiscoverer).findLinkWithRel("health", body);
				verify(this.linkDiscoverer).findLinkWithRel("info", body);
				verifyNoMoreInteractions(this.linkDiscoverer);
			});
}
 
Example #14
Source File: UrlLevelSecurityTests.java    From spring-data-examples with Apache License 2.0 5 votes vote down vote up
@Test
public void rejectsPostAccessToCollectionResource() throws Exception {

	mvc.perform(post("/employees").//
			content(PAYLOAD).//
			accept(MediaTypes.HAL_JSON)).//
			andExpect(status().isUnauthorized());
}
 
Example #15
Source File: GettingStartedDocumentation.java    From restdocs-wiremock with Apache License 2.0 5 votes vote down vote up
String createNote() throws Exception {
	Map<String, String> note = new HashMap<String, String>();
	note.put("title", "Note creation with cURL");
	note.put("body", "An example of how to create a note using cURL");

	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;
}
 
Example #16
Source File: CustomerClient.java    From microservice-consul with Apache License 2.0 5 votes vote down vote up
protected RestTemplate getRestTemplate() {
	ObjectMapper mapper = new ObjectMapper();
	mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	mapper.registerModule(new Jackson2HalModule());

	MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
	converter.setSupportedMediaTypes(Arrays.asList(MediaTypes.HAL_JSON));
	converter.setObjectMapper(mapper);

	return new RestTemplate(Collections.<HttpMessageConverter<?>>singletonList(converter));
}
 
Example #17
Source File: GettingStartedDocumentation.java    From restdocs-wiremock with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #18
Source File: RolloutResourceDocumentationTest.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
@Test
@Description("Handles the POST request of approving a rollout. Required Permission: "
        + SpPermission.APPROVE_ROLLOUT)
public void approveRollout() throws Exception {
    approvalStrategy.setApprovalNeeded(true);
    final Rollout rollout = createRolloutEntity();
    mockMvc.perform(post(MgmtRestConstants.ROLLOUT_V1_REQUEST_MAPPING + "/{rolloutId}/approve", rollout.getId())
            .accept(MediaTypes.HAL_JSON_VALUE)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
            .andDo(this.document.document(
                    pathParameters(parameterWithName("rolloutId").description(ApiModelPropertiesGeneric.ITEM_ID))));
}
 
Example #19
Source File: PatronProfileControllerIT.java    From library with MIT License 5 votes vote down vote up
@Test
public void shouldCreateLinksForHolds() throws Exception {
    given(patronProfiles.fetchFor(patronId)).willReturn(profiles());

    //expect
    mvc.perform(get("/profiles/" + patronId.getPatronId() + "/holds/")
            .accept(MediaTypes.HAL_FORMS_JSON_VALUE))
            .andExpect(status().isOk())
            .andExpect(header().string(CONTENT_TYPE, MediaTypes.HAL_FORMS_JSON_VALUE))
            .andExpect(jsonPath("$._embedded.holdList[0].bookId", is(bookId.getBookId().toString())))
            .andExpect(jsonPath("$._embedded.holdList[0]._links.self.href", containsString("/profiles/" + patronId.getPatronId() + "/holds/" + bookId.getBookId())))
            .andExpect(jsonPath("$._embedded.holdList[0].till", is(anyDate.toString())))
            .andExpect(jsonPath("$._embedded.holdList[0]._templates.default.method", is("delete")));
}
 
Example #20
Source File: JsonClientHttpRequestInterceptor.java    From bowman with Apache License 2.0 5 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
		throws IOException {
	HttpRequestWrapper wrapped = new HttpRequestWrapper(request);
	wrapped.getHeaders().put("Content-Type", asList(MediaTypes.HAL_JSON_VALUE));
	wrapped.getHeaders().put("Accept", asList(MediaTypes.HAL_JSON_VALUE));
	return execution.execute(wrapped, body);
}
 
Example #21
Source File: HomeController.java    From spring-hateoas-examples with Apache License 2.0 5 votes vote down vote up
/**
 * Instead of putting the creation link from the remote service in the template (a security concern), have a local
 * route for {@literal POST} requests. Gather up the information, and form a remote call, using {@link Traverson} to
 * fetch the {@literal employees} {@link Link}. Once a new employee is created, redirect back to the root URL.
 *
 * @param employee
 * @return
 * @throws URISyntaxException
 */
@PostMapping("/employees")
public String newEmployee(@ModelAttribute Employee employee) throws URISyntaxException {

	Traverson client = new Traverson(new URI(REMOTE_SERVICE_ROOT_URI), MediaTypes.HAL_JSON);
	Link employeesLink = client //
			.follow("employees") //
			.asLink();

	this.rest.postForEntity(employeesLink.expand().getHref(), employee, Employee.class);

	return "redirect:/";
}
 
Example #22
Source File: ApiDocumentation.java    From restdocs-raml with MIT License 5 votes vote down vote up
private void whenNoteCreated() throws Exception {
	resultActions = this.mockMvc
			.perform(post("/notes")
					.contentType(MediaTypes.HAL_JSON)
					.content(this.objectMapper.writeValueAsString(note)))
			.andExpect(status().isCreated());
	noteLocation = resultActions.andReturn().getResponse().getHeader("Location");
}
 
Example #23
Source File: RootControllerDocumentationTest.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
@Test
@Description("The SP server might cancel an operation, e.g. an unfinished update has a sucessor. "
        + "It is up to the provisiong target to decide either to accept the cancelation or reject it.")
@WithUser(tenantId = "TENANT_ID", authorities = "ROLE_CONTROLLER", allSpPermissions = true)
public void getControllerCancelAction() throws Exception {
    final DistributionSet set = testdataFactory.createDistributionSet("one");

    set.getModules().forEach(module -> {
        final byte random[] = RandomStringUtils.random(5).getBytes();

        artifactManagement.create(
                new ArtifactUpload(new ByteArrayInputStream(random), module.getId(), "binary.tgz", false, 0));
        artifactManagement.create(
                new ArtifactUpload(new ByteArrayInputStream(random), module.getId(), "file.signature", false, 0));
    });

    final Target target = targetManagement.create(entityFactory.target().create().controllerId(CONTROLLER_ID));
    final Long actionId = getFirstAssignedActionId(assignDistributionSet(set.getId(), target.getControllerId()));
    final Action cancelAction = deploymentManagement.cancelAction(actionId);

    mockMvc.perform(
            get(DdiRestConstants.BASE_V1_REQUEST_MAPPING + "/{controllerId}/" + DdiRestConstants.CANCEL_ACTION
                    + "/{actionId}", tenantAware.getCurrentTenant(), target.getControllerId(), cancelAction.getId())
                            .accept(MediaTypes.HAL_JSON_VALUE))
            .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
            .andExpect(content().contentType(MediaTypes.HAL_JSON_UTF8))
            .andDo(this.document.document(
                    pathParameters(parameterWithName("tenant").description(ApiModelPropertiesGeneric.TENANT),
                            parameterWithName("controllerId").description(DdiApiModelProperties.CONTROLLER_ID),
                            parameterWithName("actionId").description(DdiApiModelProperties.ACTION_ID_CANCELED)),

                    responseFields(fieldWithPath("id").description(DdiApiModelProperties.ACTION_ID),
                            fieldWithPath("cancelAction").description(DdiApiModelProperties.CANCEL_ACTION),
                            fieldWithPath("cancelAction.stopId")
                                    .description(DdiApiModelProperties.ACTION_ID_CANCELED)

                    )));
}
 
Example #24
Source File: RolloutResourceDocumentationTest.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
@Test
@Description("Handles the POST request of denying a rollout. Required Permission: " + SpPermission.APPROVE_ROLLOUT)
public void denyRollout() throws Exception {
    approvalStrategy.setApprovalNeeded(true);
    final Rollout rollout = createRolloutEntity();
    mockMvc.perform(post(MgmtRestConstants.ROLLOUT_V1_REQUEST_MAPPING + "/{rolloutId}/deny", rollout.getId())
            .accept(MediaTypes.HAL_JSON_VALUE)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
            .andDo(this.document.document(
                    pathParameters(parameterWithName("rolloutId").description(ApiModelPropertiesGeneric.ITEM_ID))));
}
 
Example #25
Source File: DeptRepositoryTest.java    From spring-data-jpa-demo with Apache License 2.0 5 votes vote down vote up
/**
 * Delete by id.
 *
 * @throws Exception the exception
 * @see DeptRepository#deleteById(Object)
 */
@Test
void deleteById() throws Exception {
    this.mockMvc.perform(
            delete(basePath + "/" + RESOURCE_NAME + "/{id}", id).contentType(MediaTypes.HAL_JSON))
            .andExpect(status().isNoContent())
            .andDo(document(RESOURCE_NAME + "-delete",
                    pathParameters(
                            parameterWithName("id").description("部门编号")
                    )
            ));
}
 
Example #26
Source File: TaskCommentControllerRestDocumentation.java    From taskana with Apache License 2.0 5 votes vote down vote up
@Test
void createAndDeleteTaskCommentDocTest() throws Exception {

  String createTaskCommentContent =
      "{ \"taskId\" : \"TKI:000000000000000000000000000000000000\",\n"
          + "  \"textField\" : \"some text in textfield\"} ";

  MvcResult result =
      this.mockMvc
          .perform(
              RestDocumentationRequestBuilders.post(
                      restHelper.toUrl(
                          Mapping.URL_TASK_GET_POST_COMMENTS,
                          "TKI:000000000000000000000000000000000000"))
                  .contentType(MediaTypes.HAL_JSON)
                  .content(createTaskCommentContent)
                  .header("Authorization", ADMIN_CREDENTIALS))
          .andExpect(MockMvcResultMatchers.status().isCreated())
          .andDo(
              MockMvcRestDocumentation.document(
                  "CreateTaskCommentDocTest",
                  requestFields(createTaskCommentFieldDescriptors),
                  responseFields(taskCommentFieldDescriptors)))
          .andReturn();

  String resultContent = result.getResponse().getContentAsString();
  String newId =
      resultContent.substring(resultContent.indexOf("TCI:"), resultContent.indexOf("TCI:") + 40);

  this.mockMvc
      .perform(
          RestDocumentationRequestBuilders.delete(
                  restHelper.toUrl(Mapping.URL_TASK_COMMENT, newId))
              .header("Authorization", ADMIN_CREDENTIALS)) // admin
      .andExpect(MockMvcResultMatchers.status().isNoContent())
      .andDo(MockMvcRestDocumentation.document("DeleteTaskCommentDocTest"));
}
 
Example #27
Source File: TaskCommentControllerRestDocumentation.java    From taskana with Apache License 2.0 5 votes vote down vote up
@Test
void getSpecificTaskCommentDocTest() throws Exception {
  this.mockMvc
      .perform(
          RestDocumentationRequestBuilders.get(
                  restHelper.toUrl(
                      Mapping.URL_TASK_COMMENT, "TCI:000000000000000000000000000000000000"))
              .accept(MediaTypes.HAL_JSON)
              .header("Authorization", ADMIN_CREDENTIALS))
      .andExpect(MockMvcResultMatchers.status().isOk())
      .andDo(
          MockMvcRestDocumentation.document(
              "GetSpecificTaskCommentDocTest", responseFields(taskCommentFieldDescriptors)));
}
 
Example #28
Source File: RubricsServiceImpl.java    From sakai with 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 #29
Source File: WorkbasketControllerIntTest.java    From taskana with Apache License 2.0 5 votes vote down vote up
@Test
void testGetWorkbasketDistributionTargets() {
  ResponseEntity<TaskanaPagedModel<WorkbasketSummaryRepresentationModel>> response =
      TEMPLATE.exchange(
          restHelper.toUrl(
              Mapping.URL_WORKBASKET_ID_DISTRIBUTION, "WBI:100000000000000000000000000000000001"),
          HttpMethod.GET,
          restHelper.defaultRequest(),
          WORKBASKET_SUMMARY_PAGE_MODEL_TYPE);
  assertThat(response.getBody()).isNotNull();
  assertThat(response.getBody().getLink(IanaLinkRelations.SELF)).isNotNull();
  assertThat(response.getHeaders().getContentType()).isEqualTo(MediaTypes.HAL_JSON);
  assertThat(response.getBody().getContent()).hasSize(4);
}
 
Example #30
Source File: WorkbasketControllerIntTest.java    From taskana with Apache License 2.0 5 votes vote down vote up
@Test
void testGetWorkbasketAccessItems() {
  ResponseEntity<TaskanaPagedModel<WorkbasketAccessItemRepresentationModel>> response =
      TEMPLATE.exchange(
          restHelper.toUrl(
              Mapping.URL_WORKBASKET_ID_ACCESSITEMS, "WBI:100000000000000000000000000000000005"),
          HttpMethod.GET,
          restHelper.defaultRequest(),
          WORKBASKET_ACCESS_ITEM_PAGE_MODEL_TYPE);
  assertThat(response.getBody()).isNotNull();
  assertThat(response.getBody().getLink(IanaLinkRelations.SELF)).isNotNull();
  assertThat(response.getHeaders().getContentType()).isEqualTo(MediaTypes.HAL_JSON);
  assertThat(response.getBody().getContent()).hasSize(3);
}