Search in sources :

Example 61 with Scope

use of org.wso2.carbon.apimgt.keymgt.model.entity.Scope in project ballerina by ballerina-lang.

the class StatementContextResolver method resolveItems.

@Override
@SuppressWarnings("unchecked")
public ArrayList<CompletionItem> resolveItems(TextDocumentServiceContext completionContext) {
    ArrayList<CompletionItem> completionItems = new ArrayList<>();
    // action invocation or worker invocation
    if (isInvocationOrFieldAccess(completionContext)) {
        ArrayList<SymbolInfo> actionAndFunctions = new ArrayList<>();
        PackageActionFunctionAndTypesFilter actionFunctionTypeFilter = new PackageActionFunctionAndTypesFilter();
        actionAndFunctions.addAll(actionFunctionTypeFilter.filterItems(completionContext));
        this.populateCompletionItemList(actionAndFunctions, completionItems);
    } else {
        CompletionItem xmlns = new CompletionItem();
        xmlns.setLabel(ItemResolverConstants.XMLNS);
        xmlns.setInsertText(Snippet.NAMESPACE_DECLARATION.toString());
        xmlns.setInsertTextFormat(InsertTextFormat.Snippet);
        xmlns.setDetail(ItemResolverConstants.SNIPPET_TYPE);
        completionItems.add(xmlns);
        // Add the var keyword
        CompletionItem varKeyword = new CompletionItem();
        varKeyword.setInsertText("var ");
        varKeyword.setLabel("var");
        varKeyword.setDetail(ItemResolverConstants.KEYWORD_TYPE);
        completionItems.add(varKeyword);
        StatementTemplateFilter statementTemplateFilter = new StatementTemplateFilter();
        // Add the statement templates
        completionItems.addAll(statementTemplateFilter.filterItems(completionContext));
        // We need to remove the functions having a receiver symbol and the bTypes of the following
        // ballerina.coordinator, ballerina.runtime, and anonStructs
        ArrayList<String> invalidPkgs = new ArrayList<>(Arrays.asList("ballerina.runtime", "ballerina.transactions.coordinator"));
        completionContext.get(CompletionKeys.VISIBLE_SYMBOLS_KEY).removeIf(symbolInfo -> {
            BSymbol bSymbol = symbolInfo.getScopeEntry().symbol;
            String symbolName = bSymbol.getName().getValue();
            return (bSymbol instanceof BInvokableSymbol && ((BInvokableSymbol) bSymbol).receiverSymbol != null) || (bSymbol instanceof BPackageSymbol && invalidPkgs.contains(symbolName)) || (symbolName.startsWith("$anonStruct"));
        });
        populateCompletionItemList(completionContext.get(CompletionKeys.VISIBLE_SYMBOLS_KEY), completionItems);
        // Now we need to sort the completion items and populate the completion items specific to the scope owner
        // as an example, resource, action, function scopes are different from the if-else, while, and etc
        Class itemSorter = completionContext.get(CompletionKeys.BLOCK_OWNER_KEY).getClass();
        ItemSorters.getSorterByClass(itemSorter).sortItems(completionContext, completionItems);
    }
    return completionItems;
}
Also used : BSymbol(org.wso2.ballerinalang.compiler.semantics.model.symbols.BSymbol) ArrayList(java.util.ArrayList) StatementTemplateFilter(org.ballerinalang.langserver.completions.util.filters.StatementTemplateFilter) BInvokableSymbol(org.wso2.ballerinalang.compiler.semantics.model.symbols.BInvokableSymbol) SymbolInfo(org.ballerinalang.langserver.completions.SymbolInfo) BPackageSymbol(org.wso2.ballerinalang.compiler.semantics.model.symbols.BPackageSymbol) PackageActionFunctionAndTypesFilter(org.ballerinalang.langserver.completions.util.filters.PackageActionFunctionAndTypesFilter) CompletionItem(org.eclipse.lsp4j.CompletionItem)

Example 62 with Scope

use of org.wso2.carbon.apimgt.keymgt.model.entity.Scope in project product-iots by wso2.

the class QSGUtils method getOAuthToken.

public static String getOAuthToken() {
    QSGUtils.initConfig();
    ClientCredentials clientCredentials = getClientCredentials();
    String authorizationStr = clientCredentials.getClientKey() + ":" + clientCredentials.getClientSecret();
    String authHeader = "Basic " + new String(Base64.encodeBase64(authorizationStr.getBytes()));
    HashMap<String, String> headers = new HashMap<String, String>();
    // Set the form params
    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    urlParameters.add(new BasicNameValuePair("username", EMMQSGConfig.getInstance().getUsername()));
    urlParameters.add(new BasicNameValuePair("password", EMMQSGConfig.getInstance().getPassword()));
    urlParameters.add(new BasicNameValuePair("grant_type", "password"));
    urlParameters.add(new BasicNameValuePair("scope", "user:view user:manage user:admin:reset-password role:view role:manage policy:view policy:manage " + "application:manage appm:administration appm:create appm:publish appm:update appm:read"));
    // Set the headers
    headers.put(Constants.Header.CONTENT_TYPE, Constants.ContentType.APPLICATION_URL_ENCODED);
    headers.put(Constants.Header.AUTH, authHeader);
    HTTPResponse httpResponse = HTTPInvoker.sendHTTPPostWithURLParams(EMMQSGConfig.getInstance().getOauthEndPoint(), urlParameters, headers);
    if (httpResponse.getResponseCode() == Constants.HTTPStatus.OK) {
        try {
            JSONObject jsonObject = (JSONObject) new JSONParser().parse(httpResponse.getResponse());
            return (String) jsonObject.get("access_token");
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    return null;
}
Also used : BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) JSONObject(org.json.simple.JSONObject) HashMap(java.util.HashMap) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) HTTPResponse(org.wso2.mdm.qsg.dto.HTTPResponse) ArrayList(java.util.ArrayList) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException) ClientCredentials(org.wso2.mdm.qsg.dto.ClientCredentials)

Example 63 with Scope

use of org.wso2.carbon.apimgt.keymgt.model.entity.Scope in project carbon-apimgt by wso2.

the class AbstractAPIManager method populateDevPortalAPIInformation.

protected void populateDevPortalAPIInformation(String uuid, String organization, API api) throws APIManagementException, OASPersistenceException, ParseException {
    Organization org = new Organization(organization);
    // UUID
    if (api.getUuid() == null) {
        api.setUuid(uuid);
    }
    api.setOrganization(organization);
    // environment
    String environmentString = null;
    if (api.getEnvironments() != null) {
        environmentString = String.join(",", api.getEnvironments());
    }
    api.setEnvironments(APIUtil.extractEnvironmentsForAPI(environmentString, organization));
    // workflow status
    APIIdentifier apiId = api.getId();
    String currentApiUuid = uuid;
    if (api.isRevision() && api.getRevisionedApiId() != null) {
        currentApiUuid = api.getRevisionedApiId();
    }
    // TODO try to use a single query to get info from db
    // Ratings
    int internalId = apiMgtDAO.getAPIID(currentApiUuid);
    api.setRating(APIUtil.getAverageRating(internalId));
    apiId.setId(internalId);
    // api level tier
    String apiLevelTier = apiMgtDAO.getAPILevelTier(internalId);
    api.setApiLevelPolicy(apiLevelTier);
    // available tier
    String tiers = null;
    Set<Tier> tiersSet = api.getAvailableTiers();
    Set<String> tierNameSet = new HashSet<String>();
    for (Tier t : tiersSet) {
        tierNameSet.add(t.getName());
    }
    if (api.getAvailableTiers() != null) {
        tiers = String.join("||", tierNameSet);
    }
    Map<String, Tier> definedTiers = APIUtil.getTiers(APIUtil.getInternalOrganizationId(organization));
    Set<Tier> availableTier = APIUtil.getAvailableTiers(definedTiers, tiers, api.getId().getApiName());
    api.setAvailableTiers(availableTier);
    // Scopes
    Map<String, Scope> scopeToKeyMapping = APIUtil.getAPIScopes(currentApiUuid, organization);
    api.setScopes(new LinkedHashSet<>(scopeToKeyMapping.values()));
    // templates
    String resourceConfigsString = null;
    if (api.getSwaggerDefinition() != null) {
        resourceConfigsString = api.getSwaggerDefinition();
    } else {
        resourceConfigsString = apiPersistenceInstance.getOASDefinition(org, uuid);
    }
    api.setSwaggerDefinition(resourceConfigsString);
    if (api.getType() != null && APIConstants.APITransportType.GRAPHQL.toString().equals(api.getType())) {
        api.setGraphQLSchema(getGraphqlSchemaDefinition(uuid, organization));
    }
    JSONParser jsonParser = new JSONParser();
    JSONObject paths = null;
    if (resourceConfigsString != null) {
        JSONObject resourceConfigsJSON = (JSONObject) jsonParser.parse(resourceConfigsString);
        paths = (JSONObject) resourceConfigsJSON.get(APIConstants.SWAGGER_PATHS);
    }
    Set<URITemplate> uriTemplates = apiMgtDAO.getURITemplatesOfAPI(api.getUuid());
    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);
    // CORS . if null is returned, set default config from the configuration
    if (api.getCorsConfiguration() == null) {
        api.setCorsConfiguration(APIUtil.getDefaultCorsConfiguration());
    }
    // set category
    List<APICategory> categories = api.getApiCategories();
    if (categories != null) {
        List<String> categoriesOfAPI = new ArrayList<String>();
        for (APICategory apiCategory : categories) {
            categoriesOfAPI.add(apiCategory.getName());
        }
        List<APICategory> categoryList = new ArrayList<>();
        if (!categoriesOfAPI.isEmpty()) {
            // category array retrieved from artifact has only the category name, therefore we need to fetch
            // categories
            // and fill out missing attributes before attaching the list to the api
            List<APICategory> allCategories = APIUtil.getAllAPICategoriesOfOrganization(organization);
            for (String categoryName : categoriesOfAPI) {
                for (APICategory category : allCategories) {
                    if (categoryName.equals(category.getName())) {
                        categoryList.add(category);
                        break;
                    }
                }
            }
        }
        api.setApiCategories(categoryList);
    }
}
Also used : Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) Tier(org.wso2.carbon.apimgt.api.model.Tier) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) ArrayList(java.util.ArrayList) Scope(org.wso2.carbon.apimgt.api.model.Scope) JSONObject(org.json.simple.JSONObject) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) JSONParser(org.json.simple.parser.JSONParser) APICategory(org.wso2.carbon.apimgt.api.model.APICategory) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet)

Example 64 with Scope

use of org.wso2.carbon.apimgt.keymgt.model.entity.Scope in project carbon-apimgt by wso2.

the class AbstractAPIManager method populateAPIProductInformation.

protected void populateAPIProductInformation(String uuid, String organization, APIProduct apiProduct) throws APIManagementException, OASPersistenceException, ParseException {
    Organization org = new Organization(organization);
    apiProduct.setOrganization(organization);
    ApiMgtDAO.getInstance().setAPIProductFromDB(apiProduct);
    apiProduct.setRating(Float.toString(APIUtil.getAverageRating(apiProduct.getProductId())));
    List<APIProductResource> resources = ApiMgtDAO.getInstance().getAPIProductResourceMappings(apiProduct.getId());
    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 = APIUtil.getScopeByName(scopeKey, organization);
                uniqueAPIProductScopeKeyMappings.put(scopeKey, resourceScope);
            } else {
                resourceScope = uniqueAPIProductScopeKeyMappings.get(scopeKey);
            }
            it.set(resourceScope);
        }
    }
    for (APIProductResource resource : resources) {
        String resourceAPIUUID = resource.getApiIdentifier().getUUID();
        resource.setApiId(resourceAPIUUID);
        try {
            PublisherAPI publisherAPI = apiPersistenceInstance.getPublisherAPI(org, resourceAPIUUID);
            API api = APIMapper.INSTANCE.toApi(publisherAPI);
            if (api.isAdvertiseOnly()) {
                resource.setEndpointConfig(APIUtil.generateEndpointConfigForAdvertiseOnlyApi(api));
            } else {
                resource.setEndpointConfig(api.getEndpointConfig());
            }
            resource.setEndpointSecurityMap(APIUtil.setEndpointSecurityForAPIProduct(api));
        } catch (APIPersistenceException e) {
            throw new APIManagementException("Error while retrieving the api for api product " + e);
        }
    }
    apiProduct.setProductResources(resources);
    // UUID
    if (apiProduct.getUuid() == null) {
        apiProduct.setUuid(uuid);
    }
    // environment
    String environmentString = null;
    if (apiProduct.getEnvironments() != null) {
        environmentString = String.join(",", apiProduct.getEnvironments());
    }
    apiProduct.setEnvironments(APIUtil.extractEnvironmentsForAPI(environmentString, organization));
    // workflow status
    APIProductIdentifier productIdentifier = apiProduct.getId();
    WorkflowDTO workflow;
    String currentApiProductUuid = uuid;
    if (apiProduct.isRevision() && apiProduct.getRevisionedApiProductId() != null) {
        currentApiProductUuid = apiProduct.getRevisionedApiProductId();
    }
    workflow = APIUtil.getAPIWorkflowStatus(currentApiProductUuid, WF_TYPE_AM_API_PRODUCT_STATE);
    if (workflow != null) {
        WorkflowStatus status = workflow.getStatus();
        apiProduct.setWorkflowStatus(status.toString());
    }
    // available tier
    String tiers = null;
    Set<Tier> tiersSet = apiProduct.getAvailableTiers();
    Set<String> tierNameSet = new HashSet<String>();
    for (Tier t : tiersSet) {
        tierNameSet.add(t.getName());
    }
    if (apiProduct.getAvailableTiers() != null) {
        tiers = String.join("||", tierNameSet);
    }
    Map<String, Tier> definedTiers = APIUtil.getTiers(tenantId);
    Set<Tier> availableTier = APIUtil.getAvailableTiers(definedTiers, tiers, apiProduct.getId().getName());
    apiProduct.setAvailableTiers(availableTier);
    // Scopes
    /*
        Map<String, Scope> scopeToKeyMapping = APIUtil.getAPIScopes(api.getId(), requestedTenantDomain);
        apiProduct.setScopes(new LinkedHashSet<>(scopeToKeyMapping.values()));
        */
    // templates
    String resourceConfigsString = null;
    if (apiProduct.getDefinition() != null) {
        resourceConfigsString = apiProduct.getDefinition();
    } else {
        resourceConfigsString = apiPersistenceInstance.getOASDefinition(org, uuid);
        apiProduct.setDefinition(resourceConfigsString);
    }
    // CORS . if null is returned, set default config from the configuration
    if (apiProduct.getCorsConfiguration() == null) {
        apiProduct.setCorsConfiguration(APIUtil.getDefaultCorsConfiguration());
    }
    // set category
    List<APICategory> categories = apiProduct.getApiCategories();
    if (categories != null) {
        List<String> categoriesOfAPI = new ArrayList<String>();
        for (APICategory apiCategory : categories) {
            categoriesOfAPI.add(apiCategory.getName());
        }
        List<APICategory> categoryList = new ArrayList<>();
        if (!categoriesOfAPI.isEmpty()) {
            // category array retrieved from artifact has only the category name, therefore we need to fetch
            // categories
            // and fill out missing attributes before attaching the list to the api
            List<APICategory> allCategories = APIUtil.getAllAPICategoriesOfOrganization(organization);
            // todo-category: optimize this loop with breaks
            for (String categoryName : categoriesOfAPI) {
                for (APICategory category : allCategories) {
                    if (categoryName.equals(category.getName())) {
                        categoryList.add(category);
                        break;
                    }
                }
            }
        }
        apiProduct.setApiCategories(categoryList);
    }
}
Also used : WorkflowDTO(org.wso2.carbon.apimgt.impl.dto.WorkflowDTO) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) Tier(org.wso2.carbon.apimgt.api.model.Tier) ListIterator(java.util.ListIterator) WorkflowStatus(org.wso2.carbon.apimgt.impl.workflow.WorkflowStatus) Scope(org.wso2.carbon.apimgt.api.model.Scope) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) API(org.wso2.carbon.apimgt.api.model.API) APICategory(org.wso2.carbon.apimgt.api.model.APICategory)

Example 65 with Scope

use of org.wso2.carbon.apimgt.keymgt.model.entity.Scope in project carbon-apimgt by wso2.

the class OAS2Parser method processLegacyScopes.

/**
 * This method will extract scopes from legacy x-wso2-security and add them to default scheme
 * @param swagger swagger definition
 * @return
 * @throws APIManagementException
 */
private Swagger processLegacyScopes(Swagger swagger) throws APIManagementException {
    Map<String, SecuritySchemeDefinition> securityDefinitions = swagger.getSecurityDefinitions();
    OAuth2Definition oAuth2Definition = new OAuth2Definition();
    if (securityDefinitions != null && securityDefinitions.get(APIConstants.OAUTH2_DEFAULT_SCOPE) != null) {
        oAuth2Definition = (OAuth2Definition) securityDefinitions.get(APIConstants.OAUTH2_DEFAULT_SCOPE);
    }
    Map<String, String> scopeBindings = new HashMap<>();
    Map<String, Object> vendorExtensions = oAuth2Definition.getVendorExtensions();
    if (vendorExtensions != null && vendorExtensions.get(APIConstants.SWAGGER_X_SCOPES_BINDINGS) != null) {
        scopeBindings = (Map<String, String>) vendorExtensions.get(APIConstants.SWAGGER_X_SCOPES_BINDINGS);
    }
    Set<Scope> scopes = getScopesFromExtensions(swagger);
    if (scopes != null && !scopes.isEmpty()) {
        for (Scope scope : scopes) {
            oAuth2Definition.addScope(scope.getKey(), scope.getDescription());
            String roles = (StringUtils.isNotBlank(scope.getRoles()) && scope.getRoles().trim().split(",").length > 0) ? scope.getRoles() : StringUtils.EMPTY;
            scopeBindings.put(scope.getKey(), roles);
        }
        oAuth2Definition.setVendorExtension(APIConstants.SWAGGER_X_SCOPES_BINDINGS, scopeBindings);
    }
    swagger.addSecurityDefinition(APIConstants.SWAGGER_APIM_DEFAULT_SECURITY, oAuth2Definition);
    return swagger;
}
Also used : Scope(org.wso2.carbon.apimgt.api.model.Scope) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) OAuth2Definition(io.swagger.models.auth.OAuth2Definition) SecuritySchemeDefinition(io.swagger.models.auth.SecuritySchemeDefinition)

Aggregations

Scope (org.wso2.carbon.apimgt.api.model.Scope)97 HashMap (java.util.HashMap)76 ArrayList (java.util.ArrayList)58 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)50 Scope (org.wso2.carbon.apimgt.core.models.Scope)41 Map (java.util.Map)39 URITemplate (org.wso2.carbon.apimgt.api.model.URITemplate)39 LinkedHashSet (java.util.LinkedHashSet)32 LinkedHashMap (java.util.LinkedHashMap)29 HashSet (java.util.HashSet)26 RestVariable (org.wso2.carbon.bpmn.rest.engine.variable.RestVariable)25 List (java.util.List)24 Test (org.testng.annotations.Test)23 JSONObject (org.json.simple.JSONObject)22 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)19 PreparedStatement (java.sql.PreparedStatement)17 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)17 SQLException (java.sql.SQLException)16 Gson (com.google.gson.Gson)15 Connection (java.sql.Connection)15