Search in sources :

Example 36 with ExpressionNode

use of org.wso2.carbon.identity.core.model.ExpressionNode in project identity-inbound-provisioning-scim2 by wso2-extensions.

the class SCIMUserManager method filterUsersBySingleAttribute.

/**
 * Method to filter users for a filter with a single attribute.
 *
 * @param node               Expression node for single attribute filtering
 * @param requiredAttributes Required attributes for the response
 * @param offset             Starting index of the count
 * @param limit              Counting value
 * @param sortBy             SortBy
 * @param sortOrder          Sorting order
 * @param domainName         Domain to run the filter
 * @return User list with detailed attributes
 * @throws CharonException Error while filtering
 * @throws BadRequestException
 */
private List<Object> filterUsersBySingleAttribute(ExpressionNode node, Map<String, Boolean> requiredAttributes, int offset, int limit, String sortBy, String sortOrder, String domainName) throws CharonException, BadRequestException {
    Set<org.wso2.carbon.user.core.common.User> users;
    if (log.isDebugEnabled()) {
        log.debug(String.format("Listing users by filter: %s %s %s", node.getAttributeValue(), node.getOperation(), node.getValue()));
    }
    // Check whether the filter operation is supported by the users endpoint.
    if (isFilteringNotSupported(node.getOperation())) {
        String errorMessage = "Filter operation: " + node.getOperation() + " is not supported for filtering in users endpoint.";
        throw new CharonException(errorMessage);
    }
    domainName = resolveDomainName(domainName, node);
    int totalResults = 0;
    try {
        // Check which APIs should the filter needs to follow.
        if (isUseLegacyAPIs(limit)) {
            users = filterUsersUsingLegacyAPIs(node, limit, offset, domainName);
            if (SCIMCommonUtils.isConsiderMaxLimitForTotalResultEnabled()) {
                return getDetailedUsers(users, requiredAttributes, users.size());
            }
        } else {
            users = filterUsers(node, offset, limit, sortBy, sortOrder, domainName);
        }
        int maxLimit = getMaxLimit(domainName);
        if (!SCIMCommonUtils.isConsiderMaxLimitForTotalResultEnabled()) {
            if (StringUtils.isBlank(domainName)) {
                String[] userStoreDomainNames = getDomainNames();
                boolean canCountTotalUserCount = canCountTotalUserCount(userStoreDomainNames);
                if (canCountTotalUserCount) {
                    for (String userStoreDomainName : userStoreDomainNames) {
                        maxLimit += getTotalUsers(userStoreDomainName);
                    }
                }
            } else {
                maxLimit = getMaxLimitForTotalResults(domainName);
            }
        }
        // Get total users based on the filter query without depending on pagination params.
        totalResults += filterUsers(node, 1, maxLimit, sortBy, sortOrder, domainName).size();
    } catch (NotImplementedException e) {
        String errorMessage = String.format("System does not support filter operator: %s", node.getOperation());
        throw new CharonException(errorMessage, e);
    }
    return getDetailedUsers(users, requiredAttributes, totalResults);
}
Also used : User(org.wso2.charon3.core.objects.User) NotImplementedException(org.wso2.charon3.core.exceptions.NotImplementedException) CharonException(org.wso2.charon3.core.exceptions.CharonException)

Example 37 with ExpressionNode

use of org.wso2.carbon.identity.core.model.ExpressionNode in project identity-inbound-provisioning-scim2 by wso2-extensions.

the class SCIMUserManager method filterUsersFromMultipleDomains.

/**
 * Method to perform a multiple domain search when the domain is not specified in the request. The same function
 * can be used to listing users by passing a condition for conditionForListingUsers parameter.
 *
 * @param node                     Expression or Operation node (set the value to null when method is used for
 *                                 list users)
 * @param offset                   Start index value
 * @param limit                    Count value
 * @param sortBy                   SortBy
 * @param sortOrder                Sort order
 * @param conditionForListingUsers Condition for listing users when the function is used to list users except for
 *                                 filtering. For filtering this value should be set to NULL.
 * @return User names of the filtered users
 */
private Set<org.wso2.carbon.user.core.common.User> filterUsersFromMultipleDomains(Node node, int offset, int limit, String sortBy, String sortOrder, Condition conditionForListingUsers) throws CharonException, BadRequestException {
    // Filter users when the domain is not set in the request. Then filter through multiple domains.
    String[] userStoreDomainNames = getDomainNames();
    Set<org.wso2.carbon.user.core.common.User> filteredUsernames;
    if (removeDuplicateUsersInUsersResponseEnabled) {
        filteredUsernames = new TreeSet<>(Comparator.comparing(org.wso2.carbon.user.core.common.User::getFullQualifiedUsername));
    } else {
        filteredUsernames = new LinkedHashSet<>();
    }
    Condition condition;
    for (String userStoreDomainName : userStoreDomainNames) {
        // Check for a user listing scenario. (For filtering this value will be set to NULL)
        if (conditionForListingUsers == null) {
            if (isLoginIdentifiersEnabled() && SCIMConstants.UserSchemaConstants.USER_NAME_URI.equals(((ExpressionNode) node).getAttributeValue())) {
                try {
                    ((ExpressionNode) node).setAttributeValue(getScimUriForPrimaryLoginIdentifier(node));
                } catch (org.wso2.carbon.user.core.UserStoreException e) {
                    throw new CharonException("Error in retrieving scim to local mappings.", e);
                }
            }
            // Create filter condition for each domain for single attribute filter.
            condition = createConditionForSingleAttributeFilter(userStoreDomainName, node);
        } else {
            condition = conditionForListingUsers;
        }
        // Filter users for given condition and domain.
        Set<org.wso2.carbon.user.core.common.User> coreUsers;
        try {
            coreUsers = filterUsernames(condition, offset, limit, sortBy, sortOrder, userStoreDomainName);
        } catch (CharonException e) {
            log.error("Error occurred while getting the users list for domain: " + userStoreDomainName, e);
            continue;
        }
        // Calculating new offset and limit parameters.
        int numberOfFilteredUsers = coreUsers.size();
        if (numberOfFilteredUsers <= 0 && offset > 1) {
            if (log.isDebugEnabled()) {
                log.debug(String.format("Filter returned no results for original offset: %d.", offset));
            }
            offset = calculateOffset(condition, offset, sortBy, sortOrder, userStoreDomainName);
        } else {
            // Returned user names size > 0 implies there are users in that domain which is larger than
            // the offset.
            offset = 1;
            limit = calculateLimit(limit, numberOfFilteredUsers);
        }
        filteredUsernames.addAll(coreUsers);
        // If the limit is changed then filtering needs to be stopped.
        if (limit == 0) {
            break;
        }
    }
    return filteredUsernames;
}
Also used : OperationalCondition(org.wso2.carbon.user.core.model.OperationalCondition) ExpressionCondition(org.wso2.carbon.user.core.model.ExpressionCondition) Condition(org.wso2.carbon.user.core.model.Condition) User(org.wso2.charon3.core.objects.User) ExpressionNode(org.wso2.charon3.core.utils.codeutils.ExpressionNode) CharonException(org.wso2.charon3.core.exceptions.CharonException)

Example 38 with ExpressionNode

use of org.wso2.carbon.identity.core.model.ExpressionNode in project identity-api-server by wso2.

the class ServerApplicationManagementService method buildFilterNode.

private ExpressionNode buildFilterNode(String filter) {
    if (StringUtils.isNotBlank(filter)) {
        try {
            FilterTreeBuilder filterTreeBuilder = new FilterTreeBuilder(filter);
            Node rootNode = filterTreeBuilder.buildTree();
            if (rootNode instanceof ExpressionNode) {
                ExpressionNode expressionNode = (ExpressionNode) rootNode;
                if (SEARCH_SUPPORTED_FIELDS.contains(expressionNode.getAttributeValue())) {
                    return expressionNode;
                } else {
                    throw buildClientError(ErrorMessage.UNSUPPORTED_FILTER_ATTRIBUTE, expressionNode.getAttributeValue());
                }
            } else {
                throw buildClientError(ErrorMessage.INVALID_FILTER_FORMAT);
            }
        } catch (IOException | IdentityException e) {
            throw buildClientError(ApplicationManagementConstants.ErrorMessage.INVALID_FILTER_FORMAT, null);
        }
    } else {
        return null;
    }
}
Also used : FilterTreeBuilder(org.wso2.carbon.identity.core.model.FilterTreeBuilder) ExpressionNode(org.wso2.carbon.identity.core.model.ExpressionNode) ExpressionNode(org.wso2.carbon.identity.core.model.ExpressionNode) Node(org.wso2.carbon.identity.core.model.Node) IOException(java.io.IOException) IdentityException(org.wso2.carbon.identity.base.IdentityException)

Example 39 with ExpressionNode

use of org.wso2.carbon.identity.core.model.ExpressionNode in project identity-api-server by wso2.

the class ServerAuthenticatorManagementService method getAuthenticators.

/**
 * Retrieves the list of available authenticators.
 *
 * @param filter The filter string.
 * @param limit  The items per page. **Not supported at the moment.**
 * @param offset The offset to be used with the limit parameter. **Not supported at the moment.**
 * @return The list of authenticators
 */
public List<Authenticator> getAuthenticators(String filter, Integer limit, Integer offset) {
    handleNotImplementedCapabilities(limit, offset);
    try {
        String filterAuthenticatorName = null;
        String filterOperationForName = null;
        ArrayList<String> filterTagsList = null;
        int maximumItemPerPage = IdentityUtil.getMaximumItemPerPage();
        if (StringUtils.isNotBlank(filter)) {
            List<ExpressionNode> expressionNodes = getExpressionNodesForAuthenticator(filter);
            if (CollectionUtils.isNotEmpty(expressionNodes)) {
                NameFilter nameFilter = getFilterAuthenticatorNameAndOperation(expressionNodes);
                if (nameFilter != null) {
                    filterAuthenticatorName = nameFilter.getName();
                    filterOperationForName = nameFilter.getOperation();
                }
                filterTagsList = getFilterTagsList(expressionNodes);
            }
        }
        LocalAuthenticatorConfig[] localAuthenticatorConfigs = AuthenticatorsServiceHolder.getInstance().getApplicationManagementService().getAllLocalAuthenticators(ContextLoader.getTenantDomainFromContext());
        int localAuthenticatorsCount = localAuthenticatorConfigs.length;
        RequestPathAuthenticatorConfig[] requestPathAuthenticatorConfigs = new RequestPathAuthenticatorConfig[0];
        /* If there is no filter string available in the request, the request path authenticators are required to
            be fetched only if the  no. of local authenticators retrieved are less than the maximum items per page
            count as the no. of items returned in the response will be capped at the maximum items per page count. */
        if (StringUtils.isNotBlank(filter) || (StringUtils.isBlank(filter) && localAuthenticatorsCount < maximumItemPerPage)) {
            requestPathAuthenticatorConfigs = AuthenticatorsServiceHolder.getInstance().getApplicationManagementService().getAllRequestPathAuthenticators(ContextLoader.getTenantDomainFromContext());
        }
        List<String> requestedAttributeList = new ArrayList<>();
        requestedAttributeList.add(Constants.FEDERATED_AUTHENTICATORS);
        int idPCountToBeRetrieved = maximumItemPerPage - (localAuthenticatorsCount + requestPathAuthenticatorConfigs.length);
        List<IdentityProvider> identityProviders = null;
        /* If there is no filter string available in the request, the identity providers are required to
            be fetched only if the total of local authenticators and request path authenticators retrieved above is
            less than the maximum items per page count as the no. of items returned in the response will be capped
            at the maximum items per page count. */
        if (idPCountToBeRetrieved > 0 && StringUtils.isBlank(filter)) {
            IdpSearchResult idpSearchResult = AuthenticatorsServiceHolder.getInstance().getIdentityProviderManager().getIdPs(idPCountToBeRetrieved, null, null, null, null, ContextLoader.getTenantDomainFromContext(), requestedAttributeList);
            identityProviders = idpSearchResult.getIdPs();
        }
        return buildAuthenticatorsListResponse(filter, requestedAttributeList, filterAuthenticatorName, filterOperationForName, filterTagsList, localAuthenticatorConfigs, requestPathAuthenticatorConfigs, identityProviders);
    } catch (IdentityApplicationManagementException e) {
        throw handleApplicationMgtException(e, Constants.ErrorMessage.ERROR_CODE_ERROR_LISTING_AUTHENTICATORS, null);
    } catch (IdentityProviderManagementException e) {
        throw handleIdPException(e, Constants.ErrorMessage.ERROR_CODE_ERROR_LISTING_IDPS, null);
    }
}
Also used : IdentityApplicationManagementException(org.wso2.carbon.identity.application.common.IdentityApplicationManagementException) LocalAuthenticatorConfig(org.wso2.carbon.identity.application.common.model.LocalAuthenticatorConfig) ArrayList(java.util.ArrayList) IdentityProvider(org.wso2.carbon.identity.application.common.model.IdentityProvider) IdpSearchResult(org.wso2.carbon.idp.mgt.model.IdpSearchResult) NameFilter(org.wso2.carbon.identity.api.server.authenticators.v1.model.NameFilter) ExpressionNode(org.wso2.carbon.identity.core.model.ExpressionNode) RequestPathAuthenticatorConfig(org.wso2.carbon.identity.application.common.model.RequestPathAuthenticatorConfig) IdentityProviderManagementException(org.wso2.carbon.idp.mgt.IdentityProviderManagementException)

Example 40 with ExpressionNode

use of org.wso2.carbon.identity.core.model.ExpressionNode in project ballerina by ballerina-lang.

the class SemanticAnalyzer method visit.

public void visit(BLangBinaryExpr binaryExpr) {
    ExpressionNode leftExpression = binaryExpr.getLeftExpression();
    ((BLangExpression) leftExpression).accept(this);
    ExpressionNode rightExpression = binaryExpr.getRightExpression();
    ((BLangExpression) rightExpression).accept(this);
}
Also used : SelectExpressionNode(org.ballerinalang.model.tree.clauses.SelectExpressionNode) ExpressionNode(org.ballerinalang.model.tree.expressions.ExpressionNode) BLangExpression(org.wso2.ballerinalang.compiler.tree.expressions.BLangExpression)

Aggregations

ExpressionNode (org.ballerinalang.model.tree.expressions.ExpressionNode)21 ArrayList (java.util.ArrayList)16 SelectExpressionNode (org.ballerinalang.model.tree.clauses.SelectExpressionNode)16 ExpressionNode (org.wso2.carbon.identity.core.model.ExpressionNode)15 BLangExpression (org.wso2.ballerinalang.compiler.tree.expressions.BLangExpression)12 BadRequestException (org.wso2.charon3.core.exceptions.BadRequestException)8 ExpressionNode (org.wso2.charon3.core.utils.codeutils.ExpressionNode)7 Map (java.util.Map)6 IdentityException (org.wso2.carbon.identity.base.IdentityException)6 Attribute (org.wso2.charon3.core.attributes.Attribute)6 ComplexAttribute (org.wso2.charon3.core.attributes.ComplexAttribute)6 MultiValuedAttribute (org.wso2.charon3.core.attributes.MultiValuedAttribute)6 SimpleAttribute (org.wso2.charon3.core.attributes.SimpleAttribute)6 Connection (java.sql.Connection)5 KubernetesPluginException (org.ballerinax.kubernetes.exceptions.KubernetesPluginException)5 JSONObject (org.json.JSONObject)5 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)5 Test (org.testng.annotations.Test)5 Node (org.wso2.carbon.identity.core.model.Node)5 IdpSearchResult (org.wso2.carbon.idp.mgt.model.IdpSearchResult)5