Search in sources :

Example 11 with Subtract

use of org.wso2.siddhi.query.api.expression.math.Subtract 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 12 with Subtract

use of org.wso2.siddhi.query.api.expression.math.Subtract in project carbon-apimgt by wso2.

the class APIProviderImpl method getAllPaginatedAPIs.

@Override
public Map<String, Object> getAllPaginatedAPIs(String tenantDomain, int start, int end) throws APIManagementException {
    Map<String, Object> result = new HashMap<String, Object>();
    List<API> apiSortedList = new ArrayList<API>();
    int totalLength = 0;
    boolean isTenantFlowStarted = false;
    try {
        String paginationLimit = getAPIManagerConfiguration().getFirstProperty(APIConstants.API_PUBLISHER_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_PUBLISHER_APIS_PER_PAGE + "' is too low, defaulting to 11");
            }
            maxPaginationLimit = start + pagination + 1;
        } else // Else if the config is not specifed we go with default functionality and load all
        {
            maxPaginationLimit = Integer.MAX_VALUE;
        }
        Registry userRegistry;
        boolean isTenantMode = (tenantDomain != null);
        if ((isTenantMode && this.tenantDomain == null) || (isTenantMode && isTenantDomainNotMatching(tenantDomain))) {
            if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
                PrivilegedCarbonContext.startTenantFlow();
                PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
                isTenantFlowStarted = true;
            }
            int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
            APIUtil.loadTenantRegistry(tenantId);
            userRegistry = ServiceReferenceHolder.getInstance().getRegistryService().getGovernanceUserRegistry(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME, tenantId);
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME);
        } else {
            userRegistry = registry;
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(this.username);
        }
        PaginationContext.init(start, end, "ASC", APIConstants.PROVIDER_OVERVIEW_NAME, maxPaginationLimit);
        GenericArtifactManager artifactManager = APIUtil.getArtifactManager(userRegistry, APIConstants.API_KEY);
        if (artifactManager != null) {
            List<GovernanceArtifact> genericArtifacts = null;
            if (isAccessControlRestrictionEnabled && !APIUtil.hasPermission(userNameWithoutChange, APIConstants.Permissions.APIM_ADMIN)) {
                genericArtifacts = GovernanceUtils.findGovernanceArtifacts(getUserRoleListQuery(), userRegistry, APIConstants.API_RXT_MEDIA_TYPE, true);
            } else {
                genericArtifacts = GovernanceUtils.findGovernanceArtifacts(new HashMap<String, List<String>>(), userRegistry, APIConstants.API_RXT_MEDIA_TYPE);
            }
            totalLength = PaginationContext.getInstance().getLength();
            if (genericArtifacts == null || genericArtifacts.isEmpty()) {
                result.put("apis", apiSortedList);
                result.put("totalLength", totalLength);
                return result;
            }
            // Check to see if we can speculate that there are more APIs to be loaded
            if (maxPaginationLimit == totalLength) {
                // performance hit
                // Remove the additional 1 we added earlier when setting max pagination limit
                --totalLength;
            }
            int tempLength = 0;
            for (GovernanceArtifact artifact : genericArtifacts) {
                API api = APIUtil.getAPI(artifact);
                if (api != null) {
                    apiSortedList.add(api);
                }
                tempLength++;
                if (tempLength >= totalLength) {
                    break;
                }
            }
            Collections.sort(apiSortedList, new APINameComparator());
        } else {
            String errorMessage = "Failed to retrieve artifact manager when getting paginated APIs of tenant " + tenantDomain;
            log.error(errorMessage);
            throw new APIManagementException(errorMessage);
        }
    } catch (RegistryException e) {
        handleException("Failed to get all APIs", e);
    } catch (UserStoreException e) {
        handleException("Failed to get all APIs", e);
    } finally {
        PaginationContext.destroy();
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }
    result.put("apis", apiSortedList);
    result.put("totalLength", totalLength);
    return result;
}
Also used : GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) GovernanceArtifact(org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact) ArrayList(java.util.ArrayList) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) APINameComparator(org.wso2.carbon.apimgt.impl.utils.APINameComparator) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) JSONObject(org.json.simple.JSONObject) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI)

Example 13 with Subtract

use of org.wso2.siddhi.query.api.expression.math.Subtract in project ballerina by ballerina-lang.

the class DefinitionUtil method getDefinitionPosition.

/**
 * Get definition position for the given definition context.
 *
 * @param definitionContext   context of the definition.
 * @param lSPackageCache package context for language server.
 * @return position
 */
public static List<Location> getDefinitionPosition(TextDocumentServiceContext definitionContext, LSPackageCache lSPackageCache) {
    List<Location> contents = new ArrayList<>();
    if (definitionContext.get(NodeContextKeys.SYMBOL_KIND_OF_NODE_KEY) == null) {
        return contents;
    }
    String nodeKind = definitionContext.get(NodeContextKeys.SYMBOL_KIND_OF_NODE_KEY);
    BLangPackage bLangPackage = getPackageOfTheOwner(definitionContext.get(NodeContextKeys.NODE_OWNER_PACKAGE_KEY), definitionContext, lSPackageCache);
    BLangNode bLangNode = null;
    switch(nodeKind) {
        case ContextConstants.FUNCTION:
            bLangNode = bLangPackage.functions.stream().filter(function -> function.name.getValue().equals(definitionContext.get(NodeContextKeys.NAME_OF_NODE_KEY))).findAny().orElse(null);
            break;
        case ContextConstants.STRUCT:
            bLangNode = bLangPackage.structs.stream().filter(struct -> struct.name.getValue().equals(definitionContext.get(NodeContextKeys.NAME_OF_NODE_KEY))).findAny().orElse(null);
            break;
        case ContextConstants.OBJECT:
            bLangNode = bLangPackage.objects.stream().filter(object -> object.name.getValue().equals(definitionContext.get(NodeContextKeys.NAME_OF_NODE_KEY))).findAny().orElse(null);
            break;
        case ContextConstants.ENUM:
            bLangNode = bLangPackage.enums.stream().filter(enm -> enm.name.getValue().equals(definitionContext.get(NodeContextKeys.NAME_OF_NODE_KEY))).findAny().orElse(null);
            // Fixing the position issue with enum node.
            bLangNode.getPosition().eLine = bLangNode.getPosition().sLine;
            bLangNode.getPosition().eCol = bLangNode.getPosition().sCol;
            break;
        case ContextConstants.CONNECTOR:
            bLangNode = bLangPackage.connectors.stream().filter(bConnector -> bConnector.name.getValue().equals(definitionContext.get(NodeContextKeys.NAME_OF_NODE_KEY))).findAny().orElse(null);
            break;
        case ContextConstants.ACTION:
            bLangNode = bLangPackage.connectors.stream().filter(bConnector -> bConnector.name.getValue().equals(((BLangInvocation) definitionContext.get(NodeContextKeys.PREVIOUSLY_VISITED_NODE_KEY)).symbol.owner.name.getValue())).flatMap(connector -> connector.actions.stream()).filter(bAction -> bAction.name.getValue().equals(definitionContext.get(NodeContextKeys.NAME_OF_NODE_KEY))).findAny().orElse(null);
            break;
        case ContextConstants.TRANSFORMER:
            bLangNode = bLangPackage.transformers.stream().filter(bTransformer -> bTransformer.name.getValue().equals(definitionContext.get(NodeContextKeys.NAME_OF_NODE_KEY))).findAny().orElse(null);
            break;
        case ContextConstants.ENDPOINT:
            bLangNode = bLangPackage.globalEndpoints.stream().filter(globalEndpoint -> globalEndpoint.name.value.equals(definitionContext.get(NodeContextKeys.NAME_OF_NODE_KEY))).findAny().orElse(null);
            if (bLangNode == null) {
                DefinitionTreeVisitor definitionTreeVisitor = new DefinitionTreeVisitor(definitionContext);
                definitionContext.get(NodeContextKeys.NODE_STACK_KEY).pop().accept(definitionTreeVisitor);
                if (definitionContext.get(NodeContextKeys.NODE_KEY) != null) {
                    bLangNode = definitionContext.get(NodeContextKeys.NODE_KEY);
                }
            }
            break;
        case ContextConstants.VARIABLE:
            bLangNode = bLangPackage.globalVars.stream().filter(globalVar -> globalVar.name.getValue().equals(definitionContext.get(NodeContextKeys.VAR_NAME_OF_NODE_KEY))).findAny().orElse(null);
            // BLangNode is null only when node at the cursor position is a local variable.
            if (bLangNode == null) {
                DefinitionTreeVisitor definitionTreeVisitor = new DefinitionTreeVisitor(definitionContext);
                definitionContext.get(NodeContextKeys.NODE_STACK_KEY).pop().accept(definitionTreeVisitor);
                if (definitionContext.get(NodeContextKeys.NODE_KEY) != null) {
                    bLangNode = definitionContext.get(NodeContextKeys.NODE_KEY);
                    break;
                }
            }
            break;
        default:
            break;
    }
    if (bLangNode == null) {
        return contents;
    }
    Location l = new Location();
    TextDocumentPositionParams position = definitionContext.get(DocumentServiceKeys.POSITION_KEY);
    Path parentPath = CommonUtil.getPath(new LSDocument(position.getTextDocument().getUri())).getParent();
    if (parentPath != null) {
        String fileName = bLangNode.getPosition().getSource().getCompilationUnitName();
        Path filePath = Paths.get(CommonUtil.getPackageURI(definitionContext.get(NodeContextKeys.PACKAGE_OF_NODE_KEY).name.getValue(), parentPath.toString(), definitionContext.get(NodeContextKeys.PACKAGE_OF_NODE_KEY).name.getValue()), fileName);
        l.setUri(filePath.toUri().toString());
        Range r = new Range();
        // Subtract 1 to convert the token lines and char positions to zero based indexing
        r.setStart(new Position(bLangNode.getPosition().getStartLine() - 1, bLangNode.getPosition().getStartColumn() - 1));
        r.setEnd(new Position(bLangNode.getPosition().getEndLine() - 1, bLangNode.getPosition().getEndColumn() - 1));
        l.setRange(r);
        contents.add(l);
    }
    return contents;
}
Also used : CommonUtil(org.ballerinalang.langserver.common.utils.CommonUtil) BLangPackage(org.wso2.ballerinalang.compiler.tree.BLangPackage) TextDocumentServiceContext(org.ballerinalang.langserver.TextDocumentServiceContext) TextDocumentPositionParams(org.eclipse.lsp4j.TextDocumentPositionParams) PackageID(org.ballerinalang.model.elements.PackageID) Range(org.eclipse.lsp4j.Range) LSPackageCache(org.ballerinalang.langserver.LSPackageCache) NodeContextKeys(org.ballerinalang.langserver.common.constants.NodeContextKeys) ArrayList(java.util.ArrayList) BLangNode(org.wso2.ballerinalang.compiler.tree.BLangNode) DefinitionTreeVisitor(org.ballerinalang.langserver.definition.DefinitionTreeVisitor) LSDocument(org.ballerinalang.langserver.common.LSDocument) List(java.util.List) Paths(java.nio.file.Paths) ContextConstants(org.ballerinalang.langserver.common.constants.ContextConstants) BLangInvocation(org.wso2.ballerinalang.compiler.tree.expressions.BLangInvocation) Location(org.eclipse.lsp4j.Location) Position(org.eclipse.lsp4j.Position) Path(java.nio.file.Path) DocumentServiceKeys(org.ballerinalang.langserver.DocumentServiceKeys) Path(java.nio.file.Path) Position(org.eclipse.lsp4j.Position) ArrayList(java.util.ArrayList) Range(org.eclipse.lsp4j.Range) DefinitionTreeVisitor(org.ballerinalang.langserver.definition.DefinitionTreeVisitor) BLangPackage(org.wso2.ballerinalang.compiler.tree.BLangPackage) BLangNode(org.wso2.ballerinalang.compiler.tree.BLangNode) LSDocument(org.ballerinalang.langserver.common.LSDocument) TextDocumentPositionParams(org.eclipse.lsp4j.TextDocumentPositionParams) BLangInvocation(org.wso2.ballerinalang.compiler.tree.expressions.BLangInvocation) Location(org.eclipse.lsp4j.Location)

Aggregations

ArrayList (java.util.ArrayList)9 HashMap (java.util.HashMap)8 JSONObject (org.json.simple.JSONObject)8 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)8 TreeSet (java.util.TreeSet)7 API (org.wso2.carbon.apimgt.api.model.API)7 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)7 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)6 APINameComparator (org.wso2.carbon.apimgt.impl.utils.APINameComparator)6 GenericArtifactManager (org.wso2.carbon.governance.api.generic.GenericArtifactManager)6 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)5 GovernanceArtifact (org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact)5 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)5 Registry (org.wso2.carbon.registry.core.Registry)4 UserStoreException (org.wso2.carbon.user.api.UserStoreException)4 HashSet (java.util.HashSet)3 List (java.util.List)3 DevPortalAPI (org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI)3 PublisherAPI (org.wso2.carbon.apimgt.persistence.dto.PublisherAPI)3 LinkedHashMap (java.util.LinkedHashMap)2