Search in sources :

Example 41 with FaultGatewaysException

use of org.wso2.carbon.apimgt.api.FaultGatewaysException 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 42 with FaultGatewaysException

use of org.wso2.carbon.apimgt.api.FaultGatewaysException in project carbon-apimgt by wso2.

the class APIProviderImpl method updateAPIforStateChange.

public boolean updateAPIforStateChange(API api, String currentStatus, String newStatus) throws APIManagementException, FaultGatewaysException {
    boolean isSuccess = false;
    String provider = api.getId().getProviderName();
    String providerTenantMode = api.getId().getProviderName();
    provider = APIUtil.replaceEmailDomain(provider);
    String name = api.getId().getApiName();
    String version = api.getId().getVersion();
    boolean isTenantFlowStarted = false;
    try {
        String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(providerTenantMode));
        if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            isTenantFlowStarted = true;
            PrivilegedCarbonContext.startTenantFlow();
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
        }
        // API api = getAPI(apiId);
        if (api != null) {
            if (!currentStatus.equals(newStatus)) {
                api.setStatus(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();
                api.setAsPublishedDefaultVersion(api.getId().getVersion().equals(apiMgtDAO.getPublishedDefaultVersion(api.getId())));
                if (APIConstants.RETIRED.equals(newStatus)) {
                    cleanUpPendingSubscriptionCreationProcessesByAPI(api.getUuid());
                    apiMgtDAO.removeAllSubscriptions(api.getUuid());
                    deleteAPIRevisions(api.getUuid(), tenantDomain);
                }
                // updateApiArtifactNew(api, false, false);
                PublisherAPI publisherAPI = APIMapper.INSTANCE.toPublisherApi(api);
                try {
                    apiPersistenceInstance.updateAPI(new Organization(api.getOrganization()), publisherAPI);
                } catch (APIPersistenceException e) {
                    handleException("Error while persisting the updated API ", e);
                }
            }
            isSuccess = true;
        } else {
            handleException("Couldn't find an API with the name-" + name + "version-" + version);
        }
    } finally {
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }
    return isSuccess;
}
Also used : APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI)

Aggregations

API (org.wso2.carbon.apimgt.api.model.API)26 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)25 FaultGatewaysException (org.wso2.carbon.apimgt.api.FaultGatewaysException)20 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)18 ImportExportAPI (org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)18 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)17 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)16 HashMap (java.util.HashMap)11 APIProduct (org.wso2.carbon.apimgt.api.model.APIProduct)11 Test (org.junit.Test)10 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)10 PublisherAPI (org.wso2.carbon.apimgt.persistence.dto.PublisherAPI)10 Map (java.util.Map)8 Organization (org.wso2.carbon.apimgt.persistence.dto.Organization)8 ArrayList (java.util.ArrayList)7 List (java.util.List)7 JSONObject (org.json.simple.JSONObject)6 APIProductIdentifier (org.wso2.carbon.apimgt.api.model.APIProductIdentifier)6 ServiceReferenceHolder (org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder)6 HashSet (java.util.HashSet)5