Search in sources :

Example 16 with APIVersionComparator

use of org.wso2.carbon.apimgt.impl.utils.APIVersionComparator in project carbon-apimgt by wso2.

the class APIConsumerImpl method getAllPaginatedPublishedAPIs.

/**
 * The method to get APIs to Store view      *
 *
 * @return Set<API>  Set of APIs
 * @throws APIManagementException
 */
@Override
@Deprecated
public Map<String, Object> getAllPaginatedPublishedAPIs(String tenantDomain, int start, int end) throws APIManagementException {
    Boolean displayAPIsWithMultipleStatus = false;
    try {
        if (tenantDomain != null) {
            PrivilegedCarbonContext.startTenantFlow();
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
        }
        displayAPIsWithMultipleStatus = APIUtil.isAllowDisplayAPIsWithMultipleStatus();
    } finally {
        endTenantFlow();
    }
    Map<String, List<String>> listMap = new HashMap<String, List<String>>();
    // Check the api-manager.xml config file entry <DisplayAllAPIs> value is false
    if (!displayAPIsWithMultipleStatus) {
        // Create the search attribute map
        listMap.put(APIConstants.API_OVERVIEW_STATUS, new ArrayList<String>() {

            {
                add(APIConstants.PUBLISHED);
            }
        });
    } else {
        return getAllPaginatedAPIs(tenantDomain, start, end);
    }
    Map<String, Object> result = new HashMap<String, Object>();
    SortedSet<API> apiSortedSet = new TreeSet<API>(new APINameComparator());
    SortedSet<API> apiVersionsSortedSet = new TreeSet<API>(new APIVersionComparator());
    int totalLength = 0;
    try {
        Registry userRegistry;
        boolean isTenantMode = (tenantDomain != null);
        if ((isTenantMode && this.tenantDomain == null) || (isTenantMode && isTenantDomainNotMatching(tenantDomain))) {
            // Tenant store anonymous mode
            int tenantId = getTenantId(tenantDomain);
            // explicitly load the tenant's registry
            APIUtil.loadTenantRegistry(tenantId);
            userRegistry = getGovernanceUserRegistry(tenantId);
            setUsernameToThreadLocalCarbonContext(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME);
        } else {
            userRegistry = registry;
            setUsernameToThreadLocalCarbonContext(this.username);
        }
        this.isTenantModeStoreView = isTenantMode;
        this.requestedTenant = tenantDomain;
        Map<String, API> latestPublishedAPIs = new HashMap<String, API>();
        List<API> multiVersionedAPIs = new ArrayList<API>();
        Comparator<API> versionComparator = new APIVersionComparator();
        Boolean displayMultipleVersions = APIUtil.isAllowDisplayMultipleVersions();
        PaginationContext.init(start, end, "ASC", APIConstants.API_OVERVIEW_NAME, Integer.MAX_VALUE);
        GenericArtifactManager artifactManager = APIUtil.getArtifactManager(userRegistry, APIConstants.API_KEY);
        if (artifactManager != null) {
            GenericArtifact[] genericArtifacts = artifactManager.findGenericArtifacts(listMap);
            totalLength = PaginationContext.getInstance().getLength();
            if (genericArtifacts == null || genericArtifacts.length == 0) {
                result.put("apis", apiSortedSet);
                result.put("totalLength", totalLength);
                return result;
            }
            for (GenericArtifact artifact : genericArtifacts) {
                if (artifact == null) {
                    log.error("Failed to retrieve artifact when getting paginated published API.");
                    continue;
                }
                // adding the API provider can mark the latest API .
                API api = APIUtil.getAPI(artifact);
                if (api != null) {
                    String key;
                    // Check the configuration to allow showing multiple versions of an API true/false
                    if (!displayMultipleVersions) {
                        // If allow only showing the latest version of an API
                        key = api.getId().getProviderName() + COLON_CHAR + api.getId().getApiName();
                        API existingAPI = latestPublishedAPIs.get(key);
                        if (existingAPI != null) {
                            // this one has a higher version number
                            if (versionComparator.compare(api, existingAPI) > 0) {
                                latestPublishedAPIs.put(key, api);
                            }
                        } else {
                            // We haven't seen this API before
                            latestPublishedAPIs.put(key, api);
                        }
                    } else {
                        // If allow showing multiple versions of an API
                        multiVersionedAPIs.add(api);
                    }
                }
            }
            if (!displayMultipleVersions) {
                apiSortedSet.addAll(latestPublishedAPIs.values());
                result.put("apis", apiSortedSet);
                result.put("totalLength", totalLength);
                return result;
            } else {
                apiVersionsSortedSet.addAll(multiVersionedAPIs);
                result.put("apis", apiVersionsSortedSet);
                result.put("totalLength", totalLength);
                return result;
            }
        } else {
            String errorMessage = "Artifact manager is null for tenant domain " + tenantDomain + " when retrieving all Published APIs.";
            log.error(errorMessage);
        }
    } catch (RegistryException e) {
        handleException("Failed to get all published APIs", e);
    } catch (UserStoreException e) {
        handleException("Failed to get all published APIs", e);
    } finally {
        PaginationContext.destroy();
    }
    result.put("apis", apiSortedSet);
    result.put("totalLength", totalLength);
    return result;
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) APINameComparator(org.wso2.carbon.apimgt.impl.utils.APINameComparator) APIVersionComparator(org.wso2.carbon.apimgt.impl.utils.APIVersionComparator) TreeSet(java.util.TreeSet) UserStoreException(org.wso2.carbon.user.api.UserStoreException) CommentList(org.wso2.carbon.apimgt.api.model.CommentList) ArrayList(java.util.ArrayList) List(java.util.List) GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) JSONObject(org.json.simple.JSONObject) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) API(org.wso2.carbon.apimgt.api.model.API)

Example 17 with APIVersionComparator

use of org.wso2.carbon.apimgt.impl.utils.APIVersionComparator in project carbon-apimgt by wso2.

the class APIConsumerImpl method getRecentlyAddedAPIs.

/**
 * Get the recently added APIs set
 *
 * @param limit no limit. Return everything else, limit the return list to specified value.
 * @return Set<API>
 * @throws APIManagementException
 */
@Override
public Set<API> getRecentlyAddedAPIs(int limit, String tenantDomain) throws APIManagementException {
    SortedSet<API> recentlyAddedAPIs = new TreeSet<API>(new APINameComparator());
    SortedSet<API> recentlyAddedAPIsWithMultipleVersions = new TreeSet<API>(new APIVersionComparator());
    Registry userRegistry;
    APIManagerConfiguration config = getAPIManagerConfiguration();
    boolean isRecentlyAddedAPICacheEnabled = Boolean.parseBoolean(config.getFirstProperty(APIConstants.API_STORE_RECENTLY_ADDED_API_CACHE_ENABLE));
    PrivilegedCarbonContext.startTenantFlow();
    boolean isTenantFlowStarted;
    if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
        isTenantFlowStarted = true;
    } else {
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true);
        isTenantFlowStarted = true;
    }
    try {
        boolean isTenantMode = (tenantDomain != null);
        if ((isTenantMode && this.tenantDomain == null) || (isTenantMode && isTenantDomainNotMatching(tenantDomain))) {
            // Tenant based store anonymous mode
            int tenantId = getTenantId(tenantDomain);
            // explicitly load the tenant's registry
            APIUtil.loadTenantRegistry(tenantId);
            setUsernameToThreadLocalCarbonContext(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME);
            isTenantFlowStarted = true;
            userRegistry = getGovernanceUserRegistry(tenantId);
        } else {
            userRegistry = registry;
            setUsernameToThreadLocalCarbonContext(this.username);
            isTenantFlowStarted = true;
        }
        if (isRecentlyAddedAPICacheEnabled) {
            boolean isStatusChanged = false;
            Set<API> recentlyAddedAPI = (Set<API>) Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER).getCache(APIConstants.RECENTLY_ADDED_API_CACHE_NAME).get(username + COLON_CHAR + tenantDomain);
            if (recentlyAddedAPI != null) {
                for (API api : recentlyAddedAPI) {
                    try {
                        if (!APIConstants.PUBLISHED.equalsIgnoreCase(userRegistry.get(APIUtil.getAPIPath(api.getId())).getProperty(APIConstants.API_STATUS))) {
                            isStatusChanged = true;
                            break;
                        }
                    } catch (Exception ex) {
                        log.error("Error while checking API status for APP " + api.getId().getApiName() + '-' + api.getId().getVersion(), ex);
                    }
                }
                if (!isStatusChanged) {
                    return recentlyAddedAPI;
                }
            }
        }
        PaginationContext.init(0, limit, APIConstants.REGISTRY_ARTIFACT_SEARCH_DESC_ORDER, APIConstants.CREATED_DATE, Integer.MAX_VALUE);
        Map<String, List<String>> listMap = new HashMap<String, List<String>>();
        listMap.put(APIConstants.API_OVERVIEW_STATUS, new ArrayList<String>() {

            {
                add(APIConstants.PUBLISHED);
            }
        });
        listMap.put(APIConstants.STORE_VIEW_ROLES, getUserRoleList());
        String searchCriteria = APIConstants.LCSTATE_SEARCH_KEY + "= (" + APIConstants.PUBLISHED + ")";
        // Find UUID
        GenericArtifactManager artifactManager = APIUtil.getArtifactManager(userRegistry, APIConstants.API_KEY);
        if (artifactManager != null) {
            GenericArtifact[] genericArtifacts = artifactManager.findGovernanceArtifacts(getSearchQuery(searchCriteria));
            SortedSet<API> allAPIs = new TreeSet<API>(new APINameComparator());
            for (GenericArtifact artifact : genericArtifacts) {
                API api = null;
                try {
                    api = APIUtil.getAPI(artifact);
                } catch (APIManagementException e) {
                    // just log and continue since we want to go through the other APIs as well.
                    log.error("Error loading API " + artifact.getAttribute(APIConstants.API_OVERVIEW_NAME), e);
                }
                if (api != null) {
                    allAPIs.add(api);
                }
            }
            if (!APIUtil.isAllowDisplayMultipleVersions()) {
                Map<String, API> latestPublishedAPIs = new HashMap<String, API>();
                Comparator<API> versionComparator = new APIVersionComparator();
                String key;
                for (API api : allAPIs) {
                    key = api.getId().getProviderName() + COLON_CHAR + api.getId().getApiName();
                    API existingAPI = latestPublishedAPIs.get(key);
                    if (existingAPI != null) {
                        // number
                        if (versionComparator.compare(api, existingAPI) > 0) {
                            latestPublishedAPIs.put(key, api);
                        }
                    } else {
                        // We haven't seen this API before
                        latestPublishedAPIs.put(key, api);
                    }
                }
                recentlyAddedAPIs.addAll(latestPublishedAPIs.values());
                if (isRecentlyAddedAPICacheEnabled) {
                    Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER).getCache(APIConstants.RECENTLY_ADDED_API_CACHE_NAME).put(username + COLON_CHAR + tenantDomain, allAPIs);
                }
                return recentlyAddedAPIs;
            } else {
                recentlyAddedAPIsWithMultipleVersions.addAll(allAPIs);
                if (isRecentlyAddedAPICacheEnabled) {
                    Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER).getCache(APIConstants.RECENTLY_ADDED_API_CACHE_NAME).put(username + COLON_CHAR + tenantDomain, allAPIs);
                }
                return recentlyAddedAPIsWithMultipleVersions;
            }
        } else {
            String errorMessage = "Artifact manager is null when retrieving recently added APIs for tenant domain " + tenantDomain;
            log.error(errorMessage);
        }
    } catch (RegistryException e) {
        handleException("Failed to get all published APIs", e);
    } catch (UserStoreException e) {
        handleException("Failed to get all published APIs", e);
    } finally {
        PaginationContext.destroy();
        if (isTenantFlowStarted) {
            endTenantFlow();
        }
    }
    return recentlyAddedAPIs;
}
Also used : Set(java.util.Set) TreeSet(java.util.TreeSet) LinkedHashSet(java.util.LinkedHashSet) SortedSet(java.util.SortedSet) HashSet(java.util.HashSet) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) APINameComparator(org.wso2.carbon.apimgt.impl.utils.APINameComparator) APIVersionComparator(org.wso2.carbon.apimgt.impl.utils.APIVersionComparator) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) TreeSet(java.util.TreeSet) UserStoreException(org.wso2.carbon.user.api.UserStoreException) CommentList(org.wso2.carbon.apimgt.api.model.CommentList) ArrayList(java.util.ArrayList) List(java.util.List) GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) InvocationTargetException(java.lang.reflect.InvocationTargetException) IOException(java.io.IOException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) UserAdminException(org.wso2.carbon.user.mgt.common.UserAdminException) OASPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.OASPersistenceException) WorkflowException(org.wso2.carbon.apimgt.impl.workflow.WorkflowException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) APIMgtAuthorizationFailedException(org.wso2.carbon.apimgt.api.APIMgtAuthorizationFailedException) ParseException(org.json.simple.parser.ParseException) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) API(org.wso2.carbon.apimgt.api.model.API)

Example 18 with APIVersionComparator

use of org.wso2.carbon.apimgt.impl.utils.APIVersionComparator in project carbon-apimgt by wso2.

the class APIConsumerImpl method getAllPaginatedAPIs.

/**
 * The method to get All PUBLISHED and DEPRECATED APIs, to Store view
 *
 * @return Set<API>  Set of APIs
 * @throws APIManagementException
 */
@Deprecated
public Map<String, Object> getAllPaginatedAPIs(String tenantDomain, int start, int end) throws APIManagementException {
    Map<String, Object> result = new HashMap<String, Object>();
    SortedSet<API> apiSortedSet = new TreeSet<API>(new APINameComparator());
    SortedSet<API> apiVersionsSortedSet = new TreeSet<API>(new APIVersionComparator());
    int totalLength = 0;
    try {
        Registry userRegistry;
        boolean isTenantMode = (tenantDomain != null);
        if ((isTenantMode && this.tenantDomain == null) || (isTenantMode && isTenantDomainNotMatching(tenantDomain))) {
            // Tenant store anonymous mode
            int tenantId = getTenantId(tenantDomain);
            userRegistry = getGovernanceUserRegistry(tenantId);
            setUsernameToThreadLocalCarbonContext(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME);
        } else {
            userRegistry = registry;
            setUsernameToThreadLocalCarbonContext(this.username);
        }
        this.isTenantModeStoreView = isTenantMode;
        this.requestedTenant = tenantDomain;
        Map<String, API> latestPublishedAPIs = new HashMap<String, API>();
        List<API> multiVersionedAPIs = new ArrayList<API>();
        Comparator<API> versionComparator = new APIVersionComparator();
        Boolean displayMultipleVersions = APIUtil.isAllowDisplayMultipleVersions();
        GenericArtifactManager artifactManager = APIUtil.getArtifactManager(userRegistry, APIConstants.API_KEY);
        PaginationContext.init(start, end, "ASC", APIConstants.API_OVERVIEW_NAME, Integer.MAX_VALUE);
        boolean noPublishedAPIs = false;
        if (artifactManager != null) {
            // Create the search attribute map for PUBLISHED APIs
            Map<String, List<String>> listMap = new HashMap<String, List<String>>();
            listMap.put(APIConstants.API_OVERVIEW_STATUS, new ArrayList<String>() {

                {
                    add(APIConstants.PUBLISHED);
                }
            });
            GenericArtifact[] genericArtifacts = artifactManager.findGenericArtifacts(listMap);
            totalLength = PaginationContext.getInstance().getLength();
            if (genericArtifacts == null || genericArtifacts.length == 0) {
                noPublishedAPIs = true;
            }
            int publishedAPICount;
            if (genericArtifacts != null) {
                for (GenericArtifact artifact : genericArtifacts) {
                    if (artifact == null) {
                        log.error("Failed to retrieve artifact when getting all paginated APIs.");
                        continue;
                    }
                    // adding the API provider can mark the latest API .
                    // String status = artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS);
                    API api = APIUtil.getAPI(artifact);
                    if (api != null) {
                        String key;
                        // Check the configuration to allow showing multiple versions of an API true/false
                        if (!displayMultipleVersions) {
                            // If allow only showing the latest version of an API
                            key = api.getId().getProviderName() + COLON_CHAR + api.getId().getApiName();
                            API existingAPI = latestPublishedAPIs.get(key);
                            if (existingAPI != null) {
                                // this one has a higher version number
                                if (versionComparator.compare(api, existingAPI) > 0) {
                                    latestPublishedAPIs.put(key, api);
                                }
                            } else {
                                // We haven't seen this API before
                                latestPublishedAPIs.put(key, api);
                            }
                        } else {
                            // If allow showing multiple versions of an API
                            // key = api.getId().getProviderName() + ":" + api.getId().getApiName() + ":" + api.getId()
                            // .getVersion();
                            multiVersionedAPIs.add(api);
                        }
                    }
                }
            }
            if (!displayMultipleVersions) {
                publishedAPICount = latestPublishedAPIs.size();
            } else {
                publishedAPICount = multiVersionedAPIs.size();
            }
            if ((start + end) > publishedAPICount) {
                if (publishedAPICount > 0) {
                    /*Starting to retrieve DEPRECATED APIs*/
                    start = 0;
                    /* publishedAPICount is always less than end*/
                    end = end - publishedAPICount;
                } else {
                    start = start - totalLength;
                }
                PaginationContext.init(start, end, "ASC", APIConstants.API_OVERVIEW_NAME, Integer.MAX_VALUE);
                // Create the search attribute map for DEPRECATED APIs
                Map<String, List<String>> listMapForDeprecatedAPIs = new HashMap<String, List<String>>();
                listMapForDeprecatedAPIs.put(APIConstants.API_OVERVIEW_STATUS, new ArrayList<String>() {

                    {
                        add(APIConstants.DEPRECATED);
                    }
                });
                GenericArtifact[] genericArtifactsForDeprecatedAPIs = artifactManager.findGenericArtifacts(listMapForDeprecatedAPIs);
                totalLength = totalLength + PaginationContext.getInstance().getLength();
                if ((genericArtifactsForDeprecatedAPIs == null || genericArtifactsForDeprecatedAPIs.length == 0) && noPublishedAPIs) {
                    result.put("apis", apiSortedSet);
                    result.put("totalLength", totalLength);
                    return result;
                }
                if (genericArtifactsForDeprecatedAPIs != null) {
                    for (GenericArtifact artifact : genericArtifactsForDeprecatedAPIs) {
                        if (artifact == null) {
                            log.error("Failed to retrieve artifact when getting deprecated APIs.");
                            continue;
                        }
                        // adding the API provider can mark the latest API .
                        API api = APIUtil.getAPI(artifact);
                        if (api != null) {
                            String key;
                            // Check the configuration to allow showing multiple versions of an API true/false
                            if (!displayMultipleVersions) {
                                // If allow only showing the latest version of an API
                                key = api.getId().getProviderName() + COLON_CHAR + api.getId().getApiName();
                                API existingAPI = latestPublishedAPIs.get(key);
                                if (existingAPI != null) {
                                    // this one has a higher version number
                                    if (versionComparator.compare(api, existingAPI) > 0) {
                                        latestPublishedAPIs.put(key, api);
                                    }
                                } else {
                                    // We haven't seen this API before
                                    latestPublishedAPIs.put(key, api);
                                }
                            } else {
                                // If allow showing multiple versions of an API
                                multiVersionedAPIs.add(api);
                            }
                        }
                    }
                }
            }
            if (!displayMultipleVersions) {
                for (API api : latestPublishedAPIs.values()) {
                    apiSortedSet.add(api);
                }
                result.put("apis", apiSortedSet);
                result.put("totalLength", totalLength);
                return result;
            } else {
                apiVersionsSortedSet.addAll(multiVersionedAPIs);
                result.put("apis", apiVersionsSortedSet);
                result.put("totalLength", totalLength);
                return result;
            }
        } else {
            String errorMessage = "Artifact manager is null for tenant domain " + tenantDomain + " when retrieving all paginated APIs.";
            log.error(errorMessage);
        }
    } catch (RegistryException e) {
        handleException("Failed to get all published APIs", e);
    } catch (UserStoreException e) {
        handleException("Failed to get all published APIs", e);
    } finally {
        PaginationContext.destroy();
    }
    result.put("apis", apiSortedSet);
    result.put("totalLength", totalLength);
    return result;
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) APINameComparator(org.wso2.carbon.apimgt.impl.utils.APINameComparator) APIVersionComparator(org.wso2.carbon.apimgt.impl.utils.APIVersionComparator) TreeSet(java.util.TreeSet) UserStoreException(org.wso2.carbon.user.api.UserStoreException) CommentList(org.wso2.carbon.apimgt.api.model.CommentList) ArrayList(java.util.ArrayList) List(java.util.List) GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) JSONObject(org.json.simple.JSONObject) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) API(org.wso2.carbon.apimgt.api.model.API)

Example 19 with APIVersionComparator

use of org.wso2.carbon.apimgt.impl.utils.APIVersionComparator 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)

Aggregations

APIVersionComparator (org.wso2.carbon.apimgt.impl.utils.APIVersionComparator)19 API (org.wso2.carbon.apimgt.api.model.API)13 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)13 ArrayList (java.util.ArrayList)11 DevPortalAPI (org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI)10 HashMap (java.util.HashMap)9 TreeSet (java.util.TreeSet)9 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)9 JSONObject (org.json.simple.JSONObject)8 APINameComparator (org.wso2.carbon.apimgt.impl.utils.APINameComparator)8 GenericArtifactManager (org.wso2.carbon.governance.api.generic.GenericArtifactManager)7 Registry (org.wso2.carbon.registry.core.Registry)7 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)7 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)7 UserStoreException (org.wso2.carbon.user.api.UserStoreException)7 Test (org.junit.Test)6 GenericArtifact (org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact)6 HashSet (java.util.HashSet)5 LinkedHashSet (java.util.LinkedHashSet)5 List (java.util.List)5