Search in sources :

Example 31 with APIProductResource

use of org.wso2.carbon.apimgt.api.model.APIProductResource in project carbon-apimgt by wso2.

the class APIUtil 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);
        apiProductIdentifier.setUUID(artifact.getId());
        apiProduct = new APIProduct(apiProductIdentifier);
        apiProduct.setUuid(artifact.getId());
        apiProduct.setRating(Float.toString(getAverageRating(artifact.getId())));
        ApiMgtDAO.getInstance().setAPIProductFromDB(apiProduct);
        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));
        String environments = artifact.getAttribute(APIConstants.API_OVERVIEW_ENVIRONMENTS);
        apiProduct.setEnvironments(extractEnvironmentsForAPI(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);
        Map<String, Tier> definedTiers = getTiers(tenantId);
        Set<Tier> availableTier = getAvailableTiers(definedTiers, tiers, productName);
        apiProduct.setAvailableTiers(availableTier);
        // 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);
        List<APIProductResource> resources = ApiMgtDAO.getInstance().getAPIProductResourceMappings(apiProductIdentifier);
        Map<String, Scope> uniqueAPIProductScopeKeyMappings = new LinkedHashMap<>();
        for (APIProductResource resource : resources) {
            List<Scope> resourceScopes = resource.getUriTemplate().retrieveAllScopes();
            ListIterator it = resourceScopes.listIterator();
            while (it.hasNext()) {
                Scope resourceScope = (Scope) it.next();
                String scopeKey = resourceScope.getKey();
                if (!uniqueAPIProductScopeKeyMappings.containsKey(scopeKey)) {
                    resourceScope = getScopeByName(scopeKey, tenantDomainName);
                    uniqueAPIProductScopeKeyMappings.put(scopeKey, resourceScope);
                } else {
                    resourceScope = uniqueAPIProductScopeKeyMappings.get(scopeKey);
                }
                it.set(resourceScope);
            }
        }
        Set<String> tags = new HashSet<String>();
        Tag[] tag = registry.getTags(artifactPath);
        for (Tag tag1 : tag) {
            tags.add(tag1.getTagName());
        }
        apiProduct.addTags(tags);
        for (APIProductResource resource : resources) {
            String apiPath = APIUtil.getAPIPath(resource.getApiIdentifier());
            Resource productResource = null;
            try {
                // Handles store and publisher visibility issue when associated apis have different visibility
                // restrictions.
                productResource = registry.get(apiPath);
            } catch (RegistryException e) {
                if (e.getClass().equals(AuthorizationFailedException.class)) {
                    if (log.isDebugEnabled()) {
                        log.debug("User is not authorized to access the resource " + apiPath);
                    }
                    continue;
                } else {
                    String msg = "Failed to get product resource";
                    throw new APIManagementException(msg, e);
                }
            }
            String artifactId = productResource.getUUID();
            resource.setApiId(artifactId);
            GenericArtifactManager artifactManager = getArtifactManager(registry, APIConstants.API_KEY);
            GenericArtifact apiArtifact = artifactManager.getGenericArtifact(resource.getApiId());
            API api = getAPI(apiArtifact, registry);
            resource.setEndpointConfig(api.getEndpointConfig());
            resource.setEndpointSecurityMap(setEndpointSecurityForAPIProduct(api));
        }
        apiProduct.setProductResources(resources);
        // 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 : LinkedHashMap(java.util.LinkedHashMap) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) Tier(org.wso2.carbon.apimgt.api.model.Tier) Resource(org.wso2.carbon.registry.core.Resource) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) APIResource(org.wso2.carbon.apimgt.api.doc.model.APIResource) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) ListIterator(java.util.ListIterator) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) Endpoint(org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint) Scope(org.wso2.carbon.apimgt.api.model.Scope) AuthScope(org.apache.http.auth.AuthScope) JSONObject(org.json.simple.JSONObject) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) AuthorizationFailedException(org.wso2.carbon.registry.core.secure.AuthorizationFailedException) APIMgtAuthorizationFailedException(org.wso2.carbon.apimgt.api.APIMgtAuthorizationFailedException) API(org.wso2.carbon.apimgt.api.model.API) JSONParser(org.json.simple.parser.JSONParser) Tag(org.wso2.carbon.registry.core.Tag) ParseException(org.json.simple.parser.ParseException)

Aggregations

APIProductResource (org.wso2.carbon.apimgt.api.model.APIProductResource)23 ArrayList (java.util.ArrayList)17 URITemplate (org.wso2.carbon.apimgt.api.model.URITemplate)14 APIProductIdentifier (org.wso2.carbon.apimgt.api.model.APIProductIdentifier)13 API (org.wso2.carbon.apimgt.api.model.API)12 HashMap (java.util.HashMap)11 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)11 List (java.util.List)9 APIProduct (org.wso2.carbon.apimgt.api.model.APIProduct)9 Scope (org.wso2.carbon.apimgt.api.model.Scope)8 HashSet (java.util.HashSet)7 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)7 Tier (org.wso2.carbon.apimgt.api.model.Tier)7 LinkedHashSet (java.util.LinkedHashSet)6 Map (java.util.Map)6 JSONObject (org.json.simple.JSONObject)5 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)5 PublisherAPI (org.wso2.carbon.apimgt.persistence.dto.PublisherAPI)5 VelocityContext (org.apache.velocity.VelocityContext)4 ParseException (org.json.simple.parser.ParseException)4