Search in sources :

Example 6 with OAS3Parser

use of org.wso2.carbon.apimgt.impl.definitions.OAS3Parser in project carbon-apimgt by wso2.

the class PublisherCommonUtils method addAPIWithGeneratedSwaggerDefinition.

/**
 * Add API with the generated swagger from the DTO.
 *
 * @param apiDto     API DTO of the API
 * @param oasVersion Open API Definition version
 * @param username   Username
 * @param organization  Organization Identifier
 * @return Created API object
 * @throws APIManagementException Error while creating the API
 * @throws CryptoException        Error while encrypting
 */
public static API addAPIWithGeneratedSwaggerDefinition(APIDTO apiDto, String oasVersion, String username, String organization) throws APIManagementException, CryptoException {
    if (APIUtil.isOnPremResolver()) {
        String name = apiDto.getName();
        // replace all white spaces in the API Name
        apiDto.setName(name.replaceAll("\\s+", ""));
    }
    if (APIDTO.TypeEnum.ASYNC.equals(apiDto.getType())) {
        throw new APIManagementException("ASYNC API type does not support API creation from scratch", ExceptionCodes.API_CREATION_NOT_SUPPORTED_FOR_ASYNC_TYPE_APIS);
    }
    boolean isWSAPI = APIDTO.TypeEnum.WS.equals(apiDto.getType());
    boolean isAsyncAPI = isWSAPI || APIDTO.TypeEnum.WEBSUB.equals(apiDto.getType()) || APIDTO.TypeEnum.SSE.equals(apiDto.getType()) || APIDTO.TypeEnum.ASYNC.equals(apiDto.getType());
    username = StringUtils.isEmpty(username) ? RestApiCommonUtil.getLoggedInUsername() : username;
    APIProvider apiProvider = RestApiCommonUtil.getProvider(username);
    // validate web socket api endpoint configurations
    if (isWSAPI && !PublisherCommonUtils.isValidWSAPI(apiDto)) {
        throw new APIManagementException("Endpoint URLs should be valid web socket URLs", ExceptionCodes.INVALID_ENDPOINT_URL);
    }
    // validate sandbox and production endpoints
    if (!PublisherCommonUtils.validateEndpoints(apiDto)) {
        throw new APIManagementException("Invalid/Malformed endpoint URL(s) detected", ExceptionCodes.INVALID_ENDPOINT_URL);
    }
    Map endpointConfig = (Map) apiDto.getEndpointConfig();
    CryptoUtil cryptoUtil = CryptoUtil.getDefaultCryptoUtil();
    // OAuth 2.0 backend protection: API Key and API Secret encryption
    encryptEndpointSecurityOAuthCredentials(endpointConfig, cryptoUtil, StringUtils.EMPTY, StringUtils.EMPTY, apiDto);
    // AWS Lambda: secret key encryption while creating the API
    if (apiDto.getEndpointConfig() != null) {
        if (endpointConfig.containsKey(APIConstants.AMZN_SECRET_KEY)) {
            String secretKey = (String) endpointConfig.get(APIConstants.AMZN_SECRET_KEY);
            if (!StringUtils.isEmpty(secretKey)) {
                String encryptedSecretKey = cryptoUtil.encryptAndBase64Encode(secretKey.getBytes());
                endpointConfig.put(APIConstants.AMZN_SECRET_KEY, encryptedSecretKey);
                apiDto.setEndpointConfig(endpointConfig);
            }
        }
    }
    /* if (isWSAPI) {
            ArrayList<String> websocketTransports = new ArrayList<>();
            websocketTransports.add(APIConstants.WS_PROTOCOL);
            websocketTransports.add(APIConstants.WSS_PROTOCOL);
            apiDto.setTransport(websocketTransports);
        }*/
    API apiToAdd = prepareToCreateAPIByDTO(apiDto, apiProvider, username, organization);
    validateScopes(apiToAdd);
    // validate API categories
    List<APICategory> apiCategories = apiToAdd.getApiCategories();
    List<APICategory> apiCategoriesList = new ArrayList<>();
    for (APICategory category : apiCategories) {
        category.setOrganization(organization);
        apiCategoriesList.add(category);
    }
    apiToAdd.setApiCategories(apiCategoriesList);
    if (apiCategoriesList.size() > 0) {
        if (!APIUtil.validateAPICategories(apiCategoriesList, organization)) {
            throw new APIManagementException("Invalid API Category name(s) defined", ExceptionCodes.from(ExceptionCodes.API_CATEGORY_INVALID));
        }
    }
    if (!isAsyncAPI) {
        APIDefinition oasParser;
        if (RestApiConstants.OAS_VERSION_2.equalsIgnoreCase(oasVersion)) {
            oasParser = new OAS2Parser();
        } else {
            oasParser = new OAS3Parser();
        }
        SwaggerData swaggerData = new SwaggerData(apiToAdd);
        String apiDefinition = oasParser.generateAPIDefinition(swaggerData);
        apiToAdd.setSwaggerDefinition(apiDefinition);
    } else {
        AsyncApiParser asyncApiParser = new AsyncApiParser();
        String asyncApiDefinition = asyncApiParser.generateAsyncAPIDefinition(apiToAdd);
        apiToAdd.setAsyncApiDefinition(asyncApiDefinition);
    }
    apiToAdd.setOrganization(organization);
    if (isAsyncAPI) {
        AsyncApiParser asyncApiParser = new AsyncApiParser();
        String apiDefinition = asyncApiParser.generateAsyncAPIDefinition(apiToAdd);
        apiToAdd.setAsyncApiDefinition(apiDefinition);
    }
    // adding the api
    apiProvider.addAPI(apiToAdd);
    return apiToAdd;
}
Also used : OAS2Parser(org.wso2.carbon.apimgt.impl.definitions.OAS2Parser) SwaggerData(org.wso2.carbon.apimgt.api.model.SwaggerData) ArrayList(java.util.ArrayList) OAS3Parser(org.wso2.carbon.apimgt.impl.definitions.OAS3Parser) AsyncApiParser(org.wso2.carbon.apimgt.impl.definitions.AsyncApiParser) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) CryptoUtil(org.wso2.carbon.core.util.CryptoUtil) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIDefinition(org.wso2.carbon.apimgt.api.APIDefinition) API(org.wso2.carbon.apimgt.api.model.API) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) APICategory(org.wso2.carbon.apimgt.api.model.APICategory)

Example 7 with OAS3Parser

use of org.wso2.carbon.apimgt.impl.definitions.OAS3Parser in project carbon-apimgt by wso2.

the class OASParserUtilTest method testGetOASParser.

@Test
public void testGetOASParser() throws Exception {
    String oas3 = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("definitions" + File.separator + "petstore_v3.yaml"), "UTF-8");
    APIDefinition definition = OASParserUtil.getOASParser(oas3);
    Assert.assertNotNull(definition);
    Assert.assertTrue(definition instanceof OAS3Parser);
    String oas2 = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("definitions" + File.separator + "petstore_v2.yaml"), "UTF-8");
    definition = OASParserUtil.getOASParser(oas2);
    Assert.assertNotNull(definition);
    Assert.assertTrue(definition instanceof OAS2Parser);
    String oasError = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("definitions" + File.separator + "petstore_error.json"), "UTF-8");
    try {
        definition = OASParserUtil.getOASParser(oasError);
        Assert.fail("Exception expected");
    } catch (APIManagementException e) {
        Assert.assertTrue(e.getCause() instanceof IOException);
    }
    String oasInvalid = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("definitions" + File.separator + "petstore_invalid.yaml"), "UTF-8");
    try {
        definition = OASParserUtil.getOASParser(oasInvalid);
        Assert.fail("Exception expected");
    } catch (APIManagementException e) {
        Assert.assertTrue(e.getMessage().contains("Invalid OAS definition provided."));
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIDefinition(org.wso2.carbon.apimgt.api.APIDefinition) IOException(java.io.IOException) Test(org.junit.Test)

Example 8 with OAS3Parser

use of org.wso2.carbon.apimgt.impl.definitions.OAS3Parser in project carbon-apimgt by wso2.

the class OASParserUtil method extractRelevantSourceData.

private static void extractRelevantSourceData(Map<API, List<APIProductResource>> apiToProductResourceMapping, SwaggerUpdateContext context) throws APIManagementException {
    // Extract Paths that exist in the destination swagger from the source swagger
    for (Map.Entry<API, List<APIProductResource>> mappingEntry : apiToProductResourceMapping.entrySet()) {
        String sourceSwagger = mappingEntry.getKey().getSwaggerDefinition();
        SwaggerVersion sourceSwaggerVersion = getSwaggerVersion(sourceSwagger);
        if (sourceSwaggerVersion == SwaggerVersion.OPEN_API) {
            OpenAPI srcOpenAPI = ((OAS3Parser) oas3Parser).getOpenAPI(sourceSwagger);
            Set<Components> aggregatedComponents = context.getAggregatedComponents();
            Components components = srcOpenAPI.getComponents();
            if (components != null) {
                aggregatedComponents.add(components);
            }
            Set<Scope> allScopes = oas3Parser.getScopes(sourceSwagger);
            Paths srcPaths = srcOpenAPI.getPaths();
            List<APIProductResource> apiProductResources = mappingEntry.getValue();
            for (APIProductResource apiProductResource : apiProductResources) {
                URITemplate uriTemplate = apiProductResource.getUriTemplate();
                PathItem srcPathItem = srcPaths.get(uriTemplate.getUriTemplate());
                readPathsAndScopes(srcPathItem, uriTemplate, allScopes, context);
            }
        } else if (sourceSwaggerVersion == SwaggerVersion.SWAGGER) {
            Swagger srcSwagger = ((OAS2Parser) oas2Parser).getSwagger(sourceSwagger);
            Set<Components> aggregatedComponents = context.getAggregatedComponents();
            Components components = swaggerConverter.readContents(sourceSwagger, null, null).getOpenAPI().getComponents();
            if (components != null) {
                aggregatedComponents.add(components);
            }
            Set<Scope> allScopes = oas2Parser.getScopes(sourceSwagger);
            Map<String, Path> srcPaths = srcSwagger.getPaths();
            List<APIProductResource> apiProductResources = mappingEntry.getValue();
            for (APIProductResource apiProductResource : apiProductResources) {
                URITemplate uriTemplate = apiProductResource.getUriTemplate();
                Path srcPath = srcPaths.get(uriTemplate.getUriTemplate());
                readPathsAndScopes(swaggerConverter.convert(srcPath), uriTemplate, allScopes, context);
            }
        }
    }
}
Also used : RefPath(io.swagger.models.RefPath) Path(io.swagger.models.Path) Set(java.util.Set) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) Components(io.swagger.v3.oas.models.Components) PathItem(io.swagger.v3.oas.models.PathItem) Scope(org.wso2.carbon.apimgt.api.model.Scope) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) Swagger(io.swagger.models.Swagger) OpenAPI(io.swagger.v3.oas.models.OpenAPI) API(org.wso2.carbon.apimgt.api.model.API) List(java.util.List) ArrayList(java.util.ArrayList) Paths(io.swagger.v3.oas.models.Paths) Map(java.util.Map) HashMap(java.util.HashMap) OpenAPI(io.swagger.v3.oas.models.OpenAPI)

Example 9 with OAS3Parser

use of org.wso2.carbon.apimgt.impl.definitions.OAS3Parser in project carbon-apimgt by wso2.

the class OASParserUtil method updateAPIProductSwaggerOperations.

public static String updateAPIProductSwaggerOperations(Map<API, List<APIProductResource>> apiToProductResourceMapping, String destinationSwagger) throws APIManagementException {
    SwaggerVersion destinationSwaggerVersion = getSwaggerVersion(destinationSwagger);
    OpenAPI destOpenAPI;
    if (destinationSwaggerVersion == SwaggerVersion.OPEN_API) {
        destOpenAPI = ((OAS3Parser) oas3Parser).getOpenAPI(destinationSwagger);
    } else {
        throw new APIManagementException("Cannot update destination swagger because it is not in OpenAPI format");
    }
    SwaggerUpdateContext context = new SwaggerUpdateContext();
    extractRelevantSourceData(apiToProductResourceMapping, context);
    // Update paths
    destOpenAPI.setPaths(context.getPaths());
    // Update Scopes
    setScopes(destOpenAPI, context.getAggregatedScopes());
    // Update reference definitions
    setReferenceObjectDefinitions(destOpenAPI, context);
    return Json.pretty(destOpenAPI);
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) OpenAPI(io.swagger.v3.oas.models.OpenAPI)

Example 10 with OAS3Parser

use of org.wso2.carbon.apimgt.impl.definitions.OAS3Parser in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method importGraphQLSchema.

/**
 * Import a GraphQL Schema
 * @param type APIType
 * @param fileInputStream input file
 * @param fileDetail file Detail
 * @param additionalProperties api object as string format
 * @param ifMatch If--Match header value
 * @param messageContext messageContext
 * @return Response with GraphQL API
 */
@Override
public Response importGraphQLSchema(String ifMatch, String type, InputStream fileInputStream, Attachment fileDetail, String additionalProperties, MessageContext messageContext) {
    APIDTO additionalPropertiesAPI = null;
    String schema = "";
    try {
        if (fileInputStream == null || StringUtils.isBlank(additionalProperties)) {
            String errorMessage = "GraphQL schema and api details cannot be empty.";
            RestApiUtil.handleBadRequest(errorMessage, log);
        } else {
            schema = IOUtils.toString(fileInputStream, RestApiConstants.CHARSET);
        }
        if (!StringUtils.isBlank(additionalProperties) && !StringUtils.isBlank(schema)) {
            if (log.isDebugEnabled()) {
                log.debug("Deseriallizing additionalProperties: " + additionalProperties + "/n" + "importing schema: " + schema);
            }
        }
        additionalPropertiesAPI = new ObjectMapper().readValue(additionalProperties, APIDTO.class);
        additionalPropertiesAPI.setType(APIDTO.TypeEnum.GRAPHQL);
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        API apiToAdd = PublisherCommonUtils.prepareToCreateAPIByDTO(additionalPropertiesAPI, apiProvider, RestApiCommonUtil.getLoggedInUsername(), organization);
        // Save swagger definition of graphQL
        APIDefinition parser = new OAS3Parser();
        SwaggerData swaggerData = new SwaggerData(apiToAdd);
        String apiDefinition = parser.generateAPIDefinition(swaggerData);
        apiToAdd.setSwaggerDefinition(apiDefinition);
        // adding the api
        API createdApi = apiProvider.addAPI(apiToAdd);
        apiProvider.saveGraphqlSchemaDefinition(createdApi.getUuid(), schema, organization);
        APIDTO createdApiDTO = APIMappingUtil.fromAPItoDTO(createdApi);
        // This URI used to set the location header of the POST response
        URI createdApiUri = new URI(RestApiConstants.RESOURCE_PATH_APIS + "/" + createdApiDTO.getId());
        return Response.created(createdApiUri).entity(createdApiDTO).build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while adding new API : " + additionalPropertiesAPI.getProvider() + "-" + additionalPropertiesAPI.getName() + "-" + additionalPropertiesAPI.getVersion() + " - " + e.getMessage();
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    } catch (URISyntaxException e) {
        String errorMessage = "Error while retrieving API location : " + additionalPropertiesAPI.getProvider() + "-" + additionalPropertiesAPI.getName() + "-" + additionalPropertiesAPI.getVersion();
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    } catch (IOException e) {
        String errorMessage = "Error while retrieving content from file : " + additionalPropertiesAPI.getProvider() + "-" + additionalPropertiesAPI.getName() + "-" + additionalPropertiesAPI.getVersion();
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
Also used : APIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) SwaggerData(org.wso2.carbon.apimgt.api.model.SwaggerData) APIDefinition(org.wso2.carbon.apimgt.api.APIDefinition) OAS3Parser(org.wso2.carbon.apimgt.impl.definitions.OAS3Parser) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) URI(java.net.URI) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Aggregations

OAS3Parser (org.wso2.carbon.apimgt.impl.definitions.OAS3Parser)8 APIDefinition (org.wso2.carbon.apimgt.api.APIDefinition)6 IOException (java.io.IOException)5 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)5 SwaggerData (org.wso2.carbon.apimgt.api.model.SwaggerData)5 API (org.wso2.carbon.apimgt.api.model.API)4 ArrayList (java.util.ArrayList)3 Consumes (javax.ws.rs.Consumes)3 GET (javax.ws.rs.GET)3 Produces (javax.ws.rs.Produces)3 CacheControl (javax.ws.rs.core.CacheControl)3 RESTAPICacheConfiguration (org.wso2.carbon.apimgt.impl.RESTAPICacheConfiguration)3 OpenAPI (io.swagger.v3.oas.models.OpenAPI)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)2 APIDTO (org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 Gson (com.google.gson.Gson)1 Path (io.swagger.models.Path)1