Search in sources :

Example 6 with AsyncApiParser

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

the class PublisherCommonUtils method updateAsyncAPIDefinition.

/**
 * update AsyncPI definition of the given api.
 *
 * @param apiId    API Id
 * @param response response of the AsyncAPI definition validation call
 * @param organization identifier of the organization
 * @return updated AsyncAPI definition
 * @throws APIManagementException when error occurred updating AsyncAPI definition
 * @throws FaultGatewaysException when error occurred publishing API to the gateway
 */
public static String updateAsyncAPIDefinition(String apiId, APIDefinitionValidationResponse response, String organization) throws APIManagementException, FaultGatewaysException {
    APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
    // this will fall if user does not have access to the API or the API does not exist
    API existingAPI = apiProvider.getAPIbyUUID(apiId, organization);
    existingAPI.setOrganization(organization);
    String apiDefinition = response.getJsonContent();
    AsyncApiParser asyncApiParser = new AsyncApiParser();
    // Set uri templates
    Set<URITemplate> uriTemplates = asyncApiParser.getURITemplates(apiDefinition, APIConstants.API_TYPE_WS.equals(existingAPI.getType()) || !APIConstants.WSO2_GATEWAY_ENVIRONMENT.equals(existingAPI.getGatewayVendor()));
    if (uriTemplates == null || uriTemplates.isEmpty()) {
        throw new APIManagementException(ExceptionCodes.NO_RESOURCES_FOUND);
    }
    existingAPI.setUriTemplates(uriTemplates);
    // Update ws uri mapping
    existingAPI.setWsUriMapping(asyncApiParser.buildWSUriMapping(apiDefinition));
    // updating APi with the new AsyncAPI definition
    existingAPI.setAsyncApiDefinition(apiDefinition);
    apiProvider.saveAsyncApiDefinition(existingAPI, apiDefinition);
    apiProvider.updateAPI(existingAPI);
    // retrieves the updated AsyncAPI definition
    return apiProvider.getAsyncAPIDefinition(existingAPI.getId().getUUID(), organization);
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) API(org.wso2.carbon.apimgt.api.model.API) AsyncApiParser(org.wso2.carbon.apimgt.impl.definitions.AsyncApiParser) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 7 with AsyncApiParser

use of org.wso2.carbon.apimgt.impl.definitions.AsyncApiParser 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 8 with AsyncApiParser

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

the class AsyncApiParserTest method testGetAsyncAPIDefinitionForStore.

@Test
public void testGetAsyncAPIDefinitionForStore() throws Exception {
    Map<String, String> hostsWithSchemes = new HashMap<>();
    hostsWithSchemes.put("ws", "ws://localhost:9099");
    hostsWithSchemes.put("wss", "wss://localhost:8099");
    APIIdentifier identifier = new APIIdentifier("admin", "HelloServer2", "1.0");
    API api = new API(identifier);
    api.setType("WS");
    api.setContext("/hello2/1.0");
    api.setTransports("ws,wss");
    api.setEndpointConfig("{'endpoint_type':'http','sandbox_endpoints':{'url':'wss://echo.websocket.org:443'}," + "'production_endpoints':{'url':'wss://echo.websocket.org:443'}}");
    AsyncApiParser asyncApiParser = new AsyncApiParser();
    String asyncAPIDefinition = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("definitions" + File.separator + "asyncAPI" + File.separator + "sampleWebSocket.json"), "UTF-8");
    api.setAsyncApiDefinition(asyncAPIDefinition);
    String definitionForStore = asyncApiParser.getAsyncApiDefinitionForStore(api, asyncAPIDefinition, hostsWithSchemes);
    Assert.assertNotNull(definitionForStore);
}
Also used : HashMap(java.util.HashMap) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) API(org.wso2.carbon.apimgt.api.model.API) Test(org.junit.Test)

Aggregations

API (org.wso2.carbon.apimgt.api.model.API)8 HashMap (java.util.HashMap)5 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)5 Test (org.junit.Test)4 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)4 AsyncApiParser (org.wso2.carbon.apimgt.impl.definitions.AsyncApiParser)4 LinkedHashMap (java.util.LinkedHashMap)3 Map (java.util.Map)3 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)3 ArrayList (java.util.ArrayList)2 APIDefinition (org.wso2.carbon.apimgt.api.APIDefinition)2 APICategory (org.wso2.carbon.apimgt.api.model.APICategory)2 SwaggerData (org.wso2.carbon.apimgt.api.model.SwaggerData)2 URITemplate (org.wso2.carbon.apimgt.api.model.URITemplate)2 CryptoUtil (org.wso2.carbon.core.util.CryptoUtil)2 List (java.util.List)1 JSONException (org.json.JSONException)1 JSONObject (org.json.simple.JSONObject)1 JSONParser (org.json.simple.parser.JSONParser)1 APIDefinitionValidationResponse (org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse)1