use of io.swagger.models.SecurityRequirement in project swagger-core by swagger-api.
the class ServletReaderExtension method parseAuthorizations.
private static List<SecurityRequirement> parseAuthorizations(Authorization[] authorizations) {
final List<SecurityRequirement> result = new ArrayList<SecurityRequirement>();
for (Authorization auth : authorizations) {
if (StringUtils.isNotEmpty(auth.value())) {
final SecurityRequirement security = new SecurityRequirement();
security.setName(auth.value());
for (AuthorizationScope scope : auth.scopes()) {
if (StringUtils.isNotEmpty(scope.scope())) {
security.addScope(scope.scope());
}
}
result.add(security);
}
}
return result;
}
use of io.swagger.models.SecurityRequirement in project swagger-core by swagger-api.
the class ServletReaderExtension method applySecurityRequirements.
@Override
public void applySecurityRequirements(ReaderContext context, Operation operation, Method method) {
final List<SecurityRequirement> securityRequirements = new ArrayList<SecurityRequirement>();
final ApiOperation apiOperation = ReflectionUtils.getAnnotation(method, ApiOperation.class);
final Api apiAnnotation = context.getCls().getAnnotation(Api.class);
if (apiOperation != null) {
securityRequirements.addAll(parseAuthorizations(apiOperation.authorizations()));
}
if (securityRequirements.isEmpty() && apiAnnotation != null) {
securityRequirements.addAll(parseAuthorizations(apiAnnotation.authorizations()));
}
for (SecurityRequirement securityRequirement : securityRequirements) {
operation.security(securityRequirement);
}
}
use of io.swagger.models.SecurityRequirement in project swagger-core by swagger-api.
the class Reader method parseMethod.
private Operation parseMethod(Class<?> cls, Method method, AnnotatedMethod annotatedMethod, List<Parameter> globalParameters, List<ApiResponse> classApiResponses) {
Operation operation = new Operation();
if (annotatedMethod != null) {
method = annotatedMethod.getAnnotated();
}
ApiOperation apiOperation = ReflectionUtils.getAnnotation(method, ApiOperation.class);
ApiResponses responseAnnotation = ReflectionUtils.getAnnotation(method, ApiResponses.class);
String operationId = null;
// check if it's an inherited or implemented method.
boolean methodInSuperType = false;
if (!cls.isInterface()) {
methodInSuperType = ReflectionUtils.findMethod(method, cls.getSuperclass()) != null;
}
if (!methodInSuperType) {
for (Class<?> implementedInterface : cls.getInterfaces()) {
methodInSuperType = ReflectionUtils.findMethod(method, implementedInterface) != null;
if (methodInSuperType) {
break;
}
}
}
if (!methodInSuperType) {
operationId = method.getName();
} else {
operationId = this.getOperationId(method.getName());
}
String responseContainer = null;
Type responseType = null;
Map<String, Property> defaultResponseHeaders = new LinkedHashMap<String, Property>();
if (apiOperation != null) {
if (apiOperation.hidden()) {
return null;
}
if (!apiOperation.nickname().isEmpty()) {
operationId = apiOperation.nickname();
}
defaultResponseHeaders = parseResponseHeaders(apiOperation.responseHeaders());
operation.summary(apiOperation.value()).description(apiOperation.notes());
if (!isVoid(apiOperation.response())) {
responseType = apiOperation.response();
}
if (!apiOperation.responseContainer().isEmpty()) {
responseContainer = apiOperation.responseContainer();
}
List<SecurityRequirement> securities = new ArrayList<SecurityRequirement>();
for (Authorization auth : apiOperation.authorizations()) {
if (!auth.value().isEmpty()) {
SecurityRequirement security = new SecurityRequirement();
security.setName(auth.value());
for (AuthorizationScope scope : auth.scopes()) {
if (!scope.scope().isEmpty()) {
security.addScope(scope.scope());
}
}
securities.add(security);
}
}
for (SecurityRequirement sec : securities) {
operation.security(sec);
}
if (!apiOperation.consumes().isEmpty()) {
String[] consumesAr = ReaderUtils.splitContentValues(new String[] { apiOperation.consumes() });
for (String consume : consumesAr) {
operation.consumes(consume);
}
}
if (!apiOperation.produces().isEmpty()) {
String[] producesAr = ReaderUtils.splitContentValues(new String[] { apiOperation.produces() });
for (String produce : producesAr) {
operation.produces(produce);
}
}
}
if (apiOperation != null && StringUtils.isNotEmpty(apiOperation.responseReference())) {
Response response = new Response().description(SUCCESSFUL_OPERATION);
response.schema(new RefProperty(apiOperation.responseReference()));
operation.addResponse(String.valueOf(apiOperation.code()), response);
} else if (responseType == null) {
// pick out response from method declaration
LOGGER.debug("picking up response class from method {}", method);
responseType = method.getGenericReturnType();
}
if (isValidResponse(responseType)) {
final Property property = ModelConverters.getInstance().readAsProperty(responseType);
if (property != null) {
final Property responseProperty = ContainerWrapper.wrapContainer(responseContainer, property);
final int responseCode = (apiOperation == null) ? 200 : apiOperation.code();
operation.response(responseCode, new Response().description(SUCCESSFUL_OPERATION).schema(responseProperty).headers(defaultResponseHeaders));
appendModels(responseType);
}
}
operation.operationId(operationId);
if (operation.getConsumes() == null || operation.getConsumes().isEmpty()) {
final Consumes consumes = ReflectionUtils.getAnnotation(method, Consumes.class);
if (consumes != null) {
for (String mediaType : ReaderUtils.splitContentValues(consumes.value())) {
operation.consumes(mediaType);
}
}
}
if (operation.getProduces() == null || operation.getProduces().isEmpty()) {
final Produces produces = ReflectionUtils.getAnnotation(method, Produces.class);
if (produces != null) {
for (String mediaType : ReaderUtils.splitContentValues(produces.value())) {
operation.produces(mediaType);
}
}
}
List<ApiResponse> apiResponses = new ArrayList<ApiResponse>();
if (responseAnnotation != null) {
apiResponses.addAll(Arrays.asList(responseAnnotation.value()));
}
Class<?>[] exceptionTypes = method.getExceptionTypes();
for (Class<?> exceptionType : exceptionTypes) {
ApiResponses exceptionResponses = ReflectionUtils.getAnnotation(exceptionType, ApiResponses.class);
if (exceptionResponses != null) {
apiResponses.addAll(Arrays.asList(exceptionResponses.value()));
}
}
for (ApiResponse apiResponse : apiResponses) {
addResponse(operation, apiResponse);
}
// merge class level @ApiResponse
for (ApiResponse apiResponse : classApiResponses) {
String key = (apiResponse.code() == 0) ? "default" : String.valueOf(apiResponse.code());
if (operation.getResponses() != null && operation.getResponses().containsKey(key)) {
continue;
}
addResponse(operation, apiResponse);
}
if (ReflectionUtils.getAnnotation(method, Deprecated.class) != null) {
operation.setDeprecated(true);
}
// process parameters
for (Parameter globalParameter : globalParameters) {
operation.parameter(globalParameter);
}
Annotation[][] paramAnnotations = ReflectionUtils.getParameterAnnotations(method);
if (annotatedMethod == null) {
Type[] genericParameterTypes = method.getGenericParameterTypes();
for (int i = 0; i < genericParameterTypes.length; i++) {
final Type type = TypeFactory.defaultInstance().constructType(genericParameterTypes[i], cls);
List<Parameter> parameters = getParameters(type, Arrays.asList(paramAnnotations[i]));
for (Parameter parameter : parameters) {
operation.parameter(parameter);
}
}
} else {
for (int i = 0; i < annotatedMethod.getParameterCount(); i++) {
AnnotatedParameter param = annotatedMethod.getParameter(i);
final Type type = TypeFactory.defaultInstance().constructType(param.getParameterType(), cls);
List<Parameter> parameters = getParameters(type, Arrays.asList(paramAnnotations[i]));
for (Parameter parameter : parameters) {
operation.parameter(parameter);
}
}
}
if (operation.getResponses() == null) {
Response response = new Response().description(SUCCESSFUL_OPERATION);
operation.defaultResponse(response);
}
processOperationDecorator(operation, method);
return operation;
}
use of io.swagger.models.SecurityRequirement in project swagger-core by swagger-api.
the class SecurityDefinitionTest method createModelWithSecurityRequirements.
@Test(description = "it should create a model with security requirements")
public void createModelWithSecurityRequirements() throws IOException {
final Model personModel = ModelConverters.getInstance().read(Person.class).get("Person");
final Model errorModel = ModelConverters.getInstance().read(Error.class).get("Error");
final Info info = new Info().version("1.0.0").title("Swagger Petstore");
final Contact contact = new Contact().name("Swagger API Team").email("foo@bar.baz").url("http://swagger.io");
info.setContact(contact);
final Swagger swagger = new Swagger().info(info).host("petstore.swagger.io").scheme(Scheme.HTTP).consumes("application/json").produces("application/json").model("Person", personModel).model("Error", errorModel);
swagger.securityDefinition("githubAccessCode", new OAuth2Definition().accessCode("http://foo.com/accessCode", "http://foo.com/tokenUrl").scope("user:email", "Grants read access to a user’s email addresses."));
final Operation get = new Operation().produces("application/json").summary("finds pets in the system").description("a longer description").tag("Pet Operations").operationId("get pet by id");
get.parameter(new QueryParameter().name("tags").description("tags to filter by").required(false).property(new StringProperty()));
get.parameter(new PathParameter().name("petId").description("pet to fetch").property(new LongProperty()));
final Response response = new Response().description("pets returned").schema(new RefProperty().asDefault("Person"));
final Response errorResponse = new Response().description("error response").schema(new RefProperty().asDefault("Error"));
get.response(200, response).defaultResponse(errorResponse).security(new SecurityRequirement("internal_oauth2").scope("user:email")).security(new SecurityRequirement("api_key"));
swagger.path("/pets", new Path().get(get));
final String json = ResourceUtils.loadClassResource(getClass(), "ModelWithSecurityRequirements.json");
SerializationMatchers.assertEqualsToJson(swagger, json);
}
use of io.swagger.models.SecurityRequirement in project swagger-core by swagger-api.
the class Reader method read.
private Swagger read(Class<?> cls, String parentPath, String parentMethod, boolean isSubresource, String[] parentConsumes, String[] parentProduces, Map<String, Tag> parentTags, List<Parameter> parentParameters, Set<Class<?>> scannedResources) {
Map<String, Tag> tags = new LinkedHashMap<String, Tag>();
List<SecurityRequirement> securities = new ArrayList<SecurityRequirement>();
String[] consumes = new String[0];
String[] produces = new String[0];
final Set<Scheme> globalSchemes = EnumSet.noneOf(Scheme.class);
Api api = ReflectionUtils.getAnnotation(cls, Api.class);
boolean hasPathAnnotation = (ReflectionUtils.getAnnotation(cls, javax.ws.rs.Path.class) != null);
boolean hasApiAnnotation = (api != null);
boolean isApiHidden = hasApiAnnotation && api.hidden();
// class readable only if annotated with ((@Path and @Api) or isSubresource ) - and @Api not hidden
boolean classReadable = ((hasPathAnnotation && hasApiAnnotation) || isSubresource) && !isApiHidden;
// with scanAllResources true in config and @Api not hidden scan only if it has also @Path annotation or is subresource
boolean scanAll = !isApiHidden && config.isScanAllResources() && (hasPathAnnotation || isSubresource);
// readable if classReadable or scanAll
boolean readable = classReadable || scanAll;
if (!readable) {
return swagger;
}
// api readable only if @Api present; cannot be hidden because checked in classReadable.
boolean apiReadable = hasApiAnnotation;
if (apiReadable) {
// the value will be used as a tag for 2.0 UNLESS a Tags annotation is present
Set<String> tagStrings = extractTags(api);
for (String tagString : tagStrings) {
Tag tag = new Tag().name(tagString);
tags.put(tagString, tag);
}
for (String tagName : tags.keySet()) {
swagger.tag(tags.get(tagName));
}
if (!api.produces().isEmpty()) {
produces = ReaderUtils.splitContentValues(new String[] { api.produces() });
}
if (!api.consumes().isEmpty()) {
consumes = ReaderUtils.splitContentValues(new String[] { api.consumes() });
}
globalSchemes.addAll(parseSchemes(api.protocols()));
for (Authorization auth : api.authorizations()) {
if (auth.value() != null && !auth.value().isEmpty()) {
SecurityRequirement security = new SecurityRequirement();
security.setName(auth.value());
for (AuthorizationScope scope : auth.scopes()) {
if (scope.scope() != null && !scope.scope().isEmpty()) {
security.addScope(scope.scope());
}
}
securities.add(security);
}
}
}
if (readable) {
if (isSubresource) {
if (parentTags != null) {
tags.putAll(parentTags);
}
}
// merge consumes, produces
if (consumes.length == 0 && cls.getAnnotation(Consumes.class) != null) {
consumes = ReaderUtils.splitContentValues(cls.getAnnotation(Consumes.class).value());
}
if (produces.length == 0 && cls.getAnnotation(Produces.class) != null) {
produces = ReaderUtils.splitContentValues(cls.getAnnotation(Produces.class).value());
}
// look for method-level annotated properties
// handle sub-resources by looking at return type
final List<Parameter> globalParameters = new ArrayList<Parameter>();
// look for constructor-level annotated properties
globalParameters.addAll(ReaderUtils.collectConstructorParameters(cls, swagger));
// look for field-level annotated properties
globalParameters.addAll(ReaderUtils.collectFieldParameters(cls, swagger));
// build class/interface level @ApiResponse list
ApiResponses classResponseAnnotation = ReflectionUtils.getAnnotation(cls, ApiResponses.class);
List<ApiResponse> classApiResponses = new ArrayList<ApiResponse>();
if (classResponseAnnotation != null) {
classApiResponses.addAll(Arrays.asList(classResponseAnnotation.value()));
}
// parse the method
final javax.ws.rs.Path apiPath = ReflectionUtils.getAnnotation(cls, javax.ws.rs.Path.class);
JavaType classType = TypeFactory.defaultInstance().constructType(cls);
BeanDescription bd = new ObjectMapper().getSerializationConfig().introspect(classType);
Method[] methods = cls.getMethods();
for (Method method : methods) {
AnnotatedMethod annotatedMethod = bd.findMethod(method.getName(), method.getParameterTypes());
if (ReflectionUtils.isOverriddenMethod(method, cls)) {
continue;
}
javax.ws.rs.Path methodPath = ReflectionUtils.getAnnotation(method, javax.ws.rs.Path.class);
String operationPath = getPath(apiPath, methodPath, parentPath);
Map<String, String> regexMap = new LinkedHashMap<String, String>();
operationPath = PathUtils.parsePath(operationPath, regexMap);
if (operationPath != null) {
if (isIgnored(operationPath)) {
continue;
}
final ApiOperation apiOperation = ReflectionUtils.getAnnotation(method, ApiOperation.class);
String httpMethod = extractOperationMethod(apiOperation, method, SwaggerExtensions.chain());
Operation operation = null;
if (apiOperation != null || config.isScanAllResources() || httpMethod != null || methodPath != null) {
operation = parseMethod(cls, method, annotatedMethod, globalParameters, classApiResponses);
}
if (operation == null) {
continue;
}
if (parentParameters != null) {
for (Parameter param : parentParameters) {
operation.parameter(param);
}
}
for (Parameter param : operation.getParameters()) {
if (regexMap.get(param.getName()) != null) {
String pattern = regexMap.get(param.getName());
param.setPattern(pattern);
}
}
if (apiOperation != null) {
for (Scheme scheme : parseSchemes(apiOperation.protocols())) {
operation.scheme(scheme);
}
}
if (operation.getSchemes() == null || operation.getSchemes().isEmpty()) {
for (Scheme scheme : globalSchemes) {
operation.scheme(scheme);
}
}
String[] apiConsumes = consumes;
if (parentConsumes != null) {
Set<String> both = new LinkedHashSet<String>(Arrays.asList(apiConsumes));
both.addAll(new LinkedHashSet<String>(Arrays.asList(parentConsumes)));
if (operation.getConsumes() != null) {
both.addAll(new LinkedHashSet<String>(operation.getConsumes()));
}
apiConsumes = both.toArray(new String[both.size()]);
}
String[] apiProduces = produces;
if (parentProduces != null) {
Set<String> both = new LinkedHashSet<String>(Arrays.asList(apiProduces));
both.addAll(new LinkedHashSet<String>(Arrays.asList(parentProduces)));
if (operation.getProduces() != null) {
both.addAll(new LinkedHashSet<String>(operation.getProduces()));
}
apiProduces = both.toArray(new String[both.size()]);
}
final Class<?> subResource = getSubResourceWithJaxRsSubresourceLocatorSpecs(method);
if (subResource != null && !scannedResources.contains(subResource)) {
scannedResources.add(subResource);
read(subResource, operationPath, httpMethod, true, apiConsumes, apiProduces, tags, operation.getParameters(), scannedResources);
// remove the sub resource so that it can visit it later in another path
// but we have a room for optimization in the future to reuse the scanned result
// by caching the scanned resources in the reader instance to avoid actual scanning
// the the resources again
scannedResources.remove(subResource);
}
// can't continue without a valid http method
httpMethod = (httpMethod == null) ? parentMethod : httpMethod;
if (httpMethod != null) {
if (apiOperation != null) {
for (String tag : apiOperation.tags()) {
if (!"".equals(tag)) {
operation.tag(tag);
swagger.tag(new Tag().name(tag));
}
}
operation.getVendorExtensions().putAll(BaseReaderUtils.parseExtensions(apiOperation.extensions()));
}
if (operation.getConsumes() == null) {
for (String mediaType : apiConsumes) {
operation.consumes(mediaType);
}
}
if (operation.getProduces() == null) {
for (String mediaType : apiProduces) {
operation.produces(mediaType);
}
}
if (operation.getTags() == null) {
for (String tagString : tags.keySet()) {
operation.tag(tagString);
}
}
// Only add global @Api securities if operation doesn't already have more specific securities
if (operation.getSecurity() == null) {
for (SecurityRequirement security : securities) {
operation.security(security);
}
}
Path path = swagger.getPath(operationPath);
if (path == null) {
path = new Path();
swagger.path(operationPath, path);
}
path.set(httpMethod, operation);
readImplicitParameters(method, operation);
readExternalDocs(method, operation);
}
}
}
}
return swagger;
}
Aggregations