Search in sources :

Example 41 with APIList

use of org.wso2.carbon.apimgt.keymgt.model.entity.APIList in project carbon-apimgt by wso2.

the class APIProviderImpl method searchPaginatedAPIProducts.

/**
 * Returns APIProduct Search result based on the provided query.
 *
 * @param registry
 * @param searchQuery Ex: provider=*admin*
 * @return APIProduct result
 * @throws APIManagementException
 */
public Map<String, Object> searchPaginatedAPIProducts(Registry registry, String searchQuery, int start, int end) throws APIManagementException {
    SortedSet<APIProduct> productSet = new TreeSet<APIProduct>(new APIProductNameComparator());
    List<APIProduct> productList = new ArrayList<APIProduct>();
    Map<String, Object> result = new HashMap<String, Object>();
    if (log.isDebugEnabled()) {
        log.debug("Original search query received : " + searchQuery);
    }
    Organization org = new Organization(tenantDomain);
    String[] roles = APIUtil.getFilteredUserRoles(userNameWithoutChange);
    Map<String, Object> properties = APIUtil.getUserProperties(userNameWithoutChange);
    UserContext userCtx = new UserContext(userNameWithoutChange, org, properties, roles);
    try {
        PublisherAPIProductSearchResult searchAPIs = apiPersistenceInstance.searchAPIProductsForPublisher(org, searchQuery, start, end, userCtx);
        if (log.isDebugEnabled()) {
            log.debug("searched API products for query : " + searchQuery + " :-->: " + searchAPIs.toString());
        }
        if (searchAPIs != null) {
            List<PublisherAPIProductInfo> list = searchAPIs.getPublisherAPIProductInfoList();
            List<Object> apiList = new ArrayList<>();
            for (PublisherAPIProductInfo publisherAPIInfo : list) {
                APIProduct mappedAPI = new APIProduct(new APIProductIdentifier(publisherAPIInfo.getProviderName(), publisherAPIInfo.getApiProductName(), publisherAPIInfo.getVersion()));
                mappedAPI.setUuid(publisherAPIInfo.getId());
                mappedAPI.setState(publisherAPIInfo.getState());
                mappedAPI.setContext(publisherAPIInfo.getContext());
                mappedAPI.setApiSecurity(publisherAPIInfo.getApiSecurity());
                populateAPIStatus(mappedAPI);
                productList.add(mappedAPI);
            }
            productSet.addAll(productList);
            result.put("products", productSet);
            result.put("length", searchAPIs.getTotalAPIsCount());
            result.put("isMore", true);
        } else {
            result.put("products", productSet);
            result.put("length", 0);
            result.put("isMore", false);
        }
    } catch (APIPersistenceException e) {
        throw new APIManagementException("Error while searching the api ", e);
    }
    return result;
}
Also used : APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) UserContext(org.wso2.carbon.apimgt.persistence.dto.UserContext) ArrayList(java.util.ArrayList) PublisherAPIProductSearchResult(org.wso2.carbon.apimgt.persistence.dto.PublisherAPIProductSearchResult) PublisherAPIProduct(org.wso2.carbon.apimgt.persistence.dto.PublisherAPIProduct) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) TreeSet(java.util.TreeSet) PublisherAPIProductInfo(org.wso2.carbon.apimgt.persistence.dto.PublisherAPIProductInfo) JSONObject(org.json.simple.JSONObject) APIProductNameComparator(org.wso2.carbon.apimgt.impl.utils.APIProductNameComparator)

Example 42 with APIList

use of org.wso2.carbon.apimgt.keymgt.model.entity.APIList in project carbon-apimgt by wso2.

the class APIProviderImpl method getOldPublishedAPIList.

/**
 * This method returns a list of previous versions of a given API
 *
 * @param api
 * @return oldPublishedAPIList
 * @throws APIManagementException
 */
private List<APIIdentifier> getOldPublishedAPIList(API api) throws APIManagementException {
    List<APIIdentifier> oldPublishedAPIList = new ArrayList<APIIdentifier>();
    List<API> apiList = getAPIVersionsByProviderAndName(api.getId().getProviderName(), api.getId().getName(), api.getOrganization());
    APIVersionComparator versionComparator = new APIVersionComparator();
    for (API oldAPI : apiList) {
        if (oldAPI.getId().getApiName().equals(api.getId().getApiName()) && versionComparator.compare(oldAPI, api) < 0 && (oldAPI.getStatus().equals(APIConstants.PUBLISHED))) {
            oldPublishedAPIList.add(oldAPI.getId());
        }
    }
    return oldPublishedAPIList;
}
Also used : APIVersionComparator(org.wso2.carbon.apimgt.impl.utils.APIVersionComparator) ArrayList(java.util.ArrayList) 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 43 with APIList

use of org.wso2.carbon.apimgt.keymgt.model.entity.APIList 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 44 with APIList

use of org.wso2.carbon.apimgt.keymgt.model.entity.APIList in project carbon-apimgt by wso2.

the class APIProviderImpl method searchPaginatedAPIs.

@Override
public Map<String, Object> searchPaginatedAPIs(String searchQuery, String organization, int start, int end, String sortBy, String sortOrder) throws APIManagementException {
    Map<String, Object> result = new HashMap<String, Object>();
    if (log.isDebugEnabled()) {
        log.debug("Original search query received : " + searchQuery);
    }
    Organization org = new Organization(organization);
    String[] roles = APIUtil.getFilteredUserRoles(userNameWithoutChange);
    Map<String, Object> properties = APIUtil.getUserProperties(userNameWithoutChange);
    UserContext userCtx = new UserContext(userNameWithoutChange, org, properties, roles);
    try {
        PublisherAPISearchResult searchAPIs = apiPersistenceInstance.searchAPIsForPublisher(org, searchQuery, start, end, userCtx, sortBy, sortOrder);
        if (log.isDebugEnabled()) {
            log.debug("searched APIs for query : " + searchQuery + " :-->: " + searchAPIs.toString());
        }
        Set<Object> apiSet = new LinkedHashSet<>();
        if (searchAPIs != null) {
            List<PublisherAPIInfo> list = searchAPIs.getPublisherAPIInfoList();
            List<Object> apiList = new ArrayList<>();
            for (PublisherAPIInfo publisherAPIInfo : list) {
                API mappedAPI = APIMapper.INSTANCE.toApi(publisherAPIInfo);
                populateAPIStatus(mappedAPI);
                populateDefaultVersion(mappedAPI);
                apiList.add(mappedAPI);
            }
            apiSet.addAll(apiList);
            result.put("apis", apiSet);
            result.put("length", searchAPIs.getTotalAPIsCount());
            result.put("isMore", true);
        } else {
            result.put("apis", apiSet);
            result.put("length", 0);
            result.put("isMore", false);
        }
    } catch (APIPersistenceException e) {
        throw new APIManagementException("Error while searching the api ", e);
    }
    return result;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) UserContext(org.wso2.carbon.apimgt.persistence.dto.UserContext) ArrayList(java.util.ArrayList) PublisherAPIInfo(org.wso2.carbon.apimgt.persistence.dto.PublisherAPIInfo) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) PublisherAPISearchResult(org.wso2.carbon.apimgt.persistence.dto.PublisherAPISearchResult) JSONObject(org.json.simple.JSONObject) 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 45 with APIList

use of org.wso2.carbon.apimgt.keymgt.model.entity.APIList in project carbon-apimgt by wso2.

the class AbstractAPIManager method searchPaginatedAPIs.

/**
 * Returns API Search result based on the provided query. This search method supports '&' based concatenate
 * search in multiple fields.
 *
 * @param registry
 * @param tenantId
 * @param searchQuery Ex: provider=*admin*&version=*1*
 * @return API result
 * @throws APIManagementException
 */
public Map<String, Object> searchPaginatedAPIs(Registry registry, int tenantId, String searchQuery, int start, int end, boolean limitAttributes, boolean reducedPublisherAPIInfo) throws APIManagementException {
    SortedSet<Object> apiSet = new TreeSet<>(new APIAPIProductNameComparator());
    List<Object> apiList = new ArrayList<>();
    Map<String, Object> result = new HashMap<String, Object>();
    int totalLength = 0;
    boolean isMore = false;
    try {
        String paginationLimit = getAPIManagerConfiguration().getFirstProperty(APIConstants.API_STORE_APIS_PER_PAGE);
        // If the Config exists use it to set the pagination limit
        final int maxPaginationLimit;
        if (paginationLimit != null) {
            // The additional 1 added to the maxPaginationLimit is to help us determine if more
            // APIs may exist so that we know that we are unable to determine the actual total
            // API count. We will subtract this 1 later on so that it does not interfere with
            // the logic of the rest of the application
            int pagination = Integer.parseInt(paginationLimit);
            // leading to some of the APIs not being displayed
            if (pagination < 11) {
                pagination = 11;
                log.warn("Value of '" + APIConstants.API_STORE_APIS_PER_PAGE + "' is too low, defaulting to 11");
            }
            maxPaginationLimit = start + pagination + 1;
        } else // Else if the config is not specified we go with default functionality and load all
        {
            maxPaginationLimit = Integer.MAX_VALUE;
        }
        PaginationContext.init(start, end, "ASC", APIConstants.API_OVERVIEW_NAME, maxPaginationLimit);
        List<GovernanceArtifact> governanceArtifacts = GovernanceUtils.findGovernanceArtifacts(getSearchQuery(searchQuery), registry, APIConstants.API_RXT_MEDIA_TYPE, true);
        totalLength = PaginationContext.getInstance().getLength();
        boolean isFound = true;
        if (governanceArtifacts == null || governanceArtifacts.size() == 0) {
            if (searchQuery.contains(APIConstants.API_OVERVIEW_PROVIDER)) {
                searchQuery = searchQuery.replaceAll(APIConstants.API_OVERVIEW_PROVIDER, APIConstants.API_OVERVIEW_OWNER);
                governanceArtifacts = GovernanceUtils.findGovernanceArtifacts(getSearchQuery(searchQuery), registry, APIConstants.API_RXT_MEDIA_TYPE, true);
                if (governanceArtifacts == null || governanceArtifacts.size() == 0) {
                    isFound = false;
                }
            } else {
                isFound = false;
            }
        }
        if (!isFound) {
            result.put("apis", apiSet);
            result.put("length", 0);
            result.put("isMore", isMore);
            return result;
        }
        // Check to see if we can speculate that there are more APIs to be loaded
        if (maxPaginationLimit == totalLength) {
            // More APIs exist, cannot determine total API count without incurring perf hit
            isMore = true;
            // Remove the additional 1 added earlier when setting max pagination limit
            --totalLength;
        }
        int tempLength = 0;
        for (GovernanceArtifact artifact : governanceArtifacts) {
            String type = artifact.getAttribute(APIConstants.API_OVERVIEW_TYPE);
            if (APIConstants.API_PRODUCT.equals(type)) {
                APIProduct resultAPI = APIUtil.getAPIProduct(artifact, registry);
                if (resultAPI != null) {
                    apiList.add(resultAPI);
                }
            } else {
                API resultAPI;
                if (APIUtil.getAPIIdentifierFromUUID(artifact.getId()) != null) {
                    if (limitAttributes) {
                        resultAPI = APIUtil.getAPI(artifact);
                    } else {
                        if (reducedPublisherAPIInfo) {
                            resultAPI = APIUtil.getReducedPublisherAPIForListing(artifact, registry);
                        } else {
                            resultAPI = APIUtil.getAPI(artifact, registry);
                        }
                    }
                    if (resultAPI != null) {
                        apiList.add(resultAPI);
                    }
                }
            }
            // Ensure the APIs returned matches the length, there could be an additional API
            // returned due incrementing the pagination limit when getting from registry
            tempLength++;
            if (tempLength >= totalLength) {
                break;
            }
        }
        // Creating a apiIds string
        String apiIdsString = "";
        int apiCount = apiList.size();
        if (!reducedPublisherAPIInfo) {
            for (int i = 0; i < apiCount; i++) {
                Object api = apiList.get(i);
                String apiId = "";
                if (api instanceof API) {
                    apiId = ((API) api).getId().getApplicationId();
                } else if (api instanceof APIProduct) {
                    apiId = ((APIProduct) api).getId().getApplicationId();
                }
                if (apiId != null && !apiId.isEmpty()) {
                    if (apiIdsString.isEmpty()) {
                        apiIdsString = apiId;
                    } else {
                        apiIdsString = apiIdsString + "," + apiId;
                    }
                }
            }
        }
        apiSet.addAll(apiList);
    } catch (RegistryException e) {
        String msg = "Failed to search APIs with type";
        throw new APIManagementException(msg, e);
    } finally {
        PaginationContext.destroy();
    }
    result.put("apis", apiSet);
    result.put("length", totalLength);
    result.put("isMore", isMore);
    return result;
}
Also used : LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) GovernanceArtifact(org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact) ArrayList(java.util.ArrayList) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) TreeSet(java.util.TreeSet) JSONObject(org.json.simple.JSONObject) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) API(org.wso2.carbon.apimgt.api.model.API) APIAPIProductNameComparator(org.wso2.carbon.apimgt.impl.utils.APIAPIProductNameComparator)

Aggregations

ArrayList (java.util.ArrayList)33 API (org.wso2.carbon.apimgt.core.models.API)21 CompositeAPI (org.wso2.carbon.apimgt.core.models.CompositeAPI)15 API (org.wso2.carbon.apimgt.api.model.API)14 Test (org.testng.annotations.Test)12 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)12 ApiDAO (org.wso2.carbon.apimgt.core.dao.ApiDAO)12 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)10 HashMap (java.util.HashMap)9 HashSet (java.util.HashSet)9 JSONObject (org.json.simple.JSONObject)9 APIComparator (org.wso2.carbon.apimgt.core.util.APIComparator)8 PublisherAPI (org.wso2.carbon.apimgt.persistence.dto.PublisherAPI)7 ImportExportAPI (org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)6 TreeSet (java.util.TreeSet)5 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)5 API (org.wso2.carbon.apimgt.keymgt.model.entity.API)5 IOException (java.io.IOException)4 ResultSet (java.sql.ResultSet)4 List (java.util.List)4