Search in sources :

Example 26 with io.swagger.v3.oas.models.security

use of io.swagger.v3.oas.models.security in project carbon-apimgt by wso2.

the class OAS3Parser method validateAPIDefinition.

/**
 * This method validates the given OpenAPI definition by content
 *
 * @param apiDefinition     OpenAPI Definition content
 * @param host OpenAPI Definition url
 * @param returnJsonContent whether to return the converted json form of the OpenAPI definition
 * @return APIDefinitionValidationResponse object with validation information
 */
@Override
public APIDefinitionValidationResponse validateAPIDefinition(String apiDefinition, String host, boolean returnJsonContent) throws APIManagementException {
    APIDefinitionValidationResponse validationResponse = new APIDefinitionValidationResponse();
    OpenAPIV3Parser openAPIV3Parser = new OpenAPIV3Parser();
    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    SwaggerParseResult parseAttemptForV3 = openAPIV3Parser.readContents(apiDefinition, null, options);
    if (CollectionUtils.isNotEmpty(parseAttemptForV3.getMessages())) {
        validationResponse.setValid(false);
        for (String message : parseAttemptForV3.getMessages()) {
            OASParserUtil.addErrorToValidationResponse(validationResponse, message);
            if (message.contains(APIConstants.OPENAPI_IS_MISSING_MSG)) {
                ErrorItem errorItem = new ErrorItem();
                errorItem.setErrorCode(ExceptionCodes.INVALID_OAS3_FOUND.getErrorCode());
                errorItem.setMessage(ExceptionCodes.INVALID_OAS3_FOUND.getErrorMessage());
                errorItem.setDescription(ExceptionCodes.INVALID_OAS3_FOUND.getErrorMessage());
                validationResponse.getErrorItems().add(errorItem);
            }
        }
    } else {
        OpenAPI openAPI = parseAttemptForV3.getOpenAPI();
        io.swagger.v3.oas.models.info.Info info = openAPI.getInfo();
        List<String> endpoints;
        String endpointWithHost = "";
        if (openAPI.getServers() == null || openAPI.getServers().isEmpty()) {
            endpoints = null;
        } else {
            endpoints = openAPI.getServers().stream().map(url -> url.getUrl()).collect(Collectors.toList());
            for (String endpoint : endpoints) {
                if (endpoint.startsWith("/")) {
                    if (StringUtils.isEmpty(host)) {
                        endpointWithHost = "http://api.yourdomain.com" + endpoint;
                    } else {
                        endpointWithHost = host + endpoint;
                    }
                    endpoints.set(endpoints.indexOf(endpoint), endpointWithHost);
                }
            }
        }
        String title = null;
        String context = null;
        if (!StringUtils.isBlank(info.getTitle())) {
            title = info.getTitle();
            context = info.getTitle().replaceAll("\\s", "").toLowerCase();
        }
        OASParserUtil.updateValidationResponseAsSuccess(validationResponse, apiDefinition, openAPI.getOpenapi(), title, info.getVersion(), context, info.getDescription(), endpoints);
        validationResponse.setParser(this);
        if (returnJsonContent) {
            if (!apiDefinition.trim().startsWith("{")) {
                // not a json (it is yaml)
                JsonNode jsonNode = DeserializationUtils.readYamlTree(apiDefinition);
                validationResponse.setJsonContent(jsonNode.toString());
            } else {
                validationResponse.setJsonContent(apiDefinition);
            }
        }
    }
    return validationResponse;
}
Also used : Info(io.swagger.v3.oas.models.info.Info) ErrorItem(org.wso2.carbon.apimgt.api.ErrorItem) JsonNode(com.fasterxml.jackson.databind.JsonNode) SwaggerParseResult(io.swagger.v3.parser.core.models.SwaggerParseResult) OpenAPIV3Parser(io.swagger.v3.parser.OpenAPIV3Parser) APIDefinitionValidationResponse(org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse) ParseOptions(io.swagger.v3.parser.core.models.ParseOptions) OpenAPI(io.swagger.v3.oas.models.OpenAPI)

Example 27 with io.swagger.v3.oas.models.security

use of io.swagger.v3.oas.models.security in project gravitee-management-rest-api by gravitee-io.

the class WSDLToOpenAPIConverter method processPorts.

private void processPorts(Service serviceDefinition) {
    Map<String, Port> ports = serviceDefinition.getPorts();
    Iterator<Entry<String, Port>> portIterator = ports.entrySet().iterator();
    final boolean singlePort = (ports.size() == 1);
    while (portIterator.hasNext()) {
        Entry<String, Port> entry = portIterator.next();
        String portName = entry.getKey();
        Port portDefinition = entry.getValue();
        // create Server section for the given port
        createServer(openAPI, portDefinition);
        final Binding binding = wsdlDefinition.getBinding(portDefinition.getBinding().getQName());
        for (int i = 0; i < binding.getBindingOperations().size(); ++i) {
            final BindingOperation bindingOperation = (BindingOperation) binding.getBindingOperations().get(i);
            final Operation operation = bindingOperation.getOperation();
            final String operationName = operation.getName();
            PathItem pathItem = new PathItem();
            io.swagger.v3.oas.models.Operation openApiOperation = new io.swagger.v3.oas.models.Operation();
            openApiOperation.operationId(String.join("_", binding.getQName().getLocalPart(), operationName));
            if (operation.getDocumentationElement() != null) {
                openApiOperation.description(operation.getDocumentationElement().getTextContent());
            }
            Input input = operation.getInput();
            if (input != null) {
                extractSOAPAction(bindingOperation).ifPresent(action -> openApiOperation.addExtension(SOAP_EXTENSION_ACTION, action));
                this.soapBuilder.generateSoapEnvelop(wsdlDefinition, binding, bindingOperation).ifPresent(envelope -> openApiOperation.addExtension(SOAP_EXTENSION_ENVELOPE, envelope));
            }
            // create an empty Content definition used by each response description
            Content nodefContent = new Content();
            io.swagger.v3.oas.models.media.MediaType item = new io.swagger.v3.oas.models.media.MediaType();
            io.swagger.v3.oas.models.media.Schema schema = new io.swagger.v3.oas.models.media.Schema();
            schema.setType("object");
            item.setSchema(schema);
            nodefContent.addMediaType(MediaType.APPLICATION_JSON, item);
            Output output = operation.getOutput();
            ApiResponse successResp = new ApiResponse();
            successResp.content(nodefContent);
            // description is mandatory
            successResp.setDescription("");
            if (output != null) {
                Message msg = output.getMessage();
                if (msg != null) {
                    if (msg.getDocumentationElement() != null) {
                        successResp.description(operation.getDocumentationElement().getTextContent());
                    }
                }
            }
            ApiResponse errorResp = new ApiResponse();
            errorResp.description("Error throws by the Backend Service");
            errorResp.content(nodefContent);
            ApiResponses responses = new ApiResponses();
            responses.addApiResponse(Integer.toString(HttpStatusCode.OK_200), successResp);
            responses.addApiResponse(Integer.toString(HttpStatusCode.INTERNAL_SERVER_ERROR_500), errorResp);
            openApiOperation.setResponses(responses);
            // TODO use the http:binding element to extract the HTTP method (ยง4.4) ?
            switch(detectHttpMethod(operationName)) {
                case GET:
                    pathItem.get(openApiOperation);
                    break;
                case DELETE:
                    pathItem.delete(openApiOperation);
                    break;
                case PUT:
                    pathItem.put(openApiOperation);
                    break;
                default:
                    pathItem.post(openApiOperation);
            }
            if (singlePort) {
                openAPI.path(String.join("/", "", serviceDefinition.getQName().getLocalPart(), operationName), pathItem);
            } else {
                openAPI.path(String.join("/", "", serviceDefinition.getQName().getLocalPart(), portName, operationName), pathItem);
            }
        }
    }
}
Also used : Schema(javax.wsdl.extensions.schema.Schema) ApiResponse(io.swagger.v3.oas.models.responses.ApiResponse) PathItem(io.swagger.v3.oas.models.PathItem) Entry(java.util.Map.Entry) MediaType(io.gravitee.common.http.MediaType) ApiResponses(io.swagger.v3.oas.models.responses.ApiResponses) Content(io.swagger.v3.oas.models.media.Content)

Example 28 with io.swagger.v3.oas.models.security

use of io.swagger.v3.oas.models.security in project swagger-parser by swagger-api.

the class OpenAPIV3ParserTest method testValidateExternalRefsFalse.

@Test(description = "option false, does not add Original Location to messages when ref is relative/local")
public void testValidateExternalRefsFalse() {
    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    options.setValidateExternalRefs(false);
    SwaggerParseResult result = new OpenAPIV3Parser().readLocation("./swos-443/root.yaml", null, options);
    OpenAPI openAPI = result.getOpenAPI();
    assertNotNull(openAPI);
    // keeps error messages only from original spec
    assertTrue(result.getMessages().contains("attribute components.schemas.InvalidSchema.invalid is unexpected"));
    assertTrue(result.getMessages().contains("An exception was thrown while trying to deserialize the contents of ./ref.yaml into type class io.swagger.v3.oas.models.callbacks.Callback"));
}
Also used : ParseOptions(io.swagger.v3.parser.core.models.ParseOptions) SwaggerParseResult(io.swagger.v3.parser.core.models.SwaggerParseResult) OpenAPIV3Parser(io.swagger.v3.parser.OpenAPIV3Parser) OpenAPI(io.swagger.v3.oas.models.OpenAPI) Test(org.testng.annotations.Test)

Example 29 with io.swagger.v3.oas.models.security

use of io.swagger.v3.oas.models.security in project swagger-core by swagger-api.

the class AnnotationsUtilsHeadersTest method extensionsTest.

@Test(dataProvider = "expectedData")
public void extensionsTest(String methodName, Optional<Map<String, io.swagger.v3.oas.models.headers.Header>> expected) throws NoSuchMethodException {
    final Method method = getClass().getDeclaredMethod(methodName);
    final Header[] headers = Arrays.stream(method.getAnnotation(Operation.class).responses()).flatMap(response -> Arrays.stream(response.headers())).toArray(Header[]::new);
    final Optional<Map<String, io.swagger.v3.oas.models.headers.Header>> optionalMap = AnnotationsUtils.getHeaders(headers, null);
    Assert.assertEquals(optionalMap, expected);
}
Also used : Arrays(java.util.Arrays) DataProvider(org.testng.annotations.DataProvider) ImmutableMap(com.google.common.collect.ImmutableMap) Test(org.testng.annotations.Test) AnnotationsUtils(io.swagger.v3.core.util.AnnotationsUtils) Operation(io.swagger.v3.oas.annotations.Operation) StyleEnum(io.swagger.v3.oas.models.headers.Header.StyleEnum) Assert(org.testng.Assert) ApiResponse(io.swagger.v3.oas.annotations.responses.ApiResponse) Map(java.util.Map) Optional(java.util.Optional) Method(java.lang.reflect.Method) Header(io.swagger.v3.oas.annotations.headers.Header) Header(io.swagger.v3.oas.annotations.headers.Header) Method(java.lang.reflect.Method) ImmutableMap(com.google.common.collect.ImmutableMap) Map(java.util.Map) Test(org.testng.annotations.Test)

Example 30 with io.swagger.v3.oas.models.security

use of io.swagger.v3.oas.models.security in project swagger-core by swagger-api.

the class DefaultParameterExtension method handleAdditionalAnnotation.

/**
 * Adds additional annotation processing support
 *
 * @param parameters
 * @param annotation
 * @param type
 * @param typesToSkip
 */
private boolean handleAdditionalAnnotation(List<Parameter> parameters, List<Parameter> formParameters, Annotation annotation, final Type type, Set<Type> typesToSkip, javax.ws.rs.Consumes classConsumes, javax.ws.rs.Consumes methodConsumes, Components components, boolean includeRequestBody, JsonView jsonViewAnnotation) {
    boolean processed = false;
    if (BeanParam.class.isAssignableFrom(annotation.getClass())) {
        // Use Jackson's logic for processing Beans
        final BeanDescription beanDesc = mapper.getSerializationConfig().introspect(constructType(type));
        final List<BeanPropertyDefinition> properties = beanDesc.findProperties();
        for (final BeanPropertyDefinition propDef : properties) {
            final AnnotatedField field = propDef.getField();
            final AnnotatedMethod setter = propDef.getSetter();
            final AnnotatedMethod getter = propDef.getGetter();
            final List<Annotation> paramAnnotations = new ArrayList<>();
            final Iterator<OpenAPIExtension> extensions = OpenAPIExtensions.chain();
            Type paramType = null;
            // Gather the field's details
            if (field != null) {
                paramType = field.getType();
                AnnotationMap annotationMap = field.getAllAnnotations();
                if (annotationMap != null) {
                    for (final Annotation fieldAnnotation : annotationMap.annotations()) {
                        if (!paramAnnotations.contains(fieldAnnotation)) {
                            paramAnnotations.add(fieldAnnotation);
                        }
                    }
                }
            }
            // Gather the setter's details but only the ones we need
            if (setter != null) {
                // Do not set the param class/type from the setter if the values are already identified
                if (paramType == null) {
                    // paramType will stay null if there is no parameter
                    paramType = setter.getParameterType(0);
                }
                AnnotationMap annotationMap = setter.getAllAnnotations();
                if (annotationMap != null) {
                    for (final Annotation fieldAnnotation : annotationMap.annotations()) {
                        if (!paramAnnotations.contains(fieldAnnotation)) {
                            paramAnnotations.add(fieldAnnotation);
                        }
                    }
                }
            }
            // Gather the getter's details but only the ones we need
            if (getter != null) {
                // Do not set the param class/type from the getter if the values are already identified
                if (paramType == null) {
                    paramType = getter.getType();
                }
                AnnotationMap annotationMap = getter.getAllAnnotations();
                if (annotationMap != null) {
                    for (final Annotation fieldAnnotation : annotationMap.annotations()) {
                        if (!paramAnnotations.contains(fieldAnnotation)) {
                            paramAnnotations.add(fieldAnnotation);
                        }
                    }
                }
            }
            if (paramType == null) {
                continue;
            }
            // skip hidden properties
            boolean hidden = false;
            for (Annotation a : paramAnnotations) {
                if (a instanceof io.swagger.v3.oas.annotations.media.Schema) {
                    if (((io.swagger.v3.oas.annotations.media.Schema) a).hidden()) {
                        hidden = true;
                        break;
                    }
                    ;
                } else if (a instanceof Hidden) {
                    hidden = true;
                    break;
                }
            }
            if (hidden) {
                continue;
            }
            // Re-process all Bean fields and let the default swagger-jaxrs/swagger-jersey-jaxrs processors do their thing
            ResolvedParameter resolvedParameter = extensions.next().extractParameters(paramAnnotations, paramType, typesToSkip, components, classConsumes, methodConsumes, includeRequestBody, jsonViewAnnotation, extensions);
            List<Parameter> extractedParameters = resolvedParameter.parameters;
            for (Parameter p : extractedParameters) {
                Parameter processedParam = ParameterProcessor.applyAnnotations(p, paramType, paramAnnotations, components, classConsumes == null ? new String[0] : classConsumes.value(), methodConsumes == null ? new String[0] : methodConsumes.value(), jsonViewAnnotation);
                if (processedParam != null) {
                    parameters.add(processedParam);
                }
            }
            List<Parameter> extractedFormParameters = resolvedParameter.formParameters;
            for (Parameter p : extractedFormParameters) {
                Parameter processedParam = ParameterProcessor.applyAnnotations(p, paramType, paramAnnotations, components, classConsumes == null ? new String[0] : classConsumes.value(), methodConsumes == null ? new String[0] : methodConsumes.value(), jsonViewAnnotation);
                if (processedParam != null) {
                    formParameters.add(processedParam);
                }
            }
            processed = true;
        }
    }
    return processed;
}
Also used : AnnotatedMethod(com.fasterxml.jackson.databind.introspect.AnnotatedMethod) BeanDescription(com.fasterxml.jackson.databind.BeanDescription) ArrayList(java.util.ArrayList) AbstractOpenAPIExtension(io.swagger.v3.jaxrs2.ext.AbstractOpenAPIExtension) OpenAPIExtension(io.swagger.v3.jaxrs2.ext.OpenAPIExtension) Annotation(java.lang.annotation.Annotation) Type(java.lang.reflect.Type) AnnotationMap(com.fasterxml.jackson.databind.introspect.AnnotationMap) BeanPropertyDefinition(com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition) Hidden(io.swagger.v3.oas.annotations.Hidden) Parameter(io.swagger.v3.oas.models.parameters.Parameter) AnnotatedField(com.fasterxml.jackson.databind.introspect.AnnotatedField)

Aggregations

Schema (io.swagger.v3.oas.models.media.Schema)13 ExampleObject (io.swagger.v3.oas.annotations.media.ExampleObject)11 OpenAPI (io.swagger.v3.oas.models.OpenAPI)10 Annotation (java.lang.annotation.Annotation)8 Test (org.testng.annotations.Test)8 ResolvedSchema (io.swagger.v3.core.converter.ResolvedSchema)7 ArraySchema (io.swagger.v3.oas.models.media.ArraySchema)7 Content (io.swagger.v3.oas.models.media.Content)7 ArrayList (java.util.ArrayList)7 PathItem (io.swagger.v3.oas.models.PathItem)6 Parameter (io.swagger.v3.oas.models.parameters.Parameter)6 BeanDescription (com.fasterxml.jackson.databind.BeanDescription)5 AnnotatedType (io.swagger.v3.core.converter.AnnotatedType)5 Hidden (io.swagger.v3.oas.annotations.Hidden)5 MediaType (io.swagger.v3.oas.models.media.MediaType)5 ObjectSchema (io.swagger.v3.oas.models.media.ObjectSchema)5 ApiResponse (io.swagger.v3.oas.models.responses.ApiResponse)5 Map (java.util.Map)5 JavaType (com.fasterxml.jackson.databind.JavaType)4 AnnotatedMethod (com.fasterxml.jackson.databind.introspect.AnnotatedMethod)4