use of org.wso2.carbon.apimgt.impl.importexport.lifecycle.LifeCycle in project carbon-apimgt by wso2.
the class RegistryPersistenceImpl method addAPI.
@SuppressWarnings("unchecked")
@Override
public PublisherAPI addAPI(Organization org, PublisherAPI publisherAPI) throws APIPersistenceException {
API api = APIMapper.INSTANCE.toApi(publisherAPI);
boolean transactionCommitted = false;
boolean tenantFlowStarted = false;
Registry registry = null;
try {
RegistryHolder holder = getRegistry(org.getName());
registry = holder.getRegistry();
tenantFlowStarted = holder.isTenantFlowStarted();
registry.beginTransaction();
GenericArtifactManager artifactManager = RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.API_KEY);
if (artifactManager == null) {
String errorMessage = "Failed to retrieve artifact manager when creating API " + api.getId().getApiName();
log.error(errorMessage);
throw new APIPersistenceException(errorMessage);
}
GenericArtifact genericArtifact = artifactManager.newGovernanceArtifact(new QName(api.getId().getApiName()));
if (genericArtifact == null) {
String errorMessage = "Generic artifact is null when creating API " + api.getId().getApiName();
log.error(errorMessage);
throw new APIPersistenceException(errorMessage);
}
genericArtifact.setAttribute(APIConstants.API_OVERVIEW_VERSION_TIMESTAMP, api.getVersionTimestamp());
GenericArtifact artifact = RegistryPersistenceUtil.createAPIArtifactContent(genericArtifact, api);
artifactManager.addGenericArtifact(artifact);
// Attach the API lifecycle
artifact.attachLifecycle(APIConstants.API_LIFE_CYCLE);
String artifactPath = GovernanceUtils.getArtifactPath(registry, artifact.getId());
String providerPath = RegistryPersistenceUtil.getAPIProviderPath(api.getId());
// provider ------provides----> API
registry.addAssociation(providerPath, artifactPath, APIConstants.PROVIDER_ASSOCIATION);
Set<String> tagSet = api.getTags();
if (tagSet != null) {
for (String tag : tagSet) {
registry.applyTag(artifactPath, tag);
}
}
String apiStatus = api.getStatus();
saveAPIStatus(registry, artifactPath, apiStatus);
String visibleRolesList = api.getVisibleRoles();
String[] visibleRoles = new String[0];
if (visibleRolesList != null) {
visibleRoles = visibleRolesList.split(",");
}
String publisherAccessControlRoles = api.getAccessControlRoles();
updateRegistryResources(registry, artifactPath, publisherAccessControlRoles, api.getAccessControl(), api.getAdditionalProperties());
RegistryPersistenceUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, artifactPath, registry);
if (api.getSwaggerDefinition() != null) {
String resourcePath = RegistryPersistenceUtil.getOpenAPIDefinitionFilePath(api.getId().getName(), api.getId().getVersion(), api.getId().getProviderName());
resourcePath = resourcePath + APIConstants.API_OAS_DEFINITION_RESOURCE_NAME;
Resource resource;
if (!registry.resourceExists(resourcePath)) {
resource = registry.newResource();
} else {
resource = registry.get(resourcePath);
}
resource.setContent(api.getSwaggerDefinition());
resource.setMediaType("application/json");
registry.put(resourcePath, resource);
// Need to set anonymous if the visibility is public
RegistryPersistenceUtil.clearResourcePermissions(resourcePath, api.getId(), ((UserRegistry) registry).getTenantId());
RegistryPersistenceUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, resourcePath);
} else if (api.getAsyncApiDefinition() != null) {
String resourcePath = RegistryPersistenceUtil.getOpenAPIDefinitionFilePath(api.getId().getName(), api.getId().getVersion(), api.getId().getProviderName());
resourcePath = resourcePath + APIConstants.API_ASYNC_API_DEFINITION_RESOURCE_NAME;
Resource resource;
if (!registry.resourceExists(resourcePath)) {
resource = registry.newResource();
} else {
resource = registry.get(resourcePath);
}
resource.setContent(api.getAsyncApiDefinition());
// add a constant for app.json
resource.setMediaType(APIConstants.APPLICATION_JSON_MEDIA_TYPE);
registry.put(resourcePath, resource);
RegistryPersistenceUtil.clearResourcePermissions(resourcePath, api.getId(), ((UserRegistry) registry).getTenantId());
RegistryPersistenceUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, resourcePath);
}
// Set permissions to doc path
String docLocation = RegistryPersistenceDocUtil.getDocumentPath(api.getId().getProviderName(), api.getId().getApiName(), api.getId().getVersion());
RegistryPersistenceUtil.clearResourcePermissions(docLocation, api.getId(), ((UserRegistry) registry).getTenantId());
RegistryPersistenceUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, docLocation);
registry.commitTransaction();
api.setUuid(artifact.getId());
transactionCommitted = true;
if (log.isDebugEnabled()) {
log.debug("API details successfully added to the registry. API Name: " + api.getId().getApiName() + ", API Version : " + api.getId().getVersion() + ", API context : " + api.getContext());
}
// set current time as created time for returning api.
api.setCreatedTime(String.valueOf(new Date().getTime()));
PublisherAPI returnAPI = APIMapper.INSTANCE.toPublisherApi(api);
if (log.isDebugEnabled()) {
log.debug("Created API :" + returnAPI.toString());
}
return returnAPI;
} catch (RegistryException e) {
try {
registry.rollbackTransaction();
} catch (RegistryException re) {
// Throwing an error here would mask the original exception
log.error("Error while rolling back the transaction for API: " + api.getId().getApiName(), re);
}
throw new APIPersistenceException("Error while performing registry transaction operation", e);
} catch (APIManagementException e) {
throw new APIPersistenceException("Error while creating API", e);
} finally {
if (tenantFlowStarted) {
RegistryPersistenceUtil.endTenantFlow();
}
try {
if (!transactionCommitted) {
registry.rollbackTransaction();
}
} catch (RegistryException ex) {
throw new APIPersistenceException("Error while rolling back the transaction for API: " + api.getId().getApiName(), ex);
}
}
}
use of org.wso2.carbon.apimgt.impl.importexport.lifecycle.LifeCycle in project carbon-apimgt by wso2.
the class RegistryPersistenceImpl method changeAPILifeCycle.
@Override
public void changeAPILifeCycle(Organization org, String apiId, String status) throws APIPersistenceException {
GenericArtifactManager artifactManager = null;
boolean isTenantFlowStarted = false;
try {
RegistryHolder holder = getRegistry(org.getName());
Registry registry = holder.getRegistry();
isTenantFlowStarted = holder.isTenantFlowStarted();
if (GovernanceUtils.findGovernanceArtifactConfiguration(APIConstants.API_KEY, registry) != null) {
artifactManager = new GenericArtifactManager(registry, APIConstants.API_KEY);
GenericArtifact apiArtifact = artifactManager.getGenericArtifact(apiId);
String action = LCManagerFactory.getInstance().getLCManager().getTransitionAction(apiArtifact.getLifecycleState().toUpperCase(), status.toUpperCase());
apiArtifact.invokeAction(action, APIConstants.API_LIFE_CYCLE);
} else {
log.warn("Couldn't find GovernanceArtifactConfiguration of RXT: " + APIConstants.API_KEY + ". Tenant id set in registry : " + ((UserRegistry) registry).getTenantId() + ", Tenant domain set in PrivilegedCarbonContext: " + PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId());
}
} catch (GovernanceException e) {
throw new APIPersistenceException("Error while changing the lifecycle. ", e);
} catch (RegistryException e) {
throw new APIPersistenceException("Error while accessing the registry. ", e);
} catch (PersistenceException e) {
throw new APIPersistenceException("Error while accessing the lifecycle. ", e);
} finally {
if (isTenantFlowStarted) {
PrivilegedCarbonContext.endTenantFlow();
}
}
}
use of org.wso2.carbon.apimgt.impl.importexport.lifecycle.LifeCycle in project carbon-apimgt by wso2.
the class LCManagerFactory method getLCManager.
public RegistryLCManager getLCManager() throws PersistenceException {
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
String cacheName = tenantDomain + "_" + APIConstants.LC_CACHE_NAME;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
Cache lcCache = Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER).getCache(APIConstants.LC_CACHE_NAME);
RegistryLCManager lcManager = (RegistryLCManager) lcCache.get(cacheName);
if (lcManager != null) {
log.debug("Lifecycle info servered from Cache.");
return lcManager;
} else {
try {
log.debug("Lifecycle info not found in Cache.");
lcManager = new RegistryLCManager(tenantId);
lcCache.put(cacheName, lcManager);
return lcManager;
} catch (RegistryException | XMLStreamException | ParserConfigurationException | SAXException | IOException e) {
throw new PersistenceException("Error while accessing the lifecycle resource ", e);
}
}
}
use of org.wso2.carbon.apimgt.impl.importexport.lifecycle.LifeCycle in project carbon-apimgt by wso2.
the class WorkflowUtils method completeStateChangeWorkflow.
/**
* Complete the lifecycle state change workflow
*
* @param workflowDTO Workflow DTO object
* @throws WorkflowException Exception when completing the workflow
*/
protected static void completeStateChangeWorkflow(WorkflowDTO workflowDTO) throws WorkflowException {
String externalWorkflowRef = workflowDTO.getExternalWorkflowReference();
try {
ApiMgtDAO apiMgtDAO = ApiMgtDAO.getInstance();
Workflow workflow = apiMgtDAO.getworkflowReferenceByExternalWorkflowReference(externalWorkflowRef);
String apiName = workflow.getMetadata("ApiName");
String action = workflow.getMetadata("Action");
String providerName = workflow.getMetadata("ApiProvider");
String version = workflow.getMetadata("ApiVersion");
String invoker = workflow.getMetadata("Invoker");
String currentStatus = workflow.getMetadata("CurrentState");
int tenantId = workflowDTO.getTenantId();
try {
// tenant flow is already started from the rest api service impl. no need to start from here
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(invoker);
Registry registry = ServiceReferenceHolder.getInstance().getRegistryService().getGovernanceUserRegistry(invoker, tenantId);
APIIdentifier apiIdentifier = new APIIdentifier(providerName, apiName, version);
GenericArtifact apiArtifact = APIUtil.getAPIArtifact(apiIdentifier, registry);
if (WorkflowStatus.APPROVED.equals(workflowDTO.getStatus())) {
String targetStatus;
apiArtifact.invokeAction(action, APIConstants.API_LIFE_CYCLE);
targetStatus = apiArtifact.getLifecycleState();
if (!currentStatus.equals(targetStatus)) {
apiMgtDAO.recordAPILifeCycleEvent(apiArtifact.getId(), currentStatus.toUpperCase(), targetStatus.toUpperCase(), invoker, tenantId);
}
if (log.isDebugEnabled()) {
String logMessage = "API Status changed successfully. API Name: " + apiIdentifier.getApiName() + ", API " + "Version " + apiIdentifier.getVersion() + ", New Status : " + targetStatus;
log.debug(logMessage);
}
}
} catch (RegistryException e) {
String errorMsg = "Could not complete api state change workflow";
log.error(errorMsg, e);
throw new WorkflowException(errorMsg, e);
}
} catch (APIManagementException e) {
String errorMsg = "Could not complete api state change workflow";
log.error(errorMsg, e);
}
}
use of org.wso2.carbon.apimgt.impl.importexport.lifecycle.LifeCycle in project carbon-apimgt by wso2.
the class APIProviderImpl method updateAPIProductForStateChange.
/**
* Update API Product in registry for lifecycle state change
*
* @param apiProduct API Product Object
* @param currentStatus Current state of API Product
* @param newStatus New state of API Product
* @return boolean indicates success or failure
* @throws APIManagementException if there is an error when updating API Product for lifecycle state
* @throws FaultGatewaysException if there is an error when updating API Product for lifecycle state
*/
public void updateAPIProductForStateChange(APIProduct apiProduct, String currentStatus, String newStatus) throws APIManagementException, FaultGatewaysException {
String provider = apiProduct.getId().getProviderName();
boolean isTenantFlowStarted = false;
try {
String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(provider));
if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
isTenantFlowStarted = true;
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
}
if (!currentStatus.equals(newStatus)) {
apiProduct.setState(newStatus);
// If API status changed to publish we should add it to recently added APIs list
// this should happen in store-publisher cluster domain if deployment is distributed
// IF new API published we will add it to recently added APIs
Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER).getCache(APIConstants.RECENTLY_ADDED_API_CACHE_NAME).removeAll();
if (APIConstants.RETIRED.equals(newStatus)) {
cleanUpPendingSubscriptionCreationProcessesByAPI(apiProduct.getUuid());
apiMgtDAO.removeAllSubscriptions(apiProduct.getUuid());
deleteAPIProductRevisions(apiProduct.getUuid(), tenantDomain);
}
PublisherAPIProduct publisherAPIProduct = APIProductMapper.INSTANCE.toPublisherApiProduct(apiProduct);
try {
apiPersistenceInstance.updateAPIProduct(new Organization(apiProduct.getOrganization()), publisherAPIProduct);
} catch (APIPersistenceException e) {
handleException("Error while persisting the updated API Product", e);
}
}
} finally {
if (isTenantFlowStarted) {
PrivilegedCarbonContext.endTenantFlow();
}
}
}
Aggregations