use of org.wso2.carbon.apimgt.core.workflow.Workflow in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method apisApiIdLifecycleLifecyclePendingTaskDelete.
/**
* Remove pending lifecycle state change workflow tasks.
*
* @param apiId api id
* @param request msf4j request object
* @return Empty payload
* @throws NotFoundException When the particular resource does not exist in the system
*/
@Override
public Response apisApiIdLifecycleLifecyclePendingTaskDelete(String apiId, Request request) throws NotFoundException {
try {
String username = RestApiUtil.getLoggedInUsername(request);
APIPublisher apiPublisher = RestAPIPublisherUtil.getApiPublisher(username);
apiPublisher.removePendingLifecycleWorkflowTaskForAPI(apiId);
return Response.ok().build();
} catch (APIManagementException e) {
String errorMessage = "Error while removing pending task for API state change for api " + apiId;
Map<String, String> paramList = new HashMap<>();
paramList.put(APIMgtConstants.ExceptionsConstants.API_ID, apiId);
ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler(), paramList);
log.error(errorMessage, e);
return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
}
}
use of org.wso2.carbon.apimgt.core.workflow.Workflow in project carbon-apimgt by wso2.
the class SubscriptionsApiServiceImpl method subscriptionsPost.
/**
* Adds a new subscription
*
* @param body Subscription details to be added
* @param request msf4j request object
* @return Newly added subscription as the response
* @throws NotFoundException When the particular resource does not exist in the system
*/
@Override
public Response subscriptionsPost(SubscriptionDTO body, Request request) throws NotFoundException {
String username = RestApiUtil.getLoggedInUsername(request);
SubscriptionDTO subscriptionDTO = null;
URI location = null;
try {
APIStore apiStore = RestApiUtil.getConsumer(username);
String applicationId = body.getApplicationId();
String apiId = body.getApiIdentifier();
String tier = body.getPolicy();
Application application = apiStore.getApplicationByUuid(applicationId);
if (application != null && !ApplicationStatus.APPLICATION_APPROVED.equals(application.getStatus())) {
String errorMessage = "Application " + applicationId + " is not active";
ExceptionCodes exceptionCode = ExceptionCodes.APPLICATION_INACTIVE;
APIManagementException e = new APIManagementException(errorMessage, exceptionCode);
Map<String, String> paramList = new HashMap<>();
ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler(), paramList);
log.error(errorMessage, e);
return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
}
if (application != null) {
SubscriptionResponse addSubResponse = apiStore.addApiSubscription(apiId, applicationId, tier);
String subscriptionId = addSubResponse.getSubscriptionUUID();
Subscription subscription = apiStore.getSubscriptionByUUID(subscriptionId);
location = new URI(RestApiConstants.RESOURCE_PATH_SUBSCRIPTION + "/" + subscriptionId);
subscriptionDTO = SubscriptionMappingUtil.fromSubscriptionToDTO(subscription);
// be in either pending or approved state) send back the workflow response
if (SubscriptionStatus.ON_HOLD == subscription.getStatus()) {
WorkflowResponseDTO workflowResponse = MiscMappingUtil.fromWorkflowResponseToDTO(addSubResponse.getWorkflowResponse());
return Response.status(Response.Status.ACCEPTED).header(RestApiConstants.LOCATION_HEADER, location).entity(workflowResponse).build();
}
} else {
String errorMessage = null;
ExceptionCodes exceptionCode = null;
exceptionCode = ExceptionCodes.APPLICATION_NOT_FOUND;
errorMessage = "Application not found";
APIMgtResourceNotFoundException e = new APIMgtResourceNotFoundException(errorMessage, exceptionCode);
Map<String, String> paramList = new HashMap<>();
ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler(), paramList);
log.error(errorMessage, e);
return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
}
} catch (GatewayException e) {
String errorMessage = "Failed to add subscription of API : " + body.getApiIdentifier() + " to gateway";
log.error(errorMessage, e);
return Response.status(Response.Status.ACCEPTED).build();
} catch (APIManagementException e) {
String errorMessage = "Error while adding subscriptions";
Map<String, String> paramList = new HashMap<>();
paramList.put(APIMgtConstants.ExceptionsConstants.API_ID, body.getApiIdentifier());
paramList.put(APIMgtConstants.ExceptionsConstants.APPLICATION_ID, body.getApplicationId());
paramList.put(APIMgtConstants.ExceptionsConstants.TIER, body.getPolicy());
ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler(), paramList);
log.error(errorMessage, e);
return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
} catch (URISyntaxException e) {
String errorMessage = "Error while adding location header in response for subscription : " + body.getSubscriptionId();
Map<String, String> paramList = new HashMap<>();
paramList.put(APIMgtConstants.ExceptionsConstants.SUBSCRIPTION_ID, body.getSubscriptionId());
ErrorHandler errorHandler = ExceptionCodes.LOCATION_HEADER_INCORRECT;
ErrorDTO errorDTO = RestApiUtil.getErrorDTO(errorHandler, paramList);
log.error(errorMessage, e);
return Response.status(errorHandler.getHttpStatusCode()).entity(errorDTO).build();
}
return Response.status(Response.Status.CREATED).header(RestApiConstants.LOCATION_HEADER, location).entity(subscriptionDTO).build();
}
use of org.wso2.carbon.apimgt.core.workflow.Workflow in project carbon-apimgt by wso2.
the class APIPublisherImpl method updateAPI.
/**
* Updates design and implementation of an existing API. This method must not be used to change API status.
* Implementations should throw an exceptions when such attempts are made. All life cycle state changes
* should be carried out using the changeAPIStatus method of this interface.
*
* @param apiBuilder {@code org.wso2.carbon.apimgt.core.models.API.APIBuilder} model object
* @throws APIManagementException if failed to update API
*/
@Override
public void updateAPI(API.APIBuilder apiBuilder) throws APIManagementException {
APIGateway gateway = getApiGateway();
apiBuilder.provider(getUsername());
apiBuilder.updatedBy(getUsername());
try {
API originalAPI = getAPIbyUUID(apiBuilder.getId());
if (originalAPI != null) {
// Checks whether the logged in user has the "UPDATE" permission for the API
verifyUserPermissionsToUpdateAPI(getUsername(), originalAPI);
apiBuilder.createdTime(originalAPI.getCreatedTime());
// workflow status is an internal property and shouldn't be allowed to update externally
apiBuilder.workflowStatus(originalAPI.getWorkflowStatus());
if ((originalAPI.getName().equals(apiBuilder.getName())) && (originalAPI.getVersion().equals(apiBuilder.getVersion())) && (originalAPI.getProvider().equals(apiBuilder.getProvider())) && originalAPI.getLifeCycleStatus().equalsIgnoreCase(apiBuilder.getLifeCycleStatus())) {
if (!StringUtils.isEmpty(apiBuilder.getApiPermission())) {
apiBuilder.apiPermission(replaceGroupNamesWithId(apiBuilder.getApiPermission()));
Map<String, Integer> roleNamePermissionList;
roleNamePermissionList = getAPIPermissionArray(apiBuilder.getApiPermission());
apiBuilder.permissionMap(roleNamePermissionList);
}
Map<String, Endpoint> apiEndpointMap = apiBuilder.getEndpoint();
validateEndpoints(apiEndpointMap, true);
validateLabels(apiBuilder.getLabels(), originalAPI.hasOwnGateway());
createUriTemplateList(apiBuilder, true);
validateApiPolicy(apiBuilder.getApiPolicy());
validateSubscriptionPolicies(apiBuilder);
String updatedSwagger = apiDefinitionFromSwagger20.generateMergedResourceDefinition(getApiDAO().getApiSwaggerDefinition(apiBuilder.getId()), apiBuilder.build());
String gatewayConfig = getApiGatewayConfig(apiBuilder.getId());
GatewaySourceGenerator gatewaySourceGenerator = getGatewaySourceGenerator();
APIConfigContext apiConfigContext = new APIConfigContext(apiBuilder.build(), config.getGatewayPackageName());
gatewaySourceGenerator.setApiConfigContext(apiConfigContext);
String updatedGatewayConfig = gatewaySourceGenerator.getGatewayConfigFromSwagger(gatewayConfig, updatedSwagger);
API api = apiBuilder.build();
// Add API to gateway
gateway.updateAPI(api);
if (log.isDebugEnabled()) {
log.debug("API : " + apiBuilder.getName() + " has been successfully updated in gateway");
}
if (originalAPI.getContext() != null && !originalAPI.getContext().equals(apiBuilder.getContext())) {
if (!checkIfAPIContextExists(api.getContext())) {
// if the API has public visibility, update the API without any role checking
if (API.Visibility.PUBLIC == api.getVisibility()) {
getApiDAO().updateAPI(api.getId(), api);
} else if (API.Visibility.RESTRICTED == api.getVisibility()) {
// get all the roles in the system
Set<String> availableRoles = APIUtils.getAllAvailableRoles();
// get the roles needed to be associated with the API
Set<String> apiRoleList = api.getVisibleRoles();
// if the API has role based visibility, update the API with role checking
if (APIUtils.checkAllowedRoles(availableRoles, apiRoleList)) {
getApiDAO().updateAPI(api.getId(), api);
}
}
getApiDAO().updateApiDefinition(api.getId(), updatedSwagger, api.getUpdatedBy());
getApiDAO().updateGatewayConfig(api.getId(), updatedGatewayConfig, api.getUpdatedBy());
} else {
throw new APIManagementException("Context already Exist", ExceptionCodes.API_ALREADY_EXISTS);
}
} else {
// if the API has public visibility, update the API without any role checking
if (API.Visibility.PUBLIC == api.getVisibility()) {
getApiDAO().updateAPI(api.getId(), api);
} else if (API.Visibility.RESTRICTED == api.getVisibility()) {
// get all the roles in the system
Set<String> allAvailableRoles = APIUtils.getAllAvailableRoles();
// get the roles needed to be associated with the API
Set<String> apiRoleList = api.getVisibleRoles();
// if the API has role based visibility, update the API with role checking
if (APIUtils.checkAllowedRoles(allAvailableRoles, apiRoleList)) {
getApiDAO().updateAPI(api.getId(), api);
}
}
getApiDAO().updateApiDefinition(api.getId(), updatedSwagger, api.getUpdatedBy());
getApiDAO().updateGatewayConfig(api.getId(), updatedGatewayConfig, api.getUpdatedBy());
}
if (log.isDebugEnabled()) {
log.debug("API " + api.getName() + "-" + api.getVersion() + " was updated successfully.");
// 'API_M Functions' related code
// Create a payload with event specific details
Map<String, String> eventPayload = new HashMap<>();
eventPayload.put(APIMgtConstants.FunctionsConstants.API_ID, api.getId());
eventPayload.put(APIMgtConstants.FunctionsConstants.API_NAME, api.getName());
eventPayload.put(APIMgtConstants.FunctionsConstants.API_VERSION, api.getVersion());
eventPayload.put(APIMgtConstants.FunctionsConstants.API_DESCRIPTION, api.getDescription());
eventPayload.put(APIMgtConstants.FunctionsConstants.API_CONTEXT, api.getContext());
eventPayload.put(APIMgtConstants.FunctionsConstants.API_LC_STATUS, api.getLifeCycleStatus());
// This will notify all the EventObservers(Asynchronous)
ObserverNotifier observerNotifier = new ObserverNotifier(Event.API_UPDATE, getUsername(), ZonedDateTime.now(ZoneOffset.UTC), eventPayload, this);
ObserverNotifierThreadPool.getInstance().executeTask(observerNotifier);
}
} else {
APIUtils.verifyValidityOfApiUpdate(apiBuilder, originalAPI);
}
} else {
log.error("Couldn't found API with ID " + apiBuilder.getId());
throw new APIManagementException("Couldn't found API with ID " + apiBuilder.getId(), ExceptionCodes.API_NOT_FOUND);
}
} catch (APIMgtDAOException e) {
String errorMsg = "Error occurred while updating the API - " + apiBuilder.getName();
log.error(errorMsg, e);
throw new APIManagementException(errorMsg, e, e.getErrorHandler());
} catch (ParseException e) {
String errorMsg = "Error occurred while parsing the permission json from swagger - " + apiBuilder.getName();
log.error(errorMsg, e);
throw new APIManagementException(errorMsg, e, ExceptionCodes.SWAGGER_PARSE_EXCEPTION);
} catch (GatewayException e) {
String message = "Error occurred while updating API - " + apiBuilder.getName() + " in gateway";
log.error(message, e);
throw new APIManagementException(message, ExceptionCodes.GATEWAY_EXCEPTION);
}
}
use of org.wso2.carbon.apimgt.core.workflow.Workflow in project carbon-apimgt by wso2.
the class APIPublisherImpl method updateAPIStatus.
/**
* @see org.wso2.carbon.apimgt.core.api.APIPublisher#updateAPIStatus(String, String, Map)
*/
@Override
public WorkflowResponse updateAPIStatus(String apiId, String status, Map<String, Boolean> checkListItemMap) throws APIManagementException {
WorkflowResponse workflowResponse = null;
try {
API api = getApiDAO().getAPI(apiId);
if (api != null && !APILCWorkflowStatus.PENDING.toString().equals(api.getWorkflowStatus())) {
API.APIBuilder apiBuilder = new API.APIBuilder(api);
apiBuilder.lastUpdatedTime(LocalDateTime.now());
apiBuilder.updatedBy(getUsername());
LifecycleState currentState = getApiLifecycleManager().getLifecycleDataForState(apiBuilder.getLifecycleInstanceId(), apiBuilder.getLifeCycleStatus());
apiBuilder.lifecycleState(currentState);
for (Map.Entry<String, Boolean> checkListItem : checkListItemMap.entrySet()) {
getApiLifecycleManager().checkListItemEvent(api.getLifecycleInstanceId(), api.getLifeCycleStatus(), checkListItem.getKey(), checkListItem.getValue());
}
API originalAPI = apiBuilder.build();
WorkflowExecutor executor = WorkflowExecutorFactory.getInstance().getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_API_STATE);
APIStateChangeWorkflow workflow = new APIStateChangeWorkflow(getApiDAO(), getApiSubscriptionDAO(), getWorkflowDAO(), getApiLifecycleManager(), getApiGateway(), getLabelDAO());
workflow.setApiName(originalAPI.getName());
workflow.setApiProvider(originalAPI.getProvider());
workflow.setApiVersion(originalAPI.getVersion());
workflow.setCurrentState(currentState.getState());
workflow.setTransitionState(status);
workflow.setWorkflowReference(originalAPI.getId());
workflow.setExternalWorkflowReference(UUID.randomUUID().toString());
workflow.setCreatedTime(LocalDateTime.now());
workflow.setWorkflowType(WorkflowConstants.WF_TYPE_AM_API_STATE);
workflow.setInvoker(getUsername());
// setting attributes for internal use. These are set to use from outside the executor's method
// these will be saved in the AM_WORKFLOW table so these can be retrieved later
workflow.setAttribute(WorkflowConstants.ATTRIBUTE_API_CUR_STATE, currentState.getState());
workflow.setAttribute(WorkflowConstants.ATTRIBUTE_API_TARGET_STATE, status);
workflow.setAttribute(WorkflowConstants.ATTRIBUTE_API_LC_INVOKER, getUsername());
workflow.setAttribute(WorkflowConstants.ATTRIBUTE_API_NAME, originalAPI.getId());
workflow.setAttribute(WorkflowConstants.ATTRIBUTE_API_HAS_OWN_GATEWAY, String.valueOf(originalAPI.hasOwnGateway()));
if (originalAPI.hasOwnGateway()) {
List<String> gwLabels = originalAPI.getLabels();
for (String label : gwLabels) {
if (label.contains(ContainerBasedGatewayConstants.PRIVATE_JET_API_PREFIX)) {
workflow.setAttribute(WorkflowConstants.ATTRIBUTE_API_AUTOGEN_LABEL, label);
break;
}
}
}
workflow.setAttribute(WorkflowConstants.ATTRIBUTE_HAS_OWN_GATEWAY, String.valueOf(originalAPI.hasOwnGateway()));
workflow.setAttribute(WorkflowConstants.ATTRIBUTE_API_LAST_UPTIME, originalAPI.getLastUpdatedTime().toString());
String workflowDescription = "API [" + workflow.getApiName() + " - " + workflow.getApiVersion() + "] state change [" + workflow.getCurrentState() + " to " + workflow.getTransitionState() + "] request from " + getUsername();
workflow.setWorkflowDescription(workflowDescription);
workflowResponse = executor.execute(workflow);
workflow.setStatus(workflowResponse.getWorkflowStatus());
if (WorkflowStatus.CREATED != workflowResponse.getWorkflowStatus()) {
completeWorkflow(executor, workflow);
} else {
// add entry to workflow table if it is only in pending state
addWorkflowEntries(workflow);
getApiDAO().updateAPIWorkflowStatus(api.getId(), APILCWorkflowStatus.PENDING);
}
} else if (api != null && APILCWorkflowStatus.PENDING.toString().equals(api.getWorkflowStatus())) {
String message = "Pending state transition for api :" + api.getName();
log.error(message);
throw new APIManagementException(message, ExceptionCodes.WORKFLOW_PENDING);
} else {
throw new APIMgtResourceNotFoundException("Requested API " + apiId + " Not Available");
}
} catch (APIMgtDAOException e) {
String errorMsg = "Couldn't change the status of api ID " + apiId;
log.error(errorMsg, e);
throw new APIManagementException(errorMsg, e, e.getErrorHandler());
} catch (LifecycleException e) {
String errorMsg = "Couldn't change the status of api ID " + apiId;
log.error(errorMsg, e);
throw new APIManagementException(errorMsg, e, ExceptionCodes.APIMGT_LIFECYCLE_EXCEPTION);
}
return workflowResponse;
}
use of org.wso2.carbon.apimgt.core.workflow.Workflow in project carbon-apimgt by wso2.
the class APIStoreImpl method deleteApplication.
/**
* @see APIStore#deleteApplication(String)
*/
@Override
public WorkflowResponse deleteApplication(String appId) throws APIManagementException {
try {
if (appId == null) {
String message = "Application Id is not provided";
throw new APIManagementException(message, ExceptionCodes.PARAMETER_NOT_PROVIDED);
}
// get app info
Application application = getApplicationDAO().getApplication(appId);
if (application == null) {
String message = "Application cannot be found for id :" + appId;
throw new APIManagementException(message, ExceptionCodes.APPLICATION_NOT_FOUND);
}
// delete application creation pending tasks
cleanupPendingTaskForApplicationDeletion(application);
WorkflowExecutor removeApplicationWFExecutor = WorkflowExecutorFactory.getInstance().getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_APPLICATION_DELETION);
ApplicationDeletionWorkflow workflow = new ApplicationDeletionWorkflow(getApplicationDAO(), getWorkflowDAO(), getApiGateway());
workflow.setApplication(application);
workflow.setWorkflowType(APIMgtConstants.WorkflowConstants.WF_TYPE_AM_APPLICATION_DELETION);
workflow.setWorkflowReference(application.getId());
workflow.setExternalWorkflowReference(UUID.randomUUID().toString());
workflow.setCreatedTime(LocalDateTime.now());
String workflowDescription = "Application [ " + application.getName() + " ] deletion request from - " + application.getName();
workflow.setWorkflowDescription(workflowDescription);
WorkflowResponse response = removeApplicationWFExecutor.execute(workflow);
workflow.setStatus(response.getWorkflowStatus());
if (WorkflowStatus.CREATED != response.getWorkflowStatus()) {
completeWorkflow(removeApplicationWFExecutor, workflow);
} else {
// add entry to workflow table if it is only in pending state
addWorkflowEntries(workflow);
}
return response;
} catch (APIMgtDAOException e) {
String errorMsg = "Error occurred while deleting the application - " + appId;
log.error(errorMsg, e);
throw new APIManagementException(errorMsg, e, e.getErrorHandler());
}
}
Aggregations