Search in sources :

Example 31 with SwaggerParser

use of io.swagger.parser.SwaggerParser in project carbon-apimgt by wso2.

the class APIDefinitionFromSwagger20 method getScopeOfResourcePath.

@Override
public String getScopeOfResourcePath(String resourceConfigsJSON, Request request, ServiceMethodInfo serviceMethodInfo) throws APIManagementException {
    SwaggerParser swaggerParser = new SwaggerParser();
    Swagger swagger = swaggerParser.parse(resourceConfigsJSON);
    String basepath = swagger.getBasePath();
    String verb = (String) request.getProperty(APIMgtConstants.HTTP_METHOD);
    // TODO change to this if msf4j2.3.0-m2 or higher
    // Method resourceMethod = (Method) request.getProperty("method");
    Method resourceMethod = serviceMethodInfo.getMethod();
    if (resourceMethod == null || verb == null) {
        String message = "Could not read required properties from HTTP Request. HTTP_METHOD=" + verb + " resourceTemplate=" + resourceMethod;
        log.error(message);
        throw new APIManagementException(message, ExceptionCodes.SWAGGER_URL_MALFORMED);
    }
    String apiPrefix = resourceMethod.getDeclaringClass().getAnnotation(javax.ws.rs.ApplicationPath.class).value();
    String pathTemplate = "";
    if (resourceMethod.getAnnotation(javax.ws.rs.Path.class) != null) {
        pathTemplate = resourceMethod.getAnnotation(javax.ws.rs.Path.class).value();
    }
    String nameSpace = getNamespaceFromBasePath(basepath);
    if (basepath.contains(APIMgtConstants.APPType.PUBLISHER)) {
        nameSpace = APIMgtConstants.NAMESPACE_PUBLISHER_API;
    } else if (basepath.contains(APIMgtConstants.APPType.STORE)) {
        nameSpace = APIMgtConstants.NAMESPACE_STORE_API;
    } else if (basepath.contains(APIMgtConstants.APPType.ADMIN)) {
        nameSpace = APIMgtConstants.NAMESPACE_ADMIN_API;
    } else if (basepath.contains(APIMgtConstants.APPType.ANALYTICS)) {
        nameSpace = APIMgtConstants.NAMESPACE_ANALYTICS_API;
    }
    // if namespace is not available in local cache add it.
    if (nameSpace != null && !localConfigMap.containsKey(nameSpace)) {
        localConfigMap.put(nameSpace, new ConcurrentHashMap<>());
    }
    if (nameSpace != null && localConfigMap.containsKey(nameSpace) && localConfigMap.get(nameSpace).isEmpty()) {
        populateConfigMapForScopes(swagger, nameSpace);
    }
    String resourceConfig = verb + "_" + apiPrefix + pathTemplate;
    if (localConfigMap.get(nameSpace).containsKey(resourceConfig)) {
        return localConfigMap.get(nameSpace).get(resourceConfig).toString();
    }
    return null;
}
Also used : SwaggerParser(io.swagger.parser.SwaggerParser) Path(io.swagger.models.Path) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) Swagger(io.swagger.models.Swagger) Method(java.lang.reflect.Method) HttpMethod(io.swagger.models.HttpMethod)

Example 32 with SwaggerParser

use of io.swagger.parser.SwaggerParser in project carbon-apimgt by wso2.

the class APIDefinitionFromSwagger20 method getScopesFromSecurityDefinition.

@Override
public Map<String, String> getScopesFromSecurityDefinition(String resourceConfigJSON) throws APIManagementException {
    SwaggerParser swaggerParser = new SwaggerParser();
    Swagger swagger = swaggerParser.parse(resourceConfigJSON);
    Map<String, String> scopes = new HashMap<>();
    Map<String, SecuritySchemeDefinition> securityDefinitions = swagger.getSecurityDefinitions();
    if (securityDefinitions != null) {
        for (Map.Entry<String, SecuritySchemeDefinition> securitySchemeDefinitionEntry : securityDefinitions.entrySet()) {
            if (securitySchemeDefinitionEntry.getValue() instanceof OAuth2Definition) {
                OAuth2Definition securityDefinition = (OAuth2Definition) securitySchemeDefinitionEntry.getValue();
                if (securityDefinition != null) {
                    scopes.putAll(securityDefinition.getScopes());
                }
            }
        }
    }
    return scopes;
}
Also used : SwaggerParser(io.swagger.parser.SwaggerParser) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) Swagger(io.swagger.models.Swagger) OAuth2Definition(io.swagger.models.auth.OAuth2Definition) SecuritySchemeDefinition(io.swagger.models.auth.SecuritySchemeDefinition) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap)

Example 33 with SwaggerParser

use of io.swagger.parser.SwaggerParser in project carbon-apimgt by wso2.

the class OAS2Parser method getOASDefinitionWithTierContentAwareProperty.

@Override
public String getOASDefinitionWithTierContentAwareProperty(String oasDefinition, List<String> contentAwareTiersList, String apiLevelTier) throws APIManagementException {
    SwaggerParser parser = new SwaggerParser();
    SwaggerDeserializationResult parseAttemptForV2 = parser.readWithInfo(oasDefinition);
    Swagger swagger = parseAttemptForV2.getSwagger();
    // check if API Level tier is content aware. if so, we set a extension as a global property
    if (contentAwareTiersList.contains(apiLevelTier)) {
        swagger.setVendorExtension(APIConstants.SWAGGER_X_THROTTLING_BANDWIDTH, true);
        // no need to check resource levels since both cannot exist at the same time.
        log.debug("API Level policy is content aware..");
        return Json.pretty(swagger);
    }
    // if api level tier exists, skip checking for resource level tiers since both cannot exist at the same time.
    if (apiLevelTier != null) {
        log.debug("API Level policy is not content aware..");
        return oasDefinition;
    } else {
        log.debug("API Level policy does not exist. Checking for resource level");
        for (Map.Entry<String, Path> entry : swagger.getPaths().entrySet()) {
            String path = entry.getKey();
            List<Operation> operations = swagger.getPaths().get(path).getOperations();
            for (Operation op : operations) {
                if (contentAwareTiersList.contains(op.getVendorExtensions().get(APIConstants.SWAGGER_X_THROTTLING_TIER))) {
                    if (log.isDebugEnabled()) {
                        log.debug("API resource Level policy is content aware for operation " + op.getOperationId());
                    }
                    op.setVendorExtension(APIConstants.SWAGGER_X_THROTTLING_BANDWIDTH, true);
                }
            }
        }
        return Json.pretty(swagger);
    }
}
Also used : SwaggerParser(io.swagger.parser.SwaggerParser) RefPath(io.swagger.models.RefPath) Path(io.swagger.models.Path) SwaggerDeserializationResult(io.swagger.parser.util.SwaggerDeserializationResult) Swagger(io.swagger.models.Swagger) Operation(io.swagger.models.Operation) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap)

Example 34 with SwaggerParser

use of io.swagger.parser.SwaggerParser in project carbon-apimgt by wso2.

the class OASParserUtil method extractAndValidateOpenAPIArchive.

/**
 * Extract the archive file and validates the openAPI definition
 *
 * @param inputStream   file as input stream
 * @param returnContent whether to return the content of the definition in the response DTO
 * @return APIDefinitionValidationResponse
 * @throws APIManagementException if error occurred while parsing definition
 */
public static APIDefinitionValidationResponse extractAndValidateOpenAPIArchive(InputStream inputStream, boolean returnContent) throws APIManagementException {
    String path = System.getProperty(APIConstants.JAVA_IO_TMPDIR) + File.separator + APIConstants.OPENAPI_ARCHIVES_TEMP_FOLDER + File.separator + UUID.randomUUID().toString();
    String archivePath = path + File.separator + APIConstants.OPENAPI_ARCHIVE_ZIP_FILE;
    String extractedLocation = APIFileUtil.extractUploadedArchive(inputStream, APIConstants.OPENAPI_EXTRACTED_DIRECTORY, archivePath, path);
    File[] listOfFiles = new File(extractedLocation).listFiles();
    File archiveDirectory = null;
    if (listOfFiles != null) {
        if (listOfFiles.length > 1) {
            throw new APIManagementException("Swagger Definitions should be placed under one root folder.");
        }
        for (File file : listOfFiles) {
            if (file.isDirectory()) {
                archiveDirectory = file.getAbsoluteFile();
                break;
            }
        }
    }
    // If it is a single  swagger file without remote references it can be imported directly, without zipping.
    if (archiveDirectory == null) {
        throw new APIManagementException("Could not find an archive in the given ZIP file.");
    }
    File masterSwagger = checkMasterSwagger(archiveDirectory);
    String content;
    try {
        InputStream masterInputStream = new FileInputStream(masterSwagger);
        content = IOUtils.toString(masterInputStream, APIConstants.DigestAuthConstants.CHARSET);
    } catch (IOException e) {
        throw new APIManagementException("Error reading master swagger file" + e);
    }
    String openAPIContent = "";
    SwaggerVersion version;
    version = getSwaggerVersion(content);
    String filePath = masterSwagger.getAbsolutePath();
    if (SwaggerVersion.OPEN_API.equals(version)) {
        OpenAPIV3Parser openAPIV3Parser = new OpenAPIV3Parser();
        ParseOptions options = new ParseOptions();
        options.setResolve(true);
        OpenAPI openAPI = openAPIV3Parser.read(filePath, null, options);
        openAPIContent = Json.pretty(openAPI);
    } else if (SwaggerVersion.SWAGGER.equals(version)) {
        SwaggerParser parser = new SwaggerParser();
        Swagger swagger = parser.read(filePath, null, true);
        try {
            openAPIContent = Yaml.pretty().writeValueAsString(swagger);
        } catch (IOException e) {
            throw new APIManagementException("Error in converting swagger to openAPI content. " + e);
        }
    }
    APIDefinitionValidationResponse apiDefinitionValidationResponse;
    apiDefinitionValidationResponse = OASParserUtil.validateAPIDefinition(openAPIContent, returnContent);
    return apiDefinitionValidationResponse;
}
Also used : FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) OpenAPIV3Parser(io.swagger.v3.parser.OpenAPIV3Parser) FileInputStream(java.io.FileInputStream) APIDefinitionValidationResponse(org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse) SwaggerParser(io.swagger.parser.SwaggerParser) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Swagger(io.swagger.models.Swagger) ParseOptions(io.swagger.v3.parser.core.models.ParseOptions) File(java.io.File) OpenAPI(io.swagger.v3.oas.models.OpenAPI)

Example 35 with SwaggerParser

use of io.swagger.parser.SwaggerParser in project carbon-apimgt by wso2.

the class OAS2Parser method getSwagger.

/**
 * Get parsed Swagger object
 *
 * @param oasDefinition OAS definition
 * @return Swagger
 * @throws APIManagementException
 */
Swagger getSwagger(String oasDefinition) {
    SwaggerParser parser = new SwaggerParser();
    SwaggerDeserializationResult parseAttemptForV2 = parser.readWithInfo(oasDefinition);
    if (CollectionUtils.isNotEmpty(parseAttemptForV2.getMessages())) {
        log.debug("Errors found when parsing OAS definition");
    }
    return parseAttemptForV2.getSwagger();
}
Also used : SwaggerParser(io.swagger.parser.SwaggerParser) SwaggerDeserializationResult(io.swagger.parser.util.SwaggerDeserializationResult)

Aggregations

SwaggerParser (io.swagger.parser.SwaggerParser)95 Swagger (io.swagger.models.Swagger)48 Test (org.testng.annotations.Test)37 HashSet (java.util.HashSet)21 HashMap (java.util.HashMap)15 Path (io.swagger.models.Path)12 ArrayList (java.util.ArrayList)12 IOException (java.io.IOException)11 Operation (io.swagger.models.Operation)10 Map (java.util.Map)10 List (java.util.List)9 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)9 SwaggerDeserializationResult (io.swagger.parser.util.SwaggerDeserializationResult)8 File (java.io.File)8 Test (org.junit.Test)8 HttpMethod (io.swagger.models.HttpMethod)7 OpenAPIV3Parser (io.swagger.v3.parser.OpenAPIV3Parser)7 OAuth2Definition (io.swagger.models.auth.OAuth2Definition)6 SecuritySchemeDefinition (io.swagger.models.auth.SecuritySchemeDefinition)6 Parameter (io.swagger.models.parameters.Parameter)6