List of usage examples for org.apache.commons.collections CollectionUtils filter
public static void filter(Collection collection, Predicate predicate)
From source file:ch.sentric.QueryFactory.java
public Query build(final String q) { if (null == q || "".equalsIgnoreCase(q)) { return new Query(); }// www . j ava 2s. c o m final ArrayList<QueryKeyValuePair> list = new ArrayList<QueryKeyValuePair>(0); ParserState state = ParserState.START; final StringTokenizer tokenizer = new StringTokenizer(q, "=&", true); String key = null; while (tokenizer.hasMoreTokens()) { final String token = tokenizer.nextToken(); switch (state) { case DELIMITER: if (token.equals("&")) { state = ParserState.KEY; } break; case KEY: if (!token.equals("=") && !token.equals("&") && !token.equalsIgnoreCase("PHPSESSID") && !token.equalsIgnoreCase("JSESSIONID")) { key = token; state = ParserState.EQUAL; } break; case EQUAL: if (token.equals("=")) { state = ParserState.VALUE; } else if (token.equals("&")) { list.add(new QueryKeyValuePair(key, null)); state = ParserState.KEY; } break; case VALUE: if (!token.equals("=") && !token.equals("&")) { if (token.contains(";jsessionid") || token.contains(";JSESSIONID")) { list.add(new QueryKeyValuePair(key, token.substring(0, token.lastIndexOf(";")))); } else { list.add(new QueryKeyValuePair(key, token)); } state = ParserState.DELIMITER; } else if (token.equals("&")) { list.add(new QueryKeyValuePair(key, null)); state = ParserState.KEY; } break; case START: if (!token.equalsIgnoreCase("PHPSESSID") && !token.equalsIgnoreCase("JSESSIONID")) { key = token; state = ParserState.EQUAL; } break; default: break; } } CollectionUtils.filter(list, new Predicate() { @Override public boolean evaluate(final Object object) { boolean allowedQueryParameter = true; final QueryKeyValuePair queryKeyValuePair = (QueryKeyValuePair) object; for (final String filter : filters) { if (queryKeyValuePair.getKey().startsWith(filter)) { allowedQueryParameter = false; } } return allowedQueryParameter; } }); return new Query(list, '&'); }
From source file:au.com.jwatmuff.eventmanager.model.misc.PoolChecker.java
public static List<Player> findEligiblePlayers(final Pool pool, Database database) { final CompetitionInfo ci = database.get(CompetitionInfo.class, null); final ConfigurationFile configurationFile = ConfigurationFile.getConfiguration(ci.getDrawConfiguration()); List<Player> players = database.findAll(Player.class, PlayerDAO.ALL); CollectionUtils.filter(players, new Predicate() { public boolean evaluate(Object arg0) { return checkPlayer((Player) arg0, pool, ci.getAgeThresholdDate(), configurationFile); }//from w w w . j av a 2s.c om }); return players; }
From source file:gov.nih.nci.caarray.domain.permissions.SecurityLevel.java
/** * @return the list of SecurityLevels that match the given predicate *//*www. j a v a 2 s . c o m*/ private static List<SecurityLevel> valuesSubset(Predicate p) { List<SecurityLevel> levels = new ArrayList<SecurityLevel>(Arrays.asList(SecurityLevel.values())); CollectionUtils.filter(levels, p); return levels; }
From source file:eionet.gdem.web.struts.stylesheet.EditStylesheetFormAction.java
@Override public ActionForward execute(ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) { ActionMessages errors = new ActionMessages(); StylesheetForm form = (StylesheetForm) actionForm; String stylesheetId = httpServletRequest.getParameter("stylesheetId"); if (stylesheetId == null || stylesheetId.equals("")) { stylesheetId = (String) httpServletRequest.getAttribute("stylesheetId"); }/* ww w .j a va 2 s . c o m*/ ConvTypeHolder ctHolder = new ConvTypeHolder(); StylesheetManager stylesheetManager = new StylesheetManager(); try { Stylesheet stylesheet = stylesheetManager.getStylesheet(stylesheetId); if (stylesheet == null) { try { httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); } catch (IOException ex) { LOGGER.error("Failed to set 404 response status", ex); } return actionMapping.findForward(null); } form.setDescription(stylesheet.getDescription()); form.setOutputtype(stylesheet.getType()); form.setStylesheetId(stylesheet.getConvId()); form.setXsl(stylesheet.getXsl()); form.setXslContent(stylesheet.getXslContent()); form.setXslFileName(stylesheet.getXslFileName()); form.setModified(stylesheet.getModified()); form.setChecksum(stylesheet.getChecksum()); form.setSchemas(stylesheet.getSchemas()); // set empty string if dependsOn is null to avoid struts error in define tag: // Define tag cannot set a null value form.setDependsOn(stylesheet.getDependsOn() == null ? "" : stylesheet.getDependsOn()); if (stylesheet.getSchemas().size() > 0) { //set first schema for Run Conversion link form.setSchema(stylesheet.getSchemas().get(0).getSchema()); // check if any related schema has type=EXCEL, if yes, then depends on info should be visible List<Schema> relatedSchemas = new ArrayList<Schema>(stylesheet.getSchemas()); CollectionUtils.filter(relatedSchemas, new BeanPredicate("schemaLang", new EqualPredicate("EXCEL"))); if (relatedSchemas.size() > 0) { form.setShowDependsOnInfo(true); List<Stylesheet> existingStylesheets = new ArrayList<Stylesheet>(); for (Schema relatedSchema : relatedSchemas) { CollectionUtils.addAll(existingStylesheets, stylesheetManager .getSchemaStylesheets(relatedSchema.getId(), stylesheetId).toArray()); } form.setExistingStylesheets(existingStylesheets); } } ctHolder = stylesheetManager.getConvTypes(); /** FIXME - do we need the list of DD XML Schemas on the page StylesheetListHolder stylesheetList = StylesheetListLoader.getGeneratedList(httpServletRequest); List<Schema> schemas = stylesheetList.getDdStylesheets(); httpServletRequest.setAttribute("stylesheet.DDSchemas", schemas); */ /* String schemaId = schema.getSchemaId(stylesheet.getSchema()); if (!Utils.isNullStr(schemaId)) { httpServletRequest.setAttribute("schemaInfo", schema.getSchema(schemaId)); httpServletRequest.setAttribute("existingStylesheets", stylesheetManager.getSchemaStylesheets(schemaId, stylesheetId)); } */ //httpServletRequest.setAttribute(StylesheetListLoader.STYLESHEET_LIST_ATTR, StylesheetListLoader.getStylesheetList(httpServletRequest)); } catch (DCMException e) { e.printStackTrace(); LOGGER.error("Edit stylesheet error", e); errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e.getErrorCode())); saveErrors(httpServletRequest, errors); } //TODO why is it needed to update session attribute in each request httpServletRequest.getSession().setAttribute("stylesheet.outputtype", ctHolder); return actionMapping.findForward("success"); }
From source file:com.exxonmobile.ace.hybris.test.job.AccountManagerJob.java
public void acctMgrApproveOrRejectAction(final String orderCode, final boolean approve) { final String decision = approve ? APPROVE.toString() : REJECT.toString(); LOG.info(String.format("Attempting to apply decision: %s on order: %s", orderCode, decision)); final EmployeeModel employee = getUserService().getUserForUID(ACCOUNTMANAGERUID, EmployeeModel.class); final Collection<WorkflowActionModel> workFlowActionModelList = new ArrayList<WorkflowActionModel>( getB2bWorkflowIntegrationService().getWorkflowActionsForUser(employee)); LOG.debug(ACCOUNTMANAGERUID + " has actions count:" + workFlowActionModelList.size()); CollectionUtils.filter(workFlowActionModelList, new Predicate() { @Override//from w w w. j a v a2 s . c o m public boolean evaluate(final Object object) { final WorkflowActionModel workflowActionModel = (WorkflowActionModel) object; if (APPROVAL.name().equals(workflowActionModel.getQualifier())) { return CollectionUtils.exists(workflowActionModel.getAttachmentItems(), new Predicate() { @Override public boolean evaluate(final Object object) { if (object instanceof OrderModel) { LOG.debug("This approval action is for order " + ((OrderModel) object).getCode() + " vs " + orderCode); return (orderCode.equals(((OrderModel) object).getCode())); } return false; } }); } else { return false; } } }); LOG.debug(String.format("Employee %s has %s actions to %s for this order %s", employee.getUid(), Integer.toString(workFlowActionModelList.size()), decision, orderCode)); for (final WorkflowActionModel workflowActionModel : workFlowActionModelList) { getB2bWorkflowIntegrationService().decideAction(workflowActionModel, decision); LOG.debug("Decided for ActionCode" + workflowActionModel.getCode() + " to " + decision); } }
From source file:com.prodyna.bmw.server.booking.service.BookingServiceBean.java
@Override public List<Booking> readBookingsForMonth(final Integer month) { List<Booking> allBookings = em.createNamedQuery(Booking.QUERY_GET_ALL_BOOKINGS_PAGINATED, Booking.class) .getResultList();/*from w w w. j a v a 2 s . com*/ final Calendar calendar = Calendar.getInstance(); CollectionUtils.filter(allBookings, new Predicate() { @Override public boolean evaluate(Object arg0) { Booking booking = (Booking) arg0; calendar.setTime(booking.getStart()); boolean startsInThisMonth = calendar.get(Calendar.MONTH) + 1 == month.intValue(); calendar.setTime(booking.getEnd()); boolean endsInThisMonth = calendar.get(Calendar.MONTH) + 1 == month.intValue(); return startsInThisMonth || endsInThisMonth; } }); return allBookings; }
From source file:io.coala.experimental.dynabean.DynaBeanTest.java
@Test public void testDynaBeans() throws Exception { // for usage, see // http://commons.apache.org/proper/commons-beanutils/javadocs/v1.9.2/apidocs/org/apache/commons/beanutils/package-summary.html#package_description final DynaBean dynaBean = new LazyDynaBean(); // Create LazyDynaBean final MutableDynaClass dynaClass = (MutableDynaClass) dynaBean.getDynaClass(); // get DynaClass dynaClass.add("amount", java.lang.Integer.class); // add property dynaClass.add("myMap", java.util.TreeMap.class); // add mapped property final DynaBean employee = dynaClass.newInstance(); // TODO experiment with Jackson's AnnotationIntrospector to annotate // DynaBean#get(...) method with @JsonAnyGetter and #set(...) method // with @JsonAnySetter employee.set("address", new HashMap<String, String>()); employee.set("activeEmployee", Boolean.FALSE); employee.set("firstName", "Fred"); employee.set("lastName", "Flintstone"); LOG.trace("Employee: " + JsonUtil.toPrettyJSON(employee)); // set all <activeEmployee> attribute values to <true> final BeanPropertyValueChangeClosure closure = new BeanPropertyValueChangeClosure("activeEmployee", Boolean.TRUE);/* w w w .j a v a 2s. co m*/ final Collection<?> employees = Collections.singleton(employee); LOG.trace("Mutated employees: " + JsonUtil.toPrettyJSON(employees)); // update the Collection CollectionUtils.forAllDo(employees, closure); // filter for beans with <activeEmployee> set to <false> final BeanPropertyValueEqualsPredicate predicate = new BeanPropertyValueEqualsPredicate("lastName", "Flintstone"); // filter the Collection CollectionUtils.filter(employees, predicate); LOG.trace("Filtered employees: " + JsonUtil.toPrettyJSON(employees)); }
From source file:net.hillsdon.reviki.search.impl.BasicAuthAwareSearchEngine.java
public Set<SearchMatch> search(final String query, final boolean provideExtracts, boolean singleWiki) throws IOException, QuerySyntaxException, PageStoreException { // Assuming that there are any restricted wikis configured then to avoid leaking any information we must either: // 1) Silently drop restricted results, or // 2) Ask the user to log in whether or not their query results in hits to a restricted wiki. // We implement option 1 for CTYPE_TEXT requests and option 2 otherwise. // None of this applies if the search is restricted to a single wiki (i.e. the current wiki, which occurs when using the SearchMacro, https://jira.int.corefiling.com/browse/REVIKI-654) if ((_request.get().getHeader("Authorization") == null) && !singleWiki && !ViewTypeConstants.is(_request.get(), CTYPE_TEXT)) { for (WikiConfiguration wiki : _config.getWikis()) { if (isRestrictedWiki(wiki)) { throw new PageStoreAuthenticationException("Log in to obtain search results"); }/*from www . j a v a 2s . c o m*/ } } final Map<String, Boolean> wikiAccessOkCache = new LinkedHashMap<String, Boolean>(); Set<SearchMatch> results = new LinkedHashSet<SearchMatch>(); results.addAll(_delegate.search(query, provideExtracts, singleWiki)); CollectionUtils.filter(results, new Predicate() { @Override public boolean evaluate(final Object o) { final SearchMatch match = (SearchMatch) o; Boolean accessOk = wikiAccessOkCache.get(match.getWiki()); if (accessOk == null) { // Determine if the user is allowed access to the matched wiki, based on: // * Whether or not a username and password are required to index the wiki, if not then assume everyone is allowed access // * If a username is required then determine if the current user has access. This is slower, hence the short circuit described in the first point. try { WikiConfiguration configuration = _config.getConfiguration(match.getWiki()); if (isRestrictedWiki(configuration)) { RequestScopedThreadLocalBasicSVNOperations operations = new RequestScopedThreadLocalBasicSVNOperations( new BasicAuthPassThroughBasicSVNOperationsFactory(configuration.getUrl(), new AutoPropertiesApplierImpl(new AutoProperties() { public Map<String, String> read() { return new LinkedHashMap<String, String>(); } }))); operations.create(_request.get()); try { operations.checkPath(match.getPage(), -1); } finally { operations.destroy(); } } accessOk = true; } catch (PageStoreAuthenticationException ex) { accessOk = false; } catch (PageStoreException ex) { LOG.error("Exception determining access to wiki: " + match.getWiki(), ex); return false; } wikiAccessOkCache.put(match.getWiki(), accessOk); LOG.debug("access to results in " + match.getWiki() + ": " + accessOk); } return accessOk; } }); return results; }
From source file:com.qcadoo.mes.states.service.client.StateChangeViewClientValidationUtil.java
private void addValidationErrors(final ComponentState component, final Entity entity, final List<Entity> messages) { final List<String> errorMessages = Lists.newArrayList(); CollectionUtils.filter(messages, VALIDATION_MESSAGES_PREDICATE); for (Entity message : messages) { if (MessagesUtil.hasCorrespondField(message)) { errorMessages.add(composeTranslatedFieldValidationMessage(entity, message)); } else {//from www . j a v a 2s . c o m errorMessages.add(composeTranslatedGlobalValidationMessage(message)); } } if (!errorMessages.isEmpty()) { final StringBuilder sb = new StringBuilder(); sb.append(translationService.translate("states.messages.change.failure.validationErrors", getLocale(), join(errorMessages, ' '))); component.addTranslatedMessage(sb.toString(), convertViewMessageType(VALIDATION_ERROR)); } }
From source file:models.Watch.java
public static Set<User> findActualWatchers(final Set<User> baseWatchers, final Resource resource) { Set<User> actualWatchers = new HashSet<>(); actualWatchers.addAll(baseWatchers); // Add every user who watches the project to which this resource belongs if (!(resource instanceof GlobalResource)) { Project project = resource.getProject(); actualWatchers.addAll(findWatchers(project.asResource())); }/*from ww w.ja v a 2 s . c om*/ // For this resource, add every user who watch explicitly and remove who unwatch explicitly. actualWatchers.addAll(findWatchers(resource)); actualWatchers.removeAll(findUnwatchers(resource)); // Filter the watchers who has no permission to read this resource. CollectionUtils.filter(actualWatchers, new Predicate() { @Override public boolean evaluate(Object watcher) { return AccessControl.isAllowed((User) watcher, resource, Operation.READ); } }); return actualWatchers; }