Java Code Examples for io.swagger.v3.oas.models.OpenAPI#getComponents()

The following examples show how to use io.swagger.v3.oas.models.OpenAPI#getComponents() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: OpenAPIParserTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testIssue768() {
    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    SwaggerParseResult result = new OpenAPIParser().readLocation("issue768-main.yaml", null, options);
    assertNotNull(result);

    OpenAPI openAPI = result.getOpenAPI();
    assertNotNull(openAPI);

    Components components = openAPI.getComponents();
    assertNotNull(components);

    Map<String, Schema> schemas = components.getSchemas();
    assertNotNull(schemas);

    assertEquals(schemas.size(), 1);
}
 
Example 2
Source File: OpenAPICodegenUtils.java    From product-microgateway with Apache License 2.0 6 votes vote down vote up
/**
 * store the security schemas of type "basic" and "apikey".
 *
 * @param openAPI {@link OpenAPI} object
 */
public static void setSecuritySchemaList(OpenAPI openAPI) {
    //Since the security schema list needs to instantiated per each API
    basicSecuritySchemaList = new ArrayList<>();
    apiKeySecuritySchemaMap = new HashMap();
    if (openAPI.getComponents() == null || openAPI.getComponents().getSecuritySchemes() == null) {
        return;
    }
    openAPI.getComponents().getSecuritySchemes().forEach((key, val) -> {
        if (val.getType() == SecurityScheme.Type.HTTP &&
                val.getScheme().toLowerCase(Locale.getDefault()).equals("basic")) {
            basicSecuritySchemaList.add(key);
        } else if (val.getType() == SecurityScheme.Type.APIKEY) {
            APIKey apiKey = new APIKey(val.getIn(), val.getName());
            apiKeySecuritySchemaMap.put(key, apiKey);
        }
    });
}
 
Example 3
Source File: ExtensionsUtil.java    From swagger-inflector with Apache License 2.0 6 votes vote down vote up
public  void removeExtensions(OpenAPI openAPI) {

        if (openAPI.getComponents() == null || openAPI.getComponents().getSchemas() == null) {
            schemas = new HashMap<>();
        } else {
            schemas = openAPI.getComponents().getSchemas();
            for (String name : schemas.keySet()) {
                Schema schema = schemas.get(name);
                if (schema.getExtensions() != null) {
                    if (schema.getExtensions().containsKey(Constants.X_SWAGGER_ROUTER_MODEL)) {
                        Map<String,Schema> extensions = schema.getExtensions();
                        Object value = extensions.get(Constants.X_SWAGGER_ROUTER_MODEL);
                        extensions.remove(Constants.X_SWAGGER_ROUTER_MODEL,value);
                    }
                }
            }
        }
        if (openAPI.getPaths() != null) {
            for (String pathname : openAPI.getPaths().keySet()) {
                PathItem pathItem = openAPI.getPaths().get(pathname);
                resolvePath(pathItem,false);
            }
        }

    }
 
Example 4
Source File: ExtensionsUtil.java    From swagger-inflector with Apache License 2.0 6 votes vote down vote up
public void addExtensions(OpenAPI openAPI) {
    if (openAPI.getComponents() == null || openAPI.getComponents().getSchemas() == null) {
        schemas = new HashMap<>();
    } else {
        schemas = openAPI.getComponents().getSchemas();
        for (String name : schemas.keySet()) {
            Schema schema = schemas.get(name);
            if (schema.getExtensions() != null) {
                if (!schema.getExtensions().containsKey(Constants.X_SWAGGER_ROUTER_MODEL)) {
                    schema.addExtension(Constants.X_SWAGGER_ROUTER_MODEL, name);
                }
            } else {
                schema.addExtension(Constants.X_SWAGGER_ROUTER_MODEL, name);
            }
        }
    }
    if (openAPI.getPaths() != null) {
        for (String pathname : openAPI.getPaths().keySet()) {
            PathItem pathItem = openAPI.getPaths().get(pathname);
            resolvePath(pathItem, true);
        }
    }

}
 
Example 5
Source File: ModelUtils.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
public static ApiResponse getApiResponse(OpenAPI openAPI, String name) {
    if (name == null) {
        return null;
    }

    if (openAPI != null && openAPI.getComponents() != null && openAPI.getComponents().getResponses() != null) {
        return openAPI.getComponents().getResponses().get(name);
    }
    return null;
}
 
Example 6
Source File: VaadinConnectTsGenerator.java    From flow with Apache License 2.0 5 votes vote down vote up
private static Set<File> generate(CodegenConfigurator configurator) {
    SwaggerParseResult parseResult = getParseResult(configurator);
    if (parseResult != null && parseResult.getMessages().isEmpty()) {
        OpenAPI openAPI = parseResult.getOpenAPI();
        if (openAPI.getComponents() == null) {
            openAPI.setComponents(new Components());
        }
        ClientOptInput clientOptInput = configurator.toClientOptInput()
                .openAPI(openAPI);
        Set<File> generatedFiles = new VaadinConnectTSOnlyGenerator()
                .opts(clientOptInput).generate().stream()
                .filter(Objects::nonNull).collect(Collectors.toSet());

        cleanGeneratedFolder(configurator.getOutputDir(), generatedFiles);

        return generatedFiles.stream()
                .filter(file -> file.getName().endsWith(TS))
                .collect(Collectors.toSet());
    } else {
        String error = parseResult == null ? ""
                : String.join("", parseResult.getMessages());
        cleanGeneratedFolder(configurator.getOutputDir(),
                Collections.emptySet());
        throw getUnexpectedOpenAPIException(configurator.getInputSpecURL(),
                error);
    }

}
 
Example 7
Source File: OpenAPICodegenUtils.java    From product-microgateway with Apache License 2.0 5 votes vote down vote up
/**
 * store the security schemas of type "oauth2".
 *
 * @param openAPI {@link OpenAPI} object
 */
public static void setOauthSecuritySchemaList(OpenAPI openAPI) {
    //Since the security schema list needs to instantiated per each API
    oauthSecuritySchemaList = new ArrayList<>();
    if (openAPI.getComponents() == null || openAPI.getComponents().getSecuritySchemes() == null) {
        return;
    }
    openAPI.getComponents().getSecuritySchemes().forEach((key, val) -> {
        if (val.getType() == SecurityScheme.Type.OAUTH2 ||
                (val.getType() == SecurityScheme.Type.HTTP &&
                        val.getScheme().toLowerCase(Locale.getDefault()).equals("jwt"))) {
            oauthSecuritySchemaList.add(key);
        }
    });
}
 
Example 8
Source File: ProcessUtils.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
public static Map<String, SecurityScheme> getSecuritySchemes(OpenAPI openAPI) {
    if (openAPI == null) {
        return null;
    } else {
        return openAPI.getComponents() != null ? openAPI.getComponents().getSecuritySchemes() : null;
    }
}
 
Example 9
Source File: ModelUtils.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
public static Header getHeader(OpenAPI openAPI, String name) {
    if (name == null) {
        return null;
    }

    if (openAPI != null && openAPI.getComponents() != null && openAPI.getComponents().getHeaders() != null) {
        return openAPI.getComponents().getHeaders().get(name);
    }
    return null;
}
 
Example 10
Source File: OAS3Parser.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * This method returns the oauth scopes according to the given swagger
 *
 * @param resourceConfigsJSON resource json
 * @return scope set
 * @throws APIManagementException
 */
@Override
public Set<Scope> getScopes(String resourceConfigsJSON) throws APIManagementException {
    OpenAPI openAPI = getOpenAPI(resourceConfigsJSON);
    Map<String, SecurityScheme> securitySchemes;
    SecurityScheme securityScheme;
    OAuthFlow oAuthFlow;
    Scopes scopes;
    if (openAPI.getComponents() != null && (securitySchemes = openAPI.getComponents().getSecuritySchemes()) != null
            && (securityScheme = securitySchemes.get(OPENAPI_SECURITY_SCHEMA_KEY)) != null
            && (oAuthFlow = securityScheme.getFlows().getImplicit()) != null
            && (scopes = oAuthFlow.getScopes()) != null) {
        Set<Scope> scopeSet = new HashSet<>();
        for (Map.Entry<String, String> entry : scopes.entrySet()) {
            Scope scope = new Scope();
            scope.setKey(entry.getKey());
            scope.setName(entry.getKey());
            scope.setDescription(entry.getValue());
            Map<String, String> scopeBindings;
            if (oAuthFlow.getExtensions() != null && (scopeBindings =
                    (Map<String, String>) oAuthFlow.getExtensions().get(APIConstants.SWAGGER_X_SCOPES_BINDINGS))
                    != null) {
                if (scopeBindings.get(scope.getKey()) != null) {
                    scope.setRoles(scopeBindings.get(scope.getKey()));
                }
            }
            scopeSet.add(scope);
        }
        return OASParserUtil.sortScopes(scopeSet);
    } else {
        return OASParserUtil.sortScopes(getScopesFromExtensions(openAPI));
    }
}
 
Example 11
Source File: ModelUtils.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
public static RequestBody getRequestBody(OpenAPI openAPI, String name) {
    if (name == null) {
        return null;
    }

    if (openAPI != null && openAPI.getComponents() != null && openAPI.getComponents().getRequestBodies() != null) {
        return openAPI.getComponents().getRequestBodies().get(name);
    }
    return null;
}
 
Example 12
Source File: OpenAPIParserTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testIssue749() {
    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    SwaggerParseResult result = new OpenAPIParser().readLocation("issue749-main.yaml", null, options);
    assertNotNull(result);

    OpenAPI openAPI = result.getOpenAPI();
    assertNotNull(openAPI);

    Components components = openAPI.getComponents();
    assertNotNull(components);

    PathItem pathItem = openAPI.getPaths().get("/some/ping");
    assertNotNull(pathItem);
    List<Parameter> parameters = pathItem.getGet().getParameters();
    assertNotNull(parameters);
    assertEquals(parameters.size(), 1);
    assertEquals(parameters.get(0).getName(), "i");
    assertNotNull(parameters.get(0).getSchema());
    assertEquals(parameters.get(0).getSchema().get$ref(), "#/components/schemas/SomeId");

    Map<String, Schema> schemas = components.getSchemas();
    assertNotNull(schemas);
    assertEquals(schemas.size(), 1);
    assertNotNull(schemas.get("SomeId"));
}
 
Example 13
Source File: Swagger3RestDocGenerator.java    From RestDoc with Apache License 2.0 5 votes vote down vote up
private Schema getOrGenerateComplexSchema(List<String> enums, Type type, List<PropertyModel> children, OpenAPI openAPI) {
    var componentName = ClassNameUtils.getComponentName(_config.getTypeInspector(), _config.getTypeNameParser(), type);

    if (openAPI.getComponents() == null)
        openAPI.components(new Components());
    if (openAPI.getComponents().getSchemas() == null)
        openAPI.getComponents().schemas(new LinkedHashMap<>());
    if (!openAPI.getComponents().getSchemas().containsKey(componentName)) {
        var schema = generateComplexTypeSchema(enums, type, children, openAPI);
        schema.setRequired(children.stream().filter(o -> o.isRequired()).map(o -> o.getName()).collect(Collectors.toList()));
        openAPI.getComponents().addSchemas(componentName, schema);
    }
    return openAPI.getComponents().getSchemas().get(componentName);
}
 
Example 14
Source File: TemplateTest.java    From servicecomb-toolkit with Apache License 2.0 5 votes vote down vote up
private Map<String, Object> readSwaggerModelInfo(String swaggerYamlFile, CodegenConfig config) throws IOException {

    Map<String, Object> templateData = new HashMap<>();
    String swaggerString = readResourceInClasspath(swaggerYamlFile);
    Swagger swagger = new SwaggerParser().parse(swaggerString);

    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    options.setFlatten(true);
    SwaggerParseResult result = new OpenAPIParser().readContents(swaggerString, null, options);
    OpenAPI openAPI = result.getOpenAPI();

    Components components = openAPI.getComponents();

    Map<String, Model> definitions = swagger.getDefinitions();
    if (definitions == null) {
      return templateData;
    }
    List<Map<String, String>> imports = new ArrayList<Map<String, String>>();
    for (String key : components.getSchemas().keySet()) {
      Schema mm = components.getSchemas().get(key);
      CodegenModel cm = config.fromModel(key, mm);
      Map<String, String> item = new HashMap<String, String>();
      item.put("import", config.toModelImport(cm.classname));
      imports.add(item);
    }
    templateData.put("imports", imports);
    return templateData;
  }
 
Example 15
Source File: OpenApiComponentsValidator.java    From servicecomb-toolkit with Apache License 2.0 4 votes vote down vote up
@Override
protected Components getPropertyObject(OpenAPI oasObject) {
  return oasObject.getComponents();
}
 
Example 16
Source File: OperationBuilder.java    From springdoc-openapi with Apache License 2.0 4 votes vote down vote up
/**
 * Parse open api.
 *
 * @param apiOperation the api operation
 * @param operation the operation
 * @param openAPI the open api
 * @param methodAttributes the method attributes
 * @return the open api
 */
public OpenAPI parse(io.swagger.v3.oas.annotations.Operation apiOperation,
		Operation operation, OpenAPI openAPI, MethodAttributes methodAttributes) {
	Components components = openAPI.getComponents();
	if (StringUtils.isNotBlank(apiOperation.summary()))
		operation.setSummary(propertyResolverUtils.resolve(apiOperation.summary()));

	if (StringUtils.isNotBlank(apiOperation.description()))
		operation.setDescription(propertyResolverUtils.resolve(apiOperation.description()));

	if (StringUtils.isNotBlank(apiOperation.operationId()))
		operation.setOperationId(getOperationId(apiOperation.operationId(), openAPI));

	if (apiOperation.deprecated())
		operation.setDeprecated(apiOperation.deprecated());

	buildTags(apiOperation, operation);

	if (operation.getExternalDocs() == null)  // if not set in root annotation
		AnnotationsUtils.getExternalDocumentation(apiOperation.externalDocs())
				.ifPresent(operation::setExternalDocs);

	// servers
	AnnotationsUtils.getServers(apiOperation.servers())
			.ifPresent(servers -> servers.forEach(operation::addServersItem));

	// build parameters
	for (io.swagger.v3.oas.annotations.Parameter parameterDoc : apiOperation.parameters()) {
		Parameter parameter = parameterBuilder.buildParameterFromDoc(parameterDoc, components,
				methodAttributes.getJsonViewAnnotation());
		operation.addParametersItem(parameter);
	}

	// RequestBody in Operation
	requestBodyBuilder.buildRequestBodyFromDoc(apiOperation.requestBody(), operation.getRequestBody(), methodAttributes, components).ifPresent(operation::setRequestBody);

	// build response
	buildResponse(components, apiOperation, operation, methodAttributes);

	// security
	securityParser.buildSecurityRequirement(apiOperation.security(), operation);

	// Extensions in Operation
	buildExtensions(apiOperation, operation);
	return openAPI;
}
 
Example 17
Source File: AbstractOpenApiResource.java    From springdoc-openapi with Apache License 2.0 4 votes vote down vote up
/**
 * Calculate path.
 *
 * @param handlerMethod the handler method
 * @param routerOperation the router operation
 */
protected void calculatePath(HandlerMethod handlerMethod, RouterOperation routerOperation) {
	String operationPath = routerOperation.getPath();
	Set<RequestMethod> requestMethods = new HashSet<>(Arrays.asList(routerOperation.getMethods()));
	io.swagger.v3.oas.annotations.Operation apiOperation = routerOperation.getOperation();
	String[] methodConsumes = routerOperation.getConsumes();
	String[] methodProduces = routerOperation.getProduces();
	String[] headers = routerOperation.getHeaders();
	Map<String, String> queryParams = routerOperation.getQueryParams();

	OpenAPI openAPI = openAPIBuilder.getCalculatedOpenAPI();
	Components components = openAPI.getComponents();
	Paths paths = openAPI.getPaths();

	Map<HttpMethod, Operation> operationMap = null;
	if (paths.containsKey(operationPath)) {
		PathItem pathItem = paths.get(operationPath);
		operationMap = pathItem.readOperationsMap();
	}

	for (RequestMethod requestMethod : requestMethods) {
		Operation existingOperation = getExistingOperation(operationMap, requestMethod);
		Method method = handlerMethod.getMethod();
		// skip hidden operations
		if (operationParser.isHidden(method))
			continue;

		RequestMapping reqMappingClass = AnnotatedElementUtils.findMergedAnnotation(handlerMethod.getBeanType(),
				RequestMapping.class);

		MethodAttributes methodAttributes = new MethodAttributes(springDocConfigProperties.getDefaultConsumesMediaType(), springDocConfigProperties.getDefaultProducesMediaType(), methodConsumes, methodProduces, headers);
		methodAttributes.setMethodOverloaded(existingOperation != null);

		if (reqMappingClass != null) {
			methodAttributes.setClassConsumes(reqMappingClass.consumes());
			methodAttributes.setClassProduces(reqMappingClass.produces());
		}

		methodAttributes.calculateConsumesProduces(method);

		Operation operation = (existingOperation != null) ? existingOperation : new Operation();

		if (isDeprecated(method))
			operation.setDeprecated(true);

		// Add documentation from operation annotation
		if (apiOperation == null || StringUtils.isBlank(apiOperation.operationId()))
			apiOperation = AnnotatedElementUtils.findMergedAnnotation(method,
					io.swagger.v3.oas.annotations.Operation.class);

		calculateJsonView(apiOperation, methodAttributes, method);
		if (apiOperation != null)
			openAPI = operationParser.parse(apiOperation, operation, openAPI, methodAttributes);
		fillParametersList(operation, queryParams, methodAttributes);

		// compute tags
		operation = openAPIBuilder.buildTags(handlerMethod, operation, openAPI);

		io.swagger.v3.oas.annotations.parameters.RequestBody requestBodyDoc = AnnotatedElementUtils.findMergedAnnotation(method,
				io.swagger.v3.oas.annotations.parameters.RequestBody.class);

		// RequestBody in Operation
		requestBuilder.getRequestBodyBuilder()
				.buildRequestBodyFromDoc(requestBodyDoc, methodAttributes, components,
						methodAttributes.getJsonViewAnnotationForRequestBody())
				.ifPresent(operation::setRequestBody);
		// requests
		operation = requestBuilder.build(handlerMethod, requestMethod, operation, methodAttributes, openAPI);

		// responses
		ApiResponses apiResponses = responseBuilder.build(components, handlerMethod, operation, methodAttributes);
		operation.setResponses(apiResponses);

		Set<io.swagger.v3.oas.annotations.callbacks.Callback> apiCallbacks = AnnotatedElementUtils.findMergedRepeatableAnnotations(method, io.swagger.v3.oas.annotations.callbacks.Callback.class);

		// callbacks
		buildCallbacks(openAPI, methodAttributes, operation, apiCallbacks);

		// allow for customisation
		customiseOperation(operation, handlerMethod);

		PathItem pathItemObject = buildPathItem(requestMethod, operation, operationPath, paths);
		paths.addPathItem(operationPath, pathItemObject);
	}
}
 
Example 18
Source File: OpenAPIV3ParserTest.java    From swagger-parser with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldParseApiWithParametersUsingContentvsSchema() {
    // Tests that the content method of specifying the format of a parameter
    // gets resolved.
    // Test checks if an API's single parameter of array type gets fully resolved to 
    // referenced definitions.
    String location = "src/test/resources/issue-1078/api.yaml";
    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    // This test uses an Array in the parameters, test if it get's fully resolved.
    options.setResolveFully(true);
    OpenAPIV3Parser tested = new OpenAPIV3Parser();
    
    // Parse yaml
    SwaggerParseResult result = tested.readLocation(location, emptyList(), options);

    OpenAPI api = result.getOpenAPI();
    Paths paths = api.getPaths();

    // First ensure all schemas were resolved, this is important when this library 
    // is used to generate code
    Components components = api.getComponents();
    assertNotNull(components);
    assertThat(components.getSchemas().size(), equalTo(4));
    assertNotNull(components.getSchemas().get("LocationType"));
    assertNotNull(components.getSchemas().get("Lat"));
    assertNotNull(components.getSchemas().get("Long"));
    assertNotNull(components.getSchemas().get("SearchResult"));
    
    PathItem apiEndpoint = paths.get("/api-endpoint-1");
    List<Parameter> parameters = apiEndpoint.getGet().getParameters();
    
    // Ensure there's only one parameter in this test
    assertThat(parameters.size(), equalTo(1));
    
    // We are testing content for a parameter so make sure its there.
    Content content = parameters.get(0).getContent();
    assertNotNull(content);
    // spec says only one content is permitted in 3.x
    assertThat( content.size(), equalTo(1));

    // Ensure there's a media type
    MediaType mediaType = content.entrySet().iterator().next().getValue();
    assertNotNull(mediaType);

    // This test has a single parameter of type array
    Schema parameterSchema = mediaType.getSchema();
    Assert.assertTrue(parameterSchema instanceof ArraySchema);
    ArraySchema arraySchema = (ArraySchema)parameterSchema;

    // Test if the item schema was resolved properly
    Schema itemSchema = arraySchema.getItems();
    assertNotNull(itemSchema);
    Assert.assertTrue(itemSchema instanceof ObjectSchema);

    // Ensure the referenced item's schema has been resolved.
    ObjectSchema objSchema = (ObjectSchema)itemSchema;
    Map<String, Schema> objectItemSchemas = objSchema.getProperties();
    assertThat( objectItemSchemas.size(), equalTo(2));
    Assert.assertTrue(objectItemSchemas.get("lat") instanceof IntegerSchema);
    Assert.assertTrue(objectItemSchemas.get("long") instanceof IntegerSchema);
}
 
Example 19
Source File: OpenApiComponentsDiffValidator.java    From servicecomb-toolkit with Apache License 2.0 4 votes vote down vote up
@Override
protected Components getPropertyObject(OpenAPI oasObject) {
  return oasObject.getComponents();
}
 
Example 20
Source File: ModelUtils.java    From openapi-generator with Apache License 2.0 3 votes vote down vote up
/**
 * Return a Map of the schemas defined under /components/schemas in the OAS document.
 * The returned Map only includes the direct children of /components/schemas in the OAS document; the Map
 * does not include inlined schemas.
 *
 * @param openAPI the OpenAPI document.
 * @return a map of schemas in the OAS document.
 */
public static Map<String, Schema> getSchemas(OpenAPI openAPI) {
    if (openAPI != null && openAPI.getComponents() != null && openAPI.getComponents().getSchemas() != null) {
        return openAPI.getComponents().getSchemas();
    }
    return Collections.emptyMap();
}