Search in sources :

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

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

use of io.swagger.v3.oas.models.media in project snow-owl by b2ihealthcare.

the class FhirMetadataController method collectResources.

private Collection<Resource> collectResources(final OpenAPI openAPI) {
    final Paths paths = openAPI.getPaths();
    final List<io.swagger.v3.oas.models.tags.Tag> tags = openAPI.getTags();
    return tags.stream().filter(t -> t.getExtensions() != null && t.getExtensions().containsKey(B2I_OPENAPI_X_NAME)).map(t -> {
        final Map<?, ?> nameExtensionMap = (Map<?, ?>) t.getExtensions().get(B2I_OPENAPI_X_NAME);
        final String profile = (String) nameExtensionMap.get(B2I_OPENAPI_PROFILE);
        final Resource.Builder resourceBuilder = Resource.builder().type(t.getName()).profile(profile);
        // Collect the operations that belong to the same tagged class resource
        paths.values().stream().flatMap(pi -> pi.readOperations().stream()).filter(o -> o.getTags().contains(t.getName()) && o.getExtensions() != null && o.getExtensions().containsKey(B2I_OPENAPI_X_INTERACTION)).forEachOrdered(op -> {
            final Map<String, Object> operationExtensionMap = op.getExtensions();
            final Map<?, ?> interactionMap = (Map<?, ?>) operationExtensionMap.get(B2I_OPENAPI_X_INTERACTION);
            interactionMap.entrySet().forEach(e -> {
                final Interaction.Builder interactionBuilder = Interaction.builder().code((String) e.getKey());
                final String value = (String) e.getValue();
                if (!StringUtils.isEmpty(value)) {
                    interactionBuilder.documentation((String) value);
                }
                resourceBuilder.addInteraction(interactionBuilder.build());
            });
        });
        return resourceBuilder.build();
    }).sorted(Comparator.comparing(r -> r.getType().getCodeValue())).collect(Collectors.toList());
}
Also used : PathVariable(org.springframework.web.bind.annotation.PathVariable) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) Iterables(com.google.common.collect.Iterables) OpenApiWebMvcResource(org.springdoc.webmvc.api.OpenApiWebMvcResource) Autowired(org.springframework.beans.factory.annotation.Autowired) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) Uri(com.b2international.snowowl.fhir.core.model.dt.Uri) SnowOwlOpenApiWebMvcResource(com.b2international.snowowl.core.rest.SnowOwlOpenApiWebMvcResource) OperationDefinition(com.b2international.snowowl.fhir.core.model.operationdefinition.OperationDefinition) Supplier(java.util.function.Supplier) FhirApiConfig(com.b2international.snowowl.core.rest.FhirApiConfig) Code(com.b2international.snowowl.fhir.core.model.dt.Code) Extension(io.swagger.v3.oas.annotations.extensions.Extension) Operation(io.swagger.v3.oas.annotations.Operation) StringUtils(com.b2international.commons.StringUtils) MvcUriComponentsBuilder(org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder) B2I_OPENAPI_PROFILE(com.b2international.snowowl.core.rest.OpenAPIExtensions.B2I_OPENAPI_PROFILE) OpenAPI(io.swagger.v3.oas.models.OpenAPI) Map(java.util.Map) ApiResponse(io.swagger.v3.oas.annotations.responses.ApiResponse) GetMapping(org.springframework.web.bind.annotation.GetMapping) Suppliers(com.google.common.base.Suppliers) OperationKind(com.b2international.snowowl.fhir.core.codesystems.OperationKind) Schema(io.swagger.v3.oas.models.media.Schema) SnowOwlConfiguration(com.b2international.snowowl.core.config.SnowOwlConfiguration) NotFoundException(com.b2international.commons.exceptions.NotFoundException) Maps.newHashMap(com.google.common.collect.Maps.newHashMap) Collection(java.util.Collection) RestfulCapabilityMode(com.b2international.snowowl.fhir.core.codesystems.RestfulCapabilityMode) PathItem(io.swagger.v3.oas.models.PathItem) ExtensionProperty(io.swagger.v3.oas.annotations.extensions.ExtensionProperty) Paths(io.swagger.v3.oas.models.Paths) Collectors(java.util.stream.Collectors) RestController(org.springframework.web.bind.annotation.RestController) List(java.util.List) Tag(io.swagger.v3.oas.annotations.tags.Tag) CoreActivator(com.b2international.snowowl.core.CoreActivator) CapabilityStatementKind(com.b2international.snowowl.fhir.core.codesystems.CapabilityStatementKind) Platform(org.eclipse.core.runtime.Platform) Parameter(com.b2international.snowowl.fhir.core.model.operationdefinition.Parameter) B2I_OPENAPI_INTERACTION_READ(com.b2international.snowowl.core.rest.OpenAPIExtensions.B2I_OPENAPI_INTERACTION_READ) B2I_OPENAPI_X_NAME(com.b2international.snowowl.core.rest.OpenAPIExtensions.B2I_OPENAPI_X_NAME) PublicationStatus(com.b2international.snowowl.fhir.core.codesystems.PublicationStatus) Comparator(java.util.Comparator) ApplicationContext(com.b2international.snowowl.core.ApplicationContext) com.b2international.snowowl.fhir.core.model.capabilitystatement(com.b2international.snowowl.fhir.core.model.capabilitystatement) B2I_OPENAPI_X_INTERACTION(com.b2international.snowowl.core.rest.OpenAPIExtensions.B2I_OPENAPI_X_INTERACTION) ApiResponses(io.swagger.v3.oas.annotations.responses.ApiResponses) OpenApiWebMvcResource(org.springdoc.webmvc.api.OpenApiWebMvcResource) SnowOwlOpenApiWebMvcResource(com.b2international.snowowl.core.rest.SnowOwlOpenApiWebMvcResource) Paths(io.swagger.v3.oas.models.Paths) Tag(io.swagger.v3.oas.annotations.tags.Tag) Map(java.util.Map) Maps.newHashMap(com.google.common.collect.Maps.newHashMap)

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

use of io.swagger.v3.oas.models.media in project flink by apache.

the class OpenApiSpecGenerator method createDocumentationFile.

@VisibleForTesting
static void createDocumentationFile(DocumentingRestEndpoint restEndpoint, RestAPIVersion apiVersion, Path outputFile) throws IOException {
    final OpenAPI openApi = new OpenAPI();
    // eagerly initialize some data-structures to simplify operations later on
    openApi.setPaths(new io.swagger.v3.oas.models.Paths());
    openApi.setComponents(new Components());
    setInfo(openApi, apiVersion);
    List<MessageHeaders> specs = restEndpoint.getSpecs().stream().filter(spec -> spec.getSupportedAPIVersions().contains(apiVersion)).filter(OpenApiSpecGenerator::shouldBeDocumented).collect(Collectors.toList());
    specs.forEach(spec -> add(spec, openApi));
    final List<Schema> asyncOperationSchemas = collectAsyncOperationResultVariants(specs);
    // this adds the schema for every JSON object
    openApi.components(new Components().schemas(new HashMap<>(modelConverterContext.getDefinedModels())));
    injectAsyncOperationResultSchema(openApi, asyncOperationSchemas);
    overrideIdSchemas(openApi);
    overrideSerializeThrowableSchema(openApi);
    Files.deleteIfExists(outputFile);
    Files.write(outputFile, Yaml.pretty(openApi).getBytes(StandardCharsets.UTF_8));
}
Also used : Components(io.swagger.v3.oas.models.Components) HashMap(java.util.HashMap) ComposedSchema(io.swagger.v3.oas.models.media.ComposedSchema) ArraySchema(io.swagger.v3.oas.models.media.ArraySchema) Schema(io.swagger.v3.oas.models.media.Schema) AsynchronousOperationStatusMessageHeaders(org.apache.flink.runtime.rest.handler.async.AsynchronousOperationStatusMessageHeaders) MessageHeaders(org.apache.flink.runtime.rest.messages.MessageHeaders) OpenAPI(io.swagger.v3.oas.models.OpenAPI) VisibleForTesting(org.apache.flink.annotation.VisibleForTesting)

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

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

the class ParameterProcessor method applyAnnotations.

public static Parameter applyAnnotations(Parameter parameter, Type type, List<Annotation> annotations, Components components, String[] classTypes, String[] methodTypes, JsonView jsonViewAnnotation) {
    final AnnotationsHelper helper = new AnnotationsHelper(annotations, type);
    if (helper.isContext()) {
        return null;
    }
    if (parameter == null) {
        // consider it to be body param
        parameter = new Parameter();
    }
    // first handle schema
    List<Annotation> reworkedAnnotations = new ArrayList<>(annotations);
    Annotation paramSchemaOrArrayAnnotation = getParamSchemaAnnotation(annotations);
    if (paramSchemaOrArrayAnnotation != null) {
        reworkedAnnotations.add(paramSchemaOrArrayAnnotation);
    }
    AnnotatedType annotatedType = new AnnotatedType().type(type).resolveAsRef(true).skipOverride(true).jsonViewAnnotation(jsonViewAnnotation).ctxAnnotations(reworkedAnnotations.toArray(new Annotation[reworkedAnnotations.size()]));
    ResolvedSchema resolvedSchema = ModelConverters.getInstance().resolveAsResolvedSchema(annotatedType);
    if (resolvedSchema.schema != null) {
        parameter.setSchema(resolvedSchema.schema);
    }
    resolvedSchema.referencedSchemas.forEach(components::addSchemas);
    // handle first FormParam as it affects Explode resolving
    for (Annotation annotation : annotations) {
        if (annotation.annotationType().getName().equals("javax.ws.rs.FormParam")) {
            try {
                String name = (String) annotation.annotationType().getMethod("value").invoke(annotation);
                if (StringUtils.isNotBlank(name)) {
                    parameter.setName(name);
                }
            } catch (Exception e) {
            }
            // set temporarily to "form" to inform caller that we need to further process along other form parameters
            parameter.setIn("form");
        } else if (annotation.annotationType().getName().endsWith("FormDataParam")) {
            try {
                String name = (String) annotation.annotationType().getMethod("value").invoke(annotation);
                if (StringUtils.isNotBlank(name)) {
                    parameter.setName(name);
                }
            } catch (Exception e) {
            }
            // set temporarily to "form" to inform caller that we need to further process along other form parameters
            parameter.setIn("form");
        }
    }
    for (Annotation annotation : annotations) {
        if (annotation instanceof io.swagger.v3.oas.annotations.Parameter) {
            io.swagger.v3.oas.annotations.Parameter p = (io.swagger.v3.oas.annotations.Parameter) annotation;
            if (p.hidden()) {
                return null;
            }
            if (StringUtils.isNotBlank(p.ref())) {
                parameter = new Parameter().$ref(p.ref());
                return parameter;
            }
            if (StringUtils.isNotBlank(p.description())) {
                parameter.setDescription(p.description());
            }
            if (StringUtils.isNotBlank(p.name())) {
                parameter.setName(p.name());
            }
            if (StringUtils.isNotBlank(p.in().toString())) {
                parameter.setIn(p.in().toString());
            }
            if (StringUtils.isNotBlank(p.example())) {
                try {
                    parameter.setExample(Json.mapper().readTree(p.example()));
                } catch (IOException e) {
                    parameter.setExample(p.example());
                }
            }
            if (p.deprecated()) {
                parameter.setDeprecated(p.deprecated());
            }
            if (p.required()) {
                parameter.setRequired(p.required());
            }
            if (p.allowEmptyValue()) {
                parameter.setAllowEmptyValue(p.allowEmptyValue());
            }
            if (p.allowReserved()) {
                parameter.setAllowReserved(p.allowReserved());
            }
            Map<String, Example> exampleMap = new LinkedHashMap<>();
            if (p.examples().length == 1 && StringUtils.isBlank(p.examples()[0].name())) {
                Optional<Example> exampleOptional = AnnotationsUtils.getExample(p.examples()[0], true);
                if (exampleOptional.isPresent()) {
                    parameter.setExample(exampleOptional.get());
                }
            } else {
                for (ExampleObject exampleObject : p.examples()) {
                    AnnotationsUtils.getExample(exampleObject).ifPresent(example -> exampleMap.put(exampleObject.name(), example));
                }
            }
            if (exampleMap.size() > 0) {
                parameter.setExamples(exampleMap);
            }
            if (p.extensions().length > 0) {
                Map<String, Object> extensionMap = AnnotationsUtils.getExtensions(p.extensions());
                if (extensionMap != null && !extensionMap.isEmpty()) {
                    extensionMap.forEach(parameter::addExtension);
                }
            }
            Optional<Content> content = AnnotationsUtils.getContent(p.content(), classTypes, methodTypes, parameter.getSchema(), null, jsonViewAnnotation);
            if (content.isPresent()) {
                parameter.setContent(content.get());
                parameter.setSchema(null);
            }
            setParameterStyle(parameter, p);
            setParameterExplode(parameter, p);
        } else if (annotation.annotationType().getName().equals("javax.ws.rs.PathParam")) {
            try {
                String name = (String) annotation.annotationType().getMethod("value").invoke(annotation);
                if (StringUtils.isNotBlank(name)) {
                    parameter.setName(name);
                }
            } catch (Exception e) {
            }
        } else if (annotation.annotationType().getName().equals("javax.validation.constraints.Size")) {
            try {
                if (parameter.getSchema() == null) {
                    parameter.setSchema(new ArraySchema());
                }
                if (parameter.getSchema() instanceof ArraySchema) {
                    ArraySchema as = (ArraySchema) parameter.getSchema();
                    Integer min = (Integer) annotation.annotationType().getMethod("min").invoke(annotation);
                    if (min != null) {
                        as.setMinItems(min);
                    }
                    Integer max = (Integer) annotation.annotationType().getMethod("max").invoke(annotation);
                    if (max != null) {
                        as.setMaxItems(max);
                    }
                }
            } catch (Exception e) {
                LOGGER.error("failed on " + annotation.annotationType().getName(), e);
            }
        } else if (ModelResolver.NOT_NULL_ANNOTATIONS.contains(annotation.annotationType().getSimpleName())) {
            parameter.setRequired(true);
        }
    }
    final String defaultValue = helper.getDefaultValue();
    Schema paramSchema = parameter.getSchema();
    if (paramSchema == null) {
        if (parameter.getContent() != null && !parameter.getContent().values().isEmpty()) {
            paramSchema = parameter.getContent().values().iterator().next().getSchema();
        }
    }
    if (paramSchema != null) {
        if (paramSchema instanceof ArraySchema) {
            ArraySchema as = (ArraySchema) paramSchema;
            if (defaultValue != null) {
                as.getItems().setDefault(defaultValue);
            }
        } else {
            if (defaultValue != null) {
                paramSchema.setDefault(defaultValue);
            }
        }
    }
    return parameter;
}
Also used : ExampleObject(io.swagger.v3.oas.annotations.media.ExampleObject) ResolvedSchema(io.swagger.v3.core.converter.ResolvedSchema) ArraySchema(io.swagger.v3.oas.models.media.ArraySchema) Schema(io.swagger.v3.oas.models.media.Schema) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) ArraySchema(io.swagger.v3.oas.models.media.ArraySchema) Example(io.swagger.v3.oas.models.examples.Example) ResolvedSchema(io.swagger.v3.core.converter.ResolvedSchema) IOException(java.io.IOException) Annotation(java.lang.annotation.Annotation) IOException(java.io.IOException) AnnotatedType(io.swagger.v3.core.converter.AnnotatedType) Content(io.swagger.v3.oas.models.media.Content) Parameter(io.swagger.v3.oas.models.parameters.Parameter) ExampleObject(io.swagger.v3.oas.annotations.media.ExampleObject)

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

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

the class EnumPropertyTest method testEnumRefPropertyWithFQNTypeNameResolver.

@Test(description = "it should read a model with an enum property as a reference with fqn TypeNameResolver")
public void testEnumRefPropertyWithFQNTypeNameResolver() {
    TypeNameResolver.std.setUseFqn(true);
    Schema schema = context.resolve(new AnnotatedType(ModelWithEnumRefProperty.class));
    final Map<String, Schema> models = context.getDefinedModels();
    final String yaml = "io.swagger.v3.core.oas.models.ModelWithEnumRefProperty:\n" + "  type: object\n" + "  properties:\n" + "    a:\n" + "      $ref: '#/components/schemas/io.swagger.v3.core.oas.models.TestEnum'\n" + "    b:\n" + "      $ref: '#/components/schemas/io.swagger.v3.core.oas.models.TestEnum'\n" + "    c:\n" + "      $ref: '#/components/schemas/io.swagger.v3.core.oas.models.TestSecondEnum'\n" + "    d:\n" + "      type: string\n" + "      enum:\n" + "      - A_PRIVATE\n" + "      - A_PUBLIC\n" + "      - A_SYSTEM\n" + "      - A_INVITE_ONLY\n" + "io.swagger.v3.core.oas.models.TestEnum:\n" + "  type: string\n" + "  enum:\n" + "  - PRIVATE\n" + "  - PUBLIC\n" + "  - SYSTEM\n" + "  - INVITE_ONLY\n" + "io.swagger.v3.core.oas.models.TestSecondEnum:\n" + "  type: string\n" + "  enum:\n" + "  - A_PRIVATE\n" + "  - A_PUBLIC\n" + "  - A_SYSTEM\n" + "  - A_INVITE_ONLY\n";
    TypeNameResolver.std.setUseFqn(false);
    SerializationMatchers.assertEqualsToYaml(models, yaml);
}
Also used : AnnotatedType(io.swagger.v3.core.converter.AnnotatedType) ModelWithEnumRefProperty(io.swagger.v3.core.oas.models.ModelWithEnumRefProperty) StringSchema(io.swagger.v3.oas.models.media.StringSchema) Schema(io.swagger.v3.oas.models.media.Schema) Test(org.testng.annotations.Test) AfterTest(org.testng.annotations.AfterTest)

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