Example usage for org.apache.commons.collections ListUtils intersection

List of usage examples for org.apache.commons.collections ListUtils intersection

Introduction

In this page you can find the example usage for org.apache.commons.collections ListUtils intersection.

Prototype

public static List intersection(final List list1, final List list2) 

Source Link

Document

Returns a new list containing all elements that are contained in both given lists.

Usage

From source file:org.opencms.search.CmsSearchParameters.java

/**
 * Creates a merged parameter set from this parameters, restricted by the given other parameters.<p>
 * /*from   www  .  j ava 2s. c  om*/
 * This is mainly intended for "search in search result" functions.<p>
 * 
 * The restricted query is build of the queries of both parameters, appended with AND.<p>
 * 
 * The lists in the restriction for <code>{@link #getFields()}</code>, <code>{@link #getRoots()}</code> and
 * <code>{@link #getCategories()}</code> are <b>intersected</b> with the lists of this search parameters. Only
 * elements contained in both lists are included for the created search parameters. 
 * If a list in either the restriction or in this search parameters is <code>null</code>, 
 * the list from the other search parameters is used directly.<p> 
 * 
 * The values for
 * <code>{@link #isCalculateCategories()}</code>
 * and <code>{@link #getSort()}</code> of this parameters are used for the restricted parameters.<p>
 * 
 * @param restriction the parameters to restrict this parameters with
 * @return the restricted parameters
 */
@SuppressWarnings("unchecked")
public CmsSearchParameters restrict(CmsSearchParameters restriction) {

    // append queries
    StringBuffer query = new StringBuffer(256);
    if (getQuery() != null) {
        // don't blow up unnecessary closures (if CmsSearch is reused and restricted several times)
        boolean closure = !getQuery().startsWith("+(");
        if (closure) {
            query.append("+(");
        }
        query.append(getQuery());
        if (closure) {
            query.append(")");
        }
    }
    if (restriction.getQuery() != null) {
        // don't let Lucene max terms be exceeded in case someone reuses a CmsSearch and continuously restricts 
        // query with the same restrictions...
        if (query.indexOf(restriction.getQuery()) < 0) {
            query.append(" +(");
            query.append(restriction.getQuery());
            query.append(")");
        }
    }

    // restrict fields
    List<String> fields = null;
    if ((m_fields != null) && (m_fields.size() > 0)) {
        if ((restriction.getFields() != null) && (restriction.getFields().size() > 0)) {
            fields = ListUtils.intersection(m_fields, restriction.getFields());
        } else {
            fields = m_fields;
        }
    } else {
        fields = restriction.getFields();
    }

    // restrict roots
    List<String> roots = null;
    if ((m_roots != null) && (m_roots.size() > 0)) {
        if ((restriction.getRoots() != null) && (restriction.getRoots().size() > 0)) {
            roots = ListUtils.intersection(m_roots, restriction.getRoots());
            // TODO: This only works if there are equal paths in both parameter sets - for two distinct sets 
            //       all root restrictions are dropped with an empty list. 
        } else {
            roots = m_roots;
        }
    } else {
        roots = restriction.getRoots();
    }

    // restrict categories
    List<String> categories = null;
    if ((m_categories != null) && (m_categories.size() > 0)) {
        if ((restriction.getCategories() != null) && (restriction.getCategories().size() > 0)) {
            categories = ListUtils.intersection(m_categories, restriction.getCategories());
        } else {
            categories = m_categories;
        }
    } else {
        categories = restriction.getCategories();
    }

    // restrict resource types
    List<String> resourceTypes = null;
    if ((m_resourceTypes != null) && (m_resourceTypes.size() > 0)) {
        if ((restriction.getResourceTypes() != null) && (restriction.getResourceTypes().size() > 0)) {
            resourceTypes = ListUtils.intersection(m_resourceTypes, restriction.getResourceTypes());
        } else {
            resourceTypes = m_resourceTypes;
        }
    } else {
        resourceTypes = restriction.getResourceTypes();
    }

    // create the new search parameters 
    CmsSearchParameters result = new CmsSearchParameters(query.toString(), fields, roots, categories,
            resourceTypes, m_calculateCategories, m_sort);
    result.setIndex(getIndex());
    return result;
}

From source file:org.openhab.core.items.GroupItem.java

/** 
 * The accepted data types of a group item is the same as of the underlying base item.
 * If none is defined, the intersection of all sets of accepted data types of all group
 * members is used instead./*from  ww  w. j  av a2s  .c  o m*/
 * 
 * @return the accepted data types of this group item
 */
@SuppressWarnings("unchecked")
public List<Class<? extends State>> getAcceptedDataTypes() {
    if (baseItem != null) {
        return baseItem.getAcceptedDataTypes();
    } else {
        List<Class<? extends State>> acceptedDataTypes = null;

        for (Item item : members) {
            if (acceptedDataTypes == null) {
                acceptedDataTypes = item.getAcceptedDataTypes();
            } else {
                acceptedDataTypes = ListUtils.intersection(acceptedDataTypes, item.getAcceptedDataTypes());
            }
        }
        return acceptedDataTypes == null ? ListUtils.EMPTY_LIST : acceptedDataTypes;
    }
}

From source file:org.openhab.core.items.GroupItem.java

/** 
 * The accepted command types of a group item is the same as of the underlying base item.
 * If none is defined, the intersection of all sets of accepted command types of all group
 * members is used instead.//from  ww  w  . ja  v  a2  s  .  c  o m
 * 
 * @return the accepted command types of this group item
 */
@SuppressWarnings("unchecked")
public List<Class<? extends Command>> getAcceptedCommandTypes() {
    if (baseItem != null) {
        return baseItem.getAcceptedCommandTypes();
    } else {
        List<Class<? extends Command>> acceptedCommandTypes = null;

        for (Item item : members) {
            if (acceptedCommandTypes == null) {
                acceptedCommandTypes = item.getAcceptedCommandTypes();
            } else {
                acceptedCommandTypes = ListUtils.intersection(acceptedCommandTypes,
                        item.getAcceptedCommandTypes());
            }
        }
        return acceptedCommandTypes == null ? ListUtils.EMPTY_LIST : acceptedCommandTypes;
    }
}

From source file:org.openmicroscopy.shoola.env.data.OmeroMetadataServiceImpl.java

/**
 * Implemented as specified by {@link OmeroDataService}.
 * @see OmeroMetadataService#filterByAnnotation(Class, List, FilterContext, 
 *                                     long)
 *///from  ww w . j av a  2 s  . co  m
public Collection filterByAnnotation(Class nodeType, List<Long> ids, FilterContext filter, long userID)
        throws DSOutOfServiceException, DSAccessException {
    if (filter == null)
        throw new IllegalArgumentException("No filtering context.");
    int rateIndex = filter.getIndex();
    List<Long> filteredNodes = new ArrayList<Long>();

    List<Long> userIDs = null;
    if (userID != -1) {
        userIDs = new ArrayList<Long>(1);
        userIDs.add(userID);
    }
    List<Class> annotationTypes = new ArrayList<Class>();
    //types.add(annotationType);
    Map map = gateway.loadAnnotations(nodeType, ids, annotationTypes, userIDs, new Parameters());

    if (map == null || map.size() == 0) {
        if (rateIndex == FilterContext.EQUAL && filter.getRate() == 0)
            return ids;
    }

    //TODO: retrieve the experimenter corresponding to the passed id.
    ExperimenterData exp = getUserDetails();

    Timestamp start = filter.getFromDate();
    Timestamp end = filter.getToDate();
    Set<Long> annotationsIds = new HashSet<Long>();
    Iterator i, j, k;
    Long id;
    Collection l;
    List annotations;
    int resultType = filter.getResultType();
    Map<Class, List<String>> types = filter.getAnnotationType();

    Map<Class, List<Long>> r = new HashMap<Class, List<Long>>();
    List<Long> found;
    Class type;
    Entry entry;
    if (types != null && types.size() > 0) {
        i = types.entrySet().iterator();
        Map<Long, List<Long>> m = new HashMap<Long, List<Long>>();
        List<Long> nodes;
        AnnotationData data;
        if (resultType == FilterContext.INTERSECTION) {
            while (i.hasNext()) {
                entry = (Entry) i.next();
                type = (Class) entry.getKey();
                found = new ArrayList<Long>();
                annotations = gateway.filterBy(type, (List<String>) entry.getValue(), start, end, exp);
                j = annotations.iterator();
                while (j.hasNext())
                    annotationsIds.add((Long) j.next());

                j = map.entrySet().iterator();
                while (j.hasNext()) {
                    entry = (Entry) j.next();
                    id = (Long) entry.getKey();
                    l = (Collection) entry.getValue();
                    if (l.size() >= annotations.size()) {
                        k = l.iterator();
                        while (k.hasNext()) {
                            data = (AnnotationData) k.next();
                            if (annotations.contains(data.getId())) {
                                nodes = m.get(data.getId());
                                if (nodes == null) {
                                    nodes = new ArrayList<Long>();
                                    nodes.add(id);
                                }
                                if (!nodes.contains(id))
                                    nodes.add(id);
                                m.put(data.getId(), nodes);
                            }
                        }
                    }
                }
                j = m.entrySet().iterator();
                while (j.hasNext()) {
                    entry = (Entry) j.next();
                    id = (Long) entry.getKey();
                    nodes = (List) entry.getValue();
                    if (found.size() == 0)
                        found.addAll(nodes);
                    else
                        found = ListUtils.intersection(found, nodes);
                }
                r.put(type, found);
            }
        } else if (resultType == FilterContext.UNION) {
            while (i.hasNext()) {
                type = (Class) i.next();
                annotations = gateway.filterBy(type, types.get(type), start, end, exp);
                i = annotations.iterator();
                while (i.hasNext())
                    annotationsIds.add((Long) i.next());
            }

            i = map.entrySet().iterator();

            while (i.hasNext()) {
                entry = (Entry) i.next();
                id = (Long) entry.getKey();
                l = (Collection) entry.getValue();
                j = l.iterator();
                while (j.hasNext()) {
                    data = (AnnotationData) j.next();
                    if (annotationsIds.contains(data.getId()))
                        filteredNodes.add(id);
                }
            }
        }
    }

    if (rateIndex != -1) {
        int rate = filter.getRate();
        int value;
        i = map.keySet().iterator();
        AnnotationData data;
        found = new ArrayList<Long>();
        switch (rateIndex) {
        case FilterContext.EQUAL:
            if (rate == 0) { //unrated element.
                found.addAll(ids);
                while (i.hasNext())
                    found.remove(i.next());
            } else {

                while (i.hasNext()) {
                    id = (Long) i.next();
                    l = (Collection) map.get(id);
                    j = l.iterator();
                    while (j.hasNext()) {
                        data = (AnnotationData) j.next();
                        if (data instanceof RatingAnnotationData) {
                            value = ((RatingAnnotationData) data).getRating();
                            if (rate == value)
                                found.add(id);
                        }
                    }
                }
            }
            break;
        case FilterContext.LOWER:
            if (rate == 0) { //unrated element.
                found.addAll(ids);

                while (i.hasNext())
                    found.remove(i.next());
            } else {
                while (i.hasNext()) {
                    id = (Long) i.next();
                    l = (Collection) map.get(id);
                    j = l.iterator();
                    while (j.hasNext()) {
                        data = (AnnotationData) j.next();
                        if (data instanceof RatingAnnotationData) {
                            value = ((RatingAnnotationData) data).getRating();
                            if (value <= rate)
                                found.add(id);
                        }
                    }
                }
            }
            break;
        case FilterContext.HIGHER:
            while (i.hasNext()) {
                id = (Long) i.next();
                l = (Collection) map.get(id);
                j = l.iterator();
                while (j.hasNext()) {
                    data = (AnnotationData) j.next();
                    if (data instanceof RatingAnnotationData) {
                        value = ((RatingAnnotationData) data).getRating();
                        if (value >= rate)
                            found.add(id);
                    }
                }
            }
        }
        if (resultType == FilterContext.UNION)
            filteredNodes.addAll(found);
        else if (resultType == FilterContext.INTERSECTION)
            r.put(RatingAnnotationData.class, found);
    }
    if (resultType == FilterContext.UNION)
        return filteredNodes;

    //Intersection.
    filteredNodes.clear();

    if (r.size() == 0)
        return filteredNodes;

    int index = 0;
    type = null;
    /*
    while (i.hasNext()) {
       type = (Class) i.next();
       if (index == 0) {
    filteredNodes.addAll(r.get(type));
    break;
       }
       index++;
    }
    r.remove(type);
    */
    i = r.entrySet().iterator();
    while (i.hasNext()) {
        entry = (Entry) i.next();
        if (filteredNodes.size() == 0)
            filteredNodes.addAll((List) entry.getValue());
        else
            filteredNodes = ListUtils.intersection(filteredNodes, (List) entry.getValue());
    }
    return filteredNodes;
}

From source file:org.openmrs.module.providermanagement.api.impl.ProviderManagementServiceImpl.java

@Override
@Transactional(readOnly = true)//from   w w w  .  j a  v a 2 s. c o m
public boolean canSupervise(Person supervisor, Person supervisee) {

    if (supervisor == null) {
        throw new APIException("Supervisor cannot be null");
    }

    if (supervisee == null) {
        throw new APIException("Provider cannot be null");
    }

    // return false if supervisor and supervisee are the same person!
    if (supervisor.equals(supervisee)) {
        return false;
    }

    // get all the provider roles the supervisor can supervise
    List<ProviderRole> rolesThatProviderCanSupervisee = getProviderRolesThatProviderCanSupervise(supervisor);

    // get all the roles associated with the supervisee
    List<ProviderRole> superviseeProviderRoles = getProviderRoles(supervisee);

    return ListUtils.intersection(rolesThatProviderCanSupervisee, superviseeProviderRoles).size() > 0 ? true
            : false;
}

From source file:org.structr.core.graph.search.SearchNodeCommand.java

/**
 * Return a result with a list of nodes which fit to all search criteria.
 *
 * @param securityContext               Search in this security context
 * @param topNode                       If set, return only search results below this top node (follows the HAS_CHILD relationship)
 * @param includeDeletedAndHidden       If true, include nodes marked as deleted or hidden
 * @param publicOnly                    If true, don't include nodes which are not public
 * @param searchAttrs                   List with search attributes
 * @param sortKey                       Key to sort results
 * @param sortDescending                If true, sort results in descending order (higher values first)
 * @param pageSize                      Return a portion of the overall result of this size
 * @param page                          Return the page of the result set with this page size
 * @param offsetId                      If given, start pagination at the object with this UUID
 * @param sortType                      The entity type to sort the results (needed for lucene)
 * @return/*from   w w w.j  a v a 2 s .com*/
 */
private Result<T> search(final boolean includeDeletedAndHidden, final boolean publicOnly,
        final List<SearchAttribute> searchAttrs, final PropertyKey sortKey, final boolean sortDescending,
        final int pageSize, final int page, final String offsetId, final Integer sortType)
        throws FrameworkException {

    if (page == 0 || pageSize <= 0) {

        return Result.EMPTY_RESULT;
    }

    GraphDatabaseService graphDb = (GraphDatabaseService) arguments.get("graphDb");
    NodeFactory nodeFactory = new NodeFactory(securityContext, includeDeletedAndHidden, publicOnly, pageSize,
            page, offsetId);
    Result finalResult = new Result(new ArrayList<AbstractNode>(), null, true, false);
    boolean allExactMatch = true;
    final Index<Node> index;

    // boolean allFulltext = false;
    if (graphDb != null) {

        // At this point, all search attributes are ready
        // BooleanQuery query                             = new BooleanQuery();
        List<FilterSearchAttribute> filters = new ArrayList<FilterSearchAttribute>();
        List<TextualSearchAttribute> textualAttributes = new ArrayList<TextualSearchAttribute>();
        StringBuilder queryString = new StringBuilder();
        DistanceSearchAttribute distanceSearch = null;
        GeoCodingResult coords = null;
        Double dist = null;

        for (SearchAttribute attr : searchAttrs) {

            if (attr instanceof RangeSearchAttribute) {

                handleRangeAttribute((RangeSearchAttribute) attr, queryString);

            } else if (attr instanceof DistanceSearchAttribute) {

                distanceSearch = (DistanceSearchAttribute) attr;
                coords = GeoHelper.geocode(distanceSearch.getKey().dbName());
                dist = distanceSearch.getValue();

            } else if (attr instanceof SearchAttributeGroup) {

                SearchAttributeGroup attributeGroup = (SearchAttributeGroup) attr;

                handleAttributeGroup(attributeGroup, queryString, textualAttributes, allExactMatch);

            } else if (attr instanceof TextualSearchAttribute) {

                textualAttributes.add((TextualSearchAttribute) attr);

                // query.add(toQuery((TextualSearchAttribute) attr), translateToBooleanClauseOccur(attr.getSearchOperator()));
                queryString.append(toQueryString((TextualSearchAttribute) attr,
                        StringUtils.isBlank(queryString.toString())));

                allExactMatch &= isExactMatch(((TextualSearchAttribute) attr).getValue());

            } else if (attr instanceof FilterSearchAttribute) {

                filters.add((FilterSearchAttribute) attr);
            }

        }

        // Check if all prerequisites are met
        if (distanceSearch == null && textualAttributes.size() < 1) {

            throw new UnsupportedArgumentError(
                    "At least one texutal search attribute or distance search have to be present in search attributes!");
        }

        Result intermediateResult;

        if (searchAttrs.isEmpty() && StringUtils.isBlank(queryString.toString())) {

            //                              if (topNode != null) {
            //
            //                                      intermediateResult = topNode.getAllChildren();
            //
            //                              } else {
            intermediateResult = new Result(new ArrayList<AbstractNode>(), null, false, false);

            //                              }
        } else {

            long t0 = System.nanoTime();

            logger.log(Level.FINEST, "Textual Query String: {0}", queryString);

            String query = queryString.toString();

            QueryContext queryContext = new QueryContext(query);
            IndexHits hits = null;

            if (sortKey != null) {

                if (sortType != null) {

                    queryContext.sort(new Sort(new SortField(sortKey.dbName(), sortType, sortDescending)));
                } else {

                    queryContext.sort(
                            new Sort(new SortField(sortKey.dbName(), Locale.getDefault(), sortDescending)));
                }

            }

            if (distanceSearch != null) {

                if (coords != null) {

                    Map<String, Object> params = new HashMap<String, Object>();

                    params.put(LayerNodeIndex.POINT_PARAMETER, coords.toArray());
                    params.put(LayerNodeIndex.DISTANCE_IN_KM_PARAMETER, dist);

                    index = (LayerNodeIndex) arguments.get(NodeIndex.layer.name());

                    synchronized (index) {

                        hits = index.query(LayerNodeIndex.WITHIN_DISTANCE_QUERY, params);
                    }

                }

            } else if ((textualAttributes.size() == 1)
                    && textualAttributes.get(0).getKey().equals(AbstractNode.uuid.dbName())) {

                // Search for uuid only: Use UUID index
                index = (Index<Node>) arguments.get(NodeIndex.uuid.name());

                synchronized (index) {

                    hits = index.get(AbstractNode.uuid.dbName(),
                            decodeExactMatch(textualAttributes.get(0).getValue()));
                }

            } else if ( /* (textualAttributes.size() > 1) && */allExactMatch) {

                //                                      } else if ((textualAttributes.size() > 1) && allExactMatch) {
                // Only exact machtes: Use keyword index
                index = (Index<Node>) arguments.get(NodeIndex.keyword.name());

                synchronized (index) {

                    try {
                        hits = index.query(queryContext);

                    } catch (NumberFormatException nfe) {

                        logger.log(Level.SEVERE, "Could not sort results", nfe);

                        // retry without sorting
                        queryContext.sort(null);
                        hits = index.query(queryContext);

                    }
                }
            } else {

                // Default: Mixed or fulltext-only search: Use fulltext index
                index = (Index<Node>) arguments.get(NodeIndex.fulltext.name());

                synchronized (index) {

                    hits = index.query(queryContext);
                }
            }

            long t1 = System.nanoTime();

            logger.log(Level.FINE, "Querying index took {0} ns, size() says {1} results.",
                    new Object[] { t1 - t0, (hits != null) ? hits.size() : 0 });

            //                              IndexHits hits = index.query(new QueryContext(query.toString()));//.sort("name"));
            intermediateResult = nodeFactory.createNodes(hits);

            if (hits != null) {
                hits.close();
            }

            long t2 = System.nanoTime();

            logger.log(Level.FINE, "Creating structr nodes took {0} ns, {1} nodes made.",
                    new Object[] { t2 - t1, intermediateResult.getResults().size() });

        }

        List<? extends GraphObject> intermediateResultList = intermediateResult.getResults();
        long t2 = System.nanoTime();

        if (!filters.isEmpty()) {

            // Filter intermediate result
            for (GraphObject obj : intermediateResultList) {

                AbstractNode node = (AbstractNode) obj;

                for (FilterSearchAttribute attr : filters) {

                    PropertyKey key = attr.getKey();
                    Object searchValue = attr.getValue();
                    SearchOperator op = attr.getSearchOperator();
                    Object nodeValue = node.getProperty(key);

                    if (op.equals(SearchOperator.NOT)) {

                        if ((nodeValue != null) && !(nodeValue.equals(searchValue))) {

                            attr.addToResult(node);
                        }

                    } else {

                        if ((nodeValue == null) && (searchValue == null)) {

                            attr.addToResult(node);
                        }

                        if ((nodeValue != null) && nodeValue.equals(searchValue)) {

                            attr.addToResult(node);
                        }

                    }

                }

            }

            // now sum, intersect or substract all partly results
            for (FilterSearchAttribute attr : filters) {

                SearchOperator op = attr.getSearchOperator();
                List<? extends GraphObject> result = attr.getResult();

                if (op.equals(SearchOperator.AND)) {

                    intermediateResult = new Result(ListUtils.intersection(intermediateResultList, result),
                            null, true, false);
                } else if (op.equals(SearchOperator.OR)) {

                    intermediateResult = new Result(ListUtils.sum(intermediateResultList, result), null, true,
                            false);
                } else if (op.equals(SearchOperator.NOT)) {

                    intermediateResult = new Result(ListUtils.subtract(intermediateResultList, result), null,
                            true, false);
                }

            }
        }

        // eventually filter by distance from a given point
        if (coords != null) {
        }

        finalResult = intermediateResult;

        long t3 = System.nanoTime();

        logger.log(Level.FINE, "Filtering nodes took {0} ns. Result size now {1}.",
                new Object[] { t3 - t2, finalResult.getResults().size() });

        //                      if (sortKey != null) {
        //                              
        //                              Collections.sort(finalResult.getResults(), new GraphObjectComparator(sortKey, sortDescending ? GraphObjectComparator.DESCENDING : GraphObjectComparator.ASCENDING));
        //
        //                              long t4 = System.nanoTime();
        //                      
        //                              logger.log(Level.FINE, "Sorting nodes took {0} ns.", new Object[] { t4 - t3 });
        //                      
        //                      }
    }

    return finalResult;

}

From source file:org.structr.core.graph.search.SearchRelationshipCommand.java

/**
 * Return a list of relationships which fit to all search criteria.
 *
 * @param securityContext       Search in this security context
 * @param searchAttrs           List with search attributes
 * @return/*w  ww.ja va2 s.c o m*/
 */
private List<AbstractRelationship> search(final SecurityContext securityContext,
        final List<SearchAttribute> searchAttrs) throws FrameworkException {

    GraphDatabaseService graphDb = (GraphDatabaseService) arguments.get("graphDb");
    RelationshipFactory relationshipFactory = (RelationshipFactory) arguments.get("relationshipFactory");
    List<AbstractRelationship> finalResult = new LinkedList<AbstractRelationship>();
    boolean allExactMatch = true;
    final Index<Relationship> index;

    // boolean allFulltext = false;
    if (graphDb != null) {

        // At this point, all search attributes are ready
        BooleanQuery query = new BooleanQuery();
        List<FilterSearchAttribute> filters = new LinkedList<FilterSearchAttribute>();
        List<TextualSearchAttribute> textualAttributes = new LinkedList<TextualSearchAttribute>();
        StringBuilder textualQueryString = new StringBuilder();

        for (SearchAttribute attr : searchAttrs) {

            if (attr instanceof SearchAttributeGroup) {

                SearchAttributeGroup attributeGroup = (SearchAttributeGroup) attr;
                List<SearchAttribute> groupedAttributes = attributeGroup.getSearchAttributes();
                StringBuilder subQueryString = new StringBuilder();

                if (!(groupedAttributes.isEmpty())) {

                    BooleanQuery subQuery = new BooleanQuery();
                    String subQueryPrefix = (StringUtils.isBlank(textualQueryString.toString()) ? ""
                            : attributeGroup.getSearchOperator()) + " ( ";

                    for (SearchAttribute groupedAttr : groupedAttributes) {

                        // TODO: support other than textual search attributes
                        if (groupedAttr instanceof TextualSearchAttribute) {

                            textualAttributes.add((TextualSearchAttribute) groupedAttr);
                            subQuery.add(toQuery((TextualSearchAttribute) groupedAttr),
                                    translateToBooleanClauseOccur(groupedAttr.getSearchOperator()));

                            subQueryString.append(toQueryString((TextualSearchAttribute) groupedAttr,
                                    StringUtils.isBlank(subQueryString.toString())));
                            allExactMatch &= isExactMatch(((TextualSearchAttribute) groupedAttr).getValue());

                        }
                    }

                    query.add(subQuery, translateToBooleanClauseOccur(attributeGroup.getSearchOperator()));

                    String subQuerySuffix = " ) ";

                    // Add sub query only if not blank
                    if (StringUtils.isNotBlank(subQueryString.toString())) {

                        textualQueryString.append(subQueryPrefix).append(subQueryString).append(subQuerySuffix);

                    }

                }

            } else if (attr instanceof TextualSearchAttribute) {

                textualAttributes.add((TextualSearchAttribute) attr);
                query.add(toQuery((TextualSearchAttribute) attr),
                        translateToBooleanClauseOccur(attr.getSearchOperator()));

                textualQueryString.append(toQueryString((TextualSearchAttribute) attr,
                        StringUtils.isBlank(textualQueryString.toString())));
                allExactMatch &= isExactMatch(((TextualSearchAttribute) attr).getValue());

            } else if (attr instanceof FilterSearchAttribute) {

                filters.add((FilterSearchAttribute) attr);

            }

        }

        List<AbstractRelationship> intermediateResult;

        if (searchAttrs.isEmpty() || StringUtils.isBlank(textualQueryString.toString())) {

            intermediateResult = new LinkedList<AbstractRelationship>();

        } else {

            long t0 = System.currentTimeMillis();

            logger.log(Level.FINE, "Textual Query String: {0}", textualQueryString);

            QueryContext queryContext = new QueryContext(textualQueryString);
            IndexHits hits;

            if ((textualAttributes.size() == 1)
                    && textualAttributes.get(0).getKey().equals(AbstractRelationship.uuid.dbName())) {

                // Search for uuid only: Use UUID index
                index = (Index<Relationship>) arguments.get(RelationshipIndex.rel_uuid.name());
                synchronized (index) {
                    hits = index.get(AbstractNode.uuid.dbName(),
                            decodeExactMatch(textualAttributes.get(0).getValue()));
                }
            } else if ((textualAttributes.size() > 1) && allExactMatch) {

                // Only exact machtes: Use keyword index
                index = (Index<Relationship>) arguments.get(RelationshipIndex.rel_keyword.name());
                synchronized (index) {
                    hits = index.query(queryContext);
                }
            } else {

                // Default: Mixed or fulltext-only search: Use fulltext index
                index = (Index<Relationship>) arguments.get(RelationshipIndex.rel_fulltext.name());
                synchronized (index) {
                    hits = index.query(queryContext);
                }
            }

            long t1 = System.currentTimeMillis();

            logger.log(Level.FINE, "Querying index took {0} ms, size() says {1} results.",
                    new Object[] { t1 - t0, hits.size() });

            //                              IndexHits hits = index.query(new QueryContext(query.toString()));//.sort("name"));
            intermediateResult = relationshipFactory.instantiateRelationships(securityContext, hits);

            hits.close();
            long t2 = System.currentTimeMillis();

            logger.log(Level.FINE, "Creating structr relationships took {0} ms, {1} relationships made.",
                    new Object[] { t2 - t1, intermediateResult.size() });

        }

        long t2 = System.currentTimeMillis();

        if (!filters.isEmpty()) {

            // Filter intermediate result
            for (AbstractRelationship rel : intermediateResult) {

                for (FilterSearchAttribute attr : filters) {

                    PropertyKey key = attr.getKey();
                    Object searchValue = attr.getValue();
                    SearchOperator op = attr.getSearchOperator();
                    Object nodeValue = rel.getProperty(key);

                    if (op.equals(SearchOperator.NOT)) {

                        if ((nodeValue != null) && !(nodeValue.equals(searchValue))) {

                            attr.addToResult(rel);

                        }

                    } else {

                        if ((nodeValue == null) && (searchValue == null)) {

                            attr.addToResult(rel);

                        }

                        if ((nodeValue != null) && nodeValue.equals(searchValue)) {

                            attr.addToResult(rel);

                        }

                    }

                }

            }

            // now sum, intersect or substract all partly results
            for (FilterSearchAttribute attr : filters) {

                SearchOperator op = attr.getSearchOperator();
                List<GraphObject> result = attr.getResult();

                if (op.equals(SearchOperator.AND)) {

                    intermediateResult = ListUtils.intersection(intermediateResult, result);

                } else if (op.equals(SearchOperator.OR)) {

                    intermediateResult = ListUtils.sum(intermediateResult, result);

                } else if (op.equals(SearchOperator.NOT)) {

                    intermediateResult = ListUtils.subtract(intermediateResult, result);

                }

            }
        }

        finalResult.addAll(intermediateResult);

        long t3 = System.currentTimeMillis();

        logger.log(Level.FINE, "Filtering nodes took {0} ms. Result size now {1}.",
                new Object[] { t3 - t2, finalResult.size() });
    }

    long t4 = System.currentTimeMillis();

    // sort search results; defaults to name, (@see AbstractNode.compareTo())
    Collections.sort(finalResult);

    long t5 = System.currentTimeMillis();

    logger.log(Level.FINE, "Sorting relationships took {0} ms.", new Object[] { t5 - t4 });

    return finalResult;
}

From source file:org.structr.web.resource.DynamicTypeResource.java

@Override
public Result doGet(final PropertyKey sortKey, final boolean sortDescending, final int pageSize, final int page,
        final String offsetId) throws FrameworkException {

    List<GraphObject> uuidResults = null;

    // REST path contained uuid, return result of UuidResource
    if (uuidResource != null) {

        uuidResource.setSecurityContext(this.securityContext);

        uuidResults = (List<GraphObject>) uuidResource.doGet(sortKey, sortDescending, pageSize, page, offsetId)
                .getResults();/* w ww .ja v a2 s.  c o  m*/

    }

    // check for dynamic type, use super class otherwise
    final List<SearchAttribute> searchAttributes = getSearchAttributes(rawType);

    searchAttributes.addAll(extractSearchableAttributesFromRequest(securityContext));

    // do search
    List<Component> results = getComponents(securityContext, searchAttributes);

    if (!results.isEmpty()) {

        // intersect results with uuid result
        if (uuidResults != null) {

            results = ListUtils.intersection(results, uuidResults);
        }

        // check if nested DynamicTypeResources have valid results
        for (final DynamicTypeResource res : nestedResources) {

            if (res.doGet(sortKey, sortDescending, pageSize, page, offsetId).getResults().isEmpty()) {

                throw new NotFoundException();
            }

        }

        return new Result(results, null, isCollectionResource(), isPrimitiveArray());
    }

    parentResults = true;

    return super.doGet(sortKey, sortDescending, pageSize, page, offsetId);

}

From source file:org.wso2.carbon.appmgt.gateway.handlers.security.entitlement.AuthorizationHandler.java

public boolean handleRequest(MessageContext messageContext) {

    GatewayUtils.logRequest(log, messageContext);

    String fullResourceURL = (String) messageContext.getProperty(RESTConstants.REST_FULL_REQUEST_PATH);

    if (isHandlerApplicable(messageContext)) {
        String webAppContext = (String) messageContext.getProperty(RESTConstants.REST_API_CONTEXT);
        String webAppVersion = (String) messageContext.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION);

        // Fetch the web app for the requested context and version.
        int appTenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
        try {/*w ww  .j  ava  2 s  .  co  m*/
            if (webApp == null) {
                webApp = new DefaultAppRepository(null).getWebAppByContextAndVersion(webAppContext,
                        webAppVersion, appTenantId);
            }
        } catch (AppManagementException e) {
            String errorMessage = String.format("Can't fetch the web for '%s' from the repository.",
                    fullResourceURL);
            GatewayUtils.logAndThrowException(log, errorMessage, e);
        }

        Session session = GatewayUtils.getSession(messageContext);
        List<String> roles = session.getAuthenticationContext().getRoles();
        List<String> visibleRoles = webApp.getVisibleRoleList();

        String appTenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
        String userTenantDomain = session.getAuthenticationContext().getTenantDomain();

        String appTenantAdminRole = null;
        try {
            appTenantAdminRole = getAdminRole();
        } catch (UserStoreException e) {
            GatewayUtils.logAndThrowException(log, String.format(
                    "Error occurred while retrieving realm admin for tenant domain '%s' ", appTenantDomain), e);
        }

        //Check for app visibility
        if (!visibleRoles.isEmpty()) {
            if (!isUserInCurrentTenantDomain(userTenantDomain)) {
                GatewayUtils.send401(messageContext, null);
                if (log.isDebugEnabled()) {
                    GatewayUtils.logWithRequestInfo(log, messageContext,
                            String.format("User tenant domain '%s' and app tenant domain '%s' mismatch",
                                    userTenantDomain, appTenantDomain));
                    return false;
                }
            }

            if (ListUtils.intersection(roles, visibleRoles).isEmpty() && !roles.contains(appTenantAdminRole)) {
                if (log.isDebugEnabled()) {
                    GatewayUtils.logWithRequestInfo(log, messageContext,
                            String.format("'%s' doesn't have required roles to access '%s'",
                                    session.getAuthenticationContext().getSubject(), fullResourceURL));
                }
                GatewayUtils.send401(messageContext,
                        "You don't have required user role(s) to access this resource.");
                return false;
            }
        }

        // Check role based access.

        URITemplate matchedTemplate = (URITemplate) messageContext
                .getProperty(AppMConstants.MESSAGE_CONTEXT_PROPERTY_MATCHED_URI_TEMPLATE);

        if (matchedTemplate != null && matchedTemplate.isRoleRestricted()) {

            if (log.isDebugEnabled()) {
                GatewayUtils.logWithRequestInfo(log, messageContext,
                        String.format("Resource '%s' is role restricted", fullResourceURL));
            }

            if (!isUserInCurrentTenantDomain(session.getAuthenticationContext().getTenantDomain())) {
                GatewayUtils.send401(messageContext, null);
                if (log.isDebugEnabled()) {
                    GatewayUtils.logWithRequestInfo(log, messageContext,
                            String.format("User tenant domain '%s' and app tenant domain '%s' mismatch",
                                    userTenantDomain, appTenantDomain));
                    return false;
                }
            }

            List<String> allowedRoles = matchedTemplate.getAllowedRoles();
            if (!ListUtils.intersection(roles, allowedRoles).isEmpty() || roles.contains(appTenantAdminRole)) {

                if (log.isDebugEnabled()) {
                    GatewayUtils.logWithRequestInfo(log, messageContext,
                            String.format("'%s' has required roles to access '%s'",
                                    session.getAuthenticationContext().getSubject(), fullResourceURL));
                }

                return true;
            } else {

                if (log.isDebugEnabled()) {
                    GatewayUtils.logWithRequestInfo(log, messageContext,
                            String.format("'%s' doesn't have required roles to access '%s'",
                                    session.getAuthenticationContext().getSubject(), fullResourceURL));
                }

                GatewayUtils.send401(messageContext,
                        "You don't have required user role(s) to access this resource.");
                return false;
            }
        } else {

            // This requested is not role restricted.
            return true;
        }
    } else {
        return true;
    }
}

From source file:org.wso2.carbon.appmgt.oauth.handlers.PasswordGrantHandler.java

private String[] getAuthorizedScopes(AuthenticatedUser authorizedUser, String[] requestedScopes,
        Map<String, String> scopeRoleMapping) {

    String[] authorizedScopes = new String[0];

    String[] userRoles = getUserRoles(authorizedUser);
    Map<String, Set<String>> roleScopeMapping = getRoleScopeMapping(scopeRoleMapping);

    Set<String> allowedScopes = new HashSet<String>();

    Set<String> scopesForRole = null;
    for (String role : userRoles) {
        scopesForRole = roleScopeMapping.get(role);
        if (scopesForRole != null) {
            allowedScopes.addAll(scopesForRole);
        }// www .ja v  a  2  s . co m
    }

    if (requestedScopes.length > 0 && allowedScopes.size() > 0) {
        List<String> intersection = ListUtils.intersection(Arrays.asList(requestedScopes),
                new ArrayList<String>(allowedScopes));
        authorizedScopes = intersection.toArray(new String[0]);
    }

    return authorizedScopes;
}