Search in sources :

Example 1 with GovernanceArtifact

use of org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact in project carbon-apimgt by wso2.

the class AbstractAPIManager 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>();
    int totalLength = 0;
    boolean isMore = false;
    try {
        // for now will use the same config for api products too todo: change this
        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 (!isFound) {
            result.put("products", productSet);
            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) {
            APIProduct resultAPIProduct = APIUtil.getAPIProduct(artifact, registry);
            if (resultAPIProduct != null) {
                productList.add(resultAPIProduct);
            }
            // 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;
            }
        }
        productSet.addAll(productList);
    } catch (RegistryException e) {
        String msg = "Failed to search APIProducts with type";
        throw new APIManagementException(msg, e);
    } finally {
        PaginationContext.destroy();
    }
    result.put("products", productSet);
    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) APIAPIProductNameComparator(org.wso2.carbon.apimgt.impl.utils.APIAPIProductNameComparator) APIProductNameComparator(org.wso2.carbon.apimgt.impl.utils.APIProductNameComparator)

Example 2 with GovernanceArtifact

use of org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact in project carbon-apimgt by wso2.

the class AbstractAPIManager method getApiForPublishing.

protected API getApiForPublishing(Registry registry, GovernanceArtifact apiArtifact) throws APIManagementException {
    API api = APIUtil.getAPIForPublishing(apiArtifact, registry);
    APIUtil.updateAPIProductDependencies(api, registry);
    return api;
}
Also used : SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) API(org.wso2.carbon.apimgt.api.model.API)

Example 3 with GovernanceArtifact

use of org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact in project carbon-apimgt by wso2.

the class APIUtil method getReducedPublisherAPIForListing.

/**
 * Copy of the getAPI(GovernanceArtifact artifact, Registry registry) method with reduced DB calls for api
 * publisher list view listing.
 * @param artifact
 * @param registry
 * @return
 * @throws APIManagementException
 */
public static API getReducedPublisherAPIForListing(GovernanceArtifact artifact, Registry registry) throws APIManagementException {
    API api;
    try {
        String providerName = artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER);
        String apiName = artifact.getAttribute(APIConstants.API_OVERVIEW_NAME);
        String apiVersion = artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION);
        APIIdentifier apiIdentifier = new APIIdentifier(providerName, apiName, apiVersion);
        api = new API(apiIdentifier);
        // set description
        api.setDescription(artifact.getAttribute(APIConstants.API_OVERVIEW_DESCRIPTION));
        // set uuid
        api.setUUID(artifact.getId());
        // set url
        api.setStatus(getLcStateFromArtifact(artifact));
        api.setType(artifact.getAttribute(APIConstants.API_OVERVIEW_TYPE));
        api.setThumbnailUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_THUMBNAIL_URL));
        api.setWsdlUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_WSDL));
        api.setWadlUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_WADL));
        api.setTechnicalOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_TEC_OWNER));
        api.setTechnicalOwnerEmail(artifact.getAttribute(APIConstants.API_OVERVIEW_TEC_OWNER_EMAIL));
        api.setBusinessOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER));
        api.setBusinessOwnerEmail(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER_EMAIL));
        api.setVisibility(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBILITY));
        api.setVisibleRoles(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_ROLES));
        api.setVisibleTenants(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_TENANTS));
        api.setEndpointSecured(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_SECURED)));
        api.setEndpointAuthDigest(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_AUTH_DIGEST)));
        api.setEndpointUTUsername(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_USERNAME));
        if (!((APIConstants.DEFAULT_MODIFIED_ENDPOINT_PASSWORD).equals(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_PASSWORD)))) {
            api.setEndpointUTPassword(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_PASSWORD));
        } else {
            // If APIEndpointPasswordRegistryHandler is enabled take password from the registry hidden property
            api.setEndpointUTPassword(getActualEpPswdFromHiddenProperty(api, registry));
        }
        api.setTransports(artifact.getAttribute(APIConstants.API_OVERVIEW_TRANSPORTS));
        api.setInSequence(artifact.getAttribute(APIConstants.API_OVERVIEW_INSEQUENCE));
        api.setOutSequence(artifact.getAttribute(APIConstants.API_OVERVIEW_OUTSEQUENCE));
        api.setFaultSequence(artifact.getAttribute(APIConstants.API_OVERVIEW_FAULTSEQUENCE));
        api.setResponseCache(artifact.getAttribute(APIConstants.API_OVERVIEW_RESPONSE_CACHING));
        api.setImplementation(artifact.getAttribute(APIConstants.PROTOTYPE_OVERVIEW_IMPLEMENTATION));
        api.setProductionMaxTps(artifact.getAttribute(APIConstants.API_PRODUCTION_THROTTLE_MAXTPS));
        int cacheTimeout = APIConstants.API_RESPONSE_CACHE_TIMEOUT;
        try {
            cacheTimeout = Integer.parseInt(artifact.getAttribute(APIConstants.API_OVERVIEW_CACHE_TIMEOUT));
        } catch (NumberFormatException e) {
        // ignore
        }
        api.setCacheTimeout(cacheTimeout);
        api.setEndpointConfig(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_CONFIG));
        api.setRedirectURL(artifact.getAttribute(APIConstants.API_OVERVIEW_REDIRECT_URL));
        api.setApiOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_OWNER));
        api.setAdvertiseOnly(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ADVERTISE_ONLY)));
        api.setSubscriptionAvailability(artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABILITY));
        api.setSubscriptionAvailableTenants(artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABLE_TENANTS));
        api.setContext(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT));
        // We set the context template here
        api.setContextTemplate(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT_TEMPLATE));
        api.setLatest(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_IS_LATEST)));
        api.setEnableSchemaValidation(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENABLE_JSON_SCHEMA)));
        api.setEnableStore(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENABLE_STORE)));
        api.setAsDefaultVersion(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_IS_DEFAULT_VERSION)));
        api.setImplementation(artifact.getAttribute(APIConstants.PROTOTYPE_OVERVIEW_IMPLEMENTATION));
        api.setAuthorizationHeader(artifact.getAttribute(APIConstants.API_OVERVIEW_AUTHORIZATION_HEADER));
        api.setApiSecurity(artifact.getAttribute(APIConstants.API_OVERVIEW_API_SECURITY));
    } catch (GovernanceException e) {
        String msg = "Failed to get API for artifact ";
        throw new APIManagementException(msg, e);
    } catch (RegistryException e) {
        String msg = "Failed to get LastAccess time or Rating";
        throw new APIManagementException(msg, e);
    }
    return api;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) API(org.wso2.carbon.apimgt.api.model.API) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) Endpoint(org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint)

Example 4 with GovernanceArtifact

use of org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact in project carbon-apimgt by wso2.

the class RegistryPersistenceImpl method deleteAPIProduct.

@Override
public void deleteAPIProduct(Organization org, String apiId) throws APIPersistenceException {
    boolean tenantFlowStarted = false;
    try {
        RegistryHolder holder = getRegistry(org.getName());
        tenantFlowStarted = holder.isTenantFlowStarted();
        Registry registry = holder.getRegistry();
        GovernanceUtils.loadGovernanceArtifacts((UserRegistry) registry);
        GenericArtifactManager artifactManager = RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.API_KEY);
        if (artifactManager == null) {
            String errorMessage = "Failed to retrieve artifact manager when deleting API Product" + apiId;
            log.error(errorMessage);
            throw new APIManagementException(errorMessage);
        }
        GenericArtifact apiProductArtifact = artifactManager.getGenericArtifact(apiId);
        APIProductIdentifier identifier = new APIProductIdentifier(apiProductArtifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER), apiProductArtifact.getAttribute(APIConstants.API_OVERVIEW_NAME), apiProductArtifact.getAttribute(APIConstants.API_OVERVIEW_VERSION));
        // this is the product resource collection path
        String productResourcePath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + RegistryPersistenceUtil.replaceEmailDomain(identifier.getProviderName()) + RegistryConstants.PATH_SEPARATOR + identifier.getName() + RegistryConstants.PATH_SEPARATOR + identifier.getVersion();
        // this is the product rxt instance path
        String apiProductArtifactPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + RegistryPersistenceUtil.replaceEmailDomain(identifier.getProviderName()) + RegistryConstants.PATH_SEPARATOR + identifier.getName() + RegistryConstants.PATH_SEPARATOR + identifier.getVersion() + APIConstants.API_RESOURCE_NAME;
        Resource apiProductResource = registry.get(productResourcePath);
        String productResourceUUID = apiProductResource.getUUID();
        if (productResourceUUID == null) {
            throw new APIManagementException("artifact id is null for : " + productResourcePath);
        }
        Resource apiArtifactResource = registry.get(apiProductArtifactPath);
        String apiArtifactResourceUUID = apiArtifactResource.getUUID();
        if (apiArtifactResourceUUID == null) {
            throw new APIManagementException("artifact id is null for : " + apiProductArtifactPath);
        }
        // Delete the dependencies associated with the api product artifact
        GovernanceArtifact[] dependenciesArray = apiProductArtifact.getDependencies();
        if (dependenciesArray.length > 0) {
            for (GovernanceArtifact artifact : dependenciesArray) {
                registry.delete(artifact.getPath());
            }
        }
        // delete registry resources
        artifactManager.removeGenericArtifact(apiProductArtifact);
        artifactManager.removeGenericArtifact(productResourceUUID);
        /* remove empty directories */
        String apiProductCollectionPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + identifier.getProviderName() + RegistryConstants.PATH_SEPARATOR + identifier.getName();
        if (registry.resourceExists(apiProductCollectionPath)) {
            // at the moment product versioning is not supported so we are directly deleting this collection as
            // this is known to be empty
            registry.delete(apiProductCollectionPath);
        }
        String productProviderPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + identifier.getProviderName() + RegistryConstants.PATH_SEPARATOR + identifier.getName();
        if (registry.resourceExists(productProviderPath)) {
            Resource providerCollection = registry.get(productProviderPath);
            CollectionImpl collection = (CollectionImpl) providerCollection;
            // if there is no api product for given provider delete the provider directory
            if (collection.getChildCount() == 0) {
                if (log.isDebugEnabled()) {
                    log.debug("No more API Products from the provider " + identifier.getProviderName() + " found. " + "Removing provider collection from registry");
                }
                registry.delete(productProviderPath);
            }
        }
    } catch (RegistryException e) {
        String msg = "Failed to get API";
        throw new APIPersistenceException(msg, e);
    } catch (APIManagementException e) {
        String msg = "Failed to get API";
        throw new APIPersistenceException(msg, e);
    } finally {
        if (tenantFlowStarted) {
            RegistryPersistenceUtil.endTenantFlow();
        }
    }
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) GovernanceArtifact(org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact) Resource(org.wso2.carbon.registry.core.Resource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) CollectionImpl(org.wso2.carbon.registry.core.CollectionImpl)

Example 5 with GovernanceArtifact

use of org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact in project carbon-apimgt by wso2.

the class RegistryPersistenceImpl method searchAPIProductsForPublisher.

@Override
public PublisherAPIProductSearchResult searchAPIProductsForPublisher(Organization org, String searchQuery, int start, int offset, UserContext ctx) throws APIPersistenceException {
    String requestedTenantDomain = org.getName();
    boolean isTenantFlowStarted = false;
    PublisherAPIProductSearchResult result = new PublisherAPIProductSearchResult();
    try {
        RegistryHolder holder = getRegistry(ctx.getUserame(), requestedTenantDomain);
        Registry userRegistry = holder.getRegistry();
        isTenantFlowStarted = holder.isTenantFlowStarted();
        log.debug("Requested query for publisher product search: " + searchQuery);
        String modifiedQuery = RegistrySearchUtil.getPublisherProductSearchQuery(searchQuery, ctx);
        log.debug("Modified query for publisher product search: " + modifiedQuery);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(ctx.getUserame());
        final int maxPaginationLimit = getMaxPaginationLimit();
        PaginationContext.init(start, offset, "ASC", APIConstants.API_OVERVIEW_NAME, maxPaginationLimit);
        List<GovernanceArtifact> governanceArtifacts = GovernanceUtils.findGovernanceArtifacts(modifiedQuery, userRegistry, APIConstants.API_RXT_MEDIA_TYPE, true);
        int totalLength = PaginationContext.getInstance().getLength();
        // Check to see if we can speculate that there are more APIs to be loaded
        if (maxPaginationLimit == totalLength) {
            // Remove the additional 1 added earlier when setting max pagination limit
            --totalLength;
        }
        int tempLength = 0;
        List<PublisherAPIProductInfo> publisherAPIProductInfoList = new ArrayList<PublisherAPIProductInfo>();
        for (GovernanceArtifact artifact : governanceArtifacts) {
            PublisherAPIProductInfo info = new PublisherAPIProductInfo();
            info.setProviderName(artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER));
            info.setContext(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT));
            info.setId(artifact.getId());
            info.setApiProductName(artifact.getAttribute(APIConstants.API_OVERVIEW_NAME));
            info.setState(artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS));
            info.setType(artifact.getAttribute(APIConstants.API_OVERVIEW_TYPE));
            info.setVersion(artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION));
            info.setApiSecurity(artifact.getAttribute(APIConstants.API_OVERVIEW_API_SECURITY));
            publisherAPIProductInfoList.add(info);
            // 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;
            }
        }
        result.setPublisherAPIProductInfoList(publisherAPIProductInfoList);
        result.setReturnedAPIsCount(publisherAPIProductInfoList.size());
        result.setTotalAPIsCount(totalLength);
    } catch (GovernanceException e) {
        throw new APIPersistenceException("Error while searching APIs ", e);
    } finally {
        PaginationContext.destroy();
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }
    return result;
}
Also used : APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) GovernanceArtifact(org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact) ArrayList(java.util.ArrayList) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) PublisherAPIProductSearchResult(org.wso2.carbon.apimgt.persistence.dto.PublisherAPIProductSearchResult) PublisherAPIProductInfo(org.wso2.carbon.apimgt.persistence.dto.PublisherAPIProductInfo)

Aggregations

API (org.wso2.carbon.apimgt.api.model.API)28 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)24 ArrayList (java.util.ArrayList)23 GovernanceArtifact (org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact)23 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)19 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)17 Registry (org.wso2.carbon.registry.core.Registry)17 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)17 GovernanceException (org.wso2.carbon.governance.api.exception.GovernanceException)16 Test (org.junit.Test)15 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)15 HashSet (java.util.HashSet)13 Resource (org.wso2.carbon.registry.core.Resource)13 GenericArtifactManager (org.wso2.carbon.governance.api.generic.GenericArtifactManager)12 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)11 JSONObject (org.json.simple.JSONObject)10 UserStoreException (org.wso2.carbon.user.api.UserStoreException)10 Tier (org.wso2.carbon.apimgt.api.model.Tier)9 GenericArtifact (org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact)9 RealmService (org.wso2.carbon.user.core.service.RealmService)9