use of org.wso2.carbon.apimgt.api.APIProvider in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method getAPIResourcePaths.
@Override
public Response getAPIResourcePaths(String apiId, Integer limit, Integer offset, String ifNoneMatch, MessageContext messageContext) {
try {
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
APIIdentifier apiIdentifier = APIMappingUtil.getAPIIdentifierFromUUID(apiId);
if (apiIdentifier == null) {
throw new APIMgtResourceNotFoundException("Couldn't retrieve existing API with API UUID: " + apiId, ExceptionCodes.from(ExceptionCodes.API_NOT_FOUND, apiId));
}
List<ResourcePath> apiResourcePaths = apiProvider.getResourcePathsOfAPI(apiIdentifier);
ResourcePathListDTO dto = APIMappingUtil.fromResourcePathListToDTO(apiResourcePaths, limit, offset);
APIMappingUtil.setPaginationParamsForAPIResourcePathList(dto, offset, limit, apiResourcePaths.size());
return Response.ok().entity(dto).build();
} catch (APIManagementException e) {
if (RestApiUtil.isDueToResourceNotFound(e) || RestApiUtil.isDueToAuthorizationFailure(e)) {
RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API, apiId, e, log);
} else if (isAuthorizationFailure(e)) {
RestApiUtil.handleAuthorizationFailure("Authorization failure while retrieving resource paths of API : " + apiId, e, log);
} else {
String errorMessage = "Error while retrieving resource paths of API : " + apiId;
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
}
return null;
}
use of org.wso2.carbon.apimgt.api.APIProvider in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method getGraphQLPolicyComplexityTypesOfAPI.
/**
* Get all types and fields of the GraphQL Schema of a given API
*
* @param apiId apiId
* @param messageContext message context
* @return Response with all the types and fields found within the schema definition
*/
@Override
public Response getGraphQLPolicyComplexityTypesOfAPI(String apiId, MessageContext messageContext) {
GraphQLSchemaDefinition graphql = new GraphQLSchemaDefinition();
try {
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
String organization = RestApiUtil.getValidatedOrganization(messageContext);
APIIdentifier apiIdentifier;
if (ApiMgtDAO.getInstance().checkAPIUUIDIsARevisionUUID(apiId) != null) {
apiIdentifier = APIMappingUtil.getAPIInfoFromUUID(apiId, organization).getId();
} else {
apiIdentifier = APIMappingUtil.getAPIIdentifierFromUUID(apiId);
}
API api = apiProvider.getAPIbyUUID(apiId, organization);
if (APIConstants.GRAPHQL_API.equals(api.getType())) {
String schemaContent = apiProvider.getGraphqlSchema(apiIdentifier);
List<GraphqlSchemaType> typeList = graphql.extractGraphQLTypeList(schemaContent);
GraphQLSchemaTypeListDTO graphQLSchemaTypeListDTO = GraphqlQueryAnalysisMappingUtil.fromGraphqlSchemaTypeListtoDTO(typeList);
return Response.ok().entity(graphQLSchemaTypeListDTO).build();
} else {
throw new APIManagementException(ExceptionCodes.API_NOT_GRAPHQL);
}
} 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 retrieving types and fields of API : " + apiId, e, log);
} else {
String msg = "Error while retrieving types and fields of the schema of API " + apiId;
RestApiUtil.handleInternalServerError(msg, e, log);
}
}
return null;
}
use of org.wso2.carbon.apimgt.api.APIProvider in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method deleteAPISpecificOperationPolicyByPolicyId.
/**
* Delete API specific operation policy by providing the policy ID
*
* @param apiId API UUID
* @param operationPolicyId UUID of the operation policy
* @param messageContext message context
* @return A zip file containing both (if exists) operation policy specification and policy definition
*/
@Override
public Response deleteAPISpecificOperationPolicyByPolicyId(String apiId, String operationPolicyId, MessageContext messageContext) {
try {
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
// validate if api exists
validateAPIExistence(apiId);
String organization = RestApiUtil.getValidatedOrganization(messageContext);
OperationPolicyData existingPolicy = apiProvider.getAPISpecificOperationPolicyByPolicyId(operationPolicyId, apiId, organization, false);
if (existingPolicy != null) {
apiProvider.deleteOperationPolicyById(operationPolicyId, organization);
if (log.isDebugEnabled()) {
log.debug("The operation policy " + operationPolicyId + " has been deleted from the the API " + apiId);
}
return Response.ok().build();
} else {
throw new APIMgtResourceNotFoundException("Couldn't retrieve an existing operation policy with ID: " + operationPolicyId + " for API " + apiId, ExceptionCodes.from(ExceptionCodes.OPERATION_POLICY_NOT_FOUND, operationPolicyId));
}
} catch (APIManagementException e) {
if (RestApiUtil.isDueToResourceNotFound(e) || RestApiUtil.isDueToAuthorizationFailure(e)) {
RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_PATH_OPERATION_POLICIES, operationPolicyId, e, log);
} else {
String errorMessage = "Error while deleting the API specific operation policy with ID :" + operationPolicyId + " for API " + apiId + " " + e.getMessage();
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
} catch (Exception e) {
RestApiUtil.handleInternalServerError("An error has occurred while deleting the API specific " + " operation policy with ID" + operationPolicyId + " for API " + apiId, e, log);
}
return null;
}
use of org.wso2.carbon.apimgt.api.APIProvider in project carbon-apimgt by wso2.
the class ImportUtils method importApiProduct.
/**
* This method imports an API Product.
*
* @param extractedFolderPath Location of the extracted folder of the API Product
* @param preserveProvider Decision to keep or replace the provider
* @param overwriteAPIProduct Whether to update the API Product or not
* @param overwriteAPIs Whether to update the dependent APIs or not
* @param organization Organization Identifier
* @param importAPIs Whether to import the dependent APIs or not
* @throws APIImportExportException If there is an error in importing an API
*/
public static APIProduct importApiProduct(String extractedFolderPath, Boolean preserveProvider, Boolean rotateRevision, Boolean overwriteAPIProduct, Boolean overwriteAPIs, Boolean importAPIs, String[] tokenScopes, String organization) throws APIManagementException {
String userName = RestApiCommonUtil.getLoggedInUsername();
String currentTenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(userName));
APIProduct importedApiProduct = null;
JsonArray deploymentInfoArray = null;
String currentStatus;
String targetStatus;
String lifecycleAction;
try {
JsonElement jsonObject = retrieveValidatedDTOObject(extractedFolderPath, preserveProvider, userName, ImportExportConstants.TYPE_API_PRODUCT);
APIProductDTO importedApiProductDTO = new Gson().fromJson(jsonObject, APIProductDTO.class);
// If the provided dependent APIs params config is null, it means this happening when importing an API (not
// because when importing a dependent API of an API Product). Hence, try to retrieve the definition from
// the API folder path
JsonObject paramsConfigObject = APIControllerUtil.resolveAPIControllerEnvParams(extractedFolderPath);
// If above the params configurations are not null, then resolve those
if (paramsConfigObject != null) {
importedApiProductDTO = APIControllerUtil.injectEnvParamsToAPIProduct(importedApiProductDTO, paramsConfigObject, extractedFolderPath);
JsonElement deploymentsParam = paramsConfigObject.get(ImportExportConstants.DEPLOYMENT_ENVIRONMENTS);
if (deploymentsParam != null && !deploymentsParam.isJsonNull()) {
deploymentInfoArray = deploymentsParam.getAsJsonArray();
}
}
APIProvider apiProvider = RestApiCommonUtil.getProvider(importedApiProductDTO.getProvider());
// Check whether the API resources are valid
checkAPIProductResourcesValid(extractedFolderPath, userName, apiProvider, importedApiProductDTO, preserveProvider, organization);
targetStatus = importedApiProductDTO.getState().toString();
if (importAPIs) {
// Import dependent APIs only if it is asked (the UUIDs of the dependent APIs will be updated here if a
// fresh import happens)
importedApiProductDTO = importDependentAPIs(extractedFolderPath, userName, preserveProvider, apiProvider, overwriteAPIs, rotateRevision, importedApiProductDTO, tokenScopes, organization);
} else {
// Even we do not import APIs, the UUIDs of the dependent APIs should be updated if the APIs are
// already in the APIM
importedApiProductDTO = updateDependentApiUuids(importedApiProductDTO, apiProvider, currentTenantDomain, organization);
}
APIProduct targetApiProduct = retrieveApiProductToOverwrite(importedApiProductDTO.getName(), currentTenantDomain, apiProvider, Boolean.TRUE, organization);
// If the overwrite is set to true (which means an update), retrieve the existing API
if (Boolean.TRUE.equals(overwriteAPIProduct) && targetApiProduct != null) {
log.info("Existing API Product found, attempting to update it...");
currentStatus = targetApiProduct.getState();
importedApiProduct = PublisherCommonUtils.updateApiProduct(targetApiProduct, importedApiProductDTO, RestApiCommonUtil.getLoggedInUserProvider(), userName, currentTenantDomain);
} else {
if (targetApiProduct == null && Boolean.TRUE.equals(overwriteAPIProduct)) {
log.info("Cannot find : " + importedApiProductDTO.getName() + ". Creating it.");
}
currentStatus = APIStatus.CREATED.toString();
importedApiProduct = PublisherCommonUtils.addAPIProductWithGeneratedSwaggerDefinition(importedApiProductDTO, importedApiProductDTO.getProvider(), organization);
}
// Retrieving the life cycle action to do the lifecycle state change explicitly later
lifecycleAction = getLifeCycleAction(currentTenantDomain, currentStatus, targetStatus, apiProvider);
// Add/update swagger of API Product
importedApiProduct = updateApiProductSwagger(extractedFolderPath, importedApiProduct.getUuid(), importedApiProduct, apiProvider, currentTenantDomain);
// Since Image, documents and client certificates are optional, exceptions are logged and ignored in
// implementation
ApiTypeWrapper apiTypeWrapperWithUpdatedApiProduct = new ApiTypeWrapper(importedApiProduct);
addThumbnailImage(extractedFolderPath, apiTypeWrapperWithUpdatedApiProduct, apiProvider);
addDocumentation(extractedFolderPath, apiTypeWrapperWithUpdatedApiProduct, apiProvider, organization);
if (log.isDebugEnabled()) {
log.debug("Mutual SSL enabled. Importing client certificates.");
}
addClientCertificates(extractedFolderPath, apiProvider, preserveProvider, importedApiProduct.getId().getProviderName(), organization);
// Change API Product lifecycle if state transition is required
if (StringUtils.isNotEmpty(lifecycleAction)) {
apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
log.info("Changing lifecycle from " + currentStatus + " to " + targetStatus);
apiProvider.changeLifeCycleStatus(currentTenantDomain, new ApiTypeWrapper(importedApiProduct), lifecycleAction, new HashMap<>());
}
importedApiProduct.setState(targetStatus);
if (deploymentInfoArray == null) {
// If the params have not overwritten the deployment environments, yaml file will be read
deploymentInfoArray = retrieveDeploymentLabelsFromArchive(extractedFolderPath, false);
}
List<APIRevisionDeployment> apiProductRevisionDeployments = getValidatedDeploymentsList(deploymentInfoArray, currentTenantDomain, apiProvider, organization);
if (apiProductRevisionDeployments.size() > 0) {
String importedAPIUuid = importedApiProduct.getUuid();
String revisionId;
APIRevision apiProductRevision = new APIRevision();
apiProductRevision.setApiUUID(importedAPIUuid);
apiProductRevision.setDescription("Revision created after importing the API Product");
try {
revisionId = apiProvider.addAPIProductRevision(apiProductRevision, organization);
if (log.isDebugEnabled()) {
log.debug("A new revision has been created for API Product " + importedApiProduct.getId().getName() + "_" + importedApiProduct.getId().getVersion() + " with ID: " + revisionId);
}
} catch (APIManagementException e) {
// rotateRevision enabled, earliest revision will be deleted before creating a revision again
if (e.getErrorHandler().getErrorCode() == ExceptionCodes.from(ExceptionCodes.MAXIMUM_REVISIONS_REACHED).getErrorCode() && rotateRevision) {
String earliestRevisionUuid = apiProvider.getEarliestRevisionUUID(importedAPIUuid);
List<APIRevisionDeployment> deploymentsList = apiProvider.getAPIRevisionDeploymentList(earliestRevisionUuid);
// if the earliest revision is already deployed in gateway environments, it will be undeployed
// before deleting
apiProvider.undeployAPIProductRevisionDeployment(importedAPIUuid, earliestRevisionUuid, deploymentsList);
apiProvider.deleteAPIProductRevision(importedAPIUuid, earliestRevisionUuid, organization);
revisionId = apiProvider.addAPIProductRevision(apiProductRevision, organization);
if (log.isDebugEnabled()) {
log.debug("Revision ID: " + earliestRevisionUuid + " has been undeployed from " + deploymentsList.size() + " gateway environments and created a new revision ID: " + revisionId + " for API Product " + importedApiProduct.getId().getName() + "_" + importedApiProduct.getId().getVersion());
}
} else {
throw new APIManagementException(e);
}
}
// Once the new revision successfully created, artifacts will be deployed in mentioned gateway
// environments
apiProvider.deployAPIProductRevision(importedAPIUuid, revisionId, apiProductRevisionDeployments);
} else {
log.info("Valid deployment environments were not found for the imported artifact. Hence not deployed" + " in any of the gateway environments.");
}
return importedApiProduct;
} catch (IOException e) {
// mandatory steps
throw new APIManagementException("Error while reading API Product meta information from path: " + extractedFolderPath, e);
} catch (FaultGatewaysException e) {
throw new APIManagementException("Error while updating API Product: " + importedApiProduct.getId().getName(), e);
} catch (APIManagementException e) {
String errorMessage = "Error while importing API Product: ";
if (importedApiProduct != null) {
errorMessage += importedApiProduct.getId().getName() + StringUtils.SPACE + APIConstants.API_DATA_VERSION + ": " + importedApiProduct.getId().getVersion();
}
throw new APIManagementException(errorMessage + " " + e.getMessage(), e);
}
}
use of org.wso2.carbon.apimgt.api.APIProvider in project carbon-apimgt by wso2.
the class ImportUtils method addDocumentation.
/**
* This method adds the documents to the imported API or API Product.
*
* @param pathToArchive Location of the extracted folder of the API or API Product
* @param apiTypeWrapper Imported API or API Product
* @param organization Identifier of an Organization
*/
private static void addDocumentation(String pathToArchive, ApiTypeWrapper apiTypeWrapper, APIProvider apiProvider, String organization) {
String jsonContent = null;
Identifier identifier = apiTypeWrapper.getId();
String docDirectoryPath = pathToArchive + File.separator + ImportExportConstants.DOCUMENT_DIRECTORY;
File documentsFolder = new File(docDirectoryPath);
File[] fileArray = documentsFolder.listFiles();
String provider = (apiTypeWrapper.isAPIProduct()) ? apiTypeWrapper.getApiProduct().getId().getProviderName() : apiTypeWrapper.getApi().getId().getProviderName();
String tenantDomain = MultitenantUtils.getTenantDomain(provider);
try {
// Remove all documents associated with the API before update
List<Documentation> documents = apiProvider.getAllDocumentation(identifier);
if (documents != null) {
for (Documentation documentation : documents) {
apiProvider.removeDocumentation(identifier, documentation.getId(), tenantDomain);
}
}
if (documentsFolder.isDirectory() && fileArray != null) {
// This loop locates the documents inside each repo
for (File documentFile : fileArray) {
String folderName = documentFile.getName();
String individualDocumentFilePath = docDirectoryPath + File.separator + folderName;
String pathToYamlFile = individualDocumentFilePath + ImportExportConstants.DOCUMENT_FILE_NAME + ImportExportConstants.YAML_EXTENSION;
String pathToJsonFile = individualDocumentFilePath + ImportExportConstants.DOCUMENT_FILE_NAME + ImportExportConstants.JSON_EXTENSION;
// Load document file if exists
if (CommonUtil.checkFileExistence(pathToYamlFile)) {
if (log.isDebugEnabled()) {
log.debug("Found documents definition file " + pathToYamlFile);
}
String yamlContent = FileUtils.readFileToString(new File(pathToYamlFile));
jsonContent = CommonUtil.yamlToJson(yamlContent);
} else if (CommonUtil.checkFileExistence(pathToJsonFile)) {
// load as a json fallback
if (log.isDebugEnabled()) {
log.debug("Found documents definition file " + pathToJsonFile);
}
jsonContent = FileUtils.readFileToString(new File(pathToJsonFile));
}
JsonElement configElement = new JsonParser().parse(jsonContent).getAsJsonObject().get(APIConstants.DATA);
DocumentDTO documentDTO = new Gson().fromJson(configElement.getAsJsonObject(), DocumentDTO.class);
// Add the documentation DTO
Documentation documentation = apiTypeWrapper.isAPIProduct() ? PublisherCommonUtils.addDocumentationToAPI(documentDTO, apiTypeWrapper.getApiProduct().getUuid(), organization) : PublisherCommonUtils.addDocumentationToAPI(documentDTO, apiTypeWrapper.getApi().getUuid(), organization);
// Adding doc content
String docSourceType = documentation.getSourceType().toString();
boolean docContentExists = Documentation.DocumentSourceType.INLINE.toString().equalsIgnoreCase(docSourceType) || Documentation.DocumentSourceType.MARKDOWN.toString().equalsIgnoreCase(docSourceType);
String apiOrApiProductId = (!apiTypeWrapper.isAPIProduct()) ? apiTypeWrapper.getApi().getUuid() : apiTypeWrapper.getApiProduct().getUuid();
if (docContentExists) {
try (FileInputStream inputStream = new FileInputStream(individualDocumentFilePath + File.separator + folderName)) {
String inlineContent = IOUtils.toString(inputStream, ImportExportConstants.CHARSET);
PublisherCommonUtils.addDocumentationContent(documentation, apiProvider, apiOrApiProductId, documentation.getId(), tenantDomain, inlineContent);
}
} else if (ImportExportConstants.FILE_DOC_TYPE.equalsIgnoreCase(docSourceType)) {
String filePath = documentation.getFilePath();
try (FileInputStream inputStream = new FileInputStream(individualDocumentFilePath + File.separator + filePath)) {
String docExtension = FilenameUtils.getExtension(pathToArchive + File.separator + ImportExportConstants.DOCUMENT_DIRECTORY + File.separator + filePath);
PublisherCommonUtils.addDocumentationContentForFile(inputStream, docExtension, documentation.getFilePath(), apiProvider, apiOrApiProductId, documentation.getId(), tenantDomain);
} catch (FileNotFoundException e) {
// this error is logged and ignored because documents are optional in an API
log.error("Failed to locate the document files of the API/API Product: " + apiTypeWrapper.getId().getName(), e);
continue;
}
}
}
}
} catch (FileNotFoundException e) {
// this error is logged and ignored because documents are optional in an API
log.error("Failed to locate the document files of the API/API Product: " + identifier.getName(), e);
} catch (APIManagementException | IOException e) {
// this error is logged and ignored because documents are optional in an API
log.error("Failed to add Documentations to API/API Product: " + identifier.getName(), e);
}
}
Aggregations