Search in sources :

Example 71 with APIDefinition

use of org.wso2.carbon.apimgt.api.doc.model.APIDefinition 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 72 with APIDefinition

use of org.wso2.carbon.apimgt.api.doc.model.APIDefinition 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 73 with APIDefinition

use of org.wso2.carbon.apimgt.api.doc.model.APIDefinition in project carbon-apimgt by wso2.

the class OASTestBase method testGenerateAPIDefinition.

public void testGenerateAPIDefinition(APIDefinition parser) throws Exception {
    APIIdentifier identifier = new APIIdentifier("admin", "simple", "1.0.0");
    API api = new API(identifier);
    api.setScopes(new HashSet<>(Arrays.asList(sampleScope, extensionScope)));
    api.setUriTemplates(new HashSet<>(Arrays.asList(petGet)));
    String definition = parser.generateAPIDefinition(new SwaggerData(api));
    APIDefinitionValidationResponse response = parser.validateAPIDefinition(definition, false);
    Assert.assertTrue(response.isValid());
    Assert.assertTrue(response.getParser().getClass().equals(parser.getClass()));
    Set<URITemplate> uriTemplates = parser.getURITemplates(definition);
    Assert.assertEquals(1, uriTemplates.size());
    Assert.assertTrue(uriTemplates.contains(petGet));
    Set<Scope> scopes = parser.getScopes(definition);
    Assert.assertEquals(2, scopes.size());
    Assert.assertTrue(scopes.contains(sampleScope));
    Assert.assertTrue(scopes.contains(extensionScope));
}
Also used : Scope(org.wso2.carbon.apimgt.api.model.Scope) SwaggerData(org.wso2.carbon.apimgt.api.model.SwaggerData) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) API(org.wso2.carbon.apimgt.api.model.API) APIDefinitionValidationResponse(org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse)

Example 74 with APIDefinition

use of org.wso2.carbon.apimgt.api.doc.model.APIDefinition in project carbon-apimgt by wso2.

the class OASTestBase method testGenerateAPIDefinitionWithExtension.

public String testGenerateAPIDefinitionWithExtension(APIDefinition parser, String content) throws Exception {
    JSONObject jsonObject = new JSONObject(content);
    String equalNoOfResourcesWithExtension = jsonObject.getJSONObject("equalNoOfResourcesWithExtension").toString();
    Scope newScope = new Scope();
    newScope.setName("newScope");
    newScope.setKey("newScope");
    newScope.setRoles("admin");
    newScope.setDescription("newScopeDescription");
    URITemplate updatedItemGet = new URITemplate();
    updatedItemGet.setUriTemplate("/items");
    updatedItemGet.setAuthType("Application & Application User");
    updatedItemGet.setAuthTypes("Application & Application User");
    updatedItemGet.setHTTPVerb("GET");
    updatedItemGet.setHttpVerbs("GET");
    updatedItemGet.setThrottlingTier("Unlimited");
    updatedItemGet.setThrottlingTiers("Unlimited");
    updatedItemGet.setScope(newScope);
    updatedItemGet.setScopes(newScope);
    APIIdentifier identifier = new APIIdentifier("admin", "simple", "1.0.0");
    API api = new API(identifier);
    api.setScopes(new HashSet<>(Arrays.asList(sampleScope, extensionScope, newScope)));
    api.setUriTemplates(new HashSet<>(Arrays.asList(petPost, updatedItemGet)));
    String definition = parser.generateAPIDefinition(new SwaggerData(api), equalNoOfResourcesWithExtension);
    APIDefinitionValidationResponse response = parser.validateAPIDefinition(definition, false);
    Assert.assertTrue(response.isValid());
    return definition;
}
Also used : JSONObject(org.json.JSONObject) Scope(org.wso2.carbon.apimgt.api.model.Scope) SwaggerData(org.wso2.carbon.apimgt.api.model.SwaggerData) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) API(org.wso2.carbon.apimgt.api.model.API) APIDefinitionValidationResponse(org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse)

Example 75 with APIDefinition

use of org.wso2.carbon.apimgt.api.doc.model.APIDefinition in project carbon-apimgt by wso2.

the class OASParserUtil method getSwaggerVersion.

public static SwaggerVersion getSwaggerVersion(String apiDefinition) throws APIManagementException {
    ObjectMapper mapper;
    if (apiDefinition.trim().startsWith("{")) {
        mapper = ObjectMapperFactory.createJson();
    } else {
        mapper = ObjectMapperFactory.createYaml();
    }
    JsonNode rootNode;
    try {
        rootNode = mapper.readTree(apiDefinition.getBytes());
    } catch (IOException e) {
        throw new APIManagementException("Error occurred while parsing OAS definition", e);
    }
    ObjectNode node = (ObjectNode) rootNode;
    JsonNode openapi = node.get("openapi");
    if (openapi != null && openapi.asText().startsWith("3.")) {
        return SwaggerVersion.OPEN_API;
    }
    JsonNode swagger = node.get("swagger");
    if (swagger != null) {
        return SwaggerVersion.SWAGGER;
    }
    throw new APIManagementException("Invalid OAS definition provided.");
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) JsonNode(com.fasterxml.jackson.databind.JsonNode) IOException(java.io.IOException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)32 HashMap (java.util.HashMap)30 APIDefinition (org.wso2.carbon.apimgt.api.APIDefinition)30 API (org.wso2.carbon.apimgt.core.models.API)30 CompositeAPI (org.wso2.carbon.apimgt.core.models.CompositeAPI)25 ArrayList (java.util.ArrayList)23 API (org.wso2.carbon.apimgt.api.model.API)20 Map (java.util.Map)19 IOException (java.io.IOException)18 Test (org.testng.annotations.Test)18 ApiDAO (org.wso2.carbon.apimgt.core.dao.ApiDAO)18 URITemplate (org.wso2.carbon.apimgt.api.model.URITemplate)16 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)15 Scope (org.wso2.carbon.apimgt.api.model.Scope)15 HashSet (java.util.HashSet)13 APIPolicy (org.wso2.carbon.apimgt.core.models.policy.APIPolicy)13 APIDefinitionValidationResponse (org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse)12 SwaggerData (org.wso2.carbon.apimgt.api.model.SwaggerData)12 BusinessInformation (org.wso2.carbon.apimgt.core.models.BusinessInformation)12 CorsConfiguration (org.wso2.carbon.apimgt.core.models.CorsConfiguration)12