org.springframework.restdocs.payload.JsonFieldType Java Examples

The following examples show how to use org.springframework.restdocs.payload.JsonFieldType. 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: SoftwaremoduleTypesDocumentationTest.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
@Test
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Handles the GET request of retrieving all software module types within SP. Required Permission: READ_REPOSITORY.")
public void getSoftwareModuleTypes() throws Exception {

    final SoftwareModuleType testType = testdataFactory.findOrCreateSoftwareModuleType("test123");
    softwareModuleTypeManagement
            .update(entityFactory.softwareModuleType().update(testType.getId()).description("Desc1234"));

    mockMvc.perform(get(MgmtRestConstants.SOFTWAREMODULETYPE_V1_REQUEST_MAPPING).accept(MediaType.APPLICATION_JSON))
            .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
            .andDo(this.document.document(responseFields(
                    fieldWithPath("size").type(JsonFieldType.NUMBER).description(ApiModelPropertiesGeneric.SIZE),
                    fieldWithPath("total").description(ApiModelPropertiesGeneric.TOTAL_ELEMENTS),
                    fieldWithPath("content").description(MgmtApiModelProperties.TARGET_LIST),
                    fieldWithPath("content[].createdBy").description(ApiModelPropertiesGeneric.CREATED_BY),
                    fieldWithPath("content[].createdAt").description(ApiModelPropertiesGeneric.CREATED_AT),
                    fieldWithPath("content[].description").description(ApiModelPropertiesGeneric.DESCRPTION),
                    fieldWithPath("content[].id").description(ApiModelPropertiesGeneric.ITEM_ID),
                    fieldWithPath("content[].lastModifiedAt")
                            .description(ApiModelPropertiesGeneric.LAST_MODIFIED_AT).type("Number"),
                    fieldWithPath("content[].lastModifiedBy")
                            .description(ApiModelPropertiesGeneric.LAST_MODIFIED_BY).type("String"),
                    fieldWithPath("content[].name").description(ApiModelPropertiesGeneric.NAME),
                    fieldWithPath("content[]._links.self").ignored())));
}
 
Example #2
Source File: RamlResourceSnippetParameters.java    From restdocs-raml with MIT License 6 votes vote down vote up
private static FieldDescriptor toFieldDescriptor(LinkDescriptor linkDescriptor) {

        FieldDescriptor descriptor = createLinkFieldDescriptor(linkDescriptor.getRel())
                .description(linkDescriptor.getDescription())
                .type(JsonFieldType.VARIES)
                .attributes(linkDescriptor.getAttributes().entrySet().stream()
                        .map(e -> new Attribute(e.getKey(), e.getValue()))
                        .toArray(Attribute[]::new));

        if (linkDescriptor.isOptional()) {
            descriptor = descriptor.optional();
        }
        if (linkDescriptor.isIgnored()) {
            descriptor = descriptor.ignored();
        }

        return descriptor;
    }
 
Example #3
Source File: ApiDocumentationTest.java    From spring-rest with Apache License 2.0 6 votes vote down vote up
@Test
public void greetingV1() throws Exception {
  this.mockMvc
      .perform(
          get("/v1/greeting")
              .header("Origin", "*")
      )
      .andDo(print()).andExpect(status().isOk())
      .andExpect(content().string(containsString("Hello, World!")))
      .andDo(
          document("greeting-v1",
              responseFields(
                  fieldWithPath("id").description("The number of greetings that have been requested.").type(JsonFieldType.NUMBER),
                  fieldWithPath("content").description("The content of the greeting.").type(JsonFieldType.STRING)
              )
          )
      );
}
 
Example #4
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 the deploy groups of a rollout. Required Permission: "
        + SpPermission.READ_ROLLOUT)
public void getRolloutDeployGroups() throws Exception {
    final Rollout rollout = createRolloutEntity();

    mockMvc.perform(get(MgmtRestConstants.ROLLOUT_V1_REQUEST_MAPPING + "/{rolloutId}/deploygroups", rollout.getId())
            .accept(MediaTypes.HAL_JSON_VALUE)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
            .andExpect(content().contentType(MediaTypes.HAL_JSON_UTF8))
            .andDo(this.document.document(
                    getRolloutDeployGroupResponseFields(true, false,
                            fieldWithPath("total").description(ApiModelPropertiesGeneric.TOTAL_ELEMENTS),
                            fieldWithPath("size").type(JsonFieldType.NUMBER)
                                    .description(ApiModelPropertiesGeneric.SIZE),
                            fieldWithPath("content").description(MgmtApiModelProperties.ROLLOUT_LIST)),
                    pathParameters(parameterWithName("rolloutId").description(ApiModelPropertiesGeneric.ITEM_ID))));
}
 
Example #5
Source File: Snippets.java    From genie with Apache License 2.0 6 votes vote down vote up
private static FieldDescriptor[] getClusterFieldDescriptors() {
    return ArrayUtils.addAll(
        getConfigFieldDescriptors(CLUSTER_CONSTRAINTS),
        PayloadDocumentation
            .fieldWithPath("status")
            .attributes(getConstraintsForField(CLUSTER_CONSTRAINTS, "status"))
            .description(
                "The status of the cluster. Options: " + Arrays.toString(ClusterStatus.values())
            )
            .type(JsonFieldType.STRING),
        PayloadDocumentation
            .fieldWithPath("dependencies")
            .attributes(getConstraintsForField(CLUSTER_CONSTRAINTS, "dependencies"))
            .description("The dependencies for the cluster")
            .type(JsonFieldType.ARRAY)
            .optional()
    );
}
 
Example #6
Source File: Snippets.java    From genie with Apache License 2.0 6 votes vote down vote up
static ResponseFieldsSnippet resolveClustersForCommandClusterCriteriaResponsePayload() {
    return PayloadDocumentation
        .responseFields(
            PayloadDocumentation
                .fieldWithPath("[]")
                .attributes(EMPTY_CONSTRAINTS)
                .description("The list of criterion and associated resolved clusters")
                .type(JsonFieldType.ARRAY)
                .optional()
        )
        .andWithPrefix(
            "[].",
            PayloadDocumentation
                .fieldWithPath("criterion")
                .attributes(EMPTY_CONSTRAINTS)
                .description("The criterion that was evaluated to yield the resources")
                .type(JsonFieldType.OBJECT),
            PayloadDocumentation
                .fieldWithPath("resources")
                .attributes(EMPTY_CONSTRAINTS)
                .description("The resources that were resolved by evaluating the criterion")
                .type(JsonFieldType.ARRAY)
        )
        .andWithPrefix("[].criterion.", getCriterionFieldDescriptors())
        .andWithPrefix("[].resources[].", getClusterFieldDescriptors());
}
 
Example #7
Source File: Snippets.java    From genie with Apache License 2.0 6 votes vote down vote up
private static FieldDescriptor[] getApplicationFieldDescriptors() {
    return ArrayUtils.addAll(
        getConfigFieldDescriptors(APPLICATION_CONSTRAINTS),
        PayloadDocumentation
            .fieldWithPath("type")
            .attributes(getConstraintsForField(APPLICATION_CONSTRAINTS, "type"))
            .description("The type of application this is (e.g. hadoop, presto, spark). Can be used to group.")
            .type(JsonFieldType.STRING)
            .optional(),
        PayloadDocumentation
            .fieldWithPath("status")
            .attributes(getConstraintsForField(APPLICATION_CONSTRAINTS, "status"))
            .description(
                "The status of the application. Options: " + Arrays.toString(ApplicationStatus.values())
            )
            .type(JsonFieldType.STRING),
        PayloadDocumentation
            .fieldWithPath("dependencies")
            .attributes(getConstraintsForField(APPLICATION_CONSTRAINTS, "dependencies"))
            .description("The dependencies for the application")
            .type(JsonFieldType.ARRAY)
            .optional()
    );
}
 
Example #8
Source File: ApiDocumentationTest.java    From spring-rest with Apache License 2.0 6 votes vote down vote up
@Test
public void hostinfoV1() throws Exception {
  this.mockMvc
      .perform(
          get("/v1/hostinfo")
              .header("Origin", "*")
      )
      .andDo(print()).andExpect(status().isOk())
      .andExpect(content().string(anything()))
      .andDo(
          document("hostname-v1",
              responseFields(
                  fieldWithPath("hostname").description("The instance's hostname.").type(JsonFieldType.STRING)
              )
          )
      );
}
 
Example #9
Source File: DistributionSetTagResourceDocumentationTest.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
@Test
@Description("Handles the GET request of retrieving all assigned distribution sets by the given tag id.")
public void getAssignedDistributionSets() throws Exception {
    final DistributionSetTag tag = createDistributionSetTag();
    distributionSetManagement.assignTag(Arrays.asList(distributionSet.getId()), tag.getId());

    arrayPrefix = "content[].";
    this.mockMvc
            .perform(get(MgmtRestConstants.DISTRIBUTIONSET_TAG_V1_REQUEST_MAPPING
                    + MgmtRestConstants.DISTRIBUTIONSET_TAG_DISTRIBUTIONSETS_REQUEST_MAPPING, tag.getId())
                            .contentType(MediaType.APPLICATION_JSON_UTF8))
            .andExpect(status().isOk()).andDo(MockMvcResultPrinter.print())
            .andDo(this.document.document(
                    pathParameters(parameterWithName("distributionsetTagId")
                            .description(ApiModelPropertiesGeneric.ITEM_ID)),
                    getResponseFieldsDistributionSet(true,
                            fieldWithPath("size").type(JsonFieldType.NUMBER)
                                    .description(ApiModelPropertiesGeneric.SIZE),
                            fieldWithPath("total").description(ApiModelPropertiesGeneric.TOTAL_ELEMENTS),
                            fieldWithPath("content").description(MgmtApiModelProperties.TARGET_LIST))));
}
 
Example #10
Source File: DistributionSetsDocumentationTest.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
@Test
@Description("Handles the GET request for retrieving assigned targets of a single distribution set. Required Permission: "
        + SpPermission.READ_REPOSITORY + " and " + SpPermission.READ_TARGET)
public void getAssignedTargets() throws Exception {
    final DistributionSet set = testdataFactory.createUpdatedDistributionSet();

    final Target target = testdataFactory.createTarget();
    // assign knownTargetId to distribution set
    assignDistributionSet(set.getId(), target.getControllerId());

    mockMvc.perform(
            get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/{distributionSetId}/assignedTargets",
                    set.getId()).accept(MediaType.APPLICATION_JSON))
            .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
            .andDo(this.document.document(
                    pathParameters(
                            parameterWithName("distributionSetId").description(ApiModelPropertiesGeneric.ITEM_ID)),
                    responseFields(fieldWithPath("total").description(ApiModelPropertiesGeneric.TOTAL_ELEMENTS),
                            fieldWithPath("size").type(JsonFieldType.NUMBER)
                                    .description(ApiModelPropertiesGeneric.SIZE),
                            fieldWithPath("content").description(MgmtApiModelProperties.TARGET_LIST)
                                    .type("Array[Object]"))));

}
 
Example #11
Source File: DistributionSetsDocumentationTest.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
@Test
@Description("Handles the GET request for retrieving assigned target filter queries of a single distribution set. Required Permission: "
        + SpPermission.READ_REPOSITORY + " and " + SpPermission.READ_TARGET)
public void getAutoAssignTargetFilterQueries() throws Exception {
    final DistributionSet set = testdataFactory.createUpdatedDistributionSet();
    targetFilterQueryManagement.create(entityFactory.targetFilterQuery().create().name("filter1").query("name==a")
            .autoAssignDistributionSet(set));
    targetFilterQueryManagement.create(entityFactory.targetFilterQuery().create().name("filter2").query("name==b")
            .autoAssignDistributionSet(set));

    mockMvc.perform(get(
            MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/{distributionSetId}/autoAssignTargetFilters",
            set.getId()).accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
            .andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
            .andDo(this.document.document(
                    pathParameters(
                            parameterWithName("distributionSetId").description(ApiModelPropertiesGeneric.ITEM_ID)),
                    responseFields(fieldWithPath("total").description(ApiModelPropertiesGeneric.TOTAL_ELEMENTS),
                            fieldWithPath("size").type(JsonFieldType.NUMBER)
                                    .description(ApiModelPropertiesGeneric.SIZE),
                            fieldWithPath("content").description(MgmtApiModelProperties.TARGET_FILTER_QUERIES_LIST)
                                    .type("Array[Object]"))));

}
 
Example #12
Source File: DistributionSetsDocumentationTest.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
@Test
@Description("Handles the GET request for retrieving installed targets of a single distribution set. Required Permission: "
        + SpPermission.READ_REPOSITORY + " and " + SpPermission.READ_TARGET)
public void getInstalledTargets() throws Exception {
    final DistributionSet set = testdataFactory.createUpdatedDistributionSet();

    final Target target = testdataFactory.createTarget();
    // assign knownTargetId to distribution set
    assignDistributionSet(set.getId(), target.getControllerId());
    // make it in install state
    testdataFactory.sendUpdateActionStatusToTargets(Arrays.asList(target), Status.FINISHED, "some message");

    mockMvc.perform(
            get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/{distributionSetId}/installedTargets",
                    set.getId()).accept(MediaType.APPLICATION_JSON))
            .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
            .andDo(this.document.document(
                    pathParameters(
                            parameterWithName("distributionSetId").description(ApiModelPropertiesGeneric.ITEM_ID)),
                    responseFields(fieldWithPath("total").description(ApiModelPropertiesGeneric.TOTAL_ELEMENTS),
                            fieldWithPath("size").type(JsonFieldType.NUMBER)
                                    .description(ApiModelPropertiesGeneric.SIZE),
                            fieldWithPath("content").description(MgmtApiModelProperties.TARGET_LIST)
                                    .type("Array[Object]"))));
}
 
Example #13
Source File: DistributionSetsDocumentationTest.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
@Test
@Description("Get a paged list of meta data for a distribution set with standard page size."
        + " Required Permission: " + SpPermission.READ_REPOSITORY)
public void getMetadata() throws Exception {
    final int totalMetadata = 4;
    final String knownKeyPrefix = "knownKey";
    final String knownValuePrefix = "knownValue";
    final DistributionSet testDS = testdataFactory.createDistributionSet("one");
    for (int index = 0; index < totalMetadata; index++) {
        distributionSetManagement.createMetaData(testDS.getId(), Lists
                .newArrayList(entityFactory.generateDsMetadata(knownKeyPrefix + index, knownValuePrefix + index)));
    }

    mockMvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/{distributionSetId}/metadata",
            testDS.getId())).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
            .andExpect(content().contentType(MediaTypes.HAL_JSON_UTF8))
            .andDo(this.document.document(
                    pathParameters(
                            parameterWithName("distributionSetId").description(ApiModelPropertiesGeneric.ITEM_ID)),
                    responseFields(fieldWithPath("total").description(ApiModelPropertiesGeneric.TOTAL_ELEMENTS),
                            fieldWithPath("size").type(JsonFieldType.NUMBER)
                                    .description(ApiModelPropertiesGeneric.SIZE),
                            fieldWithPath("content").description(MgmtApiModelProperties.META_DATA),
                            fieldWithPath("content[].key").description(MgmtApiModelProperties.META_DATA_KEY),
                            fieldWithPath("content[].value").description(MgmtApiModelProperties.META_DATA_VALUE))));
}
 
Example #14
Source File: TargetTagResourceDocumentationTest.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
@Test
@Description("Handles the GET request of retrieving all assigned targets by the given")
public void getAssignedTargets() throws Exception {
    final TargetTag tag = createTargetTagEntitiy();
    final Target target = createTargetByGivenNameWithAttributes("Target1", distributionSet);
    targetManagement.assignTag(Arrays.asList(target.getControllerId()), tag.getId());

    arrayPrefix = "content[].";
    this.mockMvc
            .perform(get(MgmtRestConstants.TARGET_TAG_V1_REQUEST_MAPPING
                    + MgmtRestConstants.TARGET_TAG_TARGETS_REQUEST_MAPPING, tag.getId())
                            .contentType(MediaType.APPLICATION_JSON_UTF8))
            .andExpect(status().isOk()).andDo(MockMvcResultPrinter.print())
            .andDo(this.document.document(
                    pathParameters(parameterWithName("targetTagId").description(ApiModelPropertiesGeneric.ITEM_ID)),
                    getResponseFieldTarget(true,
                            fieldWithPath("size").type(JsonFieldType.NUMBER)
                                    .description(ApiModelPropertiesGeneric.SIZE),
                            fieldWithPath("total").description(ApiModelPropertiesGeneric.TOTAL_ELEMENTS),
                            fieldWithPath("content").description(MgmtApiModelProperties.TARGET_LIST))));
}
 
Example #15
Source File: ArticleMvcTests.java    From jakduk-api with MIT License 6 votes vote down vote up
@Test
@WithMockUser
public void getBoardCategories() throws Exception {
    mvc.perform(
            get("/api/board/{board}/categories", article.getBoard().toLowerCase())
                    .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
            .andDo(
                    document("getBoardCategories",
                            pathParameters(
                                    parameterWithName("board").description("게시판 " +
                                            Stream.of(Constants.BOARD_TYPE.values()).map(Enum::name).map(String::toLowerCase).collect(Collectors.toList()))
                            ),
                            responseFields(
                                    fieldWithPath("categories").type(JsonFieldType.ARRAY).description("말머리 목록"),
                                    fieldWithPath("categories.[].code").type(JsonFieldType.STRING).description("말머리 코드"),
                                    fieldWithPath("categories.[].names").type(JsonFieldType.ARRAY).description("말머리 이름 목록(Locale 지원)"),
                                    fieldWithPath("categories.[].names.[].language").type(JsonFieldType.STRING).description("언어"),
                                    fieldWithPath("categories.[].names.[].name").type(JsonFieldType.STRING).description("이름")
                            )
                    ));
}
 
Example #16
Source File: TargetFilterQueriesResourceDocumentationTest.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
private Snippet getResponseFieldTargetFilterQuery(final boolean isArray) {
    final String arrayPrefix = getArrayPrefix(isArray);
    return responseFields(fieldWithPath(arrayPrefix + "id").description(ApiModelPropertiesGeneric.ITEM_ID),
            fieldWithPath(arrayPrefix + "name").description(ApiModelPropertiesGeneric.NAME),
            fieldWithPath(arrayPrefix + "query").description(MgmtApiModelProperties.TARGET_FILTER_QUERY),
            fieldWithPath(arrayPrefix + "autoAssignDistributionSet")
                    .description(MgmtApiModelProperties.TARGET_FILTER_QUERY_AUTO_ASSIGN_DS_ID)
                    .type(JsonFieldType.NUMBER.toString()),
            fieldWithPath(arrayPrefix + "autoAssignActionType")
                    .description(MgmtApiModelProperties.ACTION_FORCE_TYPE).type(JsonFieldType.STRING.toString())
                    .attributes(key("value").value("['forced', 'soft', 'downloadonly']")),
            fieldWithPath(arrayPrefix + "autoAssignWeight")
                    .description(MgmtApiModelProperties.RESULTING_ACTIONS_WEIGHT)
                    .type(JsonFieldType.NUMBER.toString()),
            fieldWithPath(arrayPrefix + "createdAt").description(ApiModelPropertiesGeneric.CREATED_AT),
            fieldWithPath(arrayPrefix + "createdBy").description(ApiModelPropertiesGeneric.CREATED_BY),
            fieldWithPath(arrayPrefix + "lastModifiedAt").description(ApiModelPropertiesGeneric.LAST_MODIFIED_AT),
            fieldWithPath(arrayPrefix + "lastModifiedBy").description(ApiModelPropertiesGeneric.LAST_MODIFIED_BY),
            fieldWithPath(arrayPrefix + "_links.self").ignored(), fieldWithPath(arrayPrefix + "_links.autoAssignDS")
                    .description(MgmtApiModelProperties.TARGET_FILTER_QUERY_LINK_AUTO_ASSIGN_DS));
}
 
Example #17
Source File: Snippets.java    From genie with Apache License 2.0 6 votes vote down vote up
private static FieldDescriptor[] getBaseFieldDescriptors(final ConstraintDescriptions constraintDescriptions) {
    return new FieldDescriptor[]{
        PayloadDocumentation
            .fieldWithPath("id")
            .attributes(getConstraintsForField(constraintDescriptions, "id"))
            .description("The id. If not set the system will set one.")
            .type(JsonFieldType.STRING)
            .optional(),
        PayloadDocumentation
            .fieldWithPath("created")
            .attributes(getConstraintsForField(constraintDescriptions, "created"))
            .description("The UTC time of creation. Set by system. ISO8601 format including milliseconds.")
            .type(JsonFieldType.STRING)
            .optional(),
        PayloadDocumentation
            .fieldWithPath("updated")
            .attributes(getConstraintsForField(constraintDescriptions, "updated"))
            .description("The UTC time of last update. Set by system. ISO8601 format including milliseconds.")
            .type(JsonFieldType.STRING)
            .optional(),
    };
}
 
Example #18
Source File: TargetResourceDocumentationTest.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
@Test
@Description("Handles the GET request of retrieving a specific action on a specific target. Required Permission: READ_TARGET.")
public void getStatusFromAction() throws Exception {
    final Action action = generateActionForTarget(targetId);

    mockMvc.perform(
            get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/{targetId}/" + MgmtRestConstants.TARGET_V1_ACTIONS
                    + "/{actionId}/" + MgmtRestConstants.TARGET_V1_ACTION_STATUS, targetId, action.getId()))
            .andExpect(status().isOk()).andDo(MockMvcResultPrinter.print())
            .andDo(this.document.document(
                    pathParameters(parameterWithName("targetId").description(ApiModelPropertiesGeneric.ITEM_ID),
                            parameterWithName("actionId").description(ApiModelPropertiesGeneric.ITEM_ID)),
                    responseFields(
                            fieldWithPath("size").type(JsonFieldType.NUMBER)
                                    .description(ApiModelPropertiesGeneric.SIZE),
                            fieldWithPath("total").description(ApiModelPropertiesGeneric.TOTAL_ELEMENTS),
                            fieldWithPath("content[]").description(MgmtApiModelProperties.ACTION_STATUS_LIST),
                            fieldWithPath("content[].id").description(ApiModelPropertiesGeneric.ITEM_ID),
                            fieldWithPath("content[].messages")
                                    .description(MgmtApiModelProperties.ACTION_STATUS_MESSAGES).type("String"),
                            fieldWithPath("content[].reportedAt")
                                    .description(MgmtApiModelProperties.ACTION_STATUS_REPORTED_AT).type("String"),
                            fieldWithPath("content[].type").description(MgmtApiModelProperties.ACTION_STATUS_TYPE)
                                    .attributes(key("value").value(
                                            "['finished', 'error', 'warning', 'pending', 'running', 'canceled', 'retrieved', 'canceling']")))));
}
 
Example #19
Source File: TargetResourceDocumentationTest.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
@Test
@Description("Get a paged list of meta data for a target with standard page size." + " Required Permission: "
        + SpPermission.READ_REPOSITORY)
public void getMetadata() throws Exception {
    final int totalMetadata = 4;
    final String knownKeyPrefix = "knownKey";
    final String knownValuePrefix = "knownValue";
    final Target testTarget = testdataFactory.createTarget(targetId);
    for (int index = 0; index < totalMetadata; index++) {
        targetManagement.createMetaData(testTarget.getControllerId(), Lists.newArrayList(
                entityFactory.generateTargetMetadata(knownKeyPrefix + index, knownValuePrefix + index)));
    }

    mockMvc.perform(
            get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/{targetId}/metadata", testTarget.getControllerId()))
            .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
            .andExpect(content().contentType(MediaTypes.HAL_JSON_UTF8))
            .andDo(this.document.document(
                    pathParameters(parameterWithName("targetId").description(ApiModelPropertiesGeneric.ITEM_ID)),
                    responseFields(fieldWithPath("total").description(ApiModelPropertiesGeneric.TOTAL_ELEMENTS),
                            fieldWithPath("size").type(JsonFieldType.NUMBER)
                                    .description(ApiModelPropertiesGeneric.SIZE),
                            fieldWithPath("content").description(MgmtApiModelProperties.META_DATA),
                            fieldWithPath("content[].key").description(MgmtApiModelProperties.META_DATA_KEY),
                            fieldWithPath("content[].value").description(MgmtApiModelProperties.META_DATA_VALUE))));
}
 
Example #20
Source File: AuthMvcTests.java    From jakduk-api with MIT License 5 votes vote down vote up
@Test
@WithMockJakdukUser
public void getMySessionProfileTest() throws Exception {

    SessionUser expectResponse = AuthUtils.getSessionProfile();

    mvc.perform(
            get("/api/auth/user")
                    .header("Cookie", "JSESSIONID=3F0E029648484BEAEF6B5C3578164E99")
                    .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
            .andExpect(content().json(ObjectMapperUtils.writeValueAsString(expectResponse)))
            .andDo(
                    document("get-my-session-user",
                            requestHeaders(
                                    headerWithName("Cookie").description("인증 쿠키. value는 JSESSIONID=키값")
                            ),
                            responseFields(
                                    fieldWithPath("id").type(JsonFieldType.STRING).description("회원 ID"),
                                    fieldWithPath("email").type(JsonFieldType.STRING).description("이메일 주소"),
                                    fieldWithPath("username").type(JsonFieldType.STRING).description("별명"),
                                    fieldWithPath("providerId").type(JsonFieldType.STRING).description("계정 분류 " +
                                            Stream.of(Constants.ACCOUNT_TYPE.values()).map(Enum::name).collect(Collectors.toList())),
                                    fieldWithPath("roles").type(JsonFieldType.ARRAY).description("권한 목록 " +
                                            Stream.of(JakdukAuthority.values()).map(Enum::name).collect(Collectors.toList())),
                                    fieldWithPath("picture").type(JsonFieldType.OBJECT).description("회원 사진"),
                                    fieldWithPath("picture.id").type(JsonFieldType.STRING).description("회원 사진 ID"),
                                    fieldWithPath("picture.smallPictureUrl").type(JsonFieldType.STRING).description("회원 작은 사진 URL"),
                                    fieldWithPath("picture.largePictureUrl").type(JsonFieldType.STRING).description("회원 큰 사진 URL")
                            )
                    ));
}
 
Example #21
Source File: UserMvcTests.java    From jakduk-api with MIT License 5 votes vote down vote up
@Test
@WithMockUser
public void resetPasswordTest() throws Exception {

    Map<String, Object> form = new HashMap<String, Object>() {{
        put("code", "16948f83-1af8-4736-9e12-cf57f03a981c");
        put("password", "1112");
    }};

    UserPasswordFindResponse expectResponse = new UserPasswordFindResponse(jakdukUser.getEmail(),
            JakdukUtils.getMessageSource("user.msg.success.change.password"));

    when(userService.resetPasswordWithToken(anyString(), anyString()))
            .thenReturn(expectResponse);

    ConstraintDescriptions userConstraints = new ConstraintDescriptions(UserPasswordResetForm.class, new ValidatorConstraintResolver(),
            new ResourceBundleConstraintDescriptionResolver(ResourceBundle.getBundle("ValidationMessages")));

    mvc.perform(
            post("/api/user/password/reset")
                    .contentType(MediaType.APPLICATION_JSON)
                    .with(csrf())
                    .content(ObjectMapperUtils.writeValueAsString(form)))
            .andExpect(status().isOk())
            .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
            .andExpect(content().json(ObjectMapperUtils.writeValueAsString(expectResponse)))
            .andDo(
                    document("user-reset-password",
                            requestFields(
                                    fieldWithPath("code").type(JsonFieldType.STRING).description("임시 발행한 토큰 코드. (5분간 유지) " +
                                            userConstraints.descriptionsForProperty("code")),
                                    fieldWithPath("password").type(JsonFieldType.STRING).description("바꿀 비밀번호 " +
                                            userConstraints.descriptionsForProperty("password"))
                            ),
                            responseFields(this.getPasswordFindDescriptor())
                    ));
}
 
Example #22
Source File: ArticleCommentMvcTests.java    From jakduk-api with MIT License 5 votes vote down vote up
private FieldDescriptor[] getWriteArticleCommentDescriptor() {
    return new FieldDescriptor[] {
            fieldWithPath("id").type(JsonFieldType.STRING).description("댓글 ID"),
            subsectionWithPath("article").type(JsonFieldType.OBJECT).description("연동 글"),
            fieldWithPath("article.id").type(JsonFieldType.STRING).description("글 ID"),
            fieldWithPath("article.seq").type(JsonFieldType.NUMBER).description("글 번호"),
            fieldWithPath("article.board").type(JsonFieldType.STRING).description("게시판"),
            subsectionWithPath("writer").type(JsonFieldType.OBJECT).description("글쓴이"),
            fieldWithPath("content").type(JsonFieldType.STRING).description("댓글 내용"),
            subsectionWithPath("usersLiking").type(JsonFieldType.ARRAY).description("좋아요를 한 회원 목록"),
            subsectionWithPath("usersDisliking").type(JsonFieldType.ARRAY).description("싫어요를 한 회원 목록"),
            fieldWithPath("linkedGallery").type(JsonFieldType.BOOLEAN).description("연동 그림 존재 여부"),
            subsectionWithPath("logs").type(JsonFieldType.ARRAY).description("로그 기록 목록")
    };
}
 
Example #23
Source File: ArticleCommentMvcTests.java    From jakduk-api with MIT License 5 votes vote down vote up
private FieldDescriptor[] getWriteArticleCommentFormDescriptor() {
    ConstraintDescriptions userConstraints = new ConstraintDescriptions(WriteArticleComment.class);

    return new FieldDescriptor[] {
            fieldWithPath("content").type(JsonFieldType.STRING).description("댓글 내용. " + userConstraints.descriptionsForProperty("content")),
            subsectionWithPath("galleries").type(JsonFieldType.ARRAY).description("(optional) 그림 목록")
    };
}
 
Example #24
Source File: Snippets.java    From genie with Apache License 2.0 5 votes vote down vote up
private static FieldDescriptor[] getConfigFieldDescriptors(final ConstraintDescriptions constraintDescriptions) {
    return ArrayUtils.addAll(
        getSetupFieldDescriptors(constraintDescriptions),
        PayloadDocumentation
            .fieldWithPath("configs")
            .attributes(getConstraintsForField(constraintDescriptions, "configs"))
            .description("Any configuration files needed for the resource")
            .type(JsonFieldType.ARRAY)
            .optional()
    );
}
 
Example #25
Source File: ArticleCommentMvcTests.java    From jakduk-api with MIT License 5 votes vote down vote up
@Test
@WithMockJakdukUser
public void getArticleDetailCommentsTest() throws Exception {

    GetArticleDetailCommentsResponse expectResponse = new GetArticleDetailCommentsResponse(articleComments, articleComments.size());

    when(articleService.getArticleDetailComments(any(CommonWriter.class), any(Constants.BOARD_TYPE.class), anyInt(), anyString()))
            .thenReturn(expectResponse);

    mvc.perform(
            get("/api/board/{board}/{seq}/comments", Constants.BOARD_TYPE.FOOTBALL.name().toLowerCase(), article.getSeq())
                    .cookie(new Cookie("JSESSIONID", "3F0E029648484BEAEF6B5C3578164E99"))
                    .param("commentId", "59c2ec0fbe3eb62dfca3ed9c")
                    .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
            .andExpect(content().json(ObjectMapperUtils.writeValueAsString(expectResponse)))
            .andDo(
                    document("getArticleDetailComments",
                            requestHeaders(
                                    headerWithName("Cookie").optional().description("(optional) 인증 쿠키. value는 JSESSIONID=키값")
                            ),
                            pathParameters(
                                    parameterWithName("board").description("게시판 " +
                                            Stream.of(Constants.BOARD_TYPE.values()).map(Enum::name).map(String::toLowerCase).collect(Collectors.toList())),
                                    parameterWithName("seq").description("글 번호")
                            ),
                            requestParameters(
                                    parameterWithName("commentId").description("(optional) commentId 이후부터 목록 가져옴")
                            ),
                            responseFields(
                                    this.getArticleCommentsDescriptor(fieldWithPath("count").type(JsonFieldType.NUMBER).description("댓글 수"))
                                    )
                            )
                    );
}
 
Example #26
Source File: Snippets.java    From genie with Apache License 2.0 5 votes vote down vote up
private static FieldDescriptor[] getCriterionFieldDescriptors() {
    return new FieldDescriptor[]{
        PayloadDocumentation
            .fieldWithPath("id")
            .attributes(getConstraintsForField(CRITERION_CONSTRAINTS, "id"))
            .description("The unique identifier a resource needs to have to match this criterion")
            .type(JsonFieldType.STRING)
            .optional(),
        PayloadDocumentation
            .fieldWithPath("name")
            .attributes(getConstraintsForField(CRITERION_CONSTRAINTS, "name"))
            .description("The name a resource needs to have to match this criterion")
            .type(JsonFieldType.STRING)
            .optional(),
        PayloadDocumentation
            .fieldWithPath("version")
            .attributes(getConstraintsForField(CRITERION_CONSTRAINTS, "version"))
            .description("The version a resource needs to have to match this criterion")
            .type(JsonFieldType.STRING)
            .optional(),
        PayloadDocumentation
            .fieldWithPath("status")
            .attributes(getConstraintsForField(CRITERION_CONSTRAINTS, "status"))
            .description("The status a resource needs to have to match this criterion")
            .type(JsonFieldType.STRING)
            .optional(),
        PayloadDocumentation
            .fieldWithPath("tags")
            .attributes(getConstraintsForField(CRITERION_CONSTRAINTS, "tags"))
            .description("The set of tags a resource needs to have to match this criterion")
            .type(JsonFieldType.ARRAY)
            .optional(),
    };
}
 
Example #27
Source File: Snippets.java    From genie with Apache License 2.0 5 votes vote down vote up
private static FieldDescriptor[] getJobExecutionFieldDescriptors() {
    return ArrayUtils.addAll(
        getBaseFieldDescriptors(JOB_EXECUTION_CONSTRAINTS),
        PayloadDocumentation
            .fieldWithPath("hostName")
            .attributes(getConstraintsForField(JOB_EXECUTION_CONSTRAINTS, "hostName"))
            .description("The host name of the Genie node responsible for the job")
            .type(JsonFieldType.STRING),
        PayloadDocumentation
            .fieldWithPath("processId")
            .attributes(getConstraintsForField(JOB_EXECUTION_CONSTRAINTS, "processId"))
            .description("The id of the job client process on the Genie node")
            .type(JsonFieldType.NUMBER)
            .optional(),
        PayloadDocumentation
            .fieldWithPath("checkDelay")
            .attributes(getConstraintsForField(JOB_EXECUTION_CONSTRAINTS, "checkDelay"))
            .description("The amount of time in milliseconds between checks of the job status by Genie")
            .type(JsonFieldType.NUMBER)
            .optional(),
        PayloadDocumentation
            .fieldWithPath("timeout")
            .attributes(getConstraintsForField(JOB_EXECUTION_CONSTRAINTS, "timeout"))
            .description("The date (UTC ISO8601 with millis) when the job will be killed by Genie due to timeout")
            .type(JsonFieldType.STRING)
            .optional(),
        PayloadDocumentation
            .fieldWithPath("exitCode")
            .attributes(getConstraintsForField(JOB_EXECUTION_CONSTRAINTS, "exitCode"))
            .description("The job client process exit code after the job is done")
            .type(JsonFieldType.NUMBER)
            .optional(),
        PayloadDocumentation
            .fieldWithPath("memory")
            .attributes(getConstraintsForField(JOB_EXECUTION_CONSTRAINTS, "memory"))
            .description("The amount of memory (in MB) allocated to the job client")
            .type(JsonFieldType.NUMBER)
            .optional()
    );
}
 
Example #28
Source File: UpdateGreetingDocTest.java    From skeleton-ws-spring-boot with Apache License 2.0 5 votes vote down vote up
/**
 * Generate API documentation for PUT /api/greetings/{id}.
 * 
 * @throws Exception Thrown if documentation generation failure occurs.
 */
@Test
public void documentUpdateGreeting() throws Exception {

    // Generate API Documentation
    final MvcResult result = this.mockMvc.perform(RestDocumentationRequestBuilders.put("/api/greetings/{id}", 1)
            .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON).content(REQUEST_BODY))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andDo(MockMvcRestDocumentation.document("update-greeting",
                    RequestDocumentation.pathParameters(
                            RequestDocumentation.parameterWithName("id").description("The greeting identifier.")),
                    PayloadDocumentation.relaxedRequestFields(PayloadDocumentation.fieldWithPath("text")
                            .description("The text.").type(JsonFieldType.STRING)),
                    PayloadDocumentation.relaxedResponseFields(
                            PayloadDocumentation
                                    .fieldWithPath("id")
                                    .description(
                                            "The identifier. Used to reference specific greetings in API requests.")
                                    .type(JsonFieldType.NUMBER),
                            PayloadDocumentation.fieldWithPath("referenceId")
                                    .description("The supplementary identifier.").type(JsonFieldType.STRING),
                            PayloadDocumentation.fieldWithPath("text").description("The text.")
                                    .type(JsonFieldType.STRING),
                            PayloadDocumentation.fieldWithPath("version").description("The entity version.")
                                    .type(JsonFieldType.NUMBER),
                            PayloadDocumentation.fieldWithPath("createdBy").description("The entity creator.")
                                    .type(JsonFieldType.STRING),
                            PayloadDocumentation.fieldWithPath("createdAt").description("The creation timestamp.")
                                    .type(JsonFieldType.STRING),
                            PayloadDocumentation.fieldWithPath("updatedBy").description("The last modifier.")
                                    .type(JsonFieldType.STRING).optional(),
                            PayloadDocumentation.fieldWithPath("updatedAt")
                                    .description("The last modification timestamp.").type(JsonFieldType.STRING)
                                    .optional())))
            .andReturn();

    // Perform a simple, standard JUnit assertion to satisfy PMD rule
    Assert.assertEquals("failure - expected HTTP status 200", 200, result.getResponse().getStatus());

}
 
Example #29
Source File: UserMvcTests.java    From jakduk-api with MIT License 5 votes vote down vote up
@Test
@WithAnonymousUser
public void findPasswordTest() throws Exception {

    Map<String, Object> form = new HashMap<String, Object>() {{
        put("email", jakdukUser.getEmail());
        put("callbackUrl", "http://dev-wev.jakduk/find/password");
    }};

    UserPasswordFindResponse expectResponse = new UserPasswordFindResponse(form.get("email").toString(),
            JakdukUtils.getMessageSource("user.msg.reset.password.send.email"));

    when(userService.sendEmailToResetPassword(anyString(), anyString()))
            .thenReturn(expectResponse);

    ConstraintDescriptions userConstraints = new ConstraintDescriptions(UserPasswordFindForm.class, new ValidatorConstraintResolver(),
            new ResourceBundleConstraintDescriptionResolver(ResourceBundle.getBundle("ValidationMessages")));

    mvc.perform(
            post("/api/user/password/find")
                    .contentType(MediaType.APPLICATION_JSON)
                    .with(csrf())
                    .content(ObjectMapperUtils.writeValueAsString(form)))
            .andExpect(status().isOk())
            .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
            .andExpect(content().json(ObjectMapperUtils.writeValueAsString(expectResponse)))
            .andDo(
                    document("user-find-password",
                            requestFields(
                                    fieldWithPath("email").type(JsonFieldType.STRING).description("이메일 주소. " +
                                            userConstraints.descriptionsForProperty("email")),
                                    fieldWithPath("callbackUrl").type(JsonFieldType.STRING).description("콜백 받을 URL. " +
                                            userConstraints.descriptionsForProperty("callbackUrl"))
                            ),
                            responseFields(this.getPasswordFindDescriptor())
                    ));
}
 
Example #30
Source File: CreateGreetingDocTest.java    From skeleton-ws-spring-boot with Apache License 2.0 5 votes vote down vote up
/**
 * Generate API documentation for POST /api/greetings.
 * 
 * @throws Exception Thrown if documentation generation failure occurs.
 */
@Test
public void documentCreateGreeting() throws Exception {

    // Generate API Documentation
    final MvcResult result = this.mockMvc
            .perform(RestDocumentationRequestBuilders.post("/api/greetings").contentType(MediaType.APPLICATION_JSON)
                    .accept(MediaType.APPLICATION_JSON).content(REQUEST_BODY))
            .andExpect(MockMvcResultMatchers.status().isCreated())
            .andDo(MockMvcRestDocumentation.document("create-greeting",
                    PayloadDocumentation.relaxedRequestFields(PayloadDocumentation.fieldWithPath("text")
                            .description("The text.").type(JsonFieldType.STRING)),
                    PayloadDocumentation.relaxedResponseFields(
                            PayloadDocumentation
                                    .fieldWithPath("id")
                                    .description(
                                            "The identifier. Used to reference specific greetings in API requests.")
                                    .type(JsonFieldType.NUMBER),
                            PayloadDocumentation.fieldWithPath("referenceId")
                                    .description("The supplementary identifier.").type(JsonFieldType.STRING),
                            PayloadDocumentation.fieldWithPath("text").description("The text.")
                                    .type(JsonFieldType.STRING),
                            PayloadDocumentation.fieldWithPath("version").description("The entity version.")
                                    .type(JsonFieldType.NUMBER),
                            PayloadDocumentation.fieldWithPath("createdBy").description("The entity creator.")
                                    .type(JsonFieldType.STRING),
                            PayloadDocumentation.fieldWithPath("createdAt").description("The creation timestamp.")
                                    .type(JsonFieldType.STRING),
                            PayloadDocumentation.fieldWithPath("updatedBy").description("The last modifier.")
                                    .type(JsonFieldType.STRING).optional(),
                            PayloadDocumentation.fieldWithPath("updatedAt")
                                    .description("The last modification timestamp.").type(JsonFieldType.STRING)
                                    .optional())))
            .andReturn();

    // Perform a simple, standard JUnit assertion to satisfy PMD rule
    Assert.assertEquals("failure - expected HTTP status 201", 201, result.getResponse().getStatus());

}