Search in sources :

Example 41 with GovernanceArtifact

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

the class APIUtil method getAPI.

/**
 * This method used to get API from governance artifact specific to copyAPI
 *
 * @param artifact API artifact
 * @param registry Registry
 * @return API
 * @throws APIManagementException if failed to get API from artifact
 */
public static API getAPI(GovernanceArtifact artifact, Registry registry, APIIdentifier oldId, String oldContext) 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);
        api = new API(new APIIdentifier(providerName, apiName, apiVersion));
        int apiId = ApiMgtDAO.getInstance().getAPIID(artifact.getId());
        if (apiId == -1) {
            return null;
        }
        // set rating
        String artifactPath = GovernanceUtils.getArtifactPath(registry, artifact.getId());
        BigDecimal bigDecimal = BigDecimal.valueOf(registry.getAverageRating(artifactPath));
        BigDecimal res = bigDecimal.setScale(1, RoundingMode.HALF_UP);
        api.setRating(res.floatValue());
        // set description
        api.setDescription(artifact.getAttribute(APIConstants.API_OVERVIEW_DESCRIPTION));
        // set last access time
        api.setLastUpdated(registry.get(artifactPath).getLastModified());
        // set uuid
        api.setUUID(artifact.getId());
        // 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.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.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.setResponseCache(artifact.getAttribute(APIConstants.API_OVERVIEW_RESPONSE_CACHING));
        api.setImplementation(artifact.getAttribute(APIConstants.PROTOTYPE_OVERVIEW_IMPLEMENTATION));
        api.setVisibility(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBILITY));
        String tenantDomainName = MultitenantUtils.getTenantDomain(replaceEmailDomainBack(providerName));
        int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomainName);
        String apiLevelTier = ApiMgtDAO.getInstance().getAPILevelTier(apiId);
        api.setApiLevelPolicy(apiLevelTier);
        String tiers = artifact.getAttribute(APIConstants.API_OVERVIEW_TIER);
        Map<String, Tier> definedTiers = getTiers(tenantId);
        Set<Tier> availableTier = getAvailableTiers(definedTiers, tiers, apiName);
        api.addAvailableTiers(availableTier);
        api.setContext(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT));
        api.setContextTemplate(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT_TEMPLATE));
        api.setLatest(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_IS_LATEST)));
        ArrayList<URITemplate> urlPatternsList;
        Map<String, Scope> scopeToKeyMapping = getAPIScopes(artifact.getId(), tenantDomainName);
        api.setScopes(new LinkedHashSet<>(scopeToKeyMapping.values()));
        HashMap<Integer, Set<String>> resourceScopes;
        resourceScopes = ApiMgtDAO.getInstance().getResourceToScopeMapping(artifact.getId());
        urlPatternsList = ApiMgtDAO.getInstance().getAllURITemplates(oldContext, oldId.getVersion());
        Set<URITemplate> uriTemplates = new HashSet<URITemplate>(urlPatternsList);
        for (URITemplate uriTemplate : uriTemplates) {
            uriTemplate.setResourceURI(api.getUrl());
            uriTemplate.setResourceSandboxURI(api.getSandboxUrl());
            List<String> templateScopeKeys = new ArrayList<>(resourceScopes.get(uriTemplate.getId()));
            List<Scope> newTemplateScopes = new ArrayList<>();
            if (!templateScopeKeys.isEmpty()) {
                for (String templateScope : templateScopeKeys) {
                    Scope scope = scopeToKeyMapping.get(templateScope);
                    newTemplateScopes.add(scope);
                }
            }
            uriTemplate.addAllScopes(newTemplateScopes);
        }
        api.setUriTemplates(uriTemplates);
        Set<String> tags = new HashSet<String>();
        Tag[] tag = registry.getTags(artifactPath);
        for (Tag tag1 : tag) {
            tags.add(tag1.getTagName());
        }
        api.addTags(tags);
        api.setLastUpdated(registry.get(artifactPath).getLastModified());
        api.setAsDefaultVersion(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_IS_DEFAULT_VERSION)));
        String environments = artifact.getAttribute(APIConstants.API_OVERVIEW_ENVIRONMENTS);
        api.setEnvironments(extractEnvironmentsForAPI(environments));
        api.setCorsConfiguration(getCorsConfigurationFromArtifact(artifact));
    } catch (GovernanceException e) {
        String msg = "Failed to get API fro 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);
    }
    return api;
}
Also used : SortedSet(java.util.SortedSet) HashSet(java.util.HashSet) Set(java.util.Set) TreeSet(java.util.TreeSet) LinkedHashSet(java.util.LinkedHashSet) ArrayList(java.util.ArrayList) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) Tier(org.wso2.carbon.apimgt.api.model.Tier) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) Endpoint(org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint) BigDecimal(java.math.BigDecimal) BigInteger(java.math.BigInteger) Scope(org.wso2.carbon.apimgt.api.model.Scope) AuthScope(org.apache.http.auth.AuthScope) API(org.wso2.carbon.apimgt.api.model.API) Tag(org.wso2.carbon.registry.core.Tag)

Example 42 with GovernanceArtifact

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

the class APIUtil method getLightWeightAPI.

/**
 * This method is used to get an API in the Light Weight manner.
 *
 * @param artifact generic artfact
 * @return this will return an API for the selected artifact.
 * @throws APIManagementException , if invalid json config for the API or Api cannot be retrieved from the artifact
 */
public static API getLightWeightAPI(GovernanceArtifact artifact) 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);
        int apiId = ApiMgtDAO.getInstance().getAPIID(artifact.getId());
        if (apiId == -1) {
            return null;
        }
        // set uuid
        api.setUUID(artifact.getId());
        api.setRating(getAverageRating(apiId));
        api.setThumbnailUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_THUMBNAIL_URL));
        api.setStatus(getLcStateFromArtifact(artifact));
        api.setContext(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT));
        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.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.setDescription(artifact.getAttribute(APIConstants.API_OVERVIEW_DESCRIPTION));
        api.setResponseCache(artifact.getAttribute(APIConstants.API_OVERVIEW_RESPONSE_CACHING));
        api.setType(artifact.getAttribute(APIConstants.API_OVERVIEW_TYPE));
        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);
        String apiLevelTier = ApiMgtDAO.getInstance().getAPILevelTier(apiId);
        api.setApiLevelPolicy(apiLevelTier);
        Set<Tier> availablePolicy = new HashSet<Tier>();
        String[] subscriptionPolicy = ApiMgtDAO.getInstance().getPolicyNames(PolicyConstants.POLICY_LEVEL_SUB, replaceEmailDomainBack(providerName));
        List<String> definedPolicyNames = Arrays.asList(subscriptionPolicy);
        String policies = artifact.getAttribute(APIConstants.API_OVERVIEW_TIER);
        if (!StringUtils.isEmpty(policies)) {
            String[] policyNames = policies.split("\\|\\|");
            for (String policyName : policyNames) {
                if (definedPolicyNames.contains(policyName) || APIConstants.UNLIMITED_TIER.equals(policyName)) {
                    Tier p = new Tier(policyName);
                    availablePolicy.add(p);
                } else {
                    log.warn("Unknown policy: " + policyName + " found on API: " + apiName);
                }
            }
        }
        api.addAvailableTiers(availablePolicy);
        String tenantDomainName = MultitenantUtils.getTenantDomain(replaceEmailDomainBack(providerName));
        api.setMonetizationCategory(getAPIMonetizationCategory(availablePolicy, tenantDomainName));
        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.setEndpointConfig(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_CONFIG));
        api.setSubscriptionAvailability(artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABILITY));
        api.setSubscriptionAvailableTenants(artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABLE_TENANTS));
        api.setAsDefaultVersion(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_IS_DEFAULT_VERSION)));
        api.setImplementation(artifact.getAttribute(APIConstants.PROTOTYPE_OVERVIEW_IMPLEMENTATION));
        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));
        String environments = artifact.getAttribute(APIConstants.API_OVERVIEW_ENVIRONMENTS);
        api.setEnvironments(extractEnvironmentsForAPI(environments));
        api.setCorsConfiguration(getCorsConfigurationFromArtifact(artifact));
        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;
            throw new APIManagementException(msg, e);
        } catch (ClassCastException e) {
            String msg = "Invalid endpoint config JSON found in API: " + apiName + " " + apiVersion;
            throw new APIManagementException(msg, e);
        }
    } catch (GovernanceException e) {
        String msg = "Failed to get API from artifact";
        throw new APIManagementException(msg, e);
    }
    return api;
}
Also used : Tier(org.wso2.carbon.apimgt.api.model.Tier) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) Endpoint(org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) API(org.wso2.carbon.apimgt.api.model.API) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) ParseException(org.json.simple.parser.ParseException) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

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