Java Code Examples for org.apache.commons.collections.CollectionUtils#filter()

The following examples show how to use org.apache.commons.collections.CollectionUtils#filter() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FilterACollection.java    From levelup-java-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void filter_items_in_list_with_apache_commons () {
	
	List<NFLTeam> nflTeams = Lists.newArrayList();
	nflTeams.add(new NFLTeam("Green Bay Packers", true));
	nflTeams.add(new NFLTeam("Chicago Bears", true));
	nflTeams.add(new NFLTeam("Detroit Lions", false));

	CollectionUtils.filter(nflTeams, new org.apache.commons.collections.Predicate() {
		public boolean evaluate(Object nflTeam) {
			return ((NFLTeam) nflTeam).hasWonSuperBowl;
		}
	});
	
	logger.info(nflTeams);
	
	assertTrue(nflTeams.size() == 2);
}
 
Example 2
Source File: HandlersLoader.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
static Handler<?>[] addingDefaultHandlers(Handler<?>[] result) {
   ArrayList<Class> requiredHandler = new ArrayList(defaultHandlers.size());
   requiredHandler.addAll(defaultHandlers);
   CollectionUtils.filter(requiredHandler, new HandlersLoader.DefaultHandlersPredicate(result));
   Iterator i$ = requiredHandler.iterator();

   while(i$.hasNext()) {
      Class handler = (Class)i$.next();

      try {
         LOG.debug("Adding required handler [{}]", handler.getName());
         result = (Handler[])((Handler[])ArrayUtils.add(result, handler.newInstance()));
      } catch (Exception var5) {
         LOG.warn("Unable to add required handler", var5);
      }
   }

   return result;
}
 
Example 3
Source File: AbstractPredicateUtil.java    From ranger with Apache License 2.0 6 votes vote down vote up
public void applyFilter(List<? extends RangerBaseModelObject> objList, SearchFilter filter) {
	if(CollectionUtils.isEmpty(objList)) {
		return;
	}

	Predicate pred = getPredicate(filter);

	if(pred != null) {
		CollectionUtils.filter(objList, pred);
	}

	Comparator<RangerBaseModelObject> sorter = getSorter(filter);

	if(sorter != null) {
		Collections.sort(objList, sorter);
	}
}
 
Example 4
Source File: HandlersLoader.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
static Handler<?>[] addingDefaultHandlers(Handler<?>[] result) {
   ArrayList<Class> requiredHandler = new ArrayList(defaultHandlers.size());
   requiredHandler.addAll(defaultHandlers);
   CollectionUtils.filter(requiredHandler, new HandlersLoader.DefaultHandlersPredicate(result));
   Iterator i$ = requiredHandler.iterator();

   while(i$.hasNext()) {
      Class handler = (Class)i$.next();

      try {
         LOG.debug("Adding required handler [{}]", handler.getName());
         result = (Handler[])((Handler[])ArrayUtils.add(result, handler.newInstance()));
      } catch (Exception var5) {
         LOG.warn("Unable to add required handler", var5);
      }
   }

   return result;
}
 
Example 5
Source File: AgentInfoServiceImpl.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
@Override
public Set<AgentInfo> getAgentsByApplicationNameWithoutStatus(String applicationName, long timestamp) {
    if (applicationName == null) {
        throw new NullPointerException("applicationName");
    }
    if (timestamp < 0) {
        throw new IllegalArgumentException("timestamp must not be less than 0");
    }

    List<String> agentIds = this.applicationIndexDao.selectAgentIds(applicationName);
    List<AgentInfo> agentInfos = this.agentInfoDao.getAgentInfos(agentIds, timestamp);
    CollectionUtils.filter(agentInfos, PredicateUtils.notNullPredicate());
    if (CollectionUtils.isEmpty(agentInfos)) {
        return Collections.emptySet();
    }
    return new HashSet<>(agentInfos);
}
 
Example 6
Source File: FilterNullFromCollection.java    From levelup-java-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void remove_null_from_list_apache_commons () {
	
	List<String> strings = new ArrayList<>();
	strings.add(null);
	strings.add("www");
	strings.add(null);
	strings.add("leveluplunch");
	strings.add("com");
	strings.add(null);

	
	CollectionUtils.filter(strings, new org.apache.commons.collections.Predicate() {
		public boolean evaluate(Object obj) {
			return obj != null;
		}
	});
	
	assertEquals(3, strings.size());
}
 
Example 7
Source File: EntitySearchProcessor.java    From atlas with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(List<AtlasVertex> entityVertices) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> EntitySearchProcessor.filter({})", entityVertices.size());
    }

    // Since we already have the entity vertices, a in-memory filter will be faster than fetching the same
    // vertices again with the required filtering
    if (filterGraphQueryPredicate != null) {
        LOG.debug("Filtering in-memory");
        CollectionUtils.filter(entityVertices, filterGraphQueryPredicate);
    }

    super.filter(entityVertices);

    if (LOG.isDebugEnabled()) {
        LOG.debug("<== EntitySearchProcessor.filter(): ret.size()={}", entityVertices.size());
    }
}
 
Example 8
Source File: NavigationPanel.java    From AppStash with Apache License 2.0 5 votes vote down vote up
private IModel<List<NavigationGroup>> otherNavigationModel() {
    return new AbstractReadOnlyModel<List<NavigationGroup>>() {
        private static final long serialVersionUID = 6806034829063836686L;

        @Override
        public List<NavigationGroup> getObject() {
            List<NavigationGroup> navigationGroups = new LinkedList<>(navigationProvider.getNavigation().getNavigationGroups());
            CollectionUtils.filter(navigationGroups, object -> object instanceof NavigationGroup && !"main".equals(((NavigationGroup) object).getName()));
            return navigationGroups;
        }
    };
}
 
Example 9
Source File: HistoryListServlet.java    From APM with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(final SlingHttpServletRequest request, final SlingHttpServletResponse response)
    throws IOException {

  String filter = request.getParameter("filter");
  List<HistoryEntry> executions = history.findAllHistoryEntries(request.getResourceResolver());
  if (StringUtils.isNotBlank(filter)) {
    CollectionUtils.filter(executions, new ExecutionHistoryFilter(filter));
  }
  ServletUtils.writeJson(response, executions);
}
 
Example 10
Source File: EmployeeDao.java    From projectforge-webapp with GNU General Public License v3.0 5 votes vote down vote up
@Override
public List<EmployeeDO> getList(final BaseSearchFilter filter)
{
  final EmployeeFilter myFilter;
  if (filter instanceof EmployeeFilter) {
    myFilter = (EmployeeFilter) filter;
  } else {
    myFilter = new EmployeeFilter(filter);
  }
  final QueryFilter queryFilter = new QueryFilter(myFilter);
  final List<EmployeeDO> list = getList(queryFilter);
  final Date now = new Date();
  if (myFilter.isShowOnlyActiveEntries() == true) {
    CollectionUtils.filter(list, new Predicate() {
      public boolean evaluate(final Object object)
      {
        final EmployeeDO employee = (EmployeeDO) object;
        if (employee.getEintrittsDatum() != null && now.before(employee.getEintrittsDatum()) == true) {
          return false;
        } else if (employee.getAustrittsDatum() != null && now.after(employee.getAustrittsDatum()) == true) {
          return false;
        }
        return true;
      }
    });
  }
  return list;
}
 
Example 11
Source File: TermSearchProcessor.java    From atlas with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(List<AtlasVertex> entityVertices) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> TermSearchProcessor.filter({})", entityVertices.size());
    }

    if (CollectionUtils.isNotEmpty(entityVertices)) {
        if (CollectionUtils.isEmpty(assignedEntities)) {
            entityVertices.clear();
        } else {
            CollectionUtils.filter(entityVertices, o -> {
                if (o instanceof AtlasVertex) {
                    AtlasVertex entityVertex = (AtlasVertex) o;

                    for (AtlasVertex assignedEntity : assignedEntities) {
                        if (assignedEntity.getId().equals(entityVertex.getId())) {
                            return true;
                        }
                    }
                }

                return false;
            });
        }
    }

    super.filter(entityVertices);

    if (LOG.isDebugEnabled()) {
        LOG.debug("<== TermSearchProcessor.filter(): ret.size()={}", entityVertices.size());
    }
}
 
Example 12
Source File: KmsKeyMgr.java    From ranger with Apache License 2.0 5 votes vote down vote up
public VXKmsKeyList getFilteredKeyList(HttpServletRequest request, VXKmsKeyList vXKmsKeyList){
	List<SortField> sortFields = new ArrayList<SortField>();
	sortFields.add(new SortField(KeySearchFilter.KEY_NAME, KeySearchFilter.KEY_NAME));

	KeySearchFilter filter = getKeySearchFilter(request, sortFields);
	
	Predicate pred = getPredicate(filter);
	
	if(pred != null) {
		CollectionUtils.filter(vXKmsKeyList.getVXKeys(), pred);
	}
	return vXKmsKeyList;
}
 
Example 13
Source File: FilterElementsByType.java    From levelup-java-examples with Apache License 2.0 5 votes vote down vote up
@Test
public void filter_elements_by_type_apache () {
	
	CollectionUtils.filter(objects, new org.apache.commons.collections.Predicate() {
		public boolean evaluate(Object obj) {
			return obj instanceof String;
		}
	});
	
	@SuppressWarnings("unchecked")
	Collection<String> strings = CollectionUtils.typedCollection(objects, String.class);
	
	assertThat(strings, contains(
    		"hello", "world"));
}
 
Example 14
Source File: RoleMemberLookupableHelperServiceImpl.java    From rice with Educational Community License v2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
protected List<RoleBo> searchRoles(Map<String, String> roleSearchCriteria, boolean unbounded){
	List<RoleBo> roles = (List<RoleBo>)getLookupService().findCollectionBySearchHelper(
			RoleBo.class, roleSearchCriteria, unbounded);
	String membersCrt = roleSearchCriteria.get("members.memberId");
	List<RoleBo> roles2Remove = new ArrayList<RoleBo>();
	if(StringUtils.isNotBlank(membersCrt)){
		List<String> memberSearchIds = new ArrayList<String>();
		List<String> memberIds = new ArrayList<String>(); 
		if(membersCrt.contains(KimConstants.KimUIConstants.OR_OPERATOR)) {
			memberSearchIds = new ArrayList<String>(Arrays.asList(membersCrt.split("\\|")));
           }
		else {
			memberSearchIds.add(membersCrt);
           }
		for(RoleBo roleBo : roles){
			List<RoleMemberBo> roleMembers = roleBo.getMembers();
			memberIds.clear(); 
	        CollectionUtils.filter(roleMembers, new Predicate() {
				public boolean evaluate(Object object) {
					RoleMemberBo member = (RoleMemberBo) object;
					// keep active member
					return member.isActive(new Timestamp(System.currentTimeMillis()));
				}
			});
	       
	        if(roleMembers != null && !roleMembers.isEmpty()){
	        	for(RoleMemberBo memberImpl : roleMembers) {
	        		memberIds.add(memberImpl.getMemberId());
                   }
	        	if(((List<String>)CollectionUtils.intersection(memberSearchIds, memberIds)).isEmpty()) {
	        		roles2Remove.add(roleBo);
                   }
	        }
	        else
	        {
	        	roles2Remove.add(roleBo);
	        }
		}
	}
	if(!roles2Remove.isEmpty()) {
		roles.removeAll(roles2Remove);
       }
	return roles;
}
 
Example 15
Source File: VersionUtil.java    From maven-confluence-plugin with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public static LinkedList<String> sortAndFilter(Collection<String> versionNameList,
                                               String start,
                                               String end) {

    final ArtifactVersion startVersion = parseArtifactVersion(start);
    final ArtifactVersion endVersion;
    if (end != null && !end.isEmpty()) {
        endVersion = parseArtifactVersion(end);
    } else {
        endVersion = null;
    }


    if (endVersion!=null && startVersion.compareTo(endVersion) > 0) {
        throw new IllegalArgumentException(
                String.format("startVersion %s must be less or equals to endVersion %s",
                        startVersion, endVersion));

    }

    LinkedList<String> linkedList = new LinkedList<String>();

    Map<ArtifactVersion, String> map = new HashMap<ArtifactVersion, String>();

    for (String versionTag : versionNameList) {
        map.put(parseArtifactVersion(versionTag), versionTag);
    }


    List<ArtifactVersion> artifactVersionSet = new ArrayList<ArtifactVersion>(map.keySet());


    CollectionUtils.filter(artifactVersionSet, new Predicate() {
        @Override
        public boolean evaluate(Object o) {
            ArtifactVersion current = (ArtifactVersion) o;
            if (endVersion != null) {
                if (startVersion.compareTo(current) <= 0
                        &&
                        endVersion.compareTo(current) >= 0) {
                    return true;
                }
            } else {
                if (startVersion.compareTo(current) <= 0) {
                    return true;
                }
            }

            return false;
        }
    });

    Collections.sort(artifactVersionSet);
    for (ArtifactVersion artifactVersion : artifactVersionSet) {
        linkedList.add(map.get(artifactVersion));
    }
    return linkedList;

}
 
Example 16
Source File: EntitySearchProcessor.java    From atlas with Apache License 2.0 4 votes vote down vote up
@Override
public List<AtlasVertex> execute() {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> EntitySearchProcessor.execute({})", context);
    }

    List<AtlasVertex> ret = new ArrayList<>();

    AtlasPerfTracer perf = null;

    if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
        perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "EntitySearchProcessor.execute(" + context +  ")");
    }

    try {
        final int startIdx = context.getSearchParameters().getOffset();
        final int limit    = context.getSearchParameters().getLimit();

        // when subsequent filtering stages are involved, query should start at 0 even though startIdx can be higher
        //
        // first 'startIdx' number of entries will be ignored
        int qryOffset = (nextProcessor != null || (graphQuery != null && indexQuery != null)) ? 0 : startIdx;
        int resultIdx = qryOffset;

        final List<AtlasVertex> entityVertices = new ArrayList<>();

        SortOrder sortOrder = context.getSearchParameters().getSortOrder();
        String sortBy = context.getSearchParameters().getSortBy();

        final AtlasEntityType entityType = context.getEntityTypes().iterator().next();
        AtlasAttribute sortByAttribute = entityType.getAttribute(sortBy);
        if (sortByAttribute == null) {
            sortBy = null;
        } else {
            sortBy = sortByAttribute.getVertexPropertyName();
        }

        if (sortOrder == null) { sortOrder = ASCENDING; }

        for (; ret.size() < limit; qryOffset += limit) {
            entityVertices.clear();

            if (context.terminateSearch()) {
                LOG.warn("query terminated: {}", context.getSearchParameters());

                break;
            }

            final boolean isLastResultPage;

            if (indexQuery != null) {
                Iterator<AtlasIndexQuery.Result> idxQueryResult = executeIndexQuery(context, indexQuery, qryOffset, limit);

                getVerticesFromIndexQueryResult(idxQueryResult, entityVertices);

                isLastResultPage = entityVertices.size() < limit;

                // Do in-memory filtering before the graph query
                CollectionUtils.filter(entityVertices, inMemoryPredicate);

                if (graphQueryPredicate != null) {
                    CollectionUtils.filter(entityVertices, graphQueryPredicate);
                }
            } else {
                Iterator<AtlasVertex> queryResult = graphQuery.vertices(qryOffset, limit).iterator();

                getVertices(queryResult, entityVertices);

                isLastResultPage = entityVertices.size() < limit;

                // Do in-memory filtering
                CollectionUtils.filter(entityVertices, inMemoryPredicate);

                //incase when operator is NEQ in pipeSeperatedSystemAttributes
                if (graphQueryPredicate != null) {
                    CollectionUtils.filter(entityVertices, graphQueryPredicate);
                }
            }

            super.filter(entityVertices);

            resultIdx = collectResultVertices(ret, startIdx, limit, resultIdx, entityVertices);

            if (isLastResultPage) {
                break;
            }
        }
    } finally {
        AtlasPerfTracer.log(perf);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("<== EntitySearchProcessor.execute({}): ret.size()={}", context, ret.size());
    }

    return ret;
}
 
Example 17
Source File: ConfigurationModuleLoader.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
static void filter(List<ConfigurationModule> modulesToLoad) {
   CollectionUtils.filter(modulesToLoad, new ConfigurationModuleLoader.ConfigurationModulePredicate(ConfigurationModuleClassloader.class, ConfigurationModuleLogging.class, ConfigurationModuleVersion.class, ConfigurationModuleProperties.class, ConfigurationModuleSecurityProvider.class, ConfigurationModuleTrustStore.class));
}
 
Example 18
Source File: ConfigurationModuleLoader.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
static void filter(List<ConfigurationModule> modulesToLoad) {
   CollectionUtils.filter(modulesToLoad, new ConfigurationModuleLoader.ConfigurationModulePredicate(new Class[]{ConfigurationModuleClassloader.class, ConfigurationModuleLogging.class, ConfigurationModuleVersion.class, ConfigurationModuleProperties.class, ConfigurationModuleSecurityProvider.class, ConfigurationModuleTrustStore.class}));
}
 
Example 19
Source File: ConfigurationModuleLoader.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
static void filter(List<ConfigurationModule> modulesToLoad) {
   CollectionUtils.filter(modulesToLoad, new ConfigurationModuleLoader.ConfigurationModulePredicate(new Class[]{ConfigurationModuleClassloader.class, ConfigurationModuleLogging.class, ConfigurationModuleVersion.class, ConfigurationModuleProperties.class, ConfigurationModuleSecurityProvider.class, ConfigurationModuleTrustStore.class}));
}
 
Example 20
Source File: ConfigurationModuleLoader.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
static void filter(List<ConfigurationModule> modulesToLoad) {
   CollectionUtils.filter(modulesToLoad, new ConfigurationModuleLoader.ConfigurationModulePredicate(new Class[]{ConfigurationModuleClassloader.class, ConfigurationModuleLogging.class, ConfigurationModuleVersion.class, ConfigurationModuleProperties.class, ConfigurationModuleSecurityProvider.class, ConfigurationModuleTrustStore.class, ConfigurationModuleOCSP.class}));
}