Search in sources :

Example 21 with APIEvent

use of org.wso2.carbon.apimgt.core.models.events.APIEvent in project carbon-apimgt by wso2.

the class APIProviderImpl method addAPI.

/**
 * Add API metadata, local scopes and URI templates to the database and KeyManager.
 *
 * @param api      API to add
 * @param tenantId Tenant Id
 * @throws APIManagementException if an error occurs while adding the API
 */
private void addAPI(API api, int tenantId) throws APIManagementException {
    int apiId = apiMgtDAO.addAPI(api, tenantId, api.getOrganization());
    addLocalScopes(api.getId().getApiName(), api.getUriTemplates(), api.getOrganization());
    String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(api.getId().getProviderName()));
    validateOperationPolicyParameters(api, tenantDomain);
    addURITemplates(apiId, api, tenantId);
    APIEvent apiEvent = new APIEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.API_CREATE.name(), tenantId, tenantDomain, api.getId().getApiName(), apiId, api.getUuid(), api.getId().getVersion(), api.getType(), api.getContext(), APIUtil.replaceEmailDomainBack(api.getId().getProviderName()), api.getStatus());
    APIUtil.sendNotification(apiEvent, APIConstants.NotifierType.API.name());
}
Also used : APIEvent(org.wso2.carbon.apimgt.impl.notifier.events.APIEvent)

Example 22 with APIEvent

use of org.wso2.carbon.apimgt.core.models.events.APIEvent in project carbon-apimgt by wso2.

the class APIProviderImpl method sendLCStateChangeNotification.

/**
 * @param apiName           Name of the API
 * @param apiType           API Type
 * @param apiContext        API or Product context
 * @param apiVersion        API or Product version
 * @param targetStatus      Target Lifecycle status
 * @param provider          Provider of the API or Product
 * @param apiOrApiProductId unique ID of API or API product
 * @param uuid              unique UUID of API or API Product
 */
private void sendLCStateChangeNotification(String apiName, String apiType, String apiContext, String apiVersion, String targetStatus, String provider, int apiOrApiProductId, String uuid) {
    APIEvent apiEvent = new APIEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.API_LIFECYCLE_CHANGE.name(), tenantId, tenantDomain, apiName, apiOrApiProductId, uuid, apiVersion, apiType, apiContext, APIUtil.replaceEmailDomainBack(provider), targetStatus);
    APIUtil.sendNotification(apiEvent, APIConstants.NotifierType.API.name());
}
Also used : APIEvent(org.wso2.carbon.apimgt.impl.notifier.events.APIEvent)

Example 23 with APIEvent

use of org.wso2.carbon.apimgt.core.models.events.APIEvent in project carbon-apimgt by wso2.

the class APIProviderImpl method changeLifeCycleStatus.

public APIStateChangeResponse changeLifeCycleStatus(APIIdentifier apiIdentifier, String action, String organization) throws APIManagementException, FaultGatewaysException {
    APIStateChangeResponse response = new APIStateChangeResponse();
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(this.username);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(this.tenantDomain, true);
        GenericArtifact apiArtifact = getAPIArtifact(apiIdentifier);
        String targetStatus;
        if (apiArtifact != null) {
            String providerName = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER);
            String apiName = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_NAME);
            String apiContext = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT);
            String apiType = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_TYPE);
            String apiVersion = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_VERSION);
            String currentStatus = apiArtifact.getLifecycleState();
            String uuid = apiMgtDAO.getUUIDFromIdentifier(apiIdentifier, organization);
            String gatewayVendor = apiMgtDAO.getGatewayVendorByAPIUUID(uuid);
            int apiId = apiMgtDAO.getAPIID(uuid);
            WorkflowStatus apiWFState = null;
            WorkflowDTO wfDTO = apiMgtDAO.retrieveWorkflowFromInternalReference(Integer.toString(apiId), WorkflowConstants.WF_TYPE_AM_API_STATE);
            if (wfDTO != null) {
                apiWFState = wfDTO.getStatus();
            }
            // if the workflow has started, then executor should not fire again
            if (!WorkflowStatus.CREATED.equals(apiWFState)) {
                try {
                    WorkflowProperties workflowProperties = getAPIManagerConfiguration().getWorkflowProperties();
                    WorkflowExecutor apiStateWFExecutor = WorkflowExecutorFactory.getInstance().getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_API_STATE);
                    APIStateWorkflowDTO apiStateWorkflow = new APIStateWorkflowDTO();
                    apiStateWorkflow.setApiCurrentState(currentStatus);
                    apiStateWorkflow.setApiLCAction(action);
                    apiStateWorkflow.setApiName(apiName);
                    apiStateWorkflow.setApiContext(apiContext);
                    apiStateWorkflow.setApiType(apiType);
                    apiStateWorkflow.setApiVersion(apiVersion);
                    apiStateWorkflow.setApiProvider(providerName);
                    apiStateWorkflow.setGatewayVendor(gatewayVendor);
                    apiStateWorkflow.setCallbackUrl(workflowProperties.getWorkflowCallbackAPI());
                    apiStateWorkflow.setExternalWorkflowReference(apiStateWFExecutor.generateUUID());
                    apiStateWorkflow.setTenantId(tenantId);
                    apiStateWorkflow.setTenantDomain(this.tenantDomain);
                    apiStateWorkflow.setWorkflowType(WorkflowConstants.WF_TYPE_AM_API_STATE);
                    apiStateWorkflow.setStatus(WorkflowStatus.CREATED);
                    apiStateWorkflow.setCreatedTime(System.currentTimeMillis());
                    apiStateWorkflow.setWorkflowReference(Integer.toString(apiId));
                    apiStateWorkflow.setInvoker(this.username);
                    apiStateWorkflow.setApiUUID(uuid);
                    String workflowDescription = "Pending lifecycle state change action: " + action;
                    apiStateWorkflow.setWorkflowDescription(workflowDescription);
                    WorkflowResponse workflowResponse = apiStateWFExecutor.execute(apiStateWorkflow);
                    response.setWorkflowResponse(workflowResponse);
                } catch (WorkflowException e) {
                    handleException("Failed to execute workflow for life cycle status change : " + e.getMessage(), e);
                }
                // get the workflow state once the executor is executed.
                wfDTO = apiMgtDAO.retrieveWorkflowFromInternalReference(Integer.toString(apiId), WorkflowConstants.WF_TYPE_AM_API_STATE);
                if (wfDTO != null) {
                    apiWFState = wfDTO.getStatus();
                    response.setStateChangeStatus(apiWFState.toString());
                } else {
                    response.setStateChangeStatus(WorkflowStatus.APPROVED.toString());
                }
            }
            // apiWFState is null when simple wf executor is used because wf state is not stored in the db.
            if (WorkflowStatus.APPROVED.equals(apiWFState) || apiWFState == null) {
                targetStatus = "";
                apiArtifact.invokeAction(action, APIConstants.API_LIFE_CYCLE);
                targetStatus = apiArtifact.getLifecycleState();
                if (!currentStatus.equals(targetStatus)) {
                    apiMgtDAO.recordAPILifeCycleEvent(apiId, currentStatus.toUpperCase(), targetStatus.toUpperCase(), this.username, this.tenantId);
                }
                if (log.isDebugEnabled()) {
                    String logMessage = "API Status changed successfully. API Name: " + apiIdentifier.getApiName() + ", API Version " + apiIdentifier.getVersion() + ", New Status : " + targetStatus;
                    log.debug(logMessage);
                }
                APIEvent apiEvent = new APIEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.API_LIFECYCLE_CHANGE.name(), tenantId, tenantDomain, apiName, apiId, uuid, apiVersion, apiType, apiContext, providerName, targetStatus);
                APIUtil.sendNotification(apiEvent, APIConstants.NotifierType.API.name());
                return response;
            }
        }
    } catch (GovernanceException e) {
        String cause = e.getCause().getMessage();
        if (!StringUtils.isEmpty(cause)) {
            if (cause.contains("FaultGatewaysException:")) {
                Map<String, Map<String, String>> faultMap = new HashMap<String, Map<String, String>>();
                String faultJsonString;
                if (!StringUtils.isEmpty(cause) && cause.split("FaultGatewaysException:").length > 1) {
                    faultJsonString = cause.split("FaultGatewaysException:")[1];
                    try {
                        JSONObject faultGatewayJson = (JSONObject) new JSONParser().parse(faultJsonString);
                        faultMap.putAll(faultGatewayJson);
                        throw new FaultGatewaysException(faultMap);
                    } catch (ParseException e1) {
                        log.error("Couldn't parse the Failed Environment json", e);
                        handleException("Couldn't parse the Failed Environment json : " + e.getMessage(), e);
                    }
                }
            } else if (cause.contains("APIManagementException:")) {
                // This exception already logged from APIExecutor class hence this no need to logged again
                handleException("Failed to change the life cycle status : " + cause.split("APIManagementException:")[1], e);
            } else {
                /* This exception already logged from APIExecutor class hence this no need to logged again
                    This block handles the all the exception which not have custom cause message*/
                handleException("Failed to change the life cycle status : " + e.getMessage(), e);
            }
        }
        return response;
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
    return response;
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) WorkflowDTO(org.wso2.carbon.apimgt.impl.dto.WorkflowDTO) APIStateWorkflowDTO(org.wso2.carbon.apimgt.impl.workflow.APIStateWorkflowDTO) WorkflowException(org.wso2.carbon.apimgt.impl.workflow.WorkflowException) APIStateWorkflowDTO(org.wso2.carbon.apimgt.impl.workflow.APIStateWorkflowDTO) FaultGatewaysException(org.wso2.carbon.apimgt.api.FaultGatewaysException) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) WorkflowProperties(org.wso2.carbon.apimgt.impl.dto.WorkflowProperties) WorkflowStatus(org.wso2.carbon.apimgt.impl.workflow.WorkflowStatus) APIEvent(org.wso2.carbon.apimgt.impl.notifier.events.APIEvent) JSONObject(org.json.simple.JSONObject) APIStateChangeResponse(org.wso2.carbon.apimgt.api.model.APIStateChangeResponse) WorkflowResponse(org.wso2.carbon.apimgt.api.WorkflowResponse) WorkflowExecutor(org.wso2.carbon.apimgt.impl.workflow.WorkflowExecutor) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException) Map(java.util.Map) TreeMap(java.util.TreeMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap)

Example 24 with APIEvent

use of org.wso2.carbon.apimgt.core.models.events.APIEvent in project carbon-apimgt by wso2.

the class APIProviderImpl method changeLifeCycle.

private void changeLifeCycle(API api, String currentState, String targetState, Map<String, Boolean> checklist) throws APIManagementException, FaultGatewaysException {
    String oldStatus = currentState.toUpperCase();
    String newStatus = (targetState != null) ? targetState.toUpperCase() : targetState;
    boolean isCurrentCreatedOrPrototyped = APIConstants.CREATED.equals(oldStatus) || APIConstants.PROTOTYPED.equals(oldStatus);
    boolean isStateTransitionToPublished = isCurrentCreatedOrPrototyped && APIConstants.PUBLISHED.equals(newStatus);
    if (newStatus != null) {
        // custom state to default api state
        if (isStateTransitionToPublished) {
            Set<Tier> tiers = api.getAvailableTiers();
            String endPoint = api.getEndpointConfig();
            String apiSecurity = api.getApiSecurity();
            boolean isOauthProtected = apiSecurity == null || apiSecurity.contains(APIConstants.DEFAULT_API_SECURITY_OAUTH2);
            if (APIConstants.API_TYPE_WEBSUB.equals(api.getType()) || endPoint != null && endPoint.trim().length() > 0 || api.isAdvertiseOnly() && (api.getApiExternalProductionEndpoint() != null || api.getApiExternalSandboxEndpoint() != null)) {
                if ((isOauthProtected && (tiers == null || tiers.size() == 0)) && !api.isAdvertiseOnly()) {
                    throw new APIManagementException("Failed to publish service to API store. No Tiers selected");
                }
            } else {
                throw new APIManagementException("Failed to publish service to API store. No endpoint selected");
            }
        }
        // push the state change to gateway
        Map<String, String> failedGateways = propergateAPIStatusChangeToGateways(newStatus, api);
        if (APIConstants.PUBLISHED.equals(newStatus) || !oldStatus.equals(newStatus)) {
            // if the API is websocket and if default version is selected, update the other versions
            if (APIConstants.APITransportType.WS.toString().equals(api.getType()) && api.isDefaultVersion()) {
                Set<String> versions = getAPIVersions(api.getId().getProviderName(), api.getId().getName(), api.getOrganization());
                for (String version : versions) {
                    if (version.equals(api.getId().getVersion())) {
                        continue;
                    }
                    String uuid = APIUtil.getUUIDFromIdentifier(new APIIdentifier(api.getId().getProviderName(), api.getId().getName(), version), api.getOrganization());
                    API otherApi = getLightweightAPIByUUID(uuid, api.getOrganization());
                    APIEvent apiEvent = new APIEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.API_UPDATE.name(), tenantId, tenantDomain, otherApi.getId().getApiName(), otherApi.getId().getId(), otherApi.getUuid(), version, api.getType(), otherApi.getContext(), otherApi.getId().getProviderName(), otherApi.getStatus());
                    APIUtil.sendNotification(apiEvent, APIConstants.NotifierType.API.name());
                }
            }
        }
        if (log.isDebugEnabled()) {
            String logMessage = "Publish changed status to the Gateway. API Name: " + api.getId().getApiName() + ", API Version " + api.getId().getVersion() + ", API Context: " + api.getContext() + ", New Status : " + newStatus;
            log.debug(logMessage);
        }
        // update api related information for state change
        updateAPIforStateChange(api, currentState, newStatus);
        if (log.isDebugEnabled()) {
            String logMessage = "API related information successfully updated. API Name: " + api.getId().getApiName() + ", API Version " + api.getId().getVersion() + ", API Context: " + api.getContext() + ", New Status : " + newStatus;
            log.debug(logMessage);
        }
    } else {
        throw new APIManagementException("Invalid Lifecycle status for default APIExecutor :" + targetState);
    }
    boolean deprecateOldVersions = false;
    boolean makeKeysForwardCompatible = true;
    // If the API status is CREATED/PROTOTYPED ,check for check list items of lifecycle
    if (isCurrentCreatedOrPrototyped) {
        if (checklist != null) {
            if (checklist.containsKey(APIConstants.DEPRECATE_CHECK_LIST_ITEM)) {
                deprecateOldVersions = checklist.get(APIConstants.DEPRECATE_CHECK_LIST_ITEM);
            }
            if (checklist.containsKey(APIConstants.RESUBSCRIBE_CHECK_LIST_ITEM)) {
                makeKeysForwardCompatible = !checklist.get(APIConstants.RESUBSCRIBE_CHECK_LIST_ITEM);
            }
        }
    }
    if (isStateTransitionToPublished) {
        if (makeKeysForwardCompatible) {
            makeAPIKeysForwardCompatible(api);
        }
        if (deprecateOldVersions) {
            String provider = APIUtil.replaceEmailDomain(api.getId().getProviderName());
            String apiName = api.getId().getName();
            List<API> apiList = getAPIVersionsByProviderAndName(provider, apiName, api.getOrganization());
            APIVersionComparator versionComparator = new APIVersionComparator();
            for (API oldAPI : apiList) {
                if (oldAPI.getId().getApiName().equals(api.getId().getApiName()) && versionComparator.compare(oldAPI, api) < 0 && (APIConstants.PUBLISHED.equals(oldAPI.getStatus()))) {
                    changeLifeCycleStatus(tenantDomain, new ApiTypeWrapper(oldAPI), APIConstants.API_LC_ACTION_DEPRECATE, null);
                }
            }
        }
    }
}
Also used : Tier(org.wso2.carbon.apimgt.api.model.Tier) ApiTypeWrapper(org.wso2.carbon.apimgt.api.model.ApiTypeWrapper) APIVersionComparator(org.wso2.carbon.apimgt.impl.utils.APIVersionComparator) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIEvent(org.wso2.carbon.apimgt.impl.notifier.events.APIEvent) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI)

Example 25 with APIEvent

use of org.wso2.carbon.apimgt.core.models.events.APIEvent in project carbon-apimgt by wso2.

the class KeyManagerDataServiceImpl method getAPIFromAPIEvent.

private API getAPIFromAPIEvent(APIEvent event) {
    API api = new API();
    api.setUuid(event.getUuid());
    api.setApiId(event.getApiId());
    api.setApiName(event.getApiName());
    api.setApiProvider(event.getApiProvider());
    api.setApiVersion(event.getApiVersion());
    api.setContext(event.getApiContext());
    if (log.isDebugEnabled()) {
        log.debug("Event: " + event.toString());
        log.debug("Converted : " + api.toString());
    }
    return api;
}
Also used : API(org.wso2.carbon.apimgt.keymgt.model.entity.API)

Aggregations

APIEvent (org.wso2.carbon.apimgt.impl.notifier.events.APIEvent)15 API (org.wso2.carbon.apimgt.api.model.API)8 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)7 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)6 APIEvent (org.wso2.carbon.apimgt.core.models.events.APIEvent)6 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)5 ImportExportAPI (org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)5 PublisherAPI (org.wso2.carbon.apimgt.persistence.dto.PublisherAPI)5 HashMap (java.util.HashMap)4 Map (java.util.Map)4 TreeMap (java.util.TreeMap)4 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)4 JSONObject (org.json.simple.JSONObject)4 Gson (com.google.gson.Gson)3 JSONParser (org.json.simple.parser.JSONParser)3 ParseException (org.json.simple.parser.ParseException)3 APIProductIdentifier (org.wso2.carbon.apimgt.api.model.APIProductIdentifier)3 HashSet (java.util.HashSet)2 APIProductResource (org.wso2.carbon.apimgt.api.model.APIProductResource)2 APIRevisionDeployment (org.wso2.carbon.apimgt.api.model.APIRevisionDeployment)2