Example usage for org.apache.commons.collections PredicateUtils uniquePredicate

List of usage examples for org.apache.commons.collections PredicateUtils uniquePredicate

Introduction

In this page you can find the example usage for org.apache.commons.collections PredicateUtils uniquePredicate.

Prototype

public static Predicate uniquePredicate() 

Source Link

Document

Creates a Predicate that returns true the first time an object is encountered, and false if the same object is received again.

Usage

From source file:BeanUtilsCollectionsV2.java

 public static void main(String args[]) {
   BeanPredicate predicate =//from   w  w  w .j  av a 2 s .c  om
     new BeanPredicate("title", PredicateUtils.uniquePredicate());

   Movie movie = new Movie();
   movie.setTitle("The Italian Job");

   Movie movie1 = new Movie();
   movie1.setTitle("The Italian Job");

   System.err.println(predicate.evaluate(movie)); // evaluates true
   System.err.println(predicate.evaluate(movie1)); // evaluates false

}

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

/**
 * Rest-Call for {@link AddressDao#getFavoriteVCards()}. <br/>
 * If modifiedSince is given then only those addresses will be returned:
 * <ol>/*from ww  w  .ja  va 2  s.c o  m*/
 * <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.
 * @see AddressDaoClientMain
 */
@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) {
    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);
            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);
                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.projectforge.business.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  w w .j  a  v  a  2s.  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 (getUserGroupCache().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.business.login.LoginDefaultHandler.java

protected List<?> selectUnique(final List<?> list) {
    final List<?> result = (List<?>) CollectionUtils.select(list, PredicateUtils.uniquePredicate());
    return result;
}

From source file:org.projectforge.core.BaseDao.java

protected List<O> selectUnique(final List<O> list) {
    @SuppressWarnings("unchecked")
    final List<O> result = (List<O>) CollectionUtils.select(list, PredicateUtils.uniquePredicate());
    return result;
}

From source file:org.projectforge.database.xstream.HibernateXmlConverter.java

/**
 * @param writer//from   w  w  w.  j  a  va  2s  . c o m
 * @param includeHistory
 * @param session
 * @throws DataAccessException
 * @throws HibernateException
 */
private void writeObjects(final Writer writer, final boolean includeHistory, final Session session,
        final boolean preserveIds) throws DataAccessException, HibernateException {
    // Container fr die Objekte
    final List<Object> all = new ArrayList<Object>();
    final XStream stream = initXStream(session, true);
    final XStream defaultXStream = initXStream(session, false);

    session.flush();
    // Alles laden
    List<?> list = session.createQuery("select o from java.lang.Object o").setReadOnly(true).list();
    list = (List<?>) CollectionUtils.select(list, PredicateUtils.uniquePredicate());
    final int size = list.size();
    log.info("Writing " + size + " objects");
    for (final Iterator<?> it = list.iterator(); it.hasNext();) {
        final Object obj = it.next();
        if (log.isDebugEnabled()) {
            log.debug("loaded object " + obj);
        }
        if ((obj instanceof HistoryEntry || obj instanceof PropertyDelta) && includeHistory == false) {
            continue;
        }
        Hibernate.initialize(obj);
        Class<?> targetClass = obj.getClass();
        while (Enhancer.isEnhanced(targetClass) == true) {
            targetClass = targetClass.getSuperclass();
        }
        final ClassMetadata classMetadata = session.getSessionFactory().getClassMetadata(targetClass);
        if (classMetadata == null) {
            log.fatal("Can't init " + obj + " of type " + targetClass);
            continue;
        }
        // initalisierung des Objekts...
        defaultXStream.marshal(obj, new CompactWriter(new NullWriter()));

        if (preserveIds == false) {
            // Nun kann die ID gelscht werden
            classMetadata.setIdentifier(obj, null, EntityMode.POJO);
        }
        if (log.isDebugEnabled()) {
            log.debug("loading evicted object " + obj);
        }
        if (this.ignoreFromTopLevelListing.contains(targetClass) == false) {
            all.add(obj);
        }
    }
    // und schreiben
    try {
        writer.write("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n");
    } catch (final IOException ex) {
        // ignore, will fail on stream.marshal()
    }
    log.info("Wrote " + all.size() + " objects");
    final MarshallingStrategy marshallingStrategy = new ProxyIdRefMarshallingStrategy();
    stream.setMarshallingStrategy(marshallingStrategy);
    stream.marshal(all, new PrettyPrintWriter(writer));
}

From source file:org.projectforge.framework.persistence.xstream.HibernateXmlConverter.java

/**
 * @param writer// w  w  w  .  jav a  2 s. c  om
 * @param includeHistory
 * @param session
 * @throws DataAccessException
 * @throws HibernateException
 */
private void writeObjects(final Writer writer, final boolean includeHistory, final Session session,
        final boolean preserveIds) throws DataAccessException, HibernateException {
    // Container fr die Objekte
    final List<Object> all = new ArrayList<Object>();
    final XStream stream = initXStream(session, true);
    final XStream defaultXStream = initXStream(session, false);

    session.flush();
    // Alles laden
    //    final List<Class<?>> entities = new ArrayList<Class<?>>();
    final List<Class<?>> entities = PfEmgrFactory.get().getMetadataRepository().getTableEntities().stream()
            .map((e) -> e.getJavaType()).collect(Collectors.toList());
    //    entities.addAll(HibernateEntities.instance().getOrderedEntities());
    //    entities.addAll(HibernateEntities.instance().getOrderedHistoryEntities());
    for (final Class<?> entityClass : entities) {
        final String entitySimpleName = entityClass.getSimpleName();
        final String entityType = entityClass.getName();

        if (includeHistory == false
                && entityType.startsWith("org.projectforge.framework.persistence.history.entities.") == true) {
            // Skip history entries.
            continue;
        }
        List<?> list = session.createQuery("select o from " + entityType + " o").setReadOnly(true).list();
        list = (List<?>) CollectionUtils.select(list, PredicateUtils.uniquePredicate());
        final int size = list.size();
        log.info("Writing " + size + " objects");
        for (final Iterator<?> it = list.iterator(); it.hasNext();) {
            final Object obj = it.next();
            if (log.isDebugEnabled()) {
                log.debug("loaded object " + obj);
            }
            Hibernate.initialize(obj);
            final Class<?> targetClass = HibernateProxyHelper.getClassWithoutInitializingProxy(obj);
            final ClassMetadata classMetadata = session.getSessionFactory().getClassMetadata(targetClass);
            if (classMetadata == null) {
                log.fatal("Can't init " + obj + " of type " + targetClass);
                continue;
            }
            // initalisierung des Objekts...
            defaultXStream.marshal(obj, new CompactWriter(new NullWriter()));

            if (preserveIds == false) {
                // Nun kann die ID gelscht werden
                HibernateCompatUtils.setClassMetaDataSetIdentifier(classMetadata, obj, EntityMode.POJO);
            }
            if (log.isDebugEnabled()) {
                log.debug("loading evicted object " + obj);
            }
            if (this.ignoreFromTopLevelListing.contains(targetClass) == false) {
                all.add(obj);
            }
        }
    }
    // und schreiben
    try {
        writer.write("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n");
    } catch (final IOException ex) {
        // ignore, will fail on stream.marshal()
    }
    log.info("Wrote " + all.size() + " objects");
    final MarshallingStrategy marshallingStrategy = new ProxyIdRefMarshallingStrategy();
    stream.setMarshallingStrategy(marshallingStrategy);
    stream.marshal(all, new PrettyPrintWriter(writer));
}

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 w w . j  a  v  a 2  s . c o  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>//from  w  w  w . ja va2  s. c  o m
 * <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();
}