Search in sources :

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

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

the class Reader method processRequestBody.

protected void processRequestBody(Parameter requestBodyParameter, Operation operation, Consumes methodConsumes, Consumes classConsumes, List<Parameter> operationParameters, Annotation[] paramAnnotations, Type type, JsonView jsonViewAnnotation, Map<String, Encoding> encoding) {
    io.swagger.v3.oas.annotations.parameters.RequestBody requestBodyAnnotation = getRequestBody(Arrays.asList(paramAnnotations));
    if (requestBodyAnnotation != null) {
        Optional<RequestBody> optionalRequestBody = OperationParser.getRequestBody(requestBodyAnnotation, classConsumes, methodConsumes, components, jsonViewAnnotation);
        if (optionalRequestBody.isPresent()) {
            RequestBody requestBody = optionalRequestBody.get();
            if (StringUtils.isBlank(requestBody.get$ref()) && (requestBody.getContent() == null || requestBody.getContent().isEmpty())) {
                if (requestBodyParameter.getSchema() != null) {
                    Content content = processContent(requestBody.getContent(), requestBodyParameter.getSchema(), methodConsumes, classConsumes);
                    requestBody.setContent(content);
                }
            } else if (StringUtils.isBlank(requestBody.get$ref()) && requestBody.getContent() != null && !requestBody.getContent().isEmpty()) {
                if (requestBodyParameter.getSchema() != null) {
                    for (MediaType mediaType : requestBody.getContent().values()) {
                        if (mediaType.getSchema() == null) {
                            if (requestBodyParameter.getSchema() == null) {
                                mediaType.setSchema(new Schema());
                            } else {
                                mediaType.setSchema(requestBodyParameter.getSchema());
                            }
                        }
                        if (StringUtils.isBlank(mediaType.getSchema().getType())) {
                            mediaType.getSchema().setType(requestBodyParameter.getSchema().getType());
                        }
                    }
                }
            }
            operation.setRequestBody(requestBody);
        }
    } else {
        if (operation.getRequestBody() == null) {
            boolean isRequestBodyEmpty = true;
            RequestBody requestBody = new RequestBody();
            if (StringUtils.isNotBlank(requestBodyParameter.get$ref())) {
                requestBody.set$ref(requestBodyParameter.get$ref());
                isRequestBodyEmpty = false;
            }
            if (StringUtils.isNotBlank(requestBodyParameter.getDescription())) {
                requestBody.setDescription(requestBodyParameter.getDescription());
                isRequestBodyEmpty = false;
            }
            if (Boolean.TRUE.equals(requestBodyParameter.getRequired())) {
                requestBody.setRequired(requestBodyParameter.getRequired());
                isRequestBodyEmpty = false;
            }
            if (requestBodyParameter.getSchema() != null) {
                Content content = processContent(null, requestBodyParameter.getSchema(), methodConsumes, classConsumes);
                requestBody.setContent(content);
                isRequestBodyEmpty = false;
            }
            if (!isRequestBodyEmpty) {
                // requestBody.setExtensions(extensions);
                operation.setRequestBody(requestBody);
            }
        }
    }
    if (operation.getRequestBody() != null && operation.getRequestBody().getContent() != null && encoding != null && !encoding.isEmpty()) {
        Content content = operation.getRequestBody().getContent();
        for (String mediaKey : content.keySet()) {
            if (mediaKey.equals(javax.ws.rs.core.MediaType.APPLICATION_FORM_URLENCODED) || mediaKey.equals(javax.ws.rs.core.MediaType.MULTIPART_FORM_DATA)) {
                MediaType m = content.get(mediaKey);
                m.encoding(encoding);
            }
        }
    }
}
Also used : Content(io.swagger.v3.oas.models.media.Content) ResolvedSchema(io.swagger.v3.core.converter.ResolvedSchema) ObjectSchema(io.swagger.v3.oas.models.media.ObjectSchema) Schema(io.swagger.v3.oas.models.media.Schema) MediaType(io.swagger.v3.oas.models.media.MediaType) RequestBody(io.swagger.v3.oas.models.parameters.RequestBody)

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

use of io.swagger.v3.oas.models.media 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.media

use of io.swagger.v3.oas.models.media 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.media

use of io.swagger.v3.oas.models.media 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.media

use of io.swagger.v3.oas.models.media 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