Search in sources :

Example 6 with GovernanceArtifact

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

the class RegistryPersistenceImpl method searchPaginatedPublisherAPIs.

private PublisherAPISearchResult searchPaginatedPublisherAPIs(Registry userRegistry, int tenantIDLocal, String searchQuery, int start, int offset) throws APIManagementException {
    int totalLength = 0;
    PublisherAPISearchResult searchResults = new PublisherAPISearchResult();
    try {
        final int maxPaginationLimit = getMaxPaginationLimit();
        PaginationContext.init(start, offset, "ASC", APIConstants.API_OVERVIEW_NAME, maxPaginationLimit);
        List<GovernanceArtifact> governanceArtifacts = GovernanceUtils.findGovernanceArtifacts(searchQuery, userRegistry, 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(searchQuery, userRegistry, APIConstants.API_RXT_MEDIA_TYPE, true);
                if (governanceArtifacts == null || governanceArtifacts.size() == 0) {
                    isFound = false;
                }
            } else {
                isFound = false;
            }
        }
        if (!isFound) {
            return searchResults;
        }
        // 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;
        }
        List<PublisherAPIInfo> publisherAPIInfoList = new ArrayList<PublisherAPIInfo>();
        int tempLength = 0;
        for (GovernanceArtifact artifact : governanceArtifacts) {
            PublisherAPIInfo apiInfo = new PublisherAPIInfo();
            String artifactPath = GovernanceUtils.getArtifactPath(userRegistry, artifact.getId());
            Resource apiResource = userRegistry.get(artifactPath);
            apiInfo.setType(artifact.getAttribute(APIConstants.API_OVERVIEW_TYPE));
            apiInfo.setId(artifact.getId());
            apiInfo.setApiName(artifact.getAttribute(APIConstants.API_OVERVIEW_NAME));
            apiInfo.setDescription(artifact.getAttribute(APIConstants.API_OVERVIEW_DESCRIPTION));
            apiInfo.setContext(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT_TEMPLATE));
            apiInfo.setProviderName(artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER));
            apiInfo.setStatus(artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS));
            apiInfo.setThumbnail(artifact.getAttribute(APIConstants.API_OVERVIEW_THUMBNAIL_URL));
            apiInfo.setVersion(artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION));
            apiInfo.setAudience(artifact.getAttribute(APIConstants.API_OVERVIEW_AUDIENCE));
            apiInfo.setCreatedTime(String.valueOf(apiResource.getCreatedTime().getTime()));
            apiInfo.setUpdatedTime(apiResource.getLastModified());
            apiInfo.setGatewayVendor(String.valueOf(artifact.getAttribute(APIConstants.API_GATEWAY_VENDOR)));
            apiInfo.setAdvertiseOnly(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ADVERTISE_ONLY)));
            publisherAPIInfoList.add(apiInfo);
            // 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;
            }
        }
        // Sort the publisherAPIInfoList according to the API name.
        Collections.sort(publisherAPIInfoList, new PublisherAPISearchResultComparator());
        searchResults.setPublisherAPIInfoList(publisherAPIInfoList);
        searchResults.setReturnedAPIsCount(publisherAPIInfoList.size());
        searchResults.setTotalAPIsCount(totalLength);
    } catch (RegistryException e) {
        String msg = "Failed to search APIs with type";
        throw new APIManagementException(msg, e);
    } finally {
        PaginationContext.destroy();
    }
    return searchResults;
}
Also used : GovernanceArtifact(org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact) ArrayList(java.util.ArrayList) Resource(org.wso2.carbon.registry.core.Resource) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) PublisherAPIInfo(org.wso2.carbon.apimgt.persistence.dto.PublisherAPIInfo) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) PublisherAPISearchResult(org.wso2.carbon.apimgt.persistence.dto.PublisherAPISearchResult) PublisherAPISearchResultComparator(org.wso2.carbon.apimgt.persistence.utils.PublisherAPISearchResultComparator)

Example 7 with GovernanceArtifact

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

the class RegistryPersistenceImpl method deleteAPI.

@Override
public void deleteAPI(Organization org, String apiId) throws APIPersistenceException {
    boolean transactionCommitted = false;
    boolean tenantFlowStarted = false;
    Registry registry = null;
    try {
        String tenantDomain = org.getName();
        RegistryHolder holder = getRegistry(tenantDomain);
        registry = holder.getRegistry();
        tenantFlowStarted = holder.isTenantFlowStarted();
        registry.beginTransaction();
        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 " + apiId;
            log.error(errorMessage);
            throw new APIPersistenceException(errorMessage);
        }
        GenericArtifact apiArtifact = artifactManager.getGenericArtifact(apiId);
        APIIdentifier identifier = new APIIdentifier(apiArtifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER), apiArtifact.getAttribute(APIConstants.API_OVERVIEW_NAME), apiArtifact.getAttribute(APIConstants.API_OVERVIEW_VERSION));
        // Delete the dependencies associated  with the api artifact
        GovernanceArtifact[] dependenciesArray = apiArtifact.getDependencies();
        if (dependenciesArray.length > 0) {
            for (GovernanceArtifact artifact : dependenciesArray) {
                registry.delete(artifact.getPath());
            }
        }
        artifactManager.removeGenericArtifact(apiArtifact);
        String path = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + identifier.getProviderName() + RegistryConstants.PATH_SEPARATOR + identifier.getApiName() + RegistryConstants.PATH_SEPARATOR + identifier.getVersion();
        Resource apiResource = registry.get(path);
        String artifactId = apiResource.getUUID();
        artifactManager.removeGenericArtifact(artifactId);
        String thumbPath = RegistryPersistenceUtil.getIconPath(identifier);
        if (registry.resourceExists(thumbPath)) {
            registry.delete(thumbPath);
        }
        String wsdlArchivePath = RegistryPersistenceUtil.getWsdlArchivePath(identifier);
        if (registry.resourceExists(wsdlArchivePath)) {
            registry.delete(wsdlArchivePath);
        }
        /*Remove API Definition Resource - swagger*/
        String apiDefinitionFilePath = APIConstants.API_DOC_LOCATION + RegistryConstants.PATH_SEPARATOR + identifier.getApiName() + '-' + identifier.getVersion() + '-' + identifier.getProviderName();
        if (registry.resourceExists(apiDefinitionFilePath)) {
            registry.delete(apiDefinitionFilePath);
        }
        /*remove empty directories*/
        String apiCollectionPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + identifier.getProviderName() + RegistryConstants.PATH_SEPARATOR + identifier.getApiName();
        if (registry.resourceExists(apiCollectionPath)) {
            Resource apiCollection = registry.get(apiCollectionPath);
            CollectionImpl collection = (CollectionImpl) apiCollection;
            // if there is no other versions of apis delete the directory of the api
            if (collection.getChildCount() == 0) {
                if (log.isDebugEnabled()) {
                    log.debug("No more versions of the API found, removing API collection from registry");
                }
                registry.delete(apiCollectionPath);
            }
        }
        String apiProviderPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + identifier.getProviderName();
        if (registry.resourceExists(apiProviderPath)) {
            Resource providerCollection = registry.get(apiProviderPath);
            CollectionImpl collection = (CollectionImpl) providerCollection;
            // if there is no api for given provider delete the provider directory
            if (collection.getChildCount() == 0) {
                if (log.isDebugEnabled()) {
                    log.debug("No more APIs from the provider " + identifier.getProviderName() + " found. " + "Removing provider collection from registry");
                }
                registry.delete(apiProviderPath);
            }
        }
        registry.commitTransaction();
        transactionCommitted = true;
    } catch (RegistryException e) {
        throw new APIPersistenceException("Failed to remove the API : " + apiId, e);
    } finally {
        if (tenantFlowStarted) {
            RegistryPersistenceUtil.endTenantFlow();
        }
        try {
            if (!transactionCommitted) {
                registry.rollbackTransaction();
            }
        } catch (RegistryException ex) {
            throw new APIPersistenceException("Error occurred while rolling back the transaction. ", ex);
        }
    }
}
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) CollectionImpl(org.wso2.carbon.registry.core.CollectionImpl) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier)

Example 8 with GovernanceArtifact

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

the class RegistryPersistenceUtil method getAPI.

/**
 * This Method is different from getAPI method, as this one returns
 * URLTemplates without aggregating duplicates. This is to be used for building synapse config.
 *
 * @param artifact
 * @param registry
 * @return API
 * @throws org.wso2.carbon.apimgt.api.APIManagementException
 */
public static API getAPI(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, artifact.getId());
        api = new API(apiIdentifier);
        // set uuid
        api.setUuid(artifact.getId());
        // set rating
        String artifactPath = GovernanceUtils.getArtifactPath(registry, artifact.getId());
        // String artifactPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR
        // + RegistryPersistenceUtil.replaceEmailDomain(api.getId().getProviderName())
        // + RegistryConstants.PATH_SEPARATOR + api.getId().getName() + RegistryConstants.PATH_SEPARATOR
        // + api.getId().getVersion() + RegistryConstants.PATH_SEPARATOR + APIConstants.API_KEY;
        Resource apiResource = registry.get(artifactPath);
        api = setResourceProperties(api, apiResource, artifactPath);
        // set description
        api.setDescription(artifact.getAttribute(APIConstants.API_OVERVIEW_DESCRIPTION));
        // set url
        api.setStatus(getLcStateFromArtifact(artifact));
        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(apiResource.getProperty(APIConstants.REGISTRY_HIDDEN_ENDPOINT_PROPERTY));
        }
        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.setType(artifact.getAttribute(APIConstants.API_OVERVIEW_TYPE));
        api.setProductionMaxTps(artifact.getAttribute(APIConstants.API_PRODUCTION_THROTTLE_MAXTPS));
        api.setSandboxMaxTps(artifact.getAttribute(APIConstants.API_SANDBOX_THROTTLE_MAXTPS));
        api.setGatewayVendor(artifact.getAttribute(APIConstants.API_GATEWAY_VENDOR));
        api.setAsyncTransportProtocols(artifact.getAttribute(APIConstants.ASYNC_API_TRANSPORT_PROTOCOLS));
        int cacheTimeout = APIConstants.API_RESPONSE_CACHE_TIMEOUT;
        try {
            String strCacheTimeout = artifact.getAttribute(APIConstants.API_OVERVIEW_CACHE_TIMEOUT);
            if (strCacheTimeout != null && !strCacheTimeout.isEmpty()) {
                cacheTimeout = Integer.parseInt(strCacheTimeout);
            }
        } catch (NumberFormatException e) {
            if (log.isWarnEnabled()) {
                log.warn("Error while retrieving cache timeout from the registry for " + apiIdentifier);
            }
        // ignore the exception and use default cache timeout value
        }
        api.setCacheTimeout(cacheTimeout);
        api.setEndpointConfig(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_CONFIG));
        api.setRedirectURL(artifact.getAttribute(APIConstants.API_OVERVIEW_REDIRECT_URL));
        api.setApiExternalProductionEndpoint(artifact.getAttribute(APIConstants.API_OVERVIEW_EXTERNAL_PRODUCTION_ENDPOINT));
        api.setApiExternalSandboxEndpoint(artifact.getAttribute(APIConstants.API_OVERVIEW_EXTERNAL_SANDBOX_ENDPOINT));
        api.setAdvertiseOnlyAPIVendor(artifact.getAttribute(APIConstants.API_OVERVIEW_ADVERTISE_ONLY_API_VENDOR));
        api.setApiOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_OWNER));
        api.setAdvertiseOnly(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ADVERTISE_ONLY)));
        api.setType(artifact.getAttribute(APIConstants.API_OVERVIEW_TYPE));
        api.setSubscriptionAvailability(artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABILITY));
        api.setSubscriptionAvailableTenants(artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABLE_TENANTS));
        String tenantDomainName = MultitenantUtils.getTenantDomain(replaceEmailDomainBack(providerName));
        int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomainName);
        String tiers = artifact.getAttribute(APIConstants.API_OVERVIEW_TIER);
        Set<Tier> availableTiers = new HashSet<Tier>();
        if (tiers != null) {
            String[] tiersArray = tiers.split("\\|\\|");
            for (String tierName : tiersArray) {
                availableTiers.add(new Tier(tierName));
            }
        }
        api.setAvailableTiers(availableTiers);
        // This contains the resolved context
        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.setTestKey(artifact.getAttribute(APIConstants.API_OVERVIEW_TESTKEY));
        Set<String> tags = new HashSet<String>();
        Tag[] tag = registry.getTags(artifactPath);
        for (Tag tag1 : tag) {
            tags.add(tag1.getTagName());
        }
        api.setTags(tags);
        api.setLastUpdated(apiResource.getLastModified());
        api.setCreatedTime(String.valueOf(apiResource.getCreatedTime().getTime()));
        api.setImplementation(artifact.getAttribute(APIConstants.PROTOTYPE_OVERVIEW_IMPLEMENTATION));
        api.setEnvironments(getEnvironments(artifact.getAttribute(APIConstants.API_OVERVIEW_ENVIRONMENTS)));
        api.setCorsConfiguration(getCorsConfigurationFromArtifact(artifact));
        api.setWebsubSubscriptionConfiguration(getWebsubSubscriptionConfigurationFromArtifact(artifact));
        api.setAuthorizationHeader(artifact.getAttribute(APIConstants.API_OVERVIEW_AUTHORIZATION_HEADER));
        api.setApiSecurity(artifact.getAttribute(APIConstants.API_OVERVIEW_API_SECURITY));
        // set data and status related to monetization
        api.setMonetizationEnabled(Boolean.parseBoolean(artifact.getAttribute(APIConstants.Monetization.API_MONETIZATION_STATUS)));
        String monetizationInfo = artifact.getAttribute(APIConstants.Monetization.API_MONETIZATION_PROPERTIES);
        api.setWsUriMapping(getWsUriMappingFromArtifact(artifact));
        api.setAudience(artifact.getAttribute(APIConstants.API_OVERVIEW_AUDIENCE));
        api.setVersionTimestamp(artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION_TIMESTAMP));
        // set selected clusters which API needs to be deployed
        String deployments = artifact.getAttribute(APIConstants.API_OVERVIEW_DEPLOYMENTS);
        if (StringUtils.isNotBlank(monetizationInfo)) {
            JSONParser parser = new JSONParser();
            JSONObject jsonObj = (JSONObject) parser.parse(monetizationInfo);
            api.setMonetizationProperties(jsonObj);
        }
        api.setApiCategories(getAPICategoriesFromAPIGovernanceArtifact(artifact, tenantId));
        // get endpoint config string from artifact, parse it as a json and set the environment list configured with
        // non empty URLs to API object
        String keyManagers = artifact.getAttribute(APIConstants.API_OVERVIEW_KEY_MANAGERS);
        if (StringUtils.isNotEmpty(keyManagers)) {
            api.setKeyManagers(new Gson().fromJson(keyManagers, List.class));
        } else {
            api.setKeyManagers(Arrays.asList(APIConstants.API_LEVEL_ALL_KEY_MANAGERS));
        }
        try {
            api.setEnvironmentList(extractEnvironmentListForAPI(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_CONFIG)));
        } catch (ParseException e) {
            String msg = "Failed to parse endpoint config JSON of API: " + apiName + " " + apiVersion;
            log.error(msg, e);
            throw new APIManagementException(msg, e);
        } catch (ClassCastException e) {
            String msg = "Invalid endpoint config JSON found in API: " + apiName + " " + apiVersion;
            log.error(msg, e);
            throw new APIManagementException(msg, e);
        }
    } 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);
    } catch (UserStoreException e) {
        String msg = "Failed to get User Realm of API Provider";
        throw new APIManagementException(msg, e);
    } catch (ParseException e) {
        String msg = "Failed to get parse monetization information.";
        throw new APIManagementException(msg, e);
    }
    return api;
}
Also used : Tier(org.wso2.carbon.apimgt.api.model.Tier) Resource(org.wso2.carbon.registry.core.Resource) Gson(com.google.gson.Gson) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) JSONObject(org.json.simple.JSONObject) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) API(org.wso2.carbon.apimgt.api.model.API) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) JSONParser(org.json.simple.parser.JSONParser) List(java.util.List) ArrayList(java.util.ArrayList) Tag(org.wso2.carbon.registry.core.Tag) ParseException(org.json.simple.parser.ParseException) HashSet(java.util.HashSet)

Example 9 with GovernanceArtifact

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

the class RegistryPersistenceUtil method getAPIProduct.

/**
 * Retrieves api product artifact from registry
 *
 * @param artifact
 * @param registry
 * @return APIProduct
 * @throws org.wso2.carbon.apimgt.api.APIManagementException
 */
public static APIProduct getAPIProduct(GovernanceArtifact artifact, Registry registry) throws APIManagementException {
    APIProduct apiProduct;
    try {
        String artifactPath = GovernanceUtils.getArtifactPath(registry, artifact.getId());
        String providerName = artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER);
        String productName = artifact.getAttribute(APIConstants.API_OVERVIEW_NAME);
        String productVersion = artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION);
        APIProductIdentifier apiProductIdentifier = new APIProductIdentifier(providerName, productName, productVersion);
        apiProduct = new APIProduct(apiProductIdentifier);
        setResourceProperties(apiProduct, registry, artifactPath);
        // set uuid
        apiProduct.setUuid(artifact.getId());
        apiProduct.setContext(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT));
        apiProduct.setDescription(artifact.getAttribute(APIConstants.API_OVERVIEW_DESCRIPTION));
        apiProduct.setState(getLcStateFromArtifact(artifact));
        apiProduct.setThumbnailUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_THUMBNAIL_URL));
        apiProduct.setVisibility(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBILITY));
        apiProduct.setVisibleRoles(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_ROLES));
        apiProduct.setVisibleTenants(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_TENANTS));
        apiProduct.setBusinessOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER));
        apiProduct.setBusinessOwnerEmail(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER_EMAIL));
        apiProduct.setTechnicalOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_TEC_OWNER));
        apiProduct.setTechnicalOwnerEmail(artifact.getAttribute(APIConstants.API_OVERVIEW_TEC_OWNER_EMAIL));
        apiProduct.setSubscriptionAvailability(artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABILITY));
        apiProduct.setSubscriptionAvailableTenants(artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABLE_TENANTS));
        apiProduct.setEnvironments(getEnvironments(artifact.getAttribute(APIConstants.API_OVERVIEW_ENVIRONMENTS)));
        apiProduct.setTransports(artifact.getAttribute(APIConstants.API_OVERVIEW_TRANSPORTS));
        apiProduct.setApiSecurity(artifact.getAttribute(APIConstants.API_OVERVIEW_API_SECURITY));
        apiProduct.setAuthorizationHeader(artifact.getAttribute(APIConstants.API_OVERVIEW_AUTHORIZATION_HEADER));
        apiProduct.setCorsConfiguration(getCorsConfigurationFromArtifact(artifact));
        apiProduct.setCreatedTime(registry.get(artifactPath).getCreatedTime());
        apiProduct.setLastUpdated(registry.get(artifactPath).getLastModified());
        apiProduct.setType(artifact.getAttribute(APIConstants.API_OVERVIEW_TYPE));
        apiProduct.setGatewayVendor(artifact.getAttribute(APIConstants.API_GATEWAY_VENDOR));
        String tenantDomainName = MultitenantUtils.getTenantDomain(replaceEmailDomainBack(providerName));
        apiProduct.setTenantDomain(tenantDomainName);
        int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomainName);
        String tiers = artifact.getAttribute(APIConstants.API_OVERVIEW_TIER);
        Set<Tier> availableTiers = new HashSet<Tier>();
        if (tiers != null) {
            String[] tiersArray = tiers.split("\\|\\|");
            for (String tierName : tiersArray) {
                availableTiers.add(new Tier(tierName));
            }
        }
        apiProduct.setAvailableTiers(availableTiers);
        // We set the context template here
        apiProduct.setContextTemplate(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT_TEMPLATE));
        apiProduct.setEnableSchemaValidation(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENABLE_JSON_SCHEMA)));
        apiProduct.setEnableStore(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENABLE_STORE)));
        apiProduct.setTestKey(artifact.getAttribute(APIConstants.API_OVERVIEW_TESTKEY));
        apiProduct.setResponseCache(artifact.getAttribute(APIConstants.API_OVERVIEW_RESPONSE_CACHING));
        int cacheTimeout = APIConstants.API_RESPONSE_CACHE_TIMEOUT;
        try {
            cacheTimeout = Integer.parseInt(artifact.getAttribute(APIConstants.API_OVERVIEW_CACHE_TIMEOUT));
        } catch (NumberFormatException e) {
            if (log.isDebugEnabled()) {
                log.debug("Error in converting cache time out due to " + e.getMessage());
            }
        }
        apiProduct.setCacheTimeout(cacheTimeout);
        Set<String> tags = new HashSet<String>();
        Tag[] tag = registry.getTags(artifactPath);
        for (Tag tag1 : tag) {
            tags.add(tag1.getTagName());
        }
        apiProduct.addTags(tags);
        /*
            

            */
        // set data and status related to monetization
        apiProduct.setMonetizationStatus(Boolean.parseBoolean(artifact.getAttribute(APIConstants.Monetization.API_MONETIZATION_STATUS)));
        String monetizationInfo = artifact.getAttribute(APIConstants.Monetization.API_MONETIZATION_PROPERTIES);
        if (StringUtils.isNotBlank(monetizationInfo)) {
            JSONParser parser = new JSONParser();
            JSONObject jsonObj = (JSONObject) parser.parse(monetizationInfo);
            apiProduct.setMonetizationProperties(jsonObj);
        }
        apiProduct.setApiCategories(getAPICategoriesFromAPIGovernanceArtifact(artifact, tenantId));
    } catch (GovernanceException e) {
        String msg = "Failed to get API Product for artifact ";
        throw new APIManagementException(msg, e);
    } catch (RegistryException e) {
        String msg = "Failed to get LastAccess time or Rating";
        throw new APIManagementException(msg, e);
    } catch (UserStoreException e) {
        String msg = "Failed to get User Realm of API Product Provider";
        throw new APIManagementException(msg, e);
    } catch (ParseException e) {
        String msg = "Failed to get parse monetization information.";
        throw new APIManagementException(msg, e);
    }
    return apiProduct;
}
Also used : Tier(org.wso2.carbon.apimgt.api.model.Tier) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) JSONObject(org.json.simple.JSONObject) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) JSONParser(org.json.simple.parser.JSONParser) Tag(org.wso2.carbon.registry.core.Tag) ParseException(org.json.simple.parser.ParseException) HashSet(java.util.HashSet)

Example 10 with GovernanceArtifact

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

the class RegistryPersistenceImplTestCase method testRegistrySelectionForTenantUserCrossTenatAccess.

@Test
public void testRegistrySelectionForTenantUserCrossTenatAccess() throws Exception {
    RegistryService registryService = Mockito.mock(RegistryService.class);
    TenantManager tenantManager = Mockito.mock(TenantManager.class);
    Mockito.when(tenantManager.getTenantId(TENANT_DOMAIN)).thenReturn(TENANT_ID);
    Mockito.when(tenantManager.getTenantId(SUPER_TENANT_DOMAIN)).thenReturn(SUPER_TENANT_ID);
    PowerMockito.mockStatic(CarbonContext.class);
    CarbonContext context = Mockito.mock(CarbonContext.class);
    PowerMockito.when(CarbonContext.getThreadLocalCarbonContext()).thenReturn(context);
    PowerMockito.mockStatic(PrivilegedCarbonContext.class);
    PrivilegedCarbonContext privilegedContext = Mockito.mock(PrivilegedCarbonContext.class);
    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(privilegedContext);
    PowerMockito.mockStatic(GovernanceUtils.class);
    GovernanceArtifact artifact = Mockito.mock(GovernanceArtifact.class);
    List<GovernanceArtifact> artifacts = new ArrayList<GovernanceArtifact>();
    artifacts.add(artifact);
    PowerMockito.when(GovernanceUtils.findGovernanceArtifacts(Mockito.any(String.class), Mockito.any(Registry.class), Mockito.any(String.class), Mockito.any(Boolean.class))).thenReturn(artifacts);
    PowerMockito.mockStatic(RegistryPersistenceUtil.class);
    ServiceReferenceHolder serviceRefHolder = Mockito.mock(ServiceReferenceHolder.class);
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceRefHolder);
    RealmService realmService = Mockito.mock(RealmService.class);
    PowerMockito.when(serviceRefHolder.getRealmService()).thenReturn(realmService);
    UserRealm realm = Mockito.mock(UserRealm.class);
    PowerMockito.when(realmService.getTenantUserRealm(TENANT_ID)).thenReturn(realm);
    PowerMockito.doNothing().when(RegistryPersistenceUtil.class, "loadloadTenantAPIRXT", Mockito.any(String.class), Mockito.any(Integer.class));
    Mockito.when(context.getTenantDomain()).thenReturn(TENANT_DOMAIN);
    Mockito.when(context.getTenantId()).thenReturn(TENANT_ID);
    APIPersistence apiPersistenceInstance = new RegistryPersistenceImplWrapper(tenantManager, registryService);
    // return null artifact because we are not testing artifact related params. this is only to get the registry obj
    GenericArtifactManager artifactManager = Mockito.mock(GenericArtifactManager.class);
    PowerMockito.when(RegistryPersistenceUtil.getArtifactManager(Mockito.any(Registry.class), Mockito.any(String.class))).thenReturn(artifactManager);
    Mockito.when(artifactManager.getGenericArtifact(Mockito.any(String.class))).thenReturn(null);
    // trigger registry object creation. access super tenant api
    UserContext ctx = new UserContext("user", new Organization(TENANT_DOMAIN), null, null);
    apiPersistenceInstance.searchAPIsForDevPortal(new Organization(SUPER_TENANT_DOMAIN), "", 0, 10, ctx);
    // check whether super tenant's system registy is accessed
    Mockito.verify(registryService, times(1)).getGovernanceSystemRegistry((SUPER_TENANT_ID));
}
Also used : ServiceReferenceHolder(org.wso2.carbon.apimgt.persistence.internal.ServiceReferenceHolder) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) GovernanceArtifact(org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact) UserContext(org.wso2.carbon.apimgt.persistence.dto.UserContext) ArrayList(java.util.ArrayList) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) Matchers.anyString(org.mockito.Matchers.anyString) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) CarbonContext(org.wso2.carbon.context.CarbonContext) UserRealm(org.wso2.carbon.user.core.UserRealm) RealmService(org.wso2.carbon.user.core.service.RealmService) RegistryService(org.wso2.carbon.registry.core.service.RegistryService) TenantManager(org.wso2.carbon.user.core.tenant.TenantManager) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

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