use of org.wso2.carbon.apimgt.api.model.APIRevisionDeployment 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.APIRevisionDeployment in project carbon-apimgt by wso2.
the class ImportUtils method getValidatedDeploymentsList.
/**
* This method is used to validate the Gateway environments from the deployment environments file. Gateway
* environments will be validated with a set of all the labels and environments of the tenant domain. If
* environment is not found in this set, it will be skipped with an error message in the console. This method is
* common to both APIs and API Products
*
* @param deploymentInfoArray Deployment environment array found in the import artifact
* @param tenantDomain Tenant domain
* @param apiProvider Provider of the API/ API Product
* @return a list of API/API Product revision deployments ready to be deployed.
* @throws APIManagementException If an error occurs when validating the deployments list
*/
private static List<APIRevisionDeployment> getValidatedDeploymentsList(JsonArray deploymentInfoArray, String tenantDomain, APIProvider apiProvider, String organization) throws APIManagementException {
List<APIRevisionDeployment> apiRevisionDeployments = new ArrayList<>();
if (deploymentInfoArray != null && deploymentInfoArray.size() > 0) {
Map<String, Environment> gatewayEnvironments = APIUtil.getEnvironments(organization);
for (int i = 0; i < deploymentInfoArray.size(); i++) {
JsonObject deploymentJson = deploymentInfoArray.get(i).getAsJsonObject();
JsonElement deploymentNameElement = deploymentJson.get(ImportExportConstants.DEPLOYMENT_NAME);
if (deploymentNameElement != null) {
String deploymentName = deploymentNameElement.getAsString();
Environment gatewayEnvironment = gatewayEnvironments.get(deploymentName);
if (gatewayEnvironment != null) {
JsonElement deploymentVhostElement = deploymentJson.get(ImportExportConstants.DEPLOYMENT_VHOST);
String deploymentVhost;
if (deploymentVhostElement != null) {
deploymentVhost = deploymentVhostElement.getAsString();
} else {
// set the default vhost of the given environment
if (gatewayEnvironment.getVhosts().isEmpty()) {
throw new APIManagementException("No VHosts defined for the environment: " + deploymentName);
}
deploymentVhost = gatewayEnvironment.getVhosts().get(0).getHost();
}
// resolve vhost to null if it is the default vhost of read only environment
deploymentVhost = VHostUtils.resolveIfDefaultVhostToNull(deploymentName, deploymentVhost);
JsonElement displayOnDevportalElement = deploymentJson.get(ImportExportConstants.DISPLAY_ON_DEVPORTAL_OPTION);
boolean displayOnDevportal = displayOnDevportalElement == null || displayOnDevportalElement.getAsBoolean();
APIRevisionDeployment apiRevisionDeployment = new APIRevisionDeployment();
apiRevisionDeployment.setDeployment(deploymentName);
apiRevisionDeployment.setVhost(deploymentVhost);
apiRevisionDeployment.setDisplayOnDevportal(displayOnDevportal);
apiRevisionDeployments.add(apiRevisionDeployment);
} else {
throw new APIManagementException("Label " + deploymentName + " is not a defined gateway environment. Hence " + "skipped without deployment", ExceptionCodes.from(ExceptionCodes.GATEWAY_ENVIRONMENT_NOT_FOUND, String.format("label '%s'", deploymentName)));
}
}
}
}
return apiRevisionDeployments;
}
use of org.wso2.carbon.apimgt.api.model.APIRevisionDeployment in project carbon-apimgt by wso2.
the class SolaceApplicationNotifier method renameSolaceApplication.
/**
* Rename applications on the Solace broker
*
* @param event ApplicationEvent to rename Solace applications
* @throws NotifierException if error occurs when renaming applications on the Solace broker
*/
private void renameSolaceApplication(ApplicationEvent event) throws NotifierException {
// get list of subscribed APIs in the application
Subscriber subscriber = new Subscriber(event.getSubscriber());
try {
Application application = apiMgtDAO.getApplicationByUUID(event.getUuid());
Set<SubscribedAPI> subscriptions = apiMgtDAO.getSubscribedAPIs(subscriber, event.getApplicationName(), event.getGroupId());
Map<String, Environment> gatewayEnvironments = APIUtil.getReadOnlyGatewayEnvironments();
boolean isContainsSolaceApis = false;
String organizationNameOfSolaceDeployment = null;
labelOne: // Check whether the application needs to be updated has a Solace API subscription
for (SubscribedAPI api : subscriptions) {
List<APIRevisionDeployment> deployments = apiMgtDAO.getAPIRevisionDeploymentByApiUUID(api.getIdentifier().getUUID());
for (APIRevisionDeployment deployment : deployments) {
if (gatewayEnvironments.containsKey(deployment.getDeployment())) {
if (SolaceConstants.SOLACE_ENVIRONMENT.equalsIgnoreCase(gatewayEnvironments.get(deployment.getDeployment()).getProvider())) {
isContainsSolaceApis = true;
organizationNameOfSolaceDeployment = gatewayEnvironments.get(deployment.getDeployment()).getAdditionalProperties().get(SolaceConstants.SOLACE_ENVIRONMENT_ORGANIZATION);
break labelOne;
}
}
}
}
// Renaming application using Solace Admin Apis
if (isContainsSolaceApis) {
SolaceNotifierUtils.renameSolaceApplication(organizationNameOfSolaceDeployment, application);
}
} catch (APIManagementException e) {
throw new NotifierException(e.getMessage());
}
}
use of org.wso2.carbon.apimgt.api.model.APIRevisionDeployment in project carbon-apimgt by wso2.
the class SolaceApplicationNotifier method removeSolaceApplication.
/**
* Remove applications from Solace broker
*
* @param event ApplicationEvent to remove Solace applications
* @throws NotifierException if error occurs when removing applications from Solace broker
*/
private void removeSolaceApplication(ApplicationEvent event) throws NotifierException {
// get list of subscribed APIs in the application
Subscriber subscriber = new Subscriber(event.getSubscriber());
try {
Set<SubscribedAPI> subscriptions = apiMgtDAO.getSubscribedAPIs(subscriber, event.getApplicationName(), event.getGroupId());
List<SubscribedAPI> subscribedApiList = new ArrayList<>(subscriptions);
boolean hasSubscribedAPIDeployedInSolace = false;
String organizationNameOfSolaceDeployment = null;
Map<String, Environment> gatewayEnvironments = APIUtil.getReadOnlyGatewayEnvironments();
labelOne: for (SubscribedAPI api : subscribedApiList) {
List<APIRevisionDeployment> deployments = apiMgtDAO.getAPIRevisionDeploymentByApiUUID(api.getUUID());
for (APIRevisionDeployment deployment : deployments) {
if (gatewayEnvironments.containsKey(deployment.getDeployment())) {
if (SolaceConstants.SOLACE_ENVIRONMENT.equalsIgnoreCase(gatewayEnvironments.get(deployment.getDeployment()).getProvider())) {
hasSubscribedAPIDeployedInSolace = true;
organizationNameOfSolaceDeployment = gatewayEnvironments.get(deployment.getDeployment()).getAdditionalProperties().get(SolaceConstants.SOLACE_ENVIRONMENT_ORGANIZATION);
break labelOne;
}
}
}
}
boolean applicationFoundInSolaceBroker = false;
if (hasSubscribedAPIDeployedInSolace) {
SolaceAdminApis solaceAdminApis = SolaceNotifierUtils.getSolaceAdminApis();
// check existence of application in Solace Broker
CloseableHttpResponse response1 = solaceAdminApis.applicationGet(organizationNameOfSolaceDeployment, event.getUuid(), "default");
if (response1.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
applicationFoundInSolaceBroker = true;
if (log.isDebugEnabled()) {
log.info("Found application '" + event.getApplicationName() + "' in Solace broker");
log.info("Waiting until application removing workflow gets finished");
}
} else if (response1.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
throw new NotifierException("Application '" + event.getApplicationName() + "' cannot be found in " + "Solace Broker");
} else {
if (log.isDebugEnabled()) {
log.error("Error while searching for application '" + event.getApplicationName() + "'" + " in Solace Broker. : " + response1.getStatusLine().toString());
}
throw new NotifierException("Error while searching for application '" + event.getApplicationName() + "' in Solace Broker");
}
}
if (applicationFoundInSolaceBroker) {
log.info("Deleting application from Solace Broker");
// delete application from solace
SolaceAdminApis solaceAdminApis = SolaceNotifierUtils.getSolaceAdminApis();
CloseableHttpResponse response2 = solaceAdminApis.deleteApplication(organizationNameOfSolaceDeployment, event.getUuid());
if (response2.getStatusLine().getStatusCode() == HttpStatus.SC_NO_CONTENT) {
log.info("Successfully deleted application '" + event.getApplicationName() + "' " + "in Solace Broker");
} else {
if (log.isDebugEnabled()) {
log.error("Error while deleting application " + event.getApplicationName() + " in Solace. :" + response2.getStatusLine().toString());
}
throw new NotifierException("Error while deleting application '" + event.getApplicationName() + "' in Solace");
}
}
} catch (APIManagementException e) {
throw new NotifierException(e.getMessage());
}
}
use of org.wso2.carbon.apimgt.api.model.APIRevisionDeployment in project carbon-apimgt by wso2.
the class SolaceNotifierUtils method getThirdPartySolaceBrokerOrganizationNameOfAPIDeployment.
/**
* Get third party Solace broker organization Name for API deployment
*
* @param api Name of the API
* @return String of the name of organization in Solace broker
* @throws APIManagementException is error occurs when getting the name of the organization name
*/
public static String getThirdPartySolaceBrokerOrganizationNameOfAPIDeployment(API api) throws APIManagementException {
apiMgtDAO = ApiMgtDAO.getInstance();
Map<String, Environment> gatewayEnvironments = APIUtil.getReadOnlyGatewayEnvironments();
List<APIRevisionDeployment> deployments = apiMgtDAO.getAPIRevisionDeploymentByApiUUID(api.getUuid());
for (APIRevisionDeployment deployment : deployments) {
if (deployment.isDisplayOnDevportal()) {
String environmentName = deployment.getDeployment();
if (gatewayEnvironments.containsKey(environmentName)) {
Environment deployedEnvironment = gatewayEnvironments.get(environmentName);
if (SolaceConstants.SOLACE_ENVIRONMENT.equalsIgnoreCase(deployedEnvironment.getProvider())) {
return deployedEnvironment.getAdditionalProperties().get(SolaceConstants.SOLACE_ENVIRONMENT_ORGANIZATION);
}
}
}
}
return null;
}
Aggregations