use of org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse 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.APIDefinitionValidationResponse in project carbon-apimgt by wso2.
the class ImportUtils method retrieveValidatedAsyncApiDefinitionFromArchive.
/**
* Validate Aysnc API definition from the archive directory and return it.
*
* @param pathToArchive Path to API archive
* @return APIDefinitionValidationResponse of the Async API definition content
* @throws APIManagementException If an error occurs while reading the file
*/
public static APIDefinitionValidationResponse retrieveValidatedAsyncApiDefinitionFromArchive(String pathToArchive) throws APIManagementException {
try {
String asyncApiDefinition = loadAsyncApiDefinitionFromFile(pathToArchive);
APIDefinitionValidationResponse validationResponse = AsyncApiParserUtil.validateAsyncAPISpecification(asyncApiDefinition, true);
if (!validationResponse.isValid()) {
throw new APIManagementException("Error occurred while importing the API. Invalid AsyncAPI definition found. " + validationResponse.getErrorItems());
}
return validationResponse;
} catch (IOException e) {
throw new APIManagementException("Error while reading API meta information from path: " + pathToArchive, e, ExceptionCodes.ERROR_READING_META_DATA);
}
}
use of org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse in project carbon-apimgt by wso2.
the class SynapseArtifactGenerator method generateGatewayArtifact.
@Override
public RuntimeArtifactDto generateGatewayArtifact(List<APIRuntimeArtifactDto> apiRuntimeArtifactDtoList) throws APIManagementException {
RuntimeArtifactDto runtimeArtifactDto = new RuntimeArtifactDto();
List<String> synapseArtifacts = new ArrayList<>();
for (APIRuntimeArtifactDto runTimeArtifact : apiRuntimeArtifactDtoList) {
if (runTimeArtifact.isFile()) {
String tenantDomain = runTimeArtifact.getTenantDomain();
String label = runTimeArtifact.getLabel();
Environment environment = APIUtil.getEnvironments(tenantDomain).get(label);
GatewayAPIDTO gatewayAPIDTO = null;
if (environment != null) {
try (InputStream artifact = (InputStream) runTimeArtifact.getArtifact()) {
File baseDirectory = CommonUtil.createTempDirectory(null);
try {
String extractedFolderPath = ImportUtils.getArchivePathOfExtractedDirectory(baseDirectory.getAbsolutePath(), artifact);
if (APIConstants.API_PRODUCT.equals(runTimeArtifact.getType())) {
APIProductDTO apiProductDTO = ImportUtils.retrieveAPIProductDto(extractedFolderPath);
apiProductDTO.setId(runTimeArtifact.getApiId());
APIProduct apiProduct = APIMappingUtil.fromDTOtoAPIProduct(apiProductDTO, apiProductDTO.getProvider());
APIDefinitionValidationResponse apiDefinitionValidationResponse = ImportUtils.retrieveValidatedSwaggerDefinitionFromArchive(extractedFolderPath);
apiProduct.setDefinition(apiDefinitionValidationResponse.getContent());
gatewayAPIDTO = TemplateBuilderUtil.retrieveGatewayAPIDto(apiProduct, environment, tenantDomain, extractedFolderPath);
} else {
APIDTO apidto = ImportUtils.retrievedAPIDto(extractedFolderPath);
API api = APIMappingUtil.fromDTOtoAPI(apidto, apidto.getProvider());
api.setUUID(apidto.getId());
if (APIConstants.APITransportType.GRAPHQL.toString().equals(api.getType())) {
APIDefinition parser = new OAS3Parser();
SwaggerData swaggerData = new SwaggerData(api);
String apiDefinition = parser.generateAPIDefinition(swaggerData);
api.setSwaggerDefinition(apiDefinition);
GraphqlComplexityInfo graphqlComplexityInfo = APIUtil.getComplexityDetails(api);
String graphqlSchema = ImportUtils.retrieveValidatedGraphqlSchemaFromArchive(extractedFolderPath);
api.setGraphQLSchema(graphqlSchema);
GraphQLSchemaDefinition graphQLSchemaDefinition = new GraphQLSchemaDefinition();
graphqlSchema = graphQLSchemaDefinition.buildSchemaWithAdditionalInfo(api, graphqlComplexityInfo);
api.setGraphQLSchema(graphqlSchema);
gatewayAPIDTO = TemplateBuilderUtil.retrieveGatewayAPIDto(api, environment, tenantDomain, apidto, extractedFolderPath);
} else if (api.getType() != null && (APIConstants.APITransportType.HTTP.toString().equals(api.getType()) || APIConstants.API_TYPE_SOAP.equals(api.getType()) || APIConstants.API_TYPE_SOAPTOREST.equals(api.getType()) || APIConstants.APITransportType.WEBHOOK.toString().equals(api.getType()))) {
APIDefinitionValidationResponse apiDefinitionValidationResponse = ImportUtils.retrieveValidatedSwaggerDefinitionFromArchive(extractedFolderPath);
api.setSwaggerDefinition(apiDefinitionValidationResponse.getContent());
gatewayAPIDTO = TemplateBuilderUtil.retrieveGatewayAPIDto(api, environment, tenantDomain, apidto, extractedFolderPath, apiDefinitionValidationResponse);
} else if (api.getType() != null && (APIConstants.APITransportType.WS.toString().equals(api.getType()) || APIConstants.APITransportType.SSE.toString().equals(api.getType()) || APIConstants.APITransportType.WEBSUB.toString().equals(api.getType()))) {
APIDefinitionValidationResponse asyncApiDefinition = ImportUtils.retrieveValidatedAsyncApiDefinitionFromArchive(extractedFolderPath);
api.setAsyncApiDefinition(asyncApiDefinition.getContent());
gatewayAPIDTO = TemplateBuilderUtil.retrieveGatewayAPIDtoForStreamingAPI(api, environment, tenantDomain, apidto, extractedFolderPath);
}
}
if (gatewayAPIDTO != null) {
String content = new Gson().toJson(gatewayAPIDTO);
synapseArtifacts.add(content);
}
} finally {
FileUtils.deleteQuietly(baseDirectory);
}
} catch (Exception e) {
// only do error since we need to continue for other apis
log.error("Error while creating Synapse configurations", e);
}
}
}
}
runtimeArtifactDto.setFile(false);
runtimeArtifactDto.setArtifact(synapseArtifacts);
return runtimeArtifactDto;
}
use of org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse in project carbon-apimgt by wso2.
the class ServicesApiServiceImpl method validateAsyncAPISpecification.
/**
* Validate the ASYNC API definition provided
* @param url Service Definition URL
* @param definitionContent Service Definition Content
* @return APIDefinitionValidationResponse
* @throws APIManagementException
*/
private APIDefinitionValidationResponse validateAsyncAPISpecification(String url, String definitionContent) throws APIManagementException, IOException {
APIDefinitionValidationResponse validationResponse = new APIDefinitionValidationResponse();
if (StringUtils.isNotEmpty(definitionContent)) {
// validate file
// convert .yml or .yaml to JSON for validation
String schemaToBeValidated = CommonUtil.yamlToJson(definitionContent);
validationResponse = AsyncApiParserUtil.validateAsyncAPISpecification(schemaToBeValidated, true);
} else if (url != null) {
validationResponse = AsyncApiParserUtil.validateAsyncAPISpecificationByURL(url, true);
}
return validationResponse;
}
use of org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse in project carbon-apimgt by wso2.
the class ServicesApiServiceImpl method validateAndRetrieveServiceDefinition.
private APIDefinitionValidationResponse validateAndRetrieveServiceDefinition(byte[] definitionFileByteArray, String url, ServiceEntry.DefinitionType type) throws APIManagementException, IOException {
APIDefinitionValidationResponse validationResponse = new APIDefinitionValidationResponse();
String definitionContent = new String(definitionFileByteArray);
if (ServiceEntry.DefinitionType.OAS3.equals(type) || ServiceEntry.DefinitionType.OAS2.equals(type)) {
validationResponse = validateOpenAPIDefinition(url, definitionContent);
} else if (ServiceEntry.DefinitionType.ASYNC_API.equals(type)) {
validationResponse = validateAsyncAPISpecification(url, definitionContent);
}
return validationResponse;
}
Aggregations