springfox.documentation.spi.service.contexts.OperationContext Java Examples

The following examples show how to use springfox.documentation.spi.service.contexts.OperationContext. 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: ApiMethodReader.java    From swagger-more with Apache License 2.0 6 votes vote down vote up
private void readReturnDescription(OperationContext context, ApiMethod apiMethod) {
    ResolvedType returnType = context.alternateFor(context.getReturnType());
    String message = StringUtils.isEmpty(apiMethod.returnDescription()) ? "成功" : apiMethod.returnDescription();
    ModelReference modelRef = null;
    if (!isVoid(returnType)) {
        ModelContext modelContext = ModelContext.returnValue(
                context.getGroupName(), returnType,
                context.getDocumentationType(),
                context.getAlternateTypeProvider(),
                context.getGenericsNamingStrategy(),
                context.getIgnorableParameterTypes());
        modelRef = modelRefFactory(modelContext, typeNameExtractor).apply(returnType);
    }
    ResponseMessage built = new ResponseMessageBuilder()
            .code(HttpStatus.OK.value())
            .message(message)
            .responseModel(modelRef)
            .build();
    context.operationBuilder().responseMessages(newHashSet(built));
}
 
Example #2
Source File: ApiMethodReader.java    From swagger-more with Apache License 2.0 6 votes vote down vote up
@Override
public void apply(OperationContext context) {
    Optional<ApiMethod> optional = context.findAnnotation(ApiMethod.class);
    if (optional.isPresent()) {
        OperationBuilder builder = context.operationBuilder();
        ApiMethod apiMethod = optional.get();
        if (StringUtils.hasText(apiMethod.notes())) {
            builder.notes(resolver.resolve(apiMethod.notes()));
        }
        if (StringUtils.hasText(apiMethod.value())) {
            builder.summary(resolver.resolve(apiMethod.value()));
        }
        builder.deprecated(String.valueOf(apiMethod.deprecated()));
        builder.hidden(apiMethod.hidden());
        builder.uniqueId(context.getGroupName() + context.getName());
        readTags(context);
        readReturnDescription(context, apiMethod);
    }
}
 
Example #3
Source File: PageableParameterBuilderPluginTest.java    From jhipster with Apache License 2.0 6 votes vote down vote up
@BeforeEach
public void setup() throws Exception {
    MockitoAnnotations.initMocks(this);
    Method method = this.getClass().getMethod("test", new Class<?>[]{Pageable.class, Integer.class});
    resolver = new TypeResolver();
    RequestHandler handler = new WebMvcRequestHandler(new HandlerMethodResolver(resolver), null, new
        HandlerMethod(this, method));
    DocumentationContext docContext = mock(DocumentationContext.class);
    RequestMappingContext reqContext = new RequestMappingContext(docContext, handler);
    builder = spy(new OperationBuilder(null));
    context = new OperationContext(builder, RequestMethod.GET, reqContext, 0);
    List<TypeNameProviderPlugin> plugins = new LinkedList<>();
    extractor = new TypeNameExtractor(resolver, SimplePluginRegistry.create(plugins), new
        JacksonEnumTypeDeterminer());
    plugin = new PageableParameterBuilderPlugin(extractor, resolver);
}
 
Example #4
Source File: PageableParameterBuilderPlugin.java    From jhipster with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public void apply(OperationContext context) {
    List<Parameter> parameters = newArrayList();
    for (ResolvedMethodParameter methodParameter : context.getParameters()) {
        ResolvedType resolvedType = methodParameter.getParameterType();

        if (pageableType.equals(resolvedType)) {
            ParameterContext parameterContext = new ParameterContext(methodParameter,
                new ParameterBuilder(),
                context.getDocumentationContext(),
                context.getGenericsNamingStrategy(),
                context);

            parameters.add(createPageParameter(parameterContext));
            parameters.add(createSizeParameter(parameterContext));
            parameters.add(createSortParameter(parameterContext));

            context.operationBuilder().parameters(parameters);
        }
    }
}
 
Example #5
Source File: SuccessPlugin.java    From BlogManagePlatform with Apache License 2.0 6 votes vote down vote up
@Override
public void apply(OperationContext context) {
	//TODO:这样做屏蔽了@ResponseHeader的功能,因为没有了该注解。
	//由于本项目header为统一配置,故未实现替代功能。有必要的话需要提供一个替代实现。
	if (context.findAnnotation(ApiResponses.class).isPresent()) {
		return;
	}
	Optional<Success> annotation = context.findAnnotation(Success.class);
	if (!annotation.isPresent()) {
		context.operationBuilder().responseMessages(okResponses);
		return;
	}
	ResponseMessageBuilder messageBuilder = new ResponseMessageBuilder();
	messageBuilder.code(HttpStatus.OK.value());
	messageBuilder.message(okMessage);
	ModelReference model = resolveModel(context, annotation.get());
	messageBuilder.responseModel(model);
	context.operationBuilder().responseMessages(Set.of(messageBuilder.build()));
}
 
Example #6
Source File: DefaultEndPointPlugin.java    From BlogManagePlatform with Apache License 2.0 6 votes vote down vote up
@Override
public void apply(OperationContext context) {
	if (context.findAnnotation(ApiOperation.class).isPresent()) {
		return;
	}
	EndPointInfo info = resolveNameAttribute(context);
	if (info == null) {
		log.warn(StrUtil.concat(context.requestMappingPattern(), "的信息未配置"));
		return;
	}
	OperationBuilder builder = context.operationBuilder();
	builder.summary(descriptions.resolve(info.name));
	builder.tags(Set.of(info.controllerName));
	ReflectUtil.set(OperationBuilder.class, "consumes", builder, Set.of(info.consumes));
	ReflectUtil.set(OperationBuilder.class, "produces", builder, Set.of(info.produces));
}
 
Example #7
Source File: SecurityRolesReader.java    From yes-cart with Apache License 2.0 5 votes vote down vote up
@Override
public void apply(OperationContext context) {
    try {
        Optional<ApiOperation> methodAnnotation = context.findAnnotation(ApiOperation.class);

        if (!methodAnnotation.isPresent()) {
            return;
        }

        final List<String> roles = new ArrayList<>();
        Optional<Secured> securedAnnotation = context.findAnnotation(Secured.class);
        if (securedAnnotation.isPresent()) {
            roles.addAll(Arrays.asList(securedAnnotation.get().value()));
        }
        Optional<PreAuthorize> preAnnotation = context.findAnnotation(PreAuthorize.class);
        if (preAnnotation.isPresent()) {
            roles.add(preAnnotation.get().value());
        }

        if (!roles.isEmpty()) {
            final StringBuilder apiRoleAccessNoteText = new StringBuilder(SECURE);
            for (final String role : roles) {
                apiRoleAccessNoteText.append("\n * ").append(role);
            }
            // add the note text to the Swagger UI
            context.operationBuilder().notes(descriptions.resolve(apiRoleAccessNoteText.toString()));
        }

    } catch (Exception e) {
        LOG.error("Error when creating swagger documentation for security roles: " + e.getMessage(), e);
    }
}
 
Example #8
Source File: PageableParameterBuilderPlugin.java    From albedo with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void apply(OperationContext context) {
	for (ResolvedMethodParameter methodParameter : context.getParameters()) {
		ResolvedType resolvedType = methodParameter.getParameterType();
		if (pageableType.equals(resolvedType)) {
			ParameterContext parameterContext = new ParameterContext(methodParameter,
				new ParameterBuilder(),
				context.getDocumentationContext(),
				context.getGenericsNamingStrategy(),
				context);

			ModelReference intModel = createModelRefFactory(parameterContext).apply(resolver.resolve(Integer.TYPE));
			ModelReference stringModel = createModelRefFactory(parameterContext).apply(resolver.resolve(List.class, String.class));

			List<Parameter> parameters = Lists.newArrayList(
				new ParameterBuilder()
					.parameterType("query").name("current").modelRef(intModel)
					.description("Page number of the requested page")
					.build(),
				new ParameterBuilder()
					.parameterType("query").name("size").modelRef(intModel)
					.description("Size of a page")
					.build(),
				new ParameterBuilder()
					.parameterType("query").name("descs").modelRef(stringModel).allowMultiple(true)
					.description("Sorting criteria in the format: property(,asc|desc). Default sort order is ascending. Multiple sort criteria are supported.")
					.build(),
				new ParameterBuilder()
					.parameterType("query").name("ascs").modelRef(stringModel).allowMultiple(true)
					.description("Sorting criteria in the format: property(,asc|desc). Default sort order is ascending. Multiple sort criteria are supported.")
					.build(),
				new ParameterBuilder()
					.parameterType("query").name("queryConditionJson").modelRef(stringModel).allowMultiple(true)
					.description("search json [{\"fieldName\":\"name\",\"attrType\":\"String\",\"fieldNode\":\"\",\"operate\":\"like\",\"weight\":0,\"value\":\"g\"},{\"fieldName\":\"status\",\"attrType\":\"Integer\",\"fieldNode\":\"\",\"operate\":\"in\",\"weight\":0,\"value\":\"-1\"}]}")
					.build());

			context.operationBuilder().parameters(parameters);
		}
	}
}
 
Example #9
Source File: SwaggerUtil.java    From BlogManagePlatform with Apache License 2.0 5 votes vote down vote up
/**
 * 从OperationContext转换出ModelContext
 * @author Frodez
 * @date 2019-12-15
 */
public static ModelContext resolveModelContext(OperationContext context, Type type) {
	String group = context.getGroupName();
	DocumentationType documentation = context.getDocumentationType();
	AlternateTypeProvider provider = context.getAlternateTypeProvider();
	GenericTypeNamingStrategy strategy = context.getGenericsNamingStrategy();
	@SuppressWarnings("rawtypes") ImmutableSet<Class> types = context.getIgnorableParameterTypes();
	return returnValue(group, type, documentation, provider, strategy, types);
}
 
Example #10
Source File: DefaultEndPointPlugin.java    From BlogManagePlatform with Apache License 2.0 5 votes vote down vote up
private String resolveApiName(OperationContext context) {
	Api api = context.findControllerAnnotation(Api.class).orNull();
	if (api != null) {
		return api.tags()[0];
	}
	GetMapping getMapping = context.findControllerAnnotation(GetMapping.class).orNull();
	if (getMapping != null) {
		return getMapping.name();
	}
	PostMapping postMapping = context.findControllerAnnotation(PostMapping.class).orNull();
	if (postMapping != null) {
		return postMapping.name();
	}
	DeleteMapping deleteMapping = context.findControllerAnnotation(DeleteMapping.class).orNull();
	if (deleteMapping != null) {
		return deleteMapping.name();
	}
	PutMapping putMapping = context.findControllerAnnotation(PutMapping.class).orNull();
	if (putMapping != null) {
		return putMapping.name();
	}
	RequestMapping requestMapping = context.findControllerAnnotation(RequestMapping.class).orNull();
	if (requestMapping != null) {
		return requestMapping.name();
	}
	return "";
}
 
Example #11
Source File: DefaultTokenPlugin.java    From BlogManagePlatform with Apache License 2.0 5 votes vote down vote up
@Override
public void apply(OperationContext context) {
	String path = StrUtil.concat(PropertyUtil.get(PropertyKey.Web.BASE_PATH), context.requestMappingPattern());
	if (Matcher.needVerify(path)) {
		context.operationBuilder().parameters(Arrays.asList(addTokenHeader()));
	}
}
 
Example #12
Source File: JavadocBuilderPlugin.java    From springfox-javadoc with Apache License 2.0 5 votes vote down vote up
@Override
public void apply(OperationContext context) {

    String notes = context.requestMappingPattern() + PERIOD + context.httpMethod().toString() + ".notes";
    if (StringUtils.hasText(notes) && StringUtils.hasText(environment.getProperty(notes))) {
        context.operationBuilder().notes("<b>" + context.getName() + "</b><br/>" + environment.getProperty(notes));
    }
    String returnDescription = context.requestMappingPattern() + PERIOD + context.httpMethod().toString()
      + ".return";
    if (StringUtils.hasText(returnDescription) && StringUtils.hasText(environment.getProperty(returnDescription))) {
        context.operationBuilder().summary("returns " + environment.getProperty(returnDescription));
    }
    String throwsDescription = context.requestMappingPattern() + PERIOD + context.httpMethod().toString()
      + ".throws.";
    int i = 0;
    Set<ResponseMessage> responseMessages = new HashSet<ResponseMessage>();
    while (StringUtils.hasText(throwsDescription + i)
      && StringUtils.hasText(environment.getProperty(throwsDescription + i))) {
        String[] throwsValues = StringUtils.split(environment.getProperty(throwsDescription + i), "-");
        if (throwsValues.length == 2) {
            // TODO[MN]: proper mapping once
            // https://github.com/springfox/springfox/issues/521 is solved
            String thrownExceptionName = throwsValues[0];
            String throwComment = throwsValues[1];
            ModelReference model = new ModelRef(thrownExceptionName);
            ResponseMessage message = new ResponseMessageBuilder().code(500).message(throwComment)
              .responseModel(model).build();
            responseMessages.add(message);
        }
        i++;
    }
    context.operationBuilder().responseMessages(responseMessages);

}
 
Example #13
Source File: OperationHttpMethodReader.java    From stategen with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void apply(OperationContext context) {
    HandlerMethod handlerMethod = context.getHandlerMethod();

    ApiOperation apiOperationAnnotation = handlerMethod.getMethodAnnotation(ApiOperation.class);
    HttpMethod httpMethod = null;
    if (apiOperationAnnotation != null && StringUtils.hasText(apiOperationAnnotation.httpMethod())) {
        String apiMethod = apiOperationAnnotation.httpMethod();
        try {
            RequestMethod.valueOf(apiMethod);
        } catch (IllegalArgumentException e) {
            log.error("Invalid http method: " + apiMethod + "Valid ones are [" + RequestMethod.values() + "]", e);
        }
        httpMethod = HttpMethod.valueOf(apiMethod);
    } else {
        RequestMapping requestMapping = handlerMethod.getMethodAnnotation(RequestMapping.class);
        RequestMethod[] methods = requestMapping.method();
        if (CollectionUtil.isNotEmpty(methods)) {
            httpMethod = HttpMethod.valueOf(CollectionUtil.getFirst(methods).toString());
        }
    }

    if (httpMethod == null) {
        httpMethod = HttpMethod.GET;
    }

    context.operationBuilder().method(httpMethod);
}
 
Example #14
Source File: RequestToPoOperationBuilder.java    From jframework with Apache License 2.0 5 votes vote down vote up
private void readRequestFormToPojo(OperationContext context, ResolvedMethodParameter methodParameter) {

        List<RawField> fields = methodParameter.getParameterType().getMemberFields();
        List<RawField> parentRawFields = methodParameter.getParameterType().getParentClass().getMemberFields();

        List<RawField> fieldList = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(fields)) {
            fieldList.addAll(fields);
        }
        if (!CollectionUtils.isEmpty(parentRawFields)) {
            fieldList.addAll(parentRawFields);
        }
        List<Parameter> requestMapParameters = Lists.newArrayList();
        for (RawField rawField : fieldList) {
            String name = CaseUtil.snakeCase(rawField.getName());
            Class itemClass = rawField.getRawMember().getType();
            if (itemClass != null) {
                String itemTypeName = typeNameFor(itemClass);
                if (ObjectUtils.isEmpty(itemTypeName)) {
                    // 解析出这个类型的所有成员加到文档里
                    requestMapParameters.addAll(addFieldsToDoc(rawField.getRawMember(), name, null));
                } else {
                    requestMapParameters.add(genPrimaryTypeDoc(rawField.getRawMember(), "", itemTypeName));
                }
            }
        }

        try {
            OperationBuilder operationBuilder = context.operationBuilder();
            Field parametersField = context.operationBuilder().getClass().getDeclaredField("parameters");
            parametersField.setAccessible(true);
            parametersField.set(operationBuilder, requestMapParameters);
        } catch (Exception e) {
            log.debug("swagger RequestToPo error", e);
        }
    }
 
Example #15
Source File: RequestToPoOperationBuilder.java    From jframework with Apache License 2.0 5 votes vote down vote up
private List<Parameter> readParameters(final OperationContext context) {

        List<ResolvedMethodParameter> methodParameters = context.getParameters();
        final List<Parameter> parameterList = new ArrayList<>();

        for (ResolvedMethodParameter methodParameter : methodParameters) {
            ResolvedType alternate = context.alternateFor(methodParameter.getParameterType());

            if (!shouldIgnore(methodParameter, alternate, context.getIgnorableParameterTypes()) && isRequestFormToPojo(methodParameter)) {
                readRequestFormToPojo(context, methodParameter);
            }
        }
        return parameterList.stream().filter(((Predicate<Parameter>) Parameter::isHidden).negate()).collect(Collectors.toList());
    }
 
Example #16
Source File: DefaultEndPointPlugin.java    From BlogManagePlatform with Apache License 2.0 4 votes vote down vote up
private EndPointInfo resolveNameAttribute(OperationContext context) {
	EndPointInfo info = new EndPointInfo();
	info.controllerName = resolveApiName(context);
	boolean isRestEndPoint = isRestEndPoint(context);
	GetMapping getMapping = context.findAnnotation(GetMapping.class).orNull();
	if (getMapping != null) {
		info.name = getMapping.name();
		info.consumes = getMapping.consumes();
		info.produces = resolveJsonInfo(isRestEndPoint, getMapping.produces());
		return info;
	}
	PostMapping postMapping = context.findAnnotation(PostMapping.class).orNull();
	if (postMapping != null) {
		info.name = postMapping.name();
		info.consumes = postMapping.consumes();
		info.produces = resolveJsonInfo(isRestEndPoint, postMapping.produces());
		return info;
	}
	DeleteMapping deleteMapping = context.findAnnotation(DeleteMapping.class).orNull();
	if (deleteMapping != null) {
		info.name = deleteMapping.name();
		info.consumes = deleteMapping.consumes();
		info.produces = resolveJsonInfo(isRestEndPoint, deleteMapping.produces());
		return info;
	}
	PutMapping putMapping = context.findAnnotation(PutMapping.class).orNull();
	if (putMapping != null) {
		info.name = putMapping.name();
		info.consumes = putMapping.consumes();
		info.produces = resolveJsonInfo(isRestEndPoint, putMapping.produces());
		return info;
	}
	RequestMapping requestMapping = context.findAnnotation(RequestMapping.class).orNull();
	if (requestMapping != null) {
		info.name = requestMapping.name();
		info.consumes = requestMapping.consumes();
		info.produces = resolveJsonInfo(isRestEndPoint, requestMapping.produces());
		return info;
	}
	return null;
}
 
Example #17
Source File: PageableParameterBuilderPlugin.java    From spring-cloud-gray with Apache License 2.0 4 votes vote down vote up
@Override
public void apply(OperationContext context) {
    List<ResolvedMethodParameter> methodParameters = context.getParameters();
    List<Parameter> parameters = newArrayList();

    for (ResolvedMethodParameter methodParameter : methodParameters) {
        ResolvedType resolvedType = methodParameter.getParameterType();

        if (pageableType.equals(resolvedType)) {
            ParameterContext parameterContext = new ParameterContext(methodParameter,
                    new ParameterBuilder(),
                    context.getDocumentationContext(),
                    context.getGenericsNamingStrategy(),
                    context);
            Function<ResolvedType, ? extends ModelReference> factory = createModelRefFactory(parameterContext);

            ModelReference intModel = factory.apply(resolver.resolve(Integer.TYPE));
            ModelReference stringModel = factory.apply(resolver.resolve(List.class, String.class));

            parameters.add(new ParameterBuilder()
                    .parameterType("queryRecords")
                    .name("page")
                    .modelRef(intModel)
                    .description("Results page you want to retrieve (0..N)").build());
            parameters.add(new ParameterBuilder()
                    .parameterType("queryRecords")
                    .name("size")
                    .modelRef(intModel)
                    .description("Number of records per page").build());
            parameters.add(new ParameterBuilder()
                    .parameterType("queryRecords")
                    .name("sort")
                    .modelRef(stringModel)
                    .allowMultiple(true)
                    .description("Sorting criteria in the format: property(,asc|desc). "
                            + "Default sort order is ascending. "
                            + "Multiple sort criteria are supported.")
                    .build());
            context.operationBuilder().parameters(parameters);
        }
    }
}
 
Example #18
Source File: DefaultEndPointPlugin.java    From BlogManagePlatform with Apache License 2.0 4 votes vote down vote up
private boolean isRestEndPoint(OperationContext context) {
	if (context.findControllerAnnotation(RestController.class).isPresent()) {
		return true;
	}
	if (context.findAnnotation(ResponseBody.class).isPresent()) {
		return true;
	}
	return false;
}
 
Example #19
Source File: SuccessPlugin.java    From BlogManagePlatform with Apache License 2.0 4 votes vote down vote up
private ModelReference resolveModel(OperationContext context, Success success) {
	ModelContext modelContext = SwaggerUtil.resolveModelContext(context, success.value());
	ResolvedType type = context.alternateFor(SwaggerUtil.resolvedType(typeResolver, success));
	return modelRefFactory(modelContext, typeNameExtractor).apply(type);
}
 
Example #20
Source File: ParametersReader.java    From Resource with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void apply(OperationContext context)
{
    context.operationBuilder().parameters(readParameters(context));
}
 
Example #21
Source File: ParametersReader.java    From Resource with GNU General Public License v3.0 4 votes vote down vote up
private List<Parameter> readParameters(OperationContext context)
{
    List<Parameter> parameters = Lists.newArrayList();
    List<ResolvedMethodParameter> methodParameters = context.getParameters();

    Map<String, ApiSingleParam> paramMap = new HashMap<>();
    Field[] fields = ModelCache.getInstance().getParamClass().getDeclaredFields();
    String type = new String();
    for (Field field : fields)
    {
        if (field.isAnnotationPresent(ApiSingleParam.class))
        {
            ApiSingleParam param = field.getAnnotation(ApiSingleParam.class);
            try
            {
                String name = (String)field.get(type);
                paramMap.put(name, param);
            }
            catch (Exception e)
            {
            }
        }
    }

    for (ResolvedMethodParameter methodParameter : methodParameters)
    {
        ParameterContext parameterContext = new ParameterContext(methodParameter,
            new ParameterBuilder(),
            context.getDocumentationContext(),
            context.getGenericsNamingStrategy(),
            context);
        Function<ResolvedType, ? extends ModelReference> factory = createModelRefFactory(parameterContext);
        Optional<ApiJsonObject> annotation = context.findAnnotation(ApiJsonObject.class);

        if (annotation.isPresent())
        {
            ModelCache.getInstance().setFactory(factory)
                .setParamMap(paramMap)
                .addModel(annotation.get());

        }
    }
    return parameters;
}
 
Example #22
Source File: RequestToPoOperationBuilder.java    From jframework with Apache License 2.0 4 votes vote down vote up
@Override
public void apply(OperationContext context) {
    context.operationBuilder().parameters(readParameters(context));
}
 
Example #23
Source File: ApiMethodReader.java    From swagger-more with Apache License 2.0 4 votes vote down vote up
private void readTags(OperationContext context) {
    Optional<Api> apiOptional = context.findControllerAnnotation(Api.class);
    if (apiOptional.isPresent()) {
        context.operationBuilder().tags(newHashSet(apiOptional.get().tags()));
    }
}