use of org.wso2.carbon.apimgt.api.model.ApiTypeWrapper in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method getRepliesOfComment.
@Override
public Response getRepliesOfComment(String commentId, String apiId, String xWSO2Tenant, Integer limit, Integer offset, String ifNoneMatch, Boolean includeCommenterInfo, MessageContext messageContext) throws APIManagementException {
String requestedTenantDomain = RestApiUtil.getRequestedTenantDomain(xWSO2Tenant);
try {
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
ApiTypeWrapper apiTypeWrapper = apiProvider.getAPIorAPIProductByUUID(apiId, requestedTenantDomain);
CommentList comments = apiProvider.getComments(apiTypeWrapper, commentId, limit, offset);
CommentListDTO commentDTO = CommentMappingUtil.fromCommentListToDTO(comments, includeCommenterInfo);
String uriString = RestApiConstants.RESOURCE_PATH_APIS + "/" + apiId + RestApiConstants.RESOURCE_PATH_COMMENTS;
URI uri = new URI(uriString);
return Response.ok(uri).entity(commentDTO).build();
} catch (APIManagementException e) {
if (RestApiUtil.isDueToResourceNotFound(e) || RestApiUtil.isDueToAuthorizationFailure(e)) {
RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API, apiId, e, log);
} else {
RestApiUtil.handleInternalServerError("Failed to get comments of API " + apiId, e, log);
}
} catch (URISyntaxException e) {
String errorMessage = "Error while retrieving comments content location for API " + apiId;
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
return null;
}
use of org.wso2.carbon.apimgt.api.model.ApiTypeWrapper 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.model.ApiTypeWrapper 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);
}
}
use of org.wso2.carbon.apimgt.api.model.ApiTypeWrapper in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method editCommentOfAPI.
@Override
public Response editCommentOfAPI(String commentId, String apiId, PatchRequestBodyDTO patchRequestBodyDTO, MessageContext messageContext) throws APIManagementException {
String username = RestApiCommonUtil.getLoggedInUsername();
String requestedTenantDomain = RestApiCommonUtil.getLoggedInUserTenantDomain();
try {
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
ApiTypeWrapper apiTypeWrapper = apiProvider.getAPIorAPIProductByUUID(apiId, requestedTenantDomain);
Comment comment = apiProvider.getComment(apiTypeWrapper, commentId, 0, 0);
if (comment != null) {
if (comment.getUser().equals(username)) {
boolean commentEdited = false;
if (patchRequestBodyDTO.getCategory() != null && !(patchRequestBodyDTO.getCategory().equals(comment.getCategory()))) {
comment.setCategory(patchRequestBodyDTO.getCategory());
commentEdited = true;
}
if (patchRequestBodyDTO.getContent() != null && !(patchRequestBodyDTO.getContent().equals(comment.getText()))) {
comment.setText(patchRequestBodyDTO.getContent());
commentEdited = true;
}
if (commentEdited) {
if (apiProvider.editComment(apiTypeWrapper, commentId, comment)) {
Comment editedComment = apiProvider.getComment(apiTypeWrapper, commentId, 0, 0);
CommentDTO commentDTO = CommentMappingUtil.fromCommentToDTO(editedComment);
String uriString = RestApiConstants.RESOURCE_PATH_APIS + "/" + apiId + RestApiConstants.RESOURCE_PATH_COMMENTS + "/" + commentId;
URI uri = new URI(uriString);
return Response.ok(uri).entity(commentDTO).build();
}
} else {
return Response.ok().build();
}
} else {
RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_COMMENTS, String.valueOf(commentId), log);
}
} else {
RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_COMMENTS, String.valueOf(commentId), log);
}
} catch (URISyntaxException e) {
String errorMessage = "Error while retrieving comment content location for API " + apiId;
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
return null;
}
use of org.wso2.carbon.apimgt.api.model.ApiTypeWrapper in project carbon-apimgt by wso2.
the class ImportUtils method importSubscriptions.
/**
* Import and add subscriptions of a particular application for the available APIs and API products
*
* @param subscribedAPIs Subscribed APIs
* @param userId Username of the subscriber
* @param application Application
* @param update Whether to update the application or not
* @param apiConsumer API Consumer
* @param organization Organization
* @return a list of APIIdentifiers of the skipped subscriptions
* @throws APIManagementException if an error occurs while importing and adding subscriptions
* @throws UserStoreException if an error occurs while checking whether the tenant domain exists
*/
public static List<APIIdentifier> importSubscriptions(Set<ExportedSubscribedAPI> subscribedAPIs, String userId, Application application, Boolean update, APIConsumer apiConsumer, String organization) throws APIManagementException, UserStoreException {
List<APIIdentifier> skippedAPIList = new ArrayList<>();
for (ExportedSubscribedAPI subscribedAPI : subscribedAPIs) {
APIIdentifier apiIdentifier = subscribedAPI.getApiId();
String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(apiIdentifier.getProviderName()));
if (!StringUtils.isEmpty(tenantDomain) && APIUtil.isTenantAvailable(tenantDomain)) {
String name = apiIdentifier.getApiName();
String version = apiIdentifier.getVersion();
// Creating a solr compatible search query, here we will execute a search query without wildcard *s
StringBuilder searchQuery = new StringBuilder();
String[] searchCriteria = { name, "version:" + version };
for (int i = 0; i < searchCriteria.length; i++) {
if (i == 0) {
searchQuery = new StringBuilder(APIUtil.getSingleSearchCriteria(searchCriteria[i]).replace("*", ""));
} else {
searchQuery.append(APIConstants.SEARCH_AND_TAG).append(APIUtil.getSingleSearchCriteria(searchCriteria[i]).replace("*", ""));
}
}
Map matchedAPIs;
matchedAPIs = apiConsumer.searchPaginatedAPIs(searchQuery.toString(), tenantDomain, 0, Integer.MAX_VALUE, false);
Set<Object> apiSet = (Set<Object>) matchedAPIs.get("apis");
if (apiSet != null && !apiSet.isEmpty()) {
Object type = apiSet.iterator().next();
ApiTypeWrapper apiTypeWrapper = null;
String apiOrApiProductUuid;
// Check whether the object is ApiProduct
if (isApiProduct(type)) {
APIProduct apiProduct = (APIProduct) apiSet.iterator().next();
apiOrApiProductUuid = APIUtil.getUUIDFromIdentifier(apiProduct.getId(), organization);
} else {
API api = (API) apiSet.iterator().next();
apiOrApiProductUuid = APIUtil.getUUIDFromIdentifier(api.getId(), organization);
}
apiTypeWrapper = apiConsumer.getAPIorAPIProductByUUID(apiOrApiProductUuid, organization);
// Tier of the imported subscription
String targetTier = subscribedAPI.getThrottlingPolicy();
// Checking whether the target tier is available
if (isTierAvailable(targetTier, apiTypeWrapper) && apiTypeWrapper.getStatus() != null && APIConstants.PUBLISHED.equals(apiTypeWrapper.getStatus())) {
apiTypeWrapper.setTier(targetTier);
// It will throw an error if subscriber already exists
if (update == null || !update) {
apiConsumer.addSubscription(apiTypeWrapper, userId, application);
} else if (!apiConsumer.isSubscribedToApp(subscribedAPI.getApiId(), userId, application.getId())) {
// on update skip subscriptions that already exists
apiConsumer.addSubscription(apiTypeWrapper, userId, application);
}
} else {
log.error("Failed to import Subscription as API/API Product " + name + "-" + version + " as one or more tiers may be unavailable or the API/API Product may not have been published ");
skippedAPIList.add(subscribedAPI.getApiId());
}
} else {
log.error("Failed to import Subscription as API " + name + "-" + version + " is not available");
skippedAPIList.add(subscribedAPI.getApiId());
}
} else {
log.error("Failed to import Subscription as Tenant domain: " + tenantDomain + " is not available");
skippedAPIList.add(subscribedAPI.getApiId());
}
}
return skippedAPIList;
}
Aggregations