Search in sources :

Example 51 with Tag

use of org.wso2.carbon.registry.core.Tag in project carbon-apimgt by wso2.

the class APIConsumerImpl method getAllPaginatedAPIsByStatus.

/**
 * The method to get APIs by given status to Store view
 *
 * @return Set<API>  Set of APIs
 * @throws APIManagementException
 */
@Override
@Deprecated
public Map<String, Object> getAllPaginatedAPIsByStatus(String tenantDomain, int start, int end, final String apiStatus, boolean returnAPITags) throws APIManagementException {
    try {
        if (tenantDomain != null) {
            PrivilegedCarbonContext.startTenantFlow();
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
        }
    } finally {
        endTenantFlow();
    }
    Boolean displayAPIsWithMultipleStatus = APIUtil.isAllowDisplayAPIsWithMultipleStatus();
    Map<String, List<String>> listMap = new HashMap<String, List<String>>();
    // Check the api-manager.xml config file entry <DisplayAllAPIs> value is false
    if (APIConstants.PROTOTYPED.equals(apiStatus)) {
        listMap.put(APIConstants.API_OVERVIEW_STATUS, new ArrayList<String>() {

            {
                add(apiStatus);
            }
        });
    } else {
        if (!displayAPIsWithMultipleStatus) {
            // Create the search attribute map
            listMap.put(APIConstants.API_OVERVIEW_STATUS, new ArrayList<String>() {

                {
                    add(apiStatus);
                }
            });
        } else {
            return getAllPaginatedAPIs(tenantDomain, start, end);
        }
    }
    Map<String, Object> result = new HashMap<String, Object>();
    SortedSet<API> apiSortedSet = new TreeSet<API>(new APINameComparator());
    SortedSet<API> apiVersionsSortedSet = new TreeSet<API>(new APIVersionComparator());
    int totalLength = 0;
    boolean isMore = false;
    try {
        Registry userRegistry;
        boolean isTenantMode = (tenantDomain != null);
        if ((isTenantMode && this.tenantDomain == null) || (isTenantMode && isTenantDomainNotMatching(tenantDomain))) {
            // Tenant store anonymous mode
            int tenantId = getTenantId(tenantDomain);
            // explicitly load the tenant's registry
            APIUtil.loadTenantRegistry(tenantId);
            userRegistry = getGovernanceUserRegistry(tenantId);
            setUsernameToThreadLocalCarbonContext(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME);
        } else {
            userRegistry = registry;
            setUsernameToThreadLocalCarbonContext(this.username);
        }
        this.isTenantModeStoreView = isTenantMode;
        this.requestedTenant = tenantDomain;
        Map<String, API> latestPublishedAPIs = new HashMap<String, API>();
        List<API> multiVersionedAPIs = new ArrayList<API>();
        Comparator<API> versionComparator = new APIVersionComparator();
        Boolean displayMultipleVersions = APIUtil.isAllowDisplayMultipleVersions();
        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);
        GenericArtifactManager artifactManager = APIUtil.getArtifactManager(userRegistry, APIConstants.API_KEY);
        if (artifactManager != null) {
            GenericArtifact[] genericArtifacts = artifactManager.findGenericArtifacts(listMap);
            totalLength = PaginationContext.getInstance().getLength();
            if (genericArtifacts == null || genericArtifacts.length == 0) {
                result.put("apis", apiSortedSet);
                result.put("totalLength", totalLength);
                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 so we cannot determine the total API count without incurring a
                isMore = true;
                // performance hit
                // Remove the additional 1 we added earlier when setting max pagination limit
                --totalLength;
            }
            int tempLength = 0;
            for (GenericArtifact artifact : genericArtifacts) {
                if (artifact == null) {
                    log.error("Failed to retrieve artifact when getting all paginated APIs by status.");
                    continue;
                }
                API api = null;
                try {
                    api = APIUtil.getAPI(artifact);
                } catch (APIManagementException e) {
                    // log and continue since we want to load the rest of the APIs.
                    log.error("Error while loading API " + artifact.getAttribute(APIConstants.API_OVERVIEW_NAME), e);
                }
                if (api != null) {
                    if (returnAPITags) {
                        String artifactPath = GovernanceUtils.getArtifactPath(registry, artifact.getId());
                        Set<String> tags = new HashSet<String>();
                        org.wso2.carbon.registry.core.Tag[] tag = registry.getTags(artifactPath);
                        for (org.wso2.carbon.registry.core.Tag tag1 : tag) {
                            tags.add(tag1.getTagName());
                        }
                        api.addTags(tags);
                    }
                    String key;
                    // Check the configuration to allow showing multiple versions of an API true/false
                    if (!displayMultipleVersions) {
                        // If allow only showing the latest version of an API
                        key = api.getId().getProviderName() + COLON_CHAR + api.getId().getApiName();
                        API existingAPI = latestPublishedAPIs.get(key);
                        if (existingAPI != null) {
                            // this one has a higher version number
                            if (versionComparator.compare(api, existingAPI) > 0) {
                                latestPublishedAPIs.put(key, api);
                            }
                        } else {
                            // We haven't seen this API before
                            latestPublishedAPIs.put(key, api);
                        }
                    } else {
                        // If allow showing multiple versions of an API
                        multiVersionedAPIs.add(api);
                    }
                }
                tempLength++;
                if (tempLength >= totalLength) {
                    break;
                }
            }
            if (!displayMultipleVersions) {
                apiSortedSet.addAll(latestPublishedAPIs.values());
                result.put("apis", apiSortedSet);
                result.put("totalLength", totalLength);
                result.put("isMore", isMore);
                return result;
            } else {
                apiVersionsSortedSet.addAll(multiVersionedAPIs);
                result.put("apis", apiVersionsSortedSet);
                result.put("totalLength", totalLength);
                result.put("isMore", isMore);
                return result;
            }
        } else {
            String errorMessage = "Artifact manager is null for tenant domain " + tenantDomain + " when retrieving APIs by status.";
            log.error(errorMessage);
        }
    } catch (RegistryException e) {
        handleException("Failed to get all published APIs", e);
    } catch (UserStoreException e) {
        handleException("Failed to get all published APIs", e);
    } finally {
        PaginationContext.destroy();
    }
    result.put("apis", apiSortedSet);
    result.put("totalLength", totalLength);
    result.put("isMore", isMore);
    return result;
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) APINameComparator(org.wso2.carbon.apimgt.impl.utils.APINameComparator) APIVersionComparator(org.wso2.carbon.apimgt.impl.utils.APIVersionComparator) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) TreeSet(java.util.TreeSet) UserStoreException(org.wso2.carbon.user.api.UserStoreException) CommentList(org.wso2.carbon.apimgt.api.model.CommentList) ArrayList(java.util.ArrayList) List(java.util.List) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet) GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) JSONObject(org.json.simple.JSONObject) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) API(org.wso2.carbon.apimgt.api.model.API) Tag(org.wso2.carbon.apimgt.api.model.Tag)

Example 52 with Tag

use of org.wso2.carbon.registry.core.Tag in project carbon-apimgt by wso2.

the class APIConsumerImpl method getTagsWithAttributes.

@Override
public Set<Tag> getTagsWithAttributes(String tenantDomain) throws APIManagementException {
    // Fetch the all the tags first.
    Set<Tag> tags = getAllTags(tenantDomain);
    // For each and every tag get additional attributes from the registry.
    String descriptionPathPattern = APIConstants.TAGS_INFO_ROOT_LOCATION + "/%s/description.txt";
    String thumbnailPathPattern = APIConstants.TAGS_INFO_ROOT_LOCATION + "/%s/thumbnail.png";
    // if the tenantDomain is not specified super tenant domain is used
    if (StringUtils.isBlank(tenantDomain)) {
        try {
            tenantDomain = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getSuperTenantDomain();
        } catch (org.wso2.carbon.user.core.UserStoreException e) {
            handleException("Cannot get super tenant domain name", e);
        }
    }
    // get the registry instance related to the tenant domain
    UserRegistry govRegistry = null;
    try {
        int tenantId = getTenantId(tenantDomain);
        RegistryService registryService = ServiceReferenceHolder.getInstance().getRegistryService();
        govRegistry = registryService.getGovernanceSystemRegistry(tenantId);
    } catch (UserStoreException e) {
        handleException("Cannot get tenant id for tenant domain name:" + tenantDomain, e);
    } catch (RegistryException e) {
        handleException("Cannot get registry for tenant domain name:" + tenantDomain, e);
    }
    if (govRegistry != null) {
        for (Tag tag : tags) {
            // Get the description.
            Resource descriptionResource = null;
            String descriptionPath = String.format(descriptionPathPattern, tag.getName());
            try {
                if (govRegistry.resourceExists(descriptionPath)) {
                    descriptionResource = govRegistry.get(descriptionPath);
                }
            } catch (RegistryException e) {
                // warn and proceed to the next tag
                log.warn(String.format("Error while querying the existence of the description for the tag '%s'", tag.getName()), e);
            }
            // of a text file.
            if (descriptionResource != null) {
                try {
                    String description = new String((byte[]) descriptionResource.getContent(), Charset.defaultCharset());
                    tag.setDescription(description);
                } catch (ClassCastException e) {
                    // added warnings as it can then proceed to load rest of resources/tags
                    log.warn(String.format("Cannot cast content of %s to byte[]", descriptionPath), e);
                } catch (RegistryException e) {
                    // added warnings as it can then proceed to load rest of resources/tags
                    log.warn(String.format("Cannot read content of %s", descriptionPath), e);
                }
            }
            // Checks whether the thumbnail exists.
            String thumbnailPath = String.format(thumbnailPathPattern, tag.getName());
            try {
                boolean isThumbnailExists = govRegistry.resourceExists(thumbnailPath);
                tag.setThumbnailExists(isThumbnailExists);
                if (isThumbnailExists) {
                    tag.setThumbnailUrl(APIUtil.getRegistryResourcePathForUI(APIConstants.RegistryResourceTypesForUI.TAG_THUMBNAIL, tenantDomain, thumbnailPath));
                }
            } catch (RegistryException e) {
                // warn and then proceed to load rest of tags
                log.warn(String.format("Error while querying the existence of %s", thumbnailPath), e);
            }
        }
    }
    return tags;
}
Also used : Resource(org.wso2.carbon.registry.core.Resource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) Tag(org.wso2.carbon.apimgt.api.model.Tag) RegistryService(org.wso2.carbon.registry.core.service.RegistryService)

Example 53 with Tag

use of org.wso2.carbon.registry.core.Tag in project carbon-apimgt by wso2.

the class APIConsumerImpl method getAllTags.

@Override
public Set<Tag> getAllTags(String organization) throws APIManagementException {
    /* We keep track of the lastUpdatedTime of the TagCache to determine its freshness.
         */
    long lastUpdatedTimeAtStart = lastUpdatedTime;
    long currentTimeAtStart = System.currentTimeMillis();
    if (isTagCacheEnabled && ((currentTimeAtStart - lastUpdatedTimeAtStart) < tagCacheValidityTime)) {
        if (tagSet != null) {
            return tagSet;
        }
    }
    Organization org = new Organization(organization);
    String userName = (userNameWithoutChange != null) ? userNameWithoutChange : username;
    String[] roles = APIUtil.getListOfRoles(userName);
    Map<String, Object> properties = APIUtil.getUserProperties(userName);
    UserContext userCtx = new UserContext(userNameWithoutChange, org, properties, roles);
    try {
        Set<Tag> tempTagSet = apiPersistenceInstance.getAllTags(org, userCtx);
        synchronized (tagCacheMutex) {
            lastUpdatedTime = System.currentTimeMillis();
            this.tagSet = tempTagSet;
        }
    } catch (APIPersistenceException e) {
        String msg = "Failed to get API tags";
        throw new APIManagementException(msg, e);
    }
    return tagSet;
}
Also used : APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) UserContext(org.wso2.carbon.apimgt.persistence.dto.UserContext) JSONObject(org.json.simple.JSONObject) Tag(org.wso2.carbon.apimgt.api.model.Tag)

Example 54 with Tag

use of org.wso2.carbon.registry.core.Tag in project carbon-apimgt by wso2.

the class APIUtil method getAPIForPublishing.

/**
 * 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 getAPIForPublishing(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());
        String currentApiUuid;
        APIRevision apiRevision = ApiMgtDAO.getInstance().checkAPIUUIDIsARevisionUUID(artifact.getId());
        if (apiRevision != null && apiRevision.getApiUUID() != null) {
            currentApiUuid = apiRevision.getApiUUID();
        } else {
            currentApiUuid = artifact.getId();
        }
        int apiId = ApiMgtDAO.getInstance().getAPIID(currentApiUuid);
        if (apiId == -1) {
            return null;
        }
        api = new API(apiIdentifier);
        // set uuid
        api.setUUID(artifact.getId());
        // set rating
        String artifactPath = GovernanceUtils.getArtifactPath(registry, artifact.getId());
        api = setResourceProperties(api, registry, artifactPath);
        api.setRating(getAverageRating(apiId));
        // set description
        api.setDescription(artifact.getAttribute(APIConstants.API_OVERVIEW_DESCRIPTION));
        // set last access time
        api.setLastUpdated(registry.get(artifactPath).getLastModified());
        // 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));
        api.setGatewayVendor(artifact.getAttribute(APIConstants.API_GATEWAY_VENDOR));
        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.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));
        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.setApiOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_OWNER));
        api.setAdvertiseOnly(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ADVERTISE_ONLY)));
        api.setApiExternalProductionEndpoint(artifact.getAttribute(APIConstants.API_OVERVIEW_EXTERNAL_PRODUCTION_ENDPOINT));
        api.setApiExternalSandboxEndpoint(artifact.getAttribute(APIConstants.API_OVERVIEW_EXTERNAL_SANDBOX_ENDPOINT));
        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);
        APIManagerConfiguration config = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration();
        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);
        // 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));
        Map<String, Scope> scopeToKeyMapping = getAPIScopes(api.getUuid(), tenantDomainName);
        api.setScopes(new LinkedHashSet<>(scopeToKeyMapping.values()));
        Set<URITemplate> uriTemplates = ApiMgtDAO.getInstance().getURITemplatesOfAPI(api.getUuid());
        // AWS Lambda: get paths
        OASParserUtil oasParserUtil = new OASParserUtil();
        String resourceConfigsString = oasParserUtil.getAPIDefinition(apiIdentifier, registry);
        JSONParser jsonParser = new JSONParser();
        JSONObject paths = null;
        if (resourceConfigsString != null) {
            JSONObject resourceConfigsJSON = (JSONObject) jsonParser.parse(resourceConfigsString);
            paths = (JSONObject) resourceConfigsJSON.get(APIConstants.SWAGGER_PATHS);
        }
        for (URITemplate uriTemplate : uriTemplates) {
            String uTemplate = uriTemplate.getUriTemplate();
            String method = uriTemplate.getHTTPVerb();
            List<Scope> oldTemplateScopes = uriTemplate.retrieveAllScopes();
            List<Scope> newTemplateScopes = new ArrayList<>();
            if (!oldTemplateScopes.isEmpty()) {
                for (Scope templateScope : oldTemplateScopes) {
                    Scope scope = scopeToKeyMapping.get(templateScope.getKey());
                    newTemplateScopes.add(scope);
                }
            }
            uriTemplate.addAllScopes(newTemplateScopes);
            uriTemplate.setResourceURI(api.getUrl());
            uriTemplate.setResourceSandboxURI(api.getSandboxUrl());
            // AWS Lambda: set arn & timeout to URI template
            if (paths != null) {
                JSONObject path = (JSONObject) paths.get(uTemplate);
                if (path != null) {
                    JSONObject operation = (JSONObject) path.get(method.toLowerCase());
                    if (operation != null) {
                        if (operation.containsKey(APIConstants.SWAGGER_X_AMZN_RESOURCE_NAME)) {
                            uriTemplate.setAmznResourceName((String) operation.get(APIConstants.SWAGGER_X_AMZN_RESOURCE_NAME));
                        }
                        if (operation.containsKey(APIConstants.SWAGGER_X_AMZN_RESOURCE_TIMEOUT)) {
                            uriTemplate.setAmznResourceTimeout(((Long) operation.get(APIConstants.SWAGGER_X_AMZN_RESOURCE_TIMEOUT)).intValue());
                        }
                    }
                }
            }
        }
        if (APIConstants.IMPLEMENTATION_TYPE_INLINE.equalsIgnoreCase(api.getImplementation())) {
            for (URITemplate template : uriTemplates) {
                template.setMediationScript(template.getAggregatedMediationScript());
            }
        }
        api.setUriTemplates(uriTemplates);
        api.setAsDefaultVersion(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_IS_DEFAULT_VERSION)));
        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.setCreatedTime(String.valueOf(registry.get(artifactPath).getCreatedTime().getTime()));
        api.setImplementation(artifact.getAttribute(APIConstants.PROTOTYPE_OVERVIEW_IMPLEMENTATION));
        String environments = artifact.getAttribute(APIConstants.API_OVERVIEW_ENVIRONMENTS);
        api.setEnvironments(extractEnvironmentsForAPI(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.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);
            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.KeyManager.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 : APIManagerConfiguration(org.wso2.carbon.apimgt.impl.APIManagerConfiguration) ArrayList(java.util.ArrayList) Gson(com.google.gson.Gson) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) SolrDocumentList(org.apache.solr.common.SolrDocumentList) ArrayList(java.util.ArrayList) List(java.util.List) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) APIRevision(org.wso2.carbon.apimgt.api.model.APIRevision) 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) OASParserUtil(org.wso2.carbon.apimgt.impl.definitions.OASParserUtil) Scope(org.wso2.carbon.apimgt.api.model.Scope) AuthScope(org.apache.http.auth.AuthScope) JSONObject(org.json.simple.JSONObject) 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)

Example 55 with Tag

use of org.wso2.carbon.registry.core.Tag in project carbon-apimgt by wso2.

the class APIUtil method getAPI.

/**
 * This method used to get API from governance artifact
 *
 * @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) 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);
        int apiId = ApiMgtDAO.getInstance().getAPIID(artifact.getId());
        if (apiId == -1) {
            return null;
        }
        api = new API(apiIdentifier);
        // set rating
        String artifactPath = GovernanceUtils.getArtifactPath(registry, artifact.getId());
        api = setResourceProperties(api, registry, artifactPath);
        api.setRating(getAverageRating(apiId));
        // 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());
        // setting api ID for scope retrieval
        api.getId().setApplicationId(Integer.toString(apiId));
        // 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));
        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.setMonetizationCategory(getAPIMonetizationCategory(availableTier, tenantDomainName));
        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)));
        Map<String, Scope> scopeToKeyMapping = getAPIScopes(api.getUuid(), tenantDomainName);
        api.setScopes(new LinkedHashSet<>(scopeToKeyMapping.values()));
        Set<URITemplate> uriTemplates = ApiMgtDAO.getInstance().getURITemplatesOfAPI(api.getUuid());
        for (URITemplate uriTemplate : uriTemplates) {
            List<Scope> oldTemplateScopes = uriTemplate.retrieveAllScopes();
            List<Scope> newTemplateScopes = new ArrayList<>();
            if (!oldTemplateScopes.isEmpty()) {
                for (Scope templateScope : oldTemplateScopes) {
                    Scope scope = scopeToKeyMapping.get(templateScope.getKey());
                    newTemplateScopes.add(scope);
                }
            }
            uriTemplate.addAllScopes(newTemplateScopes);
            uriTemplate.setResourceURI(api.getUrl());
            uriTemplate.setResourceSandboxURI(api.getSandboxUrl());
        }
        api.setUriTemplates(uriTemplates);
        api.setAsDefaultVersion(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_IS_DEFAULT_VERSION)));
        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.setImplementation(artifact.getAttribute(APIConstants.PROTOTYPE_OVERVIEW_IMPLEMENTATION));
        String environments = artifact.getAttribute(APIConstants.API_OVERVIEW_ENVIRONMENTS);
        api.setEnvironments(extractEnvironmentsForAPI(environments));
        api.setCorsConfiguration(getCorsConfigurationFromArtifact(artifact));
        api.setAuthorizationHeader(artifact.getAttribute(APIConstants.API_OVERVIEW_AUTHORIZATION_HEADER));
        api.setApiSecurity(artifact.getAttribute(APIConstants.API_OVERVIEW_API_SECURITY));
        api.setApiCategories(getAPICategoriesFromAPIGovernanceArtifact(artifact, tenantId));
    } 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);
    }
    return api;
}
Also used : Tier(org.wso2.carbon.apimgt.api.model.Tier) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) ArrayList(java.util.ArrayList) 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) Scope(org.wso2.carbon.apimgt.api.model.Scope) AuthScope(org.apache.http.auth.AuthScope) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) API(org.wso2.carbon.apimgt.api.model.API) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) Tag(org.wso2.carbon.registry.core.Tag) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Aggregations

ArrayList (java.util.ArrayList)21 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)21 Registry (org.wso2.carbon.registry.core.Registry)20 GenericArtifact (org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact)19 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)18 Tag (org.wso2.carbon.registry.core.Tag)18 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)18 API (org.wso2.carbon.apimgt.api.model.API)17 GenericArtifactManager (org.wso2.carbon.governance.api.generic.GenericArtifactManager)16 Resource (org.wso2.carbon.registry.core.Resource)16 DevPortalAPI (org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI)14 UserStoreException (org.wso2.carbon.user.api.UserStoreException)14 HashSet (java.util.HashSet)13 BType (org.wso2.ballerinalang.compiler.semantics.model.types.BType)12 Test (org.junit.Test)11 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)11 JSONObject (org.json.simple.JSONObject)10 Tag (org.wso2.carbon.apimgt.api.model.Tag)10 List (java.util.List)9 GovernanceException (org.wso2.carbon.governance.api.exception.GovernanceException)9