org.springframework.restdocs.operation.Operation Java Examples

The following examples show how to use org.springframework.restdocs.operation.Operation. 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: WireMockSnippet.java    From spring-cloud-contract with Apache License 2.0 6 votes vote down vote up
private MappingBuilder requestBuilder(Operation operation) {
	switch (operation.getRequest().getMethod()) {
	case DELETE:
		return delete(requestPattern(operation));
	case POST:
		return bodyPattern(post(requestPattern(operation)),
				operation.getRequest().getContentAsString());
	case PUT:
		return bodyPattern(put(requestPattern(operation)),
				operation.getRequest().getContentAsString());
	case PATCH:
		return bodyPattern(patch(requestPattern(operation)),
				operation.getRequest().getContentAsString());
	case GET:
		return get(requestPattern(operation));
	case HEAD:
		return head(requestPattern(operation));
	case OPTIONS:
		return options(requestPattern(operation));
	case TRACE:
		return trace(requestPattern(operation));
	default:
		throw new UnsupportedOperationException(
				"Unsupported method type: " + operation.getRequest().getMethod());
	}
}
 
Example #2
Source File: WireMockSnippet.java    From spring-cloud-contract with Apache License 2.0 6 votes vote down vote up
private MappingBuilder requestHeaders(MappingBuilder request, Operation operation) {
	org.springframework.http.HttpHeaders headers = operation.getRequest()
			.getHeaders();
	// TODO: whitelist headers
	for (String name : headers.keySet()) {
		if (!this.headerBlackList.contains(name.toLowerCase())) {
			if ("content-type".equalsIgnoreCase(name) && this.contentType != null) {
				continue;
			}
			request = request.withHeader(name, equalTo(headers.getFirst(name)));
		}
	}
	if (this.contentType != null) {
		request = request.withHeader("Content-Type",
				matching(Pattern.quote(this.contentType.toString()) + ".*"));
	}
	return request;
}
 
Example #3
Source File: RequestHandler.java    From restdocs-raml with MIT License 6 votes vote down vote up
public Map<String, Object> generateModel(Operation operation, RamlResourceSnippetParameters parameters) {
    final OperationRequest request = operation.getRequest();

    if (!StringUtils.isEmpty(request.getContentAsString())) {
        Map<String, Object> model = new HashMap<>();
        model.put("requestBodyFileName", getRequestFileName(operation.getName()));
        model.put("requestBodyPresent", true);
        model.put("contentTypeRequest", getContentTypeOrDefault(request));
        if (!parameters.getRequestFields().isEmpty()) {
            validateRequestFieldsAndInferTypeInformation(operation, parameters);
            model.put("requestFieldsPresent", true);
            if (shouldGenerateRequestSchemaFile(operation, parameters)) {
                model.put("requestSchemaFileName", getRequestSchemaFileName(operation.getName()));
            }
        }
        return model;
    }
    return emptyMap();
}
 
Example #4
Source File: WireMockSnippet.java    From spring-cloud-contract with Apache License 2.0 6 votes vote down vote up
private void extractMatchers(Operation operation) {
	this.stubMapping = (StubMapping) operation.getAttributes()
			.get("contract.stubMapping");
	if (this.stubMapping != null) {
		return;
	}
	@SuppressWarnings("unchecked")
	Set<String> jsonPaths = (Set<String>) operation.getAttributes()
			.get("contract.jsonPaths");
	this.jsonPaths = jsonPaths;
	this.contentType = (MediaType) operation.getAttributes()
			.get("contract.contentType");
	if (this.contentType == null) {
		this.hasJsonBodyRequestToMatch = hasJsonContentType(operation);
		this.hasXmlBodyRequestToMatch = hasXmlContentType(operation);
	}
}
 
Example #5
Source File: AbstractParameterSnippet.java    From spring-auto-restdocs with Apache License 2.0 6 votes vote down vote up
@Override
protected FieldDescriptors createFieldDescriptors(Operation operation,
        HandlerMethod handlerMethod) {
    JavadocReader javadocReader = getJavadocReader(operation);
    SnippetTranslationResolver translationResolver = getTranslationResolver(operation);
    ConstraintReader constraintReader = getConstraintReader(operation);

    FieldDescriptors fieldDescriptors = new FieldDescriptors();
    for (MethodParameter param : handlerMethod.getMethodParameters()) {
        A annot = getAnnotation(param);
        if (annot != null) {
            addFieldDescriptor(handlerMethod, javadocReader, constraintReader, fieldDescriptors,
                    param, annot);
        }
    }

    if (shouldFailOnUndocumentedParams()) {
        assertAllDocumented(fieldDescriptors.values(), translationResolver.translate(getHeaderKey(operation)).toLowerCase());
    }

    return fieldDescriptors;
}
 
Example #6
Source File: DescriptionSnippet.java    From spring-auto-restdocs with Apache License 2.0 6 votes vote down vote up
@Override
protected Map<String, Object> createModel(Operation operation) {
    HandlerMethod handlerMethod = getHandlerMethod(operation);
    Map<String, Object> model = defaultModel();
    if (handlerMethod == null) {
        return model;
    }

    JavadocReader javadocReader = getJavadocReader(operation);
    SnippetTranslationResolver translationResolver = getTranslationResolver(operation);
    String methodComment = resolveComment(handlerMethod, javadocReader);
    String seeTagComment = resolveSeeTag(handlerMethod, javadocReader, translationResolver);
    String deprecatedComment = resolveDeprecated(handlerMethod, javadocReader, translationResolver);
    String completeComment = join("<p>", deprecatedComment, methodComment, seeTagComment);
    String description = convertFromJavadoc(completeComment,
            determineTemplateFormatting(operation));

    model.put("description", description);
    return model;
}
 
Example #7
Source File: OperationBuilder.java    From restdocs-wiremock with Apache License 2.0 6 votes vote down vote up
public Operation build() {
	if (this.attributes.get(TemplateEngine.class.getName()) == null) {
		Map<String, Object> templateContext = new HashMap<>();
		templateContext.put("tableCellContent",
				new AsciidoctorTableCellContentLambda());
		this.attributes.put(TemplateEngine.class.getName(),
				new MustacheTemplateEngine(
						new StandardTemplateResourceResolver(this.templateFormat),
						Mustache.compiler().escapeHTML(false), templateContext));
	}
	RestDocumentationContext context = createContext();
	this.attributes.put(RestDocumentationContext.class.getName(), context);
	this.attributes.put(WriterResolver.class.getName(),
			new StandardWriterResolver(
					new RestDocumentationContextPlaceholderResolverFactory(), "UTF-8",
					this.templateFormat));
	return new StandardOperation(this.name,
			(this.requestBuilder == null
					? new OperationRequestBuilder("http://localhost/").buildRequest()
					: this.requestBuilder.buildRequest()),
			this.responseBuilder.buildResponse(), this.attributes);
}
 
Example #8
Source File: AbstractJacksonFieldSnippet.java    From spring-auto-restdocs with Apache License 2.0 5 votes vote down vote up
protected FieldDescriptors createFieldDescriptors(Operation operation,
        HandlerMethod handlerMethod) {
    ObjectMapper objectMapper = getObjectMapper(operation);

    JavadocReader javadocReader = getJavadocReader(operation);
    ConstraintReader constraintReader = getConstraintReader(operation);
    SnippetTranslationResolver translationResolver = getTranslationResolver(operation);
    TypeMapping typeMapping = getTypeMapping(operation);
    JsonProperty.Access skipAcessor = getSkipAcessor();

    Type type = getType(handlerMethod);
    if (type == null) {
        return new FieldDescriptors();
    }

    try {
        FieldDocumentationGenerator generator = new FieldDocumentationGenerator(
                objectMapper.writer(), objectMapper.getDeserializationConfig(), javadocReader,
                constraintReader, typeMapping, translationResolver, skipAcessor);
        FieldDescriptors fieldDescriptors = generator.generateDocumentation(type, objectMapper.getTypeFactory());

        if (shouldFailOnUndocumentedFields()) {
            assertAllDocumented(fieldDescriptors.values(),
                    translationResolver.translate(getHeaderKey(operation)).toLowerCase());
        }
        return fieldDescriptors;
    } catch (JsonMappingException e) {
        throw new JacksonFieldProcessingException("Error while parsing fields", e);
    }
}
 
Example #9
Source File: HeaderHandler.java    From restdocs-raml with MIT License 5 votes vote down vote up
@Override
public Map<String, Object> generateModel(Operation operation, RamlResourceSnippetParameters parameters) {
    List<HeaderDescriptor> headers = descriptorSupplier.apply(parameters);
    if (!headers.isEmpty()) {
        validatorSupplier.apply(headers).validateHeaders(operation);
        Map<String, Object> model = new HashMap<>();
        model.put(modelNamePrefix + "HeadersPresent", true);
        model.put(modelNamePrefix + "Headers", mapDescriptorsToModel(headers, headersSupplier.apply(operation)));
        return model;
    }
    return emptyMap();
}
 
Example #10
Source File: TraitExtractorChain.java    From restdocs-raml with MIT License 5 votes vote down vote up
@Override
public Map<String, Object> generateModel(Operation operation, RamlResourceSnippetParameters parameters) {
    List<String> traitsToApply = traitExtractors.stream()
            .flatMap(t -> t.extractTraits(operation, parameters).stream())
            .collect(toList());

    if (!traitsToApply.isEmpty()) {
        return singletonMap("traits", "[ " + String.join(",", traitsToApply.stream().map(s -> String.format("\"%s\"", s)).collect(toList())) + " ]");
    }

    return emptyMap();
}
 
Example #11
Source File: RamlResourceSnippet.java    From restdocs-raml with MIT License 5 votes vote down vote up
private String getUriPath(Operation operation) {
    String urlTemplate = (String) operation.getAttributes().get(ATTRIBUTE_NAME_URL_TEMPLATE);
    if (StringUtils.isEmpty(urlTemplate)) {
        throw new MissingUrlTemplateException();
    }
    return UriComponentsBuilder.fromUriString(urlTemplate).build().getPath();
}
 
Example #12
Source File: AuthorizationSnippet.java    From spring-auto-restdocs with Apache License 2.0 5 votes vote down vote up
protected String authorizationDescription(Operation operation) {
    String requestAuthorization = getAuthorization(operation);
    if (requestAuthorization != null) {
        return requestAuthorization;
    } else {
        return defaultAuthorization;
    }
}
 
Example #13
Source File: PrivateResourceTraitExtractor.java    From restdocs-raml with MIT License 5 votes vote down vote up
@Override
public List<String> extractTraits(Operation operation, RamlResourceSnippetParameters parameters) {
    if (parameters.isPrivateResource()) {
        return singletonList("private");
    }

    return emptyList();
}
 
Example #14
Source File: RequestParameterHandler.java    From restdocs-raml with MIT License 5 votes vote down vote up
@Override
public Map<String, Object> generateModel(Operation operation, RamlResourceSnippetParameters parameters) {
    List<ParameterDescriptorWithRamlType> requestParameters = parameters.getRequestParameters();
    if (!requestParameters.isEmpty()) {
        new RequestParameterSnippetWrapper(requestParameters).validateRequestParameters(operation);
        Map<String, Object> model = new HashMap<>();
        model.put("requestParametersPresent", true);
        model.put("requestParameters", mapParameterDescriptorsToModel(requestParameters));
        return model;
    }
    return emptyMap();
}
 
Example #15
Source File: ResponseFieldSnippet.java    From initializr with Apache License 2.0 5 votes vote down vote up
@Override
protected Map<String, Object> createModel(Operation operation) {
	try {
		Object object = this.objectMapper.readValue(operation.getResponse().getContentAsString(), Object.class);
		Object field = this.fieldProcessor.extract(JsonFieldPath.compile(this.path), object);
		if (field instanceof List && this.index != null) {
			field = ((List<?>) field).get(this.index);
		}
		return Collections.singletonMap("value", this.objectMapper.writeValueAsString(field));
	}
	catch (Exception ex) {
		throw new IllegalStateException(ex);
	}
}
 
Example #16
Source File: RamlResourceSnippet.java    From restdocs-raml with MIT License 5 votes vote down vote up
private void storeFile(Operation operation, String filename, String content) {
    File output = getOutputFile(operation, filename);
    try (Writer writer = new OutputStreamWriter(Files.newOutputStream(output.toPath()))) {
        writer.append(content);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example #17
Source File: SectionSnippet.java    From spring-auto-restdocs with Apache License 2.0 5 votes vote down vote up
private Map<String, Object> defaultModel(Operation operation) {
    // resolve path
    String path = propertyPlaceholderHelper.replacePlaceholders(operation.getName(),
            placeholderResolverFactory.create(getDocumentationContext(operation)));

    Map<String, Object> model = new HashMap<>();
    model.put("title", createTitle(operation.getName()));
    model.put("link", delimit(path));
    model.put("path", path);
    model.put("sections", emptyList());
    return model;
}
 
Example #18
Source File: PathParameterHandler.java    From restdocs-raml with MIT License 5 votes vote down vote up
@Override
public Map<String, Object> generateModel(Operation operation, RamlResourceSnippetParameters parameters) {
    List<ParameterDescriptorWithRamlType> pathParameters = parameters.getPathParameters();
    if (!pathParameters.isEmpty()) {
        new PathParametersSnippetWrapper(pathParameters).validatePathParameters(operation);
        Map<String, Object> model = new HashMap<>();
        model.put("pathParametersPresent", true);
        model.put("pathParameters", mapParameterDescriptorsToModel(pathParameters));
        return model;
    }
    return emptyMap();
}
 
Example #19
Source File: OperationAttributeHelper.java    From spring-auto-restdocs with Apache License 2.0 5 votes vote down vote up
public static TemplateFormat getTemplateFormat(Operation operation) {
    StandardWriterResolver writerResolver = (StandardWriterResolver) operation.getAttributes()
            .get(WriterResolver.class.getName());
    Field field = findField(StandardWriterResolver.class, "templateFormat");
    makeAccessible(field);
    return (TemplateFormat) getField(field, writerResolver);
}
 
Example #20
Source File: ResponseFieldSnippet.java    From initializr with Apache License 2.0 5 votes vote down vote up
@Override
public void document(Operation operation) throws IOException {
	RestDocumentationContext context = (RestDocumentationContext) operation.getAttributes()
			.get(RestDocumentationContext.class.getName());
	WriterResolver writerResolver = (WriterResolver) operation.getAttributes().get(WriterResolver.class.getName());
	try (Writer writer = writerResolver.resolve(operation.getName() + "/" + getSnippetName(), this.file, context)) {
		Map<String, Object> model = createModel(operation);
		model.putAll(getAttributes());
		TemplateEngine templateEngine = (TemplateEngine) operation.getAttributes()
				.get(TemplateEngine.class.getName());
		writer.append(templateEngine.compileTemplate(getSnippetName()).render(model));
	}
}
 
Example #21
Source File: JwtScopeHandler.java    From restdocs-raml with MIT License 5 votes vote down vote up
private Map<String, Object> handleScopes(Operation operation) {
    Map<String, Object> model = new HashMap<>();
    if (operation.getRequest().getHeaders().getFirst("Authorization") != null) {
        String jwt = operation.getRequest().getHeaders().getFirst("Authorization")
                .replace("Bearer ", "");
        List<String> scopes = jwt2scopes(jwt).stream().map(s -> "\"" + s + "\"").collect(toList());
        if (!scopes.isEmpty()) {
            String renderedScopes = "[" + String.join(", ", scopes) + "]";
            model.put("scopes", renderedScopes);
        }
    }
    return model;
}
 
Example #22
Source File: AbstractParameterSnippet.java    From spring-auto-restdocs with Apache License 2.0 5 votes vote down vote up
@Override
public boolean hasContent(Operation operation) {
    for (MethodParameter param : getHandlerMethod(operation).getMethodParameters()) {
        A annot = getAnnotation(param);
        if (annot != null) {
            return true;
        }
    }
    return false;
}
 
Example #23
Source File: SectionSnippet.java    From spring-auto-restdocs with Apache License 2.0 5 votes vote down vote up
private SectionSupport getSectionSnippet(Operation operation, String snippetName) {
    return getDefaultSnippets(operation).stream()
            .filter(snippet -> snippet instanceof SectionSupport)
            .map(snippet -> (SectionSupport) snippet)
            .filter(snippet -> snippetName.equals(snippet.getFileName()))
            .findFirst()
            .orElseGet(() -> SnippetRegistry.getClassicSnippet(snippetName));
}
 
Example #24
Source File: WireMockSnippetTests.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
private Operation operation(String name, OperationRequest request,
		OperationResponse response, RestDocumentationContext context) {
	return new Operation() {

		Map<String, Object> map = new HashMap<>();

		@Override
		public Map<String, Object> getAttributes() {
			this.map.put(RestDocumentationContext.class.getName(), context);
			return this.map;
		}

		@Override
		public String getName() {
			return name;
		}

		@Override
		public OperationRequest getRequest() {
			return request;
		}

		@Override
		public OperationResponse getResponse() {
			return response;
		}
	};
}
 
Example #25
Source File: ContractDslSnippet.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
private void storeDslContract(Operation operation, String content)
		throws IOException {
	RestDocumentationContext context = (RestDocumentationContext) operation
			.getAttributes().get(RestDocumentationContext.class.getName());
	RestDocumentationContextPlaceholderResolver resolver = new RestDocumentationContextPlaceholderResolver(
			context);
	String resolvedName = replacePlaceholders(resolver, operation.getName());
	File output = new File(context.getOutputDirectory(),
			CONTRACTS_FOLDER + "/" + resolvedName + ".groovy");
	output.getParentFile().mkdirs();
	try (Writer writer = new OutputStreamWriter(
			Files.newOutputStream(output.toPath()))) {
		writer.append(content);
	}
}
 
Example #26
Source File: RamlResourceSnippet.java    From restdocs-raml with MIT License 5 votes vote down vote up
@Override
protected Map<String, Object> createModel(Operation operation) {
    Map<String, Object> model = new HashMap<>();
    model.put("method", operation.getRequest().getMethod().name().toLowerCase());
    model.put("description", parameters.getDescription() == null ? operation.getName() : parameters.getDescription());
    model.put("resource", getUriPath(operation));
    model.put("status", operation.getResponse().getStatus().value());

    model.putAll(handlerChain.process(operation, parameters));

    return model;
}
 
Example #27
Source File: StandardTableSnippet.java    From spring-auto-restdocs with Apache License 2.0 5 votes vote down vote up
@Override
protected Map<String, Object> createModel(Operation operation) {
    HandlerMethod handlerMethod = getHandlerMethod(operation);
    SnippetTranslationResolver translationResolver = getTranslationResolver(operation);
    Map<String, Object> model = defaultModel(translationResolver);
    if (handlerMethod == null) {
        return model;
    }

    FieldDescriptors fieldDescriptors =
            createFieldDescriptors(operation, handlerMethod);
    TemplateFormatting templateFormatting = determineTemplateFormatting(operation);
    return createModel(handlerMethod, model, fieldDescriptors, templateFormatting, translationResolver);
}
 
Example #28
Source File: ContractDslSnippet.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
private void insertResponseModel(Operation operation, Map<String, Object> model) {
	OperationResponse response = operation.getResponse();
	model.put("response_status", response.getStatus().value());
	model.put("response_body_present", response.getContent().length > 0);
	model.put("response_body", response.getContentAsString());
	Map<String, String> headers = new HashMap<>(
			response.getHeaders().toSingleValueMap());
	filterHeaders(headers);
	model.put("response_headers_present", !headers.isEmpty());
	model.put("response_headers", headers.entrySet());
}
 
Example #29
Source File: ContractDslSnippet.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
@Override
public void document(Operation operation) throws IOException {
	TemplateEngine templateEngine = (TemplateEngine) operation.getAttributes()
			.get(TemplateEngine.class.getName());
	String renderedContract = templateEngine
			.compileTemplate("default-dsl-contract-only")
			.render(createModelForContract(operation));
	this.model.put("contract", renderedContract);
	storeDslContract(operation, renderedContract);
	super.document(operation);
}
 
Example #30
Source File: WireMockSnippet.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
private HttpHeaders responseHeaders(Operation operation) {
	org.springframework.http.HttpHeaders headers = operation.getResponse()
			.getHeaders();
	HttpHeaders result = new HttpHeaders();
	for (String name : headers.keySet()) {
		if (!this.headerBlackList.contains(name.toLowerCase())) {
			result = result.plus(new HttpHeader(name, headers.get(name)));
		}
	}
	return result;
}