use of org.wso2.carbon.apimgt.api.model.SwaggerData in project carbon-apimgt by wso2.
the class OASTestBase method testGenerateAPIDefinition2.
public void testGenerateAPIDefinition2(APIDefinition parser, String content, OASParserEvaluator evaluator) throws Exception {
JSONObject jsonObject = new JSONObject(content);
String equalNoOfResources = jsonObject.getJSONObject("equalNoOfResources").toString();
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, petPost, itemGet, itemPost)));
String definition = parser.generateAPIDefinition(new SwaggerData(api), equalNoOfResources);
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(4, uriTemplates.size());
Assert.assertTrue(uriTemplates.contains(petGet));
Assert.assertTrue(uriTemplates.contains(petPost));
Assert.assertTrue(uriTemplates.contains(itemGet));
Assert.assertTrue(uriTemplates.contains(itemPost));
Set<Scope> scopes = parser.getScopes(definition);
Assert.assertEquals(2, scopes.size());
Assert.assertTrue(scopes.contains(sampleScope));
Assert.assertTrue(scopes.contains(extensionScope));
// Remove operation and path from API object
String extraResourcesInDefinition = jsonObject.getJSONObject("extraResourcesInDefinition").toString();
api.setUriTemplates(new HashSet<>(Arrays.asList(itemGet, itemPost)));
definition = parser.generateAPIDefinition(new SwaggerData(api), extraResourcesInDefinition);
response = parser.validateAPIDefinition(definition, false);
Assert.assertTrue(response.isValid());
Assert.assertTrue(response.getParser().getClass().equals(parser.getClass()));
uriTemplates = parser.getURITemplates(definition);
Assert.assertEquals(2, uriTemplates.size());
// assert generated paths
if (evaluator != null) {
evaluator.eval(definition);
}
Iterator iterator = uriTemplates.iterator();
while (iterator.hasNext()) {
URITemplate element = (URITemplate) iterator.next();
if ("/pets".equalsIgnoreCase(element.getUriTemplate())) {
Assert.fail("Removed paths from API operation should not present.");
}
if ("/items".equalsIgnoreCase(element.getUriTemplate()) && "PUT".equalsIgnoreCase(element.getHTTPVerb())) {
Assert.fail("Removed item from API operation should not present.");
}
}
Assert.assertTrue(uriTemplates.contains(itemGet));
Assert.assertTrue(uriTemplates.contains(itemPost));
// Add operation and path to API object
String lessResourcesInDefinition = jsonObject.getJSONObject("lessResourcesInDefinition").toString();
api.setUriTemplates(new HashSet<>(Arrays.asList(petGet, petPost, itemGet, itemPost)));
definition = parser.generateAPIDefinition(new SwaggerData(api), lessResourcesInDefinition);
response = parser.validateAPIDefinition(definition, false);
Assert.assertTrue(response.isValid());
Assert.assertTrue(response.getParser().getClass().equals(parser.getClass()));
uriTemplates = parser.getURITemplates(definition);
Assert.assertEquals(4, uriTemplates.size());
Assert.assertTrue(uriTemplates.contains(petGet));
Assert.assertTrue(uriTemplates.contains(petPost));
Assert.assertTrue(uriTemplates.contains(itemGet));
Assert.assertTrue(uriTemplates.contains(itemPost));
}
use of org.wso2.carbon.apimgt.api.model.SwaggerData in project carbon-apimgt by wso2.
the class PublisherCommonUtils method updateApi.
/**
* Update an API.
*
* @param originalAPI Existing API
* @param apiDtoToUpdate New API DTO to update
* @param apiProvider API Provider
* @param tokenScopes Scopes of the token
* @throws ParseException If an error occurs while parsing the endpoint configuration
* @throws CryptoException If an error occurs while encrypting the secret key of API
* @throws APIManagementException If an error occurs while updating the API
* @throws FaultGatewaysException If an error occurs while updating manage of an existing API
*/
public static API updateApi(API originalAPI, APIDTO apiDtoToUpdate, APIProvider apiProvider, String[] tokenScopes) throws ParseException, CryptoException, APIManagementException, FaultGatewaysException {
APIIdentifier apiIdentifier = originalAPI.getId();
// Validate if the USER_REST_API_SCOPES is not set in WebAppAuthenticator when scopes are validated
if (tokenScopes == null) {
throw new APIManagementException("Error occurred while updating the API " + originalAPI.getUUID() + " as the token information hasn't been correctly set internally", ExceptionCodes.TOKEN_SCOPES_NOT_SET);
}
boolean isGraphql = originalAPI.getType() != null && APIConstants.APITransportType.GRAPHQL.toString().equals(originalAPI.getType());
boolean isAsyncAPI = originalAPI.getType() != null && (APIConstants.APITransportType.WS.toString().equals(originalAPI.getType()) || APIConstants.APITransportType.WEBSUB.toString().equals(originalAPI.getType()) || APIConstants.APITransportType.SSE.toString().equals(originalAPI.getType()) || APIConstants.APITransportType.ASYNC.toString().equals(originalAPI.getType()));
Scope[] apiDtoClassAnnotatedScopes = APIDTO.class.getAnnotationsByType(Scope.class);
boolean hasClassLevelScope = checkClassScopeAnnotation(apiDtoClassAnnotatedScopes, tokenScopes);
JSONParser parser = new JSONParser();
String oldEndpointConfigString = originalAPI.getEndpointConfig();
JSONObject oldEndpointConfig = null;
if (StringUtils.isNotBlank(oldEndpointConfigString)) {
oldEndpointConfig = (JSONObject) parser.parse(oldEndpointConfigString);
}
String oldProductionApiSecret = null;
String oldSandboxApiSecret = null;
if (oldEndpointConfig != null) {
if ((oldEndpointConfig.containsKey(APIConstants.ENDPOINT_SECURITY))) {
JSONObject oldEndpointSecurity = (JSONObject) oldEndpointConfig.get(APIConstants.ENDPOINT_SECURITY);
if (oldEndpointSecurity.containsKey(APIConstants.OAuthConstants.ENDPOINT_SECURITY_PRODUCTION)) {
JSONObject oldEndpointSecurityProduction = (JSONObject) oldEndpointSecurity.get(APIConstants.OAuthConstants.ENDPOINT_SECURITY_PRODUCTION);
if (oldEndpointSecurityProduction.get(APIConstants.OAuthConstants.OAUTH_CLIENT_ID) != null && oldEndpointSecurityProduction.get(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET) != null) {
oldProductionApiSecret = oldEndpointSecurityProduction.get(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET).toString();
}
}
if (oldEndpointSecurity.containsKey(APIConstants.OAuthConstants.ENDPOINT_SECURITY_SANDBOX)) {
JSONObject oldEndpointSecuritySandbox = (JSONObject) oldEndpointSecurity.get(APIConstants.OAuthConstants.ENDPOINT_SECURITY_SANDBOX);
if (oldEndpointSecuritySandbox.get(APIConstants.OAuthConstants.OAUTH_CLIENT_ID) != null && oldEndpointSecuritySandbox.get(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET) != null) {
oldSandboxApiSecret = oldEndpointSecuritySandbox.get(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET).toString();
}
}
}
}
Map endpointConfig = (Map) apiDtoToUpdate.getEndpointConfig();
CryptoUtil cryptoUtil = CryptoUtil.getDefaultCryptoUtil();
// OAuth 2.0 backend protection: API Key and API Secret encryption
encryptEndpointSecurityOAuthCredentials(endpointConfig, cryptoUtil, oldProductionApiSecret, oldSandboxApiSecret, apiDtoToUpdate);
// AWS Lambda: secret key encryption while updating the API
if (apiDtoToUpdate.getEndpointConfig() != null) {
if (endpointConfig.containsKey(APIConstants.AMZN_SECRET_KEY)) {
String secretKey = (String) endpointConfig.get(APIConstants.AMZN_SECRET_KEY);
if (!StringUtils.isEmpty(secretKey)) {
if (!APIConstants.AWS_SECRET_KEY.equals(secretKey)) {
String encryptedSecretKey = cryptoUtil.encryptAndBase64Encode(secretKey.getBytes());
endpointConfig.put(APIConstants.AMZN_SECRET_KEY, encryptedSecretKey);
apiDtoToUpdate.setEndpointConfig(endpointConfig);
} else {
JSONParser jsonParser = new JSONParser();
JSONObject originalEndpointConfig = (JSONObject) jsonParser.parse(originalAPI.getEndpointConfig());
String encryptedSecretKey = (String) originalEndpointConfig.get(APIConstants.AMZN_SECRET_KEY);
endpointConfig.put(APIConstants.AMZN_SECRET_KEY, encryptedSecretKey);
apiDtoToUpdate.setEndpointConfig(endpointConfig);
}
}
}
}
if (!hasClassLevelScope) {
// Validate per-field scopes
apiDtoToUpdate = getFieldOverriddenAPIDTO(apiDtoToUpdate, originalAPI, tokenScopes);
}
// API Name change not allowed if OnPrem
if (APIUtil.isOnPremResolver()) {
apiDtoToUpdate.setName(apiIdentifier.getApiName());
}
apiDtoToUpdate.setVersion(apiIdentifier.getVersion());
apiDtoToUpdate.setProvider(apiIdentifier.getProviderName());
apiDtoToUpdate.setContext(originalAPI.getContextTemplate());
apiDtoToUpdate.setLifeCycleStatus(originalAPI.getStatus());
apiDtoToUpdate.setType(APIDTO.TypeEnum.fromValue(originalAPI.getType()));
List<APIResource> removedProductResources = getRemovedProductResources(apiDtoToUpdate, originalAPI);
if (!removedProductResources.isEmpty()) {
throw new APIManagementException("Cannot remove following resource paths " + removedProductResources.toString() + " because they are used by one or more API Products", ExceptionCodes.from(ExceptionCodes.API_PRODUCT_USED_RESOURCES, originalAPI.getId().getApiName(), originalAPI.getId().getVersion()));
}
// Validate API Security
List<String> apiSecurity = apiDtoToUpdate.getSecurityScheme();
// validation for tiers
List<String> tiersFromDTO = apiDtoToUpdate.getPolicies();
String originalStatus = originalAPI.getStatus();
if (apiSecurity.contains(APIConstants.DEFAULT_API_SECURITY_OAUTH2) || apiSecurity.contains(APIConstants.API_SECURITY_API_KEY)) {
if ((tiersFromDTO == null || tiersFromDTO.isEmpty() && !(APIConstants.CREATED.equals(originalStatus) || APIConstants.PROTOTYPED.equals(originalStatus))) && !apiDtoToUpdate.getAdvertiseInfo().isAdvertised()) {
throw new APIManagementException("A tier should be defined if the API is not in CREATED or PROTOTYPED state", ExceptionCodes.TIER_CANNOT_BE_NULL);
}
}
if (tiersFromDTO != null && !tiersFromDTO.isEmpty()) {
// check whether the added API's tiers are all valid
Set<Tier> definedTiers = apiProvider.getTiers();
List<String> invalidTiers = getInvalidTierNames(definedTiers, tiersFromDTO);
if (invalidTiers.size() > 0) {
throw new APIManagementException("Specified tier(s) " + Arrays.toString(invalidTiers.toArray()) + " are invalid", ExceptionCodes.TIER_NAME_INVALID);
}
}
if (apiDtoToUpdate.getAccessControlRoles() != null) {
String errorMessage = validateUserRoles(apiDtoToUpdate.getAccessControlRoles());
if (!errorMessage.isEmpty()) {
throw new APIManagementException(errorMessage, ExceptionCodes.INVALID_USER_ROLES);
}
}
if (apiDtoToUpdate.getVisibleRoles() != null) {
String errorMessage = validateRoles(apiDtoToUpdate.getVisibleRoles());
if (!errorMessage.isEmpty()) {
throw new APIManagementException(errorMessage, ExceptionCodes.INVALID_USER_ROLES);
}
}
if (apiDtoToUpdate.getAdditionalProperties() != null) {
String errorMessage = validateAdditionalProperties(apiDtoToUpdate.getAdditionalProperties());
if (!errorMessage.isEmpty()) {
throw new APIManagementException(errorMessage, ExceptionCodes.from(ExceptionCodes.INVALID_ADDITIONAL_PROPERTIES, apiDtoToUpdate.getName(), apiDtoToUpdate.getVersion()));
}
}
// Validate if resources are empty
if (apiDtoToUpdate.getOperations() == null || apiDtoToUpdate.getOperations().isEmpty()) {
throw new APIManagementException(ExceptionCodes.NO_RESOURCES_FOUND);
}
API apiToUpdate = APIMappingUtil.fromDTOtoAPI(apiDtoToUpdate, apiIdentifier.getProviderName());
if (APIConstants.PUBLIC_STORE_VISIBILITY.equals(apiToUpdate.getVisibility())) {
apiToUpdate.setVisibleRoles(StringUtils.EMPTY);
}
apiToUpdate.setUUID(originalAPI.getUUID());
apiToUpdate.setOrganization(originalAPI.getOrganization());
validateScopes(apiToUpdate);
apiToUpdate.setThumbnailUrl(originalAPI.getThumbnailUrl());
if (apiDtoToUpdate.getKeyManagers() instanceof List) {
apiToUpdate.setKeyManagers((List<String>) apiDtoToUpdate.getKeyManagers());
} else {
apiToUpdate.setKeyManagers(Collections.singletonList(APIConstants.KeyManager.API_LEVEL_ALL_KEY_MANAGERS));
}
if (!isAsyncAPI) {
String oldDefinition = apiProvider.getOpenAPIDefinition(apiToUpdate.getUuid(), originalAPI.getOrganization());
APIDefinition apiDefinition = OASParserUtil.getOASParser(oldDefinition);
SwaggerData swaggerData = new SwaggerData(apiToUpdate);
String newDefinition = apiDefinition.generateAPIDefinition(swaggerData, oldDefinition);
apiProvider.saveSwaggerDefinition(apiToUpdate, newDefinition, originalAPI.getOrganization());
if (!isGraphql) {
Set<URITemplate> uriTemplates = apiDefinition.getURITemplates(newDefinition);
// set operation policies from the original API Payload
Set<URITemplate> uriTemplatesFromPayload = apiToUpdate.getUriTemplates();
Map<String, List<OperationPolicy>> operationPoliciesPerURITemplate = new HashMap<>();
for (URITemplate uriTemplate : uriTemplatesFromPayload) {
if (!uriTemplate.getOperationPolicies().isEmpty()) {
String key = uriTemplate.getHTTPVerb() + ":" + uriTemplate.getUriTemplate();
operationPoliciesPerURITemplate.put(key, uriTemplate.getOperationPolicies());
}
}
for (URITemplate uriTemplate : uriTemplates) {
String key = uriTemplate.getHTTPVerb() + ":" + uriTemplate.getUriTemplate();
if (operationPoliciesPerURITemplate.containsKey(key)) {
uriTemplate.setOperationPolicies(operationPoliciesPerURITemplate.get(key));
}
}
apiToUpdate.setUriTemplates(uriTemplates);
}
} else {
String oldDefinition = apiProvider.getAsyncAPIDefinition(apiToUpdate.getUuid(), originalAPI.getOrganization());
AsyncApiParser asyncApiParser = new AsyncApiParser();
String updateAsyncAPIDefinition = asyncApiParser.updateAsyncAPIDefinition(oldDefinition, apiToUpdate);
apiProvider.saveAsyncApiDefinition(originalAPI, updateAsyncAPIDefinition);
}
apiToUpdate.setWsdlUrl(apiDtoToUpdate.getWsdlUrl());
// validate API categories
List<APICategory> apiCategories = apiToUpdate.getApiCategories();
List<APICategory> apiCategoriesList = new ArrayList<>();
for (APICategory category : apiCategories) {
category.setOrganization(originalAPI.getOrganization());
apiCategoriesList.add(category);
}
apiToUpdate.setApiCategories(apiCategoriesList);
if (apiCategoriesList.size() > 0) {
if (!APIUtil.validateAPICategories(apiCategoriesList, originalAPI.getOrganization())) {
throw new APIManagementException("Invalid API Category name(s) defined", ExceptionCodes.from(ExceptionCodes.API_CATEGORY_INVALID));
}
}
apiToUpdate.setOrganization(originalAPI.getOrganization());
apiProvider.updateAPI(apiToUpdate, originalAPI);
return apiProvider.getAPIbyUUID(originalAPI.getUuid(), originalAPI.getOrganization());
// TODO use returend api
}
use of org.wso2.carbon.apimgt.api.model.SwaggerData in project carbon-apimgt by wso2.
the class PublisherCommonUtils method updateSwagger.
/**
* update swagger definition of the given api.
*
* @param apiId API Id
* @param response response of a swagger definition validation call
* @param organization Organization Identifier
* @return updated swagger definition
* @throws APIManagementException when error occurred updating swagger
* @throws FaultGatewaysException when error occurred publishing API to the gateway
*/
public static String updateSwagger(String apiId, APIDefinitionValidationResponse response, boolean isServiceAPI, String organization) throws APIManagementException, FaultGatewaysException {
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
// this will fail if user does not have access to the API or the API does not exist
API existingAPI = apiProvider.getAPIbyUUID(apiId, organization);
APIDefinition oasParser = response.getParser();
String apiDefinition = response.getJsonContent();
if (isServiceAPI) {
apiDefinition = oasParser.copyVendorExtensions(existingAPI.getSwaggerDefinition(), apiDefinition);
} else {
apiDefinition = OASParserUtil.preProcess(apiDefinition);
}
if (APIConstants.API_TYPE_SOAPTOREST.equals(existingAPI.getType())) {
List<SOAPToRestSequence> sequenceList = SequenceGenerator.generateSequencesFromSwagger(apiDefinition);
existingAPI.setSoapToRestSequences(sequenceList);
}
Set<URITemplate> uriTemplates = null;
uriTemplates = oasParser.getURITemplates(apiDefinition);
if (uriTemplates == null || uriTemplates.isEmpty()) {
throw new APIManagementException(ExceptionCodes.NO_RESOURCES_FOUND);
}
Set<org.wso2.carbon.apimgt.api.model.Scope> scopes = oasParser.getScopes(apiDefinition);
// validating scope roles
for (org.wso2.carbon.apimgt.api.model.Scope scope : scopes) {
String roles = scope.getRoles();
if (roles != null) {
for (String aRole : roles.split(",")) {
boolean isValidRole = APIUtil.isRoleNameExist(RestApiCommonUtil.getLoggedInUsername(), aRole);
if (!isValidRole) {
throw new APIManagementException("Role '" + aRole + "' Does not exist.");
}
}
}
}
List<APIResource> removedProductResources = apiProvider.getRemovedProductResources(uriTemplates, existingAPI);
if (!removedProductResources.isEmpty()) {
throw new APIManagementException("Cannot remove following resource paths " + removedProductResources.toString() + " because they are used by one or more API Products", ExceptionCodes.from(ExceptionCodes.API_PRODUCT_USED_RESOURCES, existingAPI.getId().getApiName(), existingAPI.getId().getVersion()));
}
// set existing operation policies to URI templates
apiProvider.setOperationPoliciesToURITemplates(apiId, uriTemplates);
existingAPI.setUriTemplates(uriTemplates);
existingAPI.setScopes(scopes);
PublisherCommonUtils.validateScopes(existingAPI);
// Update API is called to update URITemplates and scopes of the API
SwaggerData swaggerData = new SwaggerData(existingAPI);
String updatedApiDefinition = oasParser.populateCustomManagementInfo(apiDefinition, swaggerData);
apiProvider.saveSwaggerDefinition(existingAPI, updatedApiDefinition, organization);
existingAPI.setSwaggerDefinition(updatedApiDefinition);
API unModifiedAPI = apiProvider.getAPIbyUUID(apiId, organization);
existingAPI.setStatus(unModifiedAPI.getStatus());
apiProvider.updateAPI(existingAPI, unModifiedAPI);
// retrieves the updated swagger definition
// TODO see why we need to get it
String apiSwagger = apiProvider.getOpenAPIDefinition(apiId, organization);
// instead of passing same
return oasParser.getOASDefinitionForPublisher(existingAPI, apiSwagger);
}
use of org.wso2.carbon.apimgt.api.model.SwaggerData 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;
}
use of org.wso2.carbon.apimgt.api.model.SwaggerData 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));
}
Aggregations