use of org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse 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.APIDefinitionValidationResponse in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method validateAsyncAPISpecification.
/**
* Validate the provided AsyncAPI specification (via file or url) and return a Map with the validation response
* information
*
* @param url AsyncAPI specification url
* @param fileInputStream file as input stream
* @param returnContent whether to return the content of the definition in the response DTO
* @param isServiceAPI whether the request is to create API from a service in Service Catalog
* @return Map with the validation response information. A value with key 'dto' will have the response DTO
* of type AsyncAPISpecificationValidationResponseDTO for the REST API. A value with the key 'model' will have the
* validation response of type APIDefinitionValidationResponse coming from the impl level
*/
private Map validateAsyncAPISpecification(String url, InputStream fileInputStream, Attachment fileDetail, Boolean returnContent, Boolean isServiceAPI) throws APIManagementException {
// validate inputs
handleInvalidParams(fileInputStream, fileDetail, url, null, isServiceAPI);
AsyncAPISpecificationValidationResponseDTO responseDTO;
APIDefinitionValidationResponse validationResponse = new APIDefinitionValidationResponse();
String schemaToBeValidated = null;
if (url != null) {
// validate URL
validationResponse = AsyncApiParserUtil.validateAsyncAPISpecificationByURL(url, returnContent);
} else if (fileInputStream != null) {
// validate file
String fileName = fileDetail != null ? fileDetail.getContentDisposition().getFilename() : StringUtils.EMPTY;
try {
if (isServiceAPI || fileName.endsWith(APIConstants.YAML_FILE_EXTENSION) || fileName.endsWith(APIConstants.YML_FILE_EXTENSION)) {
// convert .yml or .yaml to JSON for validation
ObjectMapper yamlReader = new ObjectMapper(new YAMLFactory());
Object obj = yamlReader.readValue(fileInputStream, Object.class);
ObjectMapper jsonWriter = new ObjectMapper();
schemaToBeValidated = jsonWriter.writeValueAsString(obj);
} else if (fileName.endsWith(APIConstants.JSON_FILE_EXTENSION)) {
// continue with .json
JSONTokener jsonDataFile = new JSONTokener(fileInputStream);
schemaToBeValidated = new org.json.JSONObject(jsonDataFile).toString();
}
validationResponse = AsyncApiParserUtil.validateAsyncAPISpecification(schemaToBeValidated, returnContent);
} catch (IOException e) {
// error while reading the schemas
RestApiUtil.handleInternalServerError("Error while reading file content", e, log);
}
}
responseDTO = APIMappingUtil.getAsyncAPISpecificationValidationResponseFromModel(validationResponse, returnContent);
Map response = new HashMap();
response.put(RestApiConstants.RETURN_MODEL, validationResponse);
response.put(RestApiConstants.RETURN_DTO, responseDTO);
return response;
}
use of org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method importAsyncAPISpecification.
private APIDTO importAsyncAPISpecification(InputStream definition, String definitionUrl, APIDTO apiDTOFromProperties, Attachment fileDetail, ServiceEntry service, String organization) {
// validate and retrieve the AsyncAPI specification
Map validationResponseMap = null;
boolean isServiceAPI = false;
try {
if (service != null) {
isServiceAPI = true;
}
validationResponseMap = validateAsyncAPISpecification(definitionUrl, definition, fileDetail, true, isServiceAPI);
} catch (APIManagementException e) {
RestApiUtil.handleInternalServerError("Error occurred while validating API Definition", e, log);
}
AsyncAPISpecificationValidationResponseDTO validationResponseDTO = (AsyncAPISpecificationValidationResponseDTO) validationResponseMap.get(RestApiConstants.RETURN_DTO);
APIDefinitionValidationResponse validationResponse = (APIDefinitionValidationResponse) validationResponseMap.get(RestApiConstants.RETURN_MODEL);
if (!validationResponseDTO.isIsValid()) {
ErrorDTO errorDTO = APIMappingUtil.getErrorDTOFromErrorListItems(validationResponseDTO.getErrors());
throw RestApiUtil.buildBadRequestException(errorDTO);
}
// Import the API and Definition
try {
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
String definitionToAdd = validationResponse.getJsonContent();
String protocol = validationResponse.getProtocol();
if (isServiceAPI) {
apiDTOFromProperties.setType(PublisherCommonUtils.getAPIType(service.getDefinitionType(), protocol));
}
if (!APIConstants.WSO2_GATEWAY_ENVIRONMENT.equals(apiDTOFromProperties.getGatewayVendor())) {
apiDTOFromProperties.getPolicies().add(APIConstants.DEFAULT_SUB_POLICY_ASYNC_UNLIMITED);
apiDTOFromProperties.setAsyncTransportProtocols(AsyncApiParser.getTransportProtocolsForAsyncAPI(definitionToAdd));
}
API apiToAdd = PublisherCommonUtils.prepareToCreateAPIByDTO(apiDTOFromProperties, apiProvider, RestApiCommonUtil.getLoggedInUsername(), organization);
if (isServiceAPI) {
apiToAdd.setServiceInfo("key", service.getKey());
apiToAdd.setServiceInfo("md5", service.getMd5());
if (!APIConstants.API_TYPE_WEBSUB.equals(protocol.toUpperCase())) {
apiToAdd.setEndpointConfig(PublisherCommonUtils.constructEndpointConfigForService(service.getServiceUrl(), protocol));
}
}
apiToAdd.setAsyncApiDefinition(definitionToAdd);
// load topics from AsyncAPI
apiToAdd.setUriTemplates(new AsyncApiParser().getURITemplates(definitionToAdd, APIConstants.API_TYPE_WS.equals(apiToAdd.getType()) || !APIConstants.WSO2_GATEWAY_ENVIRONMENT.equals(apiToAdd.getGatewayVendor())));
apiToAdd.setOrganization(organization);
apiToAdd.setAsyncApiDefinition(definitionToAdd);
apiProvider.addAPI(apiToAdd);
return APIMappingUtil.fromAPItoDTO(apiProvider.getAPIbyUUID(apiToAdd.getUuid(), organization));
} catch (APIManagementException e) {
String errorMessage = "Error while adding new API : " + apiDTOFromProperties.getProvider() + "-" + apiDTOFromProperties.getName() + "-" + apiDTOFromProperties.getVersion() + " - " + e.getMessage();
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
return null;
}
use of org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method apisApiIdAsyncapiPut.
@Override
public Response apisApiIdAsyncapiPut(String apiId, String ifMatch, String apiDefinition, String url, InputStream fileInputStream, Attachment fileDetail, MessageContext messageContext) throws APIManagementException {
try {
String updatedAsyncAPIDefinition;
String organization = RestApiUtil.getValidatedOrganization(messageContext);
// validate if api exists
APIInfo apiInfo = validateAPIExistence(apiId);
// validate API update operation permitted based on the LC state
validateAPIOperationsPerLC(apiInfo.getStatus().toString());
// Handle URL and file based definition imports
if (url != null || fileInputStream != null) {
// Validate and retrieve the AsyncAPI definition
Map validationResponseMap = validateAsyncAPISpecification(url, fileInputStream, fileDetail, true, false);
APIDefinitionValidationResponse validationResponse = (APIDefinitionValidationResponse) validationResponseMap.get(RestApiConstants.RETURN_MODEL);
if (!validationResponse.isValid()) {
RestApiUtil.handleBadRequest(validationResponse.getErrorItems(), log);
}
updatedAsyncAPIDefinition = PublisherCommonUtils.updateAsyncAPIDefinition(apiId, validationResponse, organization);
} else {
updatedAsyncAPIDefinition = updateAsyncAPIDefinition(apiId, apiDefinition, organization);
}
return Response.ok().entity(updatedAsyncAPIDefinition).build();
} catch (APIManagementException e) {
// to expose the existence of the resource
if (RestApiUtil.isDueToResourceNotFound(e) || RestApiUtil.isDueToAuthorizationFailure(e)) {
RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API, apiId, e, log);
} else if (isAuthorizationFailure(e)) {
RestApiUtil.handleAuthorizationFailure("Authorization failure while updating AsyncAPI definition of API: " + apiId, e, log);
} else {
String errorMessage = "Error while updating the AsyncAPI definition of the API: " + apiId + " - " + e.getMessage();
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
} catch (FaultGatewaysException e) {
String errorMessage = "Error while updating API : " + apiId;
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
return null;
}
use of org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method importOpenAPIDefinition.
private APIDTO importOpenAPIDefinition(InputStream definition, String definitionUrl, String inlineDefinition, APIDTO apiDTOFromProperties, Attachment fileDetail, ServiceEntry service, String organization) throws APIManagementException {
// Validate and retrieve the OpenAPI definition
Map validationResponseMap = null;
boolean isServiceAPI = false;
try {
if (service != null) {
isServiceAPI = true;
}
validationResponseMap = validateOpenAPIDefinition(definitionUrl, definition, fileDetail, inlineDefinition, true, isServiceAPI);
} catch (APIManagementException e) {
RestApiUtil.handleInternalServerError("Error occurred while validating API Definition", e, log);
}
OpenAPIDefinitionValidationResponseDTO validationResponseDTO = (OpenAPIDefinitionValidationResponseDTO) validationResponseMap.get(RestApiConstants.RETURN_DTO);
APIDefinitionValidationResponse validationResponse = (APIDefinitionValidationResponse) validationResponseMap.get(RestApiConstants.RETURN_MODEL);
if (!validationResponseDTO.isIsValid()) {
ErrorDTO errorDTO = APIMappingUtil.getErrorDTOFromErrorListItems(validationResponseDTO.getErrors());
throw RestApiUtil.buildBadRequestException(errorDTO);
}
// Only HTTP or WEBHOOK type APIs should be allowed
if (!(APIDTO.TypeEnum.HTTP.equals(apiDTOFromProperties.getType()) || APIDTO.TypeEnum.WEBHOOK.equals(apiDTOFromProperties.getType()))) {
throw RestApiUtil.buildBadRequestException("The API's type is not supported when importing an OpenAPI definition");
}
// Import the API and Definition
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
if (isServiceAPI) {
apiDTOFromProperties.setType(PublisherCommonUtils.getAPIType(service.getDefinitionType(), null));
}
API apiToAdd = PublisherCommonUtils.prepareToCreateAPIByDTO(apiDTOFromProperties, apiProvider, RestApiCommonUtil.getLoggedInUsername(), organization);
if (isServiceAPI) {
apiToAdd.setServiceInfo("key", service.getKey());
apiToAdd.setServiceInfo("md5", service.getMd5());
apiToAdd.setEndpointConfig(PublisherCommonUtils.constructEndpointConfigForService(service.getServiceUrl(), null));
}
boolean syncOperations = apiDTOFromProperties.getOperations().size() > 0;
// Rearrange paths according to the API payload and save the OpenAPI definition
APIDefinition apiDefinition = validationResponse.getParser();
SwaggerData swaggerData;
String definitionToAdd = validationResponse.getJsonContent();
if (syncOperations) {
PublisherCommonUtils.validateScopes(apiToAdd);
swaggerData = new SwaggerData(apiToAdd);
definitionToAdd = apiDefinition.populateCustomManagementInfo(definitionToAdd, swaggerData);
}
definitionToAdd = OASParserUtil.preProcess(definitionToAdd);
Set<URITemplate> uriTemplates = apiDefinition.getURITemplates(definitionToAdd);
Set<Scope> scopes = apiDefinition.getScopes(definitionToAdd);
apiToAdd.setUriTemplates(uriTemplates);
apiToAdd.setScopes(scopes);
// Set extensions from API definition to API object
apiToAdd = OASParserUtil.setExtensionsToAPI(definitionToAdd, apiToAdd);
if (!syncOperations) {
PublisherCommonUtils.validateScopes(apiToAdd);
swaggerData = new SwaggerData(apiToAdd);
definitionToAdd = apiDefinition.populateCustomManagementInfo(validationResponse.getJsonContent(), swaggerData);
}
// adding the API and definition
apiToAdd.setSwaggerDefinition(definitionToAdd);
API addedAPI = apiProvider.addAPI(apiToAdd);
// apiProvider.saveSwaggerDefinition(apiToAdd, definitionToAdd);
// retrieving the added API for returning as the response
// this would provide the updated templates
addedAPI = apiProvider.getAPIbyUUID(addedAPI.getUuid(), organization);
return APIMappingUtil.fromAPItoDTO(addedAPI);
}
Aggregations