Apply filters from filters information to base query

    :param DeclarativeMeta model: the model of the node
    :param dict filter_info: current node filter information
    :param Resource resource: the resource
510554
def create_filters(model, filter_info, resource):
    
    filters = []
    for filter_ in filter_info:
        filters.append(Node(model, filter_, resource, resource.schema).resolve())

    return filters
753054
private List<MetadataResolver> buildSingleMetadataResolver(final MetadataFilter metadataFilterChain, final Resource resource, final Document document) {
        try {
            val metadataRoot = document.getDocumentElement();
            val metadataProvider = new DOMMetadataResolver(metadataRoot);
            metadataProvider.setParserPool(this.configBean.getParserPool());
            metadataProvider.setFailFastInitialization(true);
            metadataProvider.setRequireValidMetadata(this.requireValidMetadata);
            metadataProvider.setId(metadataProvider.getClass().getCanonicalName());
            if (metadataFilterChain != null) {
                metadataProvider.setMetadataFilter(metadataFilterChain);
            }
            LOGGER.debug("Initializing metadata resolver for [{}]", resource);
            metadataProvider.initialize();
            val resolvers = new ArrayList<MetadataResolver>();
            resolvers.add(metadataProvider);
            return resolvers;
        } catch (final Exception ex) {
            LOGGER.warn("Could not initialize metadata resolver. Resource will be ignored", ex);
        }
        return new ArrayList<>(0);
    }
1285409
protected void buildMetadataFilters(final SamlRegisteredService service, final AbstractMetadataResolver metadataProvider,
                                        final List<MetadataFilter> metadataFilterList) throws Exception {
        buildRequiredValidUntilFilterIfNeeded(service, metadataFilterList);
        buildSignatureValidationFilterIfNeeded(service, metadataFilterList);

        buildEntityRoleFilterIfNeeded(service, metadataFilterList);
        buildPredicateFilterIfNeeded(service, metadataFilterList);

        if (!metadataFilterList.isEmpty()) {
            addMetadataFiltersToMetadataResolver(metadataProvider, metadataFilterList);
        }
    }
373380
def get_filters(self, filter_id=None, params=None):
        
        return self.transport.perform_request(
            "GET", _make_path("_ml", "filters", filter_id), params=params
        )
1331178
def source_filter(method_name, *args, **kwargs):
    

    def source_filter(value, context, **_params):
        method = getattr(context["model"].source, method_name)
        return _filter(method, value, args, kwargs)

    return source_filter
898994
def _all_resources(self):
        
        queryset = self.__model__.query
        args = {k: v for (k, v) in request.args.items() if k not in ('page', 'export')}
        limit = None
        if args:
            filters = []
            order = []
            for key, value in args.items():
                if value.startswith('%'):
                    filters.append(getattr(self.__model__, key).like(str(value), escape='/'))
                elif key == 'sort':
                    direction = desc if value.startswith('-') else asc
                    order.append(direction(getattr(self.__model__, value.lstrip('-'))))
                elif key == 'limit':
                    limit = int(value)
                elif hasattr(self.__model__, key):
                    filters.append(getattr(self.__model__, key) == value)
                else:
                    raise BadRequestException('Invalid field [{}]'.format(key))
                queryset = queryset.filter(*filters).order_by(*order)
        if 'page' in request.args:
            resources = queryset.paginate(page=int(request.args['page']), per_page=limit).items
        else:
            queryset = queryset.limit(limit)
            resources = queryset.all()
        return [r.to_dict() for r in resources]
357933
def filter_link(model_class, filter_name, filters: {}, url_params: {})
      is_all = filter_name == :all
      config = filters[filter_name] || {}
      label = is_all ? all_label : filter_label(filter_name, filters)
      url_params =
        if config[:default] then index_params.except(:filter).merge(url_params)
        else index_params.merge(filter: filter_name).merge(url_params)
        end
      index_link(model_class, url_params: url_params) { label }
    end
322877
def filter(self, filter):
        
        new_query_set = self.clone()
        new_query_set.query.add_filter(filter)
        
        return new_query_set
1088743
def apply_filters(self, queryset, applicable_filters=None, applicable_exclusions=None):
        
        for field, options in applicable_filters["field_facets"].items():
            queryset = queryset.facet(field, **options)

        for field, options in applicable_filters["date_facets"].items():
            queryset = queryset.date_facet(field, **options)

        for field, options in applicable_filters["query_facets"].items():
            queryset = queryset.query_facet(field, **options)

        return queryset
476778
def add_filter(self, filter_id, description):
        
        filter_line = '##FILTER=<ID={0},Description="{1}">'.format(
            filter_id, description
        )
        logger.info("Adding filter line to vcf: {0}".format(filter_line))
        self.parse_meta_data(filter_line)
        return
880085
def add_filter(self, filter_expr, connector=AND, negate=False, trim=False,
            can_reuse=None, process_extras=True, force_having=False):
        
        if force_having:
            import warnings
            warnings.warn("multilingual-ng doesn't support force_having (see Django ticket #11293)")
        arg, value = filter_expr
        parts = arg.split(LOOKUP_SEP)
        if not parts:
            raise FieldError("Cannot parse keyword query %r" % arg)

        # Work out the lookup type and remove it from 'parts', if necessary.
        if len(parts) == 1 or parts[-1] not in self.query_terms:
            lookup_type = 'exact'
        else:
            lookup_type = parts.pop()

        # Interpret '__exact=None' as the sql 'is NULL'; otherwise, reject all
        # uses of None as a query value.
        if value is None:
            if lookup_type != 'exact':
                raise ValueError("Cannot use None as a query value")
            lookup_type = 'isnull'
            value = True
        elif (value == '' and lookup_type == 'exact' and
              self.get_compiler(DEFAULT_DB_ALIAS).connection.features.interprets_empty_strings_as_nulls):
            lookup_type = 'isnull'
            value = True
        elif callable(value):
            value = value()

        opts = self.get_meta()
        alias = self.get_initial_alias()
        allow_many = trim or not negate

        try:
            field, target, opts, join_list, last, extra_filters = self.setup_joins(
                    parts, opts, alias, True, allow_many, can_reuse=can_reuse,
                    negate=negate, process_extras=process_extras)
        except MultiJoin, e:
            self.split_exclude(filter_expr, LOOKUP_SEP.join(parts[:e.level]),
                    can_reuse)
            return

        #=======================================================================
        # Django Mulitlingual NG Specific Code START
        #=======================================================================
        if hasattr(opts, 'translation_model'):
            field_name = parts[-1]
            if field_name == 'pk':
                field_name = opts.pk.name
            translation_opts = opts.translation_model._meta
            if field_name in translation_opts.translated_fields.keys():
                field, model, direct, m2m = opts.get_field_by_name(field_name)
                if model == opts.translation_model:
                    language_code = translation_opts.translated_fields[field_name][1]
                    if language_code is None:
                        language_code = get_default_language()
                    master_table_name = opts.db_table
                    trans_table_alias = get_translation_table_alias(
                        model._meta.db_table, language_code)
                    new_table = (master_table_name + "__" + trans_table_alias)
                    self.where.add(constraint_tuple(new_table, field.column, field, lookup_type, value), connector)
                    return
        #=======================================================================
        # Django Mulitlingual NG Specific Code END
        #=======================================================================
        final = len(join_list)
        penultimate = last.pop()
        if penultimate == final:
            penultimate = last.pop()
        if trim and len(join_list) > 1:
            extra = join_list[penultimate:]
            join_list = join_list[:penultimate]
            final = penultimate
            penultimate = last.pop()
            col = self.alias_map[extra[0]][LHS_JOIN_COL]
            for alias in extra:
                self.unref_alias(alias)
        else:
            col = target.column
        alias = join_list[-1]

        while final > 1:
            # An optimization: if the final join is against the same column as
            # we are comparing against, we can go back one step in the join
            # chain and compare against the lhs of the join instead (and then
            # repeat the optimization). The result, potentially, involves less
            # table joins.
            join = self.alias_map[alias]
            if col != join[RHS_JOIN_COL]:
                break
            self.unref_alias(alias)
            alias = join[LHS_ALIAS]
            col = join[LHS_JOIN_COL]
            join_list = join_list[:-1]
            final -= 1
            if final == penultimate:
                penultimate = last.pop()

        if (lookup_type == 'isnull' and value is True and not negate and
                final > 1):
            # If the comparison is against NULL, we need to use a left outer
            # join when connecting to the previous model. We make that
            # adjustment here. We don't do this unless needed as it's less
            # efficient at the database level.
            self.promote_alias(join_list[penultimate])

        if connector == OR:
            # Some joins may need to be promoted when adding a new filter to a
            # disjunction. We walk the list of new joins and where it diverges
            # from any previous joins (ref count is 1 in the table list), we
            # make the new additions (and any existing ones not used in the new
            # join list) an outer join.
            join_it = iter(join_list)
            table_it = iter(self.tables)
            join_it.next(), table_it.next()
            table_promote = False
            join_promote = False
            for join in join_it:
                table = table_it.next()
                if join == table and self.alias_refcount[join] > 1:
                    continue
                join_promote = self.promote_alias(join)
                if table != join:
                    table_promote = self.promote_alias(table)
                break
            self.promote_alias_chain(join_it, join_promote)
            self.promote_alias_chain(table_it, table_promote)

        self.where.add(constraint_tuple(alias, col, field, lookup_type, value), connector)

        if negate:
            self.promote_alias_chain(join_list)
            if lookup_type != 'isnull':
                if final > 1:
                    for alias in join_list:
                        if self.alias_map[alias][JOIN_TYPE] == self.LOUTER:
                            j_col = self.alias_map[alias][RHS_JOIN_COL]
                            entry = self.where_class()
                            entry.add(constraint_tuple(alias, j_col, None, 'isnull', True), AND)
                            entry.negate()
                            self.where.add(entry, AND)
                            break
                elif not (lookup_type == 'in' and not value) and field.null:
                    # Leaky abstraction artifact: We have to specifically
                    # exclude the "foo__in=[]" case from this handling, because
                    # it's short-circuited in the Where class.
                    entry = self.where_class()
                    entry.add(constraint_tuple(alias, col, None, 'isnull', True), AND)
                    entry.negate()
                    self.where.add(entry, AND)

        if can_reuse is not None:
            can_reuse.update(join_list)
        if process_extras:
            for filter in extra_filters:
                self.add_filter(filter, negate=negate, can_reuse=can_reuse,
                        process_extras=False)
1199696
def get_collection(self, request, **resources):
        
        if self._meta.queryset is None:
            return []

        # Filter collection
        filters = self.get_filters(request, **resources)
        filters.update(self.get_default_filters(**resources))
        qs = self._meta.queryset
        for key, (value, exclude) in filters.items():
            try:
                if exclude:
                    qs = qs.exclude(**{key: value})

                else:
                    qs = qs.filter(**{key: value})
            except FieldError, e:
                logger.warning(e)

        sorting = self.get_sorting(request, **resources)
        if sorting:
            qs = qs.order_by(*sorting)

        return qs
556940
private ResourceMeta filter(Path path, ResourceMeta resourceMeta, Operation op) {
        ResourceMetaBuilder resourceMetaBuilder = StorageUtil.create(new HashMap<String,
                String>(resourceMeta.getMeta()));
        final HasInputStream result;
        switch (op) {
            case READ:
            case UPDATE:
            case CREATE:
                try {
                    if (op == Operation.CREATE) {
                        result = plugin.createResource(path, resourceMetaBuilder, resourceMeta);
                    } else if (op == Operation.READ) {
                        result = plugin.readResource(path, resourceMetaBuilder, resourceMeta);
                    } else {
                        result = plugin.updateResource(path, resourceMetaBuilder, resourceMeta);
                    }
                } catch (Throwable e) {
                    throw new StorageException("Converter Plugin " + providerName + " threw exception during " + op +
                            ": " + e.getMessage(), e, StorageException.Event.valueOf(op.toString()), path);
                }
                break;
            default:
                throw new IllegalStateException();
        }
        logger.debug(
                "Plugin(" + providerName + "):" + op + ":" + path +
                ";" + (null == result ? "_" : "+") + ":" + resourceMetaBuilder.getResourceMeta()
        );
        //construct the new data
        return StorageUtil.withStream(null == result ? resourceMeta : result, resourceMetaBuilder.getResourceMeta());
    }
1259817
public static base_response update(nitro_service client, filterpolicy resource) throws Exception {
		filterpolicy updateresource = new filterpolicy();
		updateresource.name = resource.name;
		updateresource.rule = resource.rule;
		updateresource.reqaction = resource.reqaction;
		updateresource.resaction = resource.resaction;
		return updateresource.update_resource(client);
	}
970015
protected void addMetadataFiltersToMetadataResolver(final AbstractMetadataResolver metadataProvider, final List<MetadataFilter> metadataFilterList) {
        val metadataFilterChain = new MetadataFilterChain();
        metadataFilterChain.setFilters(metadataFilterList);

        LOGGER.debug("Metadata filter chain initialized with [{}] filters", metadataFilterList.size());
        metadataProvider.setMetadataFilter(metadataFilterChain);
    }
424176
def where(filter)
      if filter.is_a?(String) # we got a Sparql snippet
        where_clauses << filter
      elsif filter.is_a?(Hash)
        filter.each_pair do |key, value|
          field = resource_class.get_field(key)
          value = RDF::Literal.new(value) unless value.respond_to?(:to_base)
          where_clauses << "?uri <#{ field.predicate }> #{ value.to_base }"
        end
      end
      self
    end
437919
def attach_core_filters(cls):
        
        opts = cls._meta
        base_filters = cls.base_filters.copy()
        cls.base_filters.clear()
        for name, filter_ in six.iteritems(base_filters):
            if isinstance(filter_, AutoFilters):
                field = filterset.get_model_field(opts.model, filter_.name)
                filter_exclusion = filter_.extra.pop('drop', [])
                for lookup_expr in utils.lookups_for_field(field):
                    if lookup_expr not in filter_exclusion:
                        new_filter = cls.filter_for_field(field, filter_.name, lookup_expr)
                        # by convention use field name for filters with exact lookup_expr
                        if lookup_expr != 'exact':
                            filter_name = LOOKUP_SEP.join([name, lookup_expr])
                        else:
                            filter_name = name
                        cls.base_filters[filter_name] = new_filter