Example usage for org.apache.commons.collections CollectionUtils select

List of usage examples for org.apache.commons.collections CollectionUtils select

Introduction

In this page you can find the example usage for org.apache.commons.collections CollectionUtils select.

Prototype

public static Collection select(Collection inputCollection, Predicate predicate) 

Source Link

Document

Selects all elements from input collection which match the given predicate into an output collection.

Usage

From source file:org.projectforge.humanresources.HRPlanningEntryDao.java

@Override
public List<HRPlanningEntryDO> getList(final BaseSearchFilter filter) {
    final HRPlanningFilter myFilter = (HRPlanningFilter) filter;
    if (myFilter.getStopTime() != null) {
        final DateHolder date = new DateHolder(myFilter.getStopTime());
        date.setEndOfDay();// w  ww. ja  v a2s  .  co m
        myFilter.setStopTime(date.getDate());
    }
    final QueryFilter queryFilter = buildQueryFilter(myFilter);
    myFilter.setIgnoreDeleted(true); // Ignore deleted flag of HRPlanningEntryDOs, use instead:
    if (myFilter.isDeleted() == true) {
        queryFilter.add(Restrictions.or(Restrictions.eq("deleted", true), Restrictions.eq("p.deleted", true)));
    } else {
        queryFilter
                .add(Restrictions.and(Restrictions.eq("deleted", false), Restrictions.eq("p.deleted", false)));
    }
    final List<HRPlanningEntryDO> list = getList(queryFilter);
    if (list == null) {
        return null;
    }
    for (final HRPlanningEntryDO entry : list) {
        @SuppressWarnings("unchecked")
        final List<HRPlanningEntryDO> entries = (List<HRPlanningEntryDO>) CollectionUtils
                .select(entry.getPlanning().getEntries(), PredicateUtils.uniquePredicate());
        entry.getPlanning().setEntries(entries);
    }
    if (myFilter.isGroupEntries() == false && myFilter.isOnlyMyProjects() == false) {
        return list;
    }
    final List<HRPlanningEntryDO> result = new ArrayList<HRPlanningEntryDO>();
    final Set<Integer> set = (myFilter.isGroupEntries() == true) ? new HashSet<Integer>() : null;
    for (final HRPlanningEntryDO entry : list) {
        if (myFilter.isOnlyMyProjects() == true) {
            if (entry.getProjekt() == null) {
                continue;
            }
            final ProjektDO projekt = entry.getProjekt();
            if (projekt.getProjektManagerGroup() == null) {
                continue;
            }
            if (userGroupCache.isLoggedInUserMemberOfGroup(projekt.getProjektManagerGroupId()) == false) {
                continue;
            }
        }
        if (myFilter.isGroupEntries() == true) {
            if (set.contains(entry.getPlanningId()) == true) {
                // Entry is already in result list.
                continue;
            }
            final HRPlanningEntryDO sumEntry = new HRPlanningEntryDO();
            final HRPlanningDO planning = entry.getPlanning();
            sumEntry.setPlanning(planning);
            sumEntry.setUnassignedHours(planning.getTotalUnassignedHours());
            sumEntry.setMondayHours(planning.getTotalMondayHours());
            sumEntry.setTuesdayHours(planning.getTotalTuesdayHours());
            sumEntry.setWednesdayHours(planning.getTotalWednesdayHours());
            sumEntry.setThursdayHours(planning.getTotalThursdayHours());
            sumEntry.setFridayHours(planning.getTotalFridayHours());
            sumEntry.setWeekendHours(planning.getTotalWeekendHours());
            final StringBuffer buf = new StringBuffer();
            boolean first = true;
            for (final HRPlanningEntryDO pos : planning.getEntries()) {
                final String str = pos.getProjektNameOrStatus();
                if (StringUtils.isNotBlank(str) == true) {
                    if (first == true) {
                        first = false;
                    } else {
                        buf.append("; ");
                    }
                    buf.append(str);
                }
            }
            sumEntry.setDescription(buf.toString());
            result.add(sumEntry);
            set.add(planning.getId());
        } else {
            result.add(entry);
        }
    }
    return result;
}

From source file:org.projectforge.rest.AddressDaoRest.java

/**
 * Rest-Call for {@link AddressDao#getFavoriteVCards()}. <br/>
 * If modifiedSince is given then only those addresses will be returned:
 * <ol>/*ww  w  .  j a  v a2  s  .com*/
 * <li>The address was changed after the given modifiedSince date, or</li>
 * <li>the address was added to the user's personal address book after the given modifiedSince date, or</li>
 * <li>the address was removed from the user's personal address book after the given modifiedSince date.</li>
 * </ol>
 * 
 * @param searchTerm
 * @param modifiedSince milliseconds since 1970 (UTC)
 * @param all If true and the user is member of the ProjectForge's group {@link ProjectForgeGroup#FINANCE_GROUP} or
 *          {@link ProjectForgeGroup#MARKETING_GROUP} the export contains all addresses instead of only favorite
 *          addresses.
 */
@GET
@Path(RestPaths.LIST)
@Produces(MediaType.APPLICATION_JSON)
public Response getList(@QueryParam("search") final String searchTerm,
        @QueryParam("modifiedSince") final Long modifiedSince, @QueryParam("all") final Boolean all,
        @QueryParam("disableImageData") final Boolean disableImageData) {
    final AddressFilter filter = new AddressFilter(new BaseSearchFilter());
    Date modifiedSinceDate = null;
    if (modifiedSince != null) {
        modifiedSinceDate = new Date(modifiedSince);
        filter.setModifiedSince(modifiedSinceDate);
    }
    filter.setSearchString(searchTerm);
    final List<AddressDO> list = addressDao.getList(filter);

    boolean exportAll = false;
    if (BooleanUtils.isTrue(all) == true
            && accessChecker.isLoggedInUserMemberOfGroup(ProjectForgeGroup.FINANCE_GROUP,
                    ProjectForgeGroup.MARKETING_GROUP) == true) {
        exportAll = true;
    }

    List<PersonalAddressDO> favorites = null;
    Set<Integer> favoritesSet = null;
    if (exportAll == false) {
        favorites = personalAddressDao.getList();
        favoritesSet = new HashSet<Integer>();
        if (favorites != null) {
            for (final PersonalAddressDO personalAddress : favorites) {
                if (personalAddress.isFavoriteCard() == true && personalAddress.isDeleted() == false) {
                    favoritesSet.add(personalAddress.getAddressId());
                }
            }
        }
    }
    final List<AddressObject> result = new LinkedList<AddressObject>();
    final Set<Integer> alreadyExported = new HashSet<Integer>();
    if (list != null) {
        for (final AddressDO addressDO : list) {
            if (exportAll == false && favoritesSet.contains(addressDO.getId()) == false) {
                // Export only personal favorites due to data-protection.
                continue;
            }
            final AddressObject address = AddressDOConverter.getAddressObject(addressDO,
                    BooleanUtils.isTrue(disableImageData));
            result.add(address);
            alreadyExported.add(address.getId());
        }
    }
    if (exportAll == false && modifiedSinceDate != null) {
        // Add now personal address entries which were modified since the given date (deleted or added):
        for (final PersonalAddressDO personalAddress : favorites) {
            if (alreadyExported.contains(personalAddress.getAddressId()) == true) {
                // Already exported:
            }
            if (personalAddress.getLastUpdate() != null
                    && personalAddress.getLastUpdate().before(modifiedSinceDate) == false) {
                final AddressDO addressDO = addressDao.getById(personalAddress.getAddressId());
                final AddressObject address = AddressDOConverter.getAddressObject(addressDO,
                        BooleanUtils.isTrue(disableImageData));
                if (personalAddress.isFavorite() == false) {
                    // This address was may-be removed by the user from the personal address book, so add this address as deleted to the result
                    // list.
                    address.setDeleted(true);
                }
                result.add(address);
            }
        }
    }
    @SuppressWarnings("unchecked")
    final List<AddressObject> uniqResult = (List<AddressObject>) CollectionUtils.select(result,
            PredicateUtils.uniquePredicate());
    final String json = JsonUtils.toJson(uniqResult);
    log.info("Rest call finished (" + result.size() + " addresses)...");
    return Response.ok(json).build();
}

From source file:org.sipfoundry.sipxconfig.device.FilteredModelSource.java

public Collection<T> getModels() {
    Collection<T> models = m_modelSource.getModels();
    if (m_filter != null) {
        models = CollectionUtils.select(models, m_filter);
    }/*from  w w  w.j  av  a2  s . c  o m*/
    return models;
}

From source file:org.sipfoundry.sipxconfig.feature.Bundle.java

public Collection<GlobalFeature> getGlobalFeatures() {
    return CollectionUtils.select(m_features.keySet(), new Predicate() {
        public boolean evaluate(Object arg0) {
            return arg0 instanceof GlobalFeature;
        }//from   w ww  .j  a  v a 2s .  c  om
    });
}

From source file:org.sipfoundry.sipxconfig.feature.Bundle.java

public Collection<LocationFeature> getLocationFeatures() {
    return CollectionUtils.select(m_features.keySet(), new Predicate() {
        public boolean evaluate(Object arg0) {
            return arg0 instanceof LocationFeature;
        }//from   w w w .j  a  v a 2s . c  o  m
    });
}

From source file:org.sipfoundry.sipxconfig.feature.FeatureChangeRequest.java

@SuppressWarnings({ "unchecked", "rawtypes" })
Collection<Location> findLocationsByFeature(LocationFeature f, Map<Location, Set<LocationFeature>> map) {
    LocationByFeature findAndFilter = new LocationByFeature(f);
    Collection select = CollectionUtils.select(map.entrySet(), findAndFilter);
    Collection locations = CollectionUtils.collect(select, findAndFilter);
    return (Collection<Location>) locations;
}

From source file:org.sipfoundry.sipxconfig.firewall.FirewallConfig.java

void writeIptables(Writer w, Set<String> whiteList, Set<String> blackList, FirewallSettings settings,
        List<CallRateRule> rateRules, List<FirewallRule> rules, List<CustomFirewallRule> custom,
        List<ServerGroup> groups, List<Location> cluster, Location thisLocation) throws IOException {
    YamlConfiguration c = new YamlConfiguration(w);

    Collection<?> ips = CollectionUtils.collect(cluster, Location.GET_ADDRESS);
    c.write("logdropped", settings.isLogDroppedPacketsEnabled());
    c.write("logdos", settings.isLogDosPacketsEnabled());
    c.write("lograte", settings.isLogRatePacketsEnabled());
    c.write("logregister", settings.isLogSipRegisterEnabled());
    c.write("loginvite", settings.isLogSipInviteEnabled());
    c.write("logack", settings.isLogSipAckEnabled());
    c.write("logoptions", settings.isLogSipOptionsEnabled());
    c.write("logsubscribe", settings.isLogSipSubscribeEnabled());
    c.write("loglimit", settings.getLogLimitNumber());
    c.write("loginterval", settings.getLogLimitInterval());

    c.writeInlineArray("cluster", ips);

    c.startArray("chains");
    for (ServerGroup group : groups) {
        c.nextElement();//from   ww w  .j  a  v  a2 s. c om
        c.write(":name", group.getName());
        List<String> sourceIPs = new ArrayList<String>();
        String servers = group.getServerList();
        if (StringUtils.isNotBlank(servers)) {
            sourceIPs = Arrays.asList(StringUtils.split(servers, " "));
        }
        c.writeArray(":ipv4s", sourceIPs);
    }
    c.endArray();

    c.writeArray("whitelist", whiteList);
    c.writeArray("blacklist", blackList);
    c.writeArray("deniedsip", settings.getDeniedSipUAs());

    c.startArray("raterules");
    for (CallRateRule rule : rateRules) {
        c.nextElement();
        c.write(":rule", StringUtils.deleteWhitespace(rule.getName()));
        c.write(":startIp", rule.getStartIp());
        if (rule.getEndIp() != null) {
            c.write(":endIp", rule.getEndIp());
        }
        c.startArray(":limits");
        for (CallRateLimit limit : rule.getCallRateLimits()) {
            c.nextElement();
            c.write(":method", limit.getSipMethod());
            c.write(":rate", limit.getRate());
            c.write(":interval", limit.getInterval());
        }
        c.endArray();
    }
    c.endArray();

    c.startArray("rules");
    for (FirewallRule rule : rules) {
        AddressType type = rule.getAddressType();
        List<Address> addresses = m_addressManager.getAddresses(type, thisLocation);
        if (addresses != null) {
            for (Address address : addresses) {

                // not a rule for this server
                if (!address.getAddress().equals(thisLocation.getAddress())) {
                    continue;
                }

                AddressType atype = address.getType();
                String id = atype.getId();
                int port = address.getCanonicalPort();
                // internal error
                if (port == 0) {
                    LOG.error("Cannot open up port zero for service id " + id);
                    continue;
                }

                // blindly allowed
                if (FirewallRule.SystemId.CLUSTER == rule.getSystemId() && rule.getServerGroup() == null) {
                    continue;
                }

                c.write(":port", port);
                c.write(":protocol", atype.getProtocol());
                c.write(":sip", atype.isExternalSip());
                c.write(":service", id);
                c.write(":priority", rule.isPriority());
                if (address.getEndPort() != 0) {
                    c.write(":end_port", address.getEndPort());
                }
                ServerGroup group = rule.getServerGroup();
                String chain;
                if (group != null) {
                    chain = group.getName();
                } else if (rule.getSystemId() == FirewallRule.SystemId.PUBLIC) {
                    chain = "ACCEPT";
                } else {
                    chain = rule.getSystemId().name();
                }
                c.write(":chain", chain);
                c.nextElement();
            }
        }
    }
    c.endArray();

    for (FirewallTable table : FirewallTable.values()) {
        Collection<?> tableRules = CollectionUtils.select(custom, CustomFirewallRule.byTable(table));
        if (!tableRules.isEmpty()) {
            c.writeArray(table.toString(), tableRules);
        }
    }
}

From source file:org.sipfoundry.sipxconfig.firewall.FirewallManagerImpl.java

@SuppressWarnings({ "unchecked", "rawtypes" })
EditableFirewallRule[] getChanged(List<EditableFirewallRule> rules) {
    Predicate selectChanged = new Predicate() {
        public boolean evaluate(Object arg0) {
            return ((EditableFirewallRule) arg0).isChangedFromDefault();
        }/*from   w  w w.j av a2 s . c om*/
    };

    Collection changedCol = CollectionUtils.select(rules, selectChanged);
    return (EditableFirewallRule[]) changedCol.toArray(new EditableFirewallRule[0]);
}

From source file:org.sipfoundry.sipxconfig.phonebook.PhonebookManagerTest.java

public void testEntrySearchPredicates() {
    PhonebookEntry a = new FilePhonebookEntry();
    a.setInternalId("internalId");
    PhonebookEntry b = new PhonebookEntry();
    b.setInternalId("internalId");
    GooglePhonebookEntry c = new GooglePhonebookEntry();
    c.setGoogleAccount("account1");
    GooglePhonebookEntry d = new GooglePhonebookEntry();
    d.setGoogleAccount("account1");
    GooglePhonebookEntry e = new GooglePhonebookEntry();
    e.setGoogleAccount("account2");

    Collection<PhonebookEntry> entries = new ArrayList<PhonebookEntry>();
    entries.add(a);/*  w  w w. ja v  a 2 s .  co  m*/
    entries.add(b);
    entries.add(c);
    entries.add(d);
    entries.add(e);

    assertEquals(1, CollectionUtils.select(entries, new FileEntrySearchPredicate("internalId")).size());
    assertEquals(2, CollectionUtils.select(entries, new GoogleEntrySearchPredicate("account1")).size());
}

From source file:org.sipfoundry.sipxconfig.site.admin.commserver.BundlePanel.java

@SuppressWarnings("unchecked")
public FeatureChangeRequest buildFeatureChangeRequest() {
    Map<Location, Set<LocationFeature>> byLocation = new HashMap<Location, Set<LocationFeature>>();
    // location/*from  w  w w .  j  av  a 2 s  .  c  om*/
    for (Location l : getLocations()) {
        ByLocation filter = new ByLocation(l, getBundle());
        Collection<String> subset = CollectionUtils.select(getCellIds(), filter);
        Collection<LocationFeature> selected = CollectionUtils.collect(subset, filter);
        Set<LocationFeature> featureSet = new HashSet<LocationFeature>(selected);
        byLocation.put(l, featureSet);
    }

    FeatureChangeRequest req = FeatureChangeRequest.byBundle(getBundle(), getGlobalFeatures(), byLocation);
    return req;
}