Search in sources :

Example 76 with Info

use of io.swagger.v3.oas.models.info.Info in project flow by vaadin.

the class SchemaGenerator method getFieldsAndOptionalMap.

/**
 * Because it's not possible to check the `transient` modifier and
 * annotation of a field using JavaParser API. We need this method to
 * reflect the type and get those information from the reflected object.
 *
 * @param type
 *            type of the class to get fields information
 * @return set of fields' name that we should generate.
 */
private Map<String, Boolean> getFieldsAndOptionalMap(GeneratorType type) {
    ResolvedReferenceType resolvedReferenceType = type.asResolvedType().asReferenceType();
    Optional<ResolvedReferenceTypeDeclaration> typeDeclaration = resolvedReferenceType.getTypeDeclaration();
    if (!typeDeclaration.filter(td -> td.isClass() && !td.isAnonymousClass()).isPresent()) {
        return Collections.emptyMap();
    }
    HashMap<String, Boolean> validFields = new HashMap<>();
    try {
        Class<?> aClass = openApiObjectGenerator.getClassFromReflection(type);
        Arrays.stream(aClass.getDeclaredFields()).filter(field -> {
            int modifiers = field.getModifiers();
            return !Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers) && !field.isAnnotationPresent(JsonIgnore.class);
        }).forEach(field -> validFields.put(field.getName(), !ExplicitNullableTypeChecker.isRequired(field)));
    } catch (ClassNotFoundException e) {
        String message = String.format("Can't get list of fields from class '%s'." + "Please make sure that class '%s' is in your project's compile classpath. " + "As the result, the generated TypeScript file will be empty.", resolvedReferenceType.getQualifiedName(), resolvedReferenceType.getQualifiedName());
        getLogger().info(message);
        getLogger().debug(message, e);
    }
    return validFields;
}
Also used : Arrays(java.util.Arrays) AnnotationExpr(com.github.javaparser.ast.expr.AnnotationExpr) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) ComposedSchema(io.swagger.v3.oas.models.media.ComposedSchema) LinkedHashMap(java.util.LinkedHashMap) ResolvedReferenceTypeDeclaration(com.github.javaparser.resolution.declarations.ResolvedReferenceTypeDeclaration) ResolvedType(com.github.javaparser.resolution.types.ResolvedType) Type(com.github.javaparser.ast.type.Type) ResolvedFieldDeclaration(com.github.javaparser.resolution.declarations.ResolvedFieldDeclaration) Map(java.util.Map) JsonIgnore(com.fasterxml.jackson.annotation.JsonIgnore) Schema(io.swagger.v3.oas.models.media.Schema) LinkedHashSet(java.util.LinkedHashSet) Logger(org.slf4j.Logger) TypeDeclaration(com.github.javaparser.ast.body.TypeDeclaration) Set(java.util.Set) ResolvedReferenceType(com.github.javaparser.resolution.types.ResolvedReferenceType) Collectors(java.util.stream.Collectors) List(java.util.List) FieldDeclaration(com.github.javaparser.ast.body.FieldDeclaration) StringSchema(io.swagger.v3.oas.models.media.StringSchema) ResolvedEnumConstantDeclaration(com.github.javaparser.resolution.declarations.ResolvedEnumConstantDeclaration) Modifier(java.lang.reflect.Modifier) Optional(java.util.Optional) ObjectSchema(io.swagger.v3.oas.models.media.ObjectSchema) Pattern(java.util.regex.Pattern) Collections(java.util.Collections) ExplicitNullableTypeChecker(dev.hilla.ExplicitNullableTypeChecker) ResolvedReferenceTypeDeclaration(com.github.javaparser.resolution.declarations.ResolvedReferenceTypeDeclaration) JsonIgnore(com.fasterxml.jackson.annotation.JsonIgnore) ResolvedReferenceType(com.github.javaparser.resolution.types.ResolvedReferenceType) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap)

Example 77 with Info

use of io.swagger.v3.oas.models.info.Info in project cxf by apache.

the class OpenApiFeature method initialize.

@Override
public void initialize(Server server, Bus bus) {
    final JAXRSServiceFactoryBean sfb = (JAXRSServiceFactoryBean) server.getEndpoint().get(JAXRSServiceFactoryBean.class.getName());
    final ServerProviderFactory factory = (ServerProviderFactory) server.getEndpoint().get(ServerProviderFactory.class.getName());
    final Set<String> packages = new HashSet<>();
    if (resourcePackages != null) {
        packages.addAll(resourcePackages);
    }
    Properties swaggerProps = null;
    GenericOpenApiContextBuilder<?> openApiConfiguration;
    final Application application = getApplicationOrDefault(server, factory, sfb, bus);
    if (StringUtils.isEmpty(getConfigLocation())) {
        swaggerProps = getSwaggerProperties(propertiesLocation, bus);
        if (isScan()) {
            packages.addAll(scanResourcePackages(sfb));
        }
        final OpenAPI oas = new OpenAPI().info(getInfo(swaggerProps));
        registerComponents(securityDefinitions).ifPresent(oas::setComponents);
        final SwaggerConfiguration config = new SwaggerConfiguration().openAPI(oas).prettyPrint(getOrFallback(isPrettyPrint(), swaggerProps, PRETTY_PRINT_PROPERTY)).readAllResources(isReadAllResources()).ignoredRoutes(getIgnoredRoutes()).filterClass(getOrFallback(getFilterClass(), swaggerProps, FILTER_CLASS_PROPERTY)).resourceClasses(getResourceClasses()).resourcePackages(getOrFallback(packages, swaggerProps, RESOURCE_PACKAGE_PROPERTY));
        openApiConfiguration = new JaxrsOpenApiContextBuilder<>().application(application).openApiConfiguration(config);
    } else {
        openApiConfiguration = new JaxrsOpenApiContextBuilder<>().application(application).configLocation(getConfigLocation());
    }
    try {
        final OpenApiContext context = openApiConfiguration.buildContext(true);
        final Properties userProperties = getUserProperties(context.getOpenApiConfiguration().getUserDefinedOptions());
        registerOpenApiResources(sfb, packages, context.getOpenApiConfiguration());
        registerSwaggerUiResources(sfb, combine(swaggerProps, userProperties), factory, bus);
        if (customizer != null) {
            customizer.setApplicationInfo(factory.getApplicationProvider());
        }
    } catch (OpenApiConfigurationException ex) {
        throw new RuntimeException("Unable to initialize OpenAPI context", ex);
    }
}
Also used : ServerProviderFactory(org.apache.cxf.jaxrs.provider.ServerProviderFactory) OpenApiConfigurationException(io.swagger.v3.oas.integration.OpenApiConfigurationException) Properties(java.util.Properties) SwaggerConfiguration(io.swagger.v3.oas.integration.SwaggerConfiguration) JAXRSServiceFactoryBean(org.apache.cxf.jaxrs.JAXRSServiceFactoryBean) Application(javax.ws.rs.core.Application) OpenAPI(io.swagger.v3.oas.models.OpenAPI) HashSet(java.util.HashSet) OpenApiContext(io.swagger.v3.oas.integration.api.OpenApiContext)

Example 78 with Info

use of io.swagger.v3.oas.models.info.Info in project hippo by NHS-digital-website.

the class ApiSpecificationStaticHtml2Codegen method sanitiseDefaultDate.

private Optional<String> sanitiseDefaultDate(final String defaultValue, final String dataFormat, final String parameter) {
    if ("date".equals(dataFormat) && StringUtils.isNotBlank(defaultValue)) {
        // Sun Jan 01 00:00:00 GMT 1984
        final String pattern = "E MMM dd HH:mm:ss VV uuuu";
        final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
        try {
            return Optional.of(LocalDate.parse(defaultValue.trim(), dateTimeFormatter).toString());
        } catch (final Exception e) {
            final String apiTitle = Optional.ofNullable(openAPI.getInfo()).map(Info::getTitle).orElse("n/a");
            log.warn("Unable to fix default value of '{}' as ISO-8601 format uuuu-MM-dd despite format being 'date' for parameter '{}' in API specification '{}'.", defaultValue, parameter, apiTitle);
        }
    }
    return Optional.empty();
}
Also used : Info(io.swagger.v3.oas.models.info.Info) DateTimeFormatter(java.time.format.DateTimeFormatter)

Example 79 with Info

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

the class OAS3Parser method updateOperationManagedInfo.

/**
 * Updates managed info of a provided operation such as auth type and throttling
 *
 * @param resource  API resource data
 * @param operation swagger operation
 */
private void updateOperationManagedInfo(SwaggerData.Resource resource, Operation operation) {
    String authType = resource.getAuthType();
    if (APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN.equals(authType)) {
        authType = "Application & Application User";
    }
    if (APIConstants.AUTH_APPLICATION_USER_LEVEL_TOKEN.equals(authType)) {
        authType = "Application User";
    }
    if (APIConstants.AUTH_APPLICATION_LEVEL_TOKEN.equals(authType)) {
        authType = "Application";
    }
    operation.addExtension(APIConstants.SWAGGER_X_AUTH_TYPE, authType);
    if (resource.getPolicy() != null) {
        operation.addExtension(APIConstants.SWAGGER_X_THROTTLING_TIER, resource.getPolicy());
    } else {
        operation.addExtension(APIConstants.SWAGGER_X_THROTTLING_TIER, APIConstants.DEFAULT_API_POLICY_UNLIMITED);
    }
    // AWS Lambda: set arn & timeout to swagger
    if (resource.getAmznResourceName() != null) {
        operation.addExtension(APIConstants.SWAGGER_X_AMZN_RESOURCE_NAME, resource.getAmznResourceName());
    }
    if (resource.getAmznResourceTimeout() != 0) {
        operation.addExtension(APIConstants.SWAGGER_X_AMZN_RESOURCE_TIMEOUT, resource.getAmznResourceTimeout());
    }
    updateLegacyScopesFromOperation(resource, operation);
    List<SecurityRequirement> security = operation.getSecurity();
    if (security == null) {
        security = new ArrayList<>();
        operation.setSecurity(security);
    }
    for (Map<String, List<String>> requirement : security) {
        if (requirement.get(OPENAPI_SECURITY_SCHEMA_KEY) != null) {
            if (resource.getScopes().isEmpty()) {
                requirement.put(OPENAPI_SECURITY_SCHEMA_KEY, Collections.EMPTY_LIST);
            } else {
                requirement.put(OPENAPI_SECURITY_SCHEMA_KEY, resource.getScopes().stream().map(Scope::getKey).collect(Collectors.toList()));
            }
            return;
        }
    }
    // if oauth2SchemeKey not present, add a new
    SecurityRequirement defaultRequirement = new SecurityRequirement();
    if (resource.getScopes().isEmpty()) {
        defaultRequirement.put(OPENAPI_SECURITY_SCHEMA_KEY, Collections.EMPTY_LIST);
    } else {
        defaultRequirement.put(OPENAPI_SECURITY_SCHEMA_KEY, resource.getScopes().stream().map(Scope::getKey).collect(Collectors.toList()));
    }
    security.add(defaultRequirement);
}
Also used : Scope(org.wso2.carbon.apimgt.api.model.Scope) List(java.util.List) ArrayList(java.util.ArrayList) SecurityRequirement(io.swagger.v3.oas.models.security.SecurityRequirement)

Example 80 with Info

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

the class OAS3Parser method generateAPIDefinition.

/**
 * This method generates API definition to the given api
 *
 * @param swaggerData api
 * @return API definition in string format
 * @throws APIManagementException
 */
@Override
public String generateAPIDefinition(SwaggerData swaggerData) throws APIManagementException {
    OpenAPI openAPI = new OpenAPI();
    // create path if null
    if (openAPI.getPaths() == null) {
        openAPI.setPaths(new Paths());
    }
    // Create info object
    Info info = new Info();
    info.setTitle(swaggerData.getTitle());
    if (swaggerData.getDescription() != null) {
        info.setDescription(swaggerData.getDescription());
    }
    Contact contact = new Contact();
    // Create contact object and map business owner info
    if (swaggerData.getContactName() != null) {
        contact.setName(swaggerData.getContactName());
    }
    if (swaggerData.getContactEmail() != null) {
        contact.setEmail(swaggerData.getContactEmail());
    }
    if (swaggerData.getContactName() != null || swaggerData.getContactEmail() != null) {
        // put contact object to info object
        info.setContact(contact);
    }
    info.setVersion(swaggerData.getVersion());
    openAPI.setInfo(info);
    updateSwaggerSecurityDefinition(openAPI, swaggerData, OPENAPI_DEFAULT_AUTHORIZATION_URL);
    updateLegacyScopesFromSwagger(openAPI, swaggerData);
    if (APIConstants.GRAPHQL_API.equals(swaggerData.getTransportType())) {
        modifyGraphQLSwagger(openAPI);
    } else {
        for (SwaggerData.Resource resource : swaggerData.getResources()) {
            addOrUpdatePathToSwagger(openAPI, resource);
        }
    }
    return Json.pretty(openAPI);
}
Also used : SwaggerData(org.wso2.carbon.apimgt.api.model.SwaggerData) Paths(io.swagger.v3.oas.models.Paths) Info(io.swagger.v3.oas.models.info.Info) OpenAPI(io.swagger.v3.oas.models.OpenAPI) Contact(io.swagger.v3.oas.models.info.Contact)

Aggregations

Test (org.testng.annotations.Test)91 OpenAPI (io.swagger.v3.oas.models.OpenAPI)77 OpenAPIV3Parser (io.swagger.v3.parser.OpenAPIV3Parser)60 SwaggerParseResult (io.swagger.v3.parser.core.models.SwaggerParseResult)56 Info (io.swagger.v3.oas.models.info.Info)39 Schema (io.swagger.v3.oas.models.media.Schema)24 IntegerSchema (io.swagger.v3.oas.models.media.IntegerSchema)22 StringSchema (io.swagger.v3.oas.models.media.StringSchema)22 ObjectSchema (io.swagger.v3.oas.models.media.ObjectSchema)19 Components (io.swagger.v3.oas.models.Components)18 ArraySchema (io.swagger.v3.oas.models.media.ArraySchema)18 ComposedSchema (io.swagger.v3.oas.models.media.ComposedSchema)17 Parameter (io.swagger.v3.oas.models.parameters.Parameter)17 ByteArraySchema (io.swagger.v3.oas.models.media.ByteArraySchema)15 QueryParameter (io.swagger.v3.oas.models.parameters.QueryParameter)15 ParseOptions (io.swagger.v3.parser.core.models.ParseOptions)15 BinarySchema (io.swagger.v3.oas.models.media.BinarySchema)14 MapSchema (io.swagger.v3.oas.models.media.MapSchema)14 DateSchema (io.swagger.v3.oas.models.media.DateSchema)13 DateTimeSchema (io.swagger.v3.oas.models.media.DateTimeSchema)13