Example usage for org.apache.commons.collections Predicate Predicate

List of usage examples for org.apache.commons.collections Predicate Predicate

Introduction

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

Prototype

Predicate

Source Link

Usage

From source file:au.edu.uq.cmm.paul.grabber.Analyser.java

public Analyser analyse(Date lwmTimestamp, Date hwmTimestamp, DateRange queueRange, boolean checkHashes) {
    this.lwm = lwmTimestamp;
    this.hwm = hwmTimestamp;
    if (queueRange == null) {
        this.qStart = null;
        this.qEnd = null;
    } else {/* w  w  w  .  j ava  2 s.  c om*/
        this.qStart = queueRange.getFromDate();
        this.qEnd = queueRange.getToDate();
    }
    this.checkHashes = checkHashes;
    LOG.info("Analysing queues and folders for " + getFacility().getFacilityName());
    SortedSet<DatasetMetadata> inFolder = buildInFolderMetadata();
    SortedSet<DatasetMetadata> inDatabase = buildInDatabaseMetadata();
    LOG.debug("Got " + inFolder.size() + " in folders and " + inDatabase.size() + " in database");
    LOG.info("Grouping datasets for " + getFacility().getFacilityName());
    grouped = groupDatasets(inFolder, inDatabase);
    LOG.debug("Got " + grouped.size() + " groups");
    LOG.info("Gathering statistics for " + getFacility().getFacilityName());
    determineFolderRange(inFolder);
    all = gatherStats(grouped, PredicateUtils.truePredicate());
    if (hwmTimestamp == null || lwmTimestamp == null) {
        beforeLWM = null;
        afterHWM = null;
        intertidal = null;
    } else {
        final long lwmTime = lwmTimestamp.getTime();
        beforeLWM = gatherStats(grouped, new Predicate() {
            public boolean evaluate(Object metadata) {
                return ((DatasetMetadata) metadata).getLastFileTimestamp().getTime() < lwmTime;
            }
        });
        final long hwmTime = hwmTimestamp.getTime();
        afterHWM = gatherStats(grouped, new Predicate() {
            public boolean evaluate(Object metadata) {
                return ((DatasetMetadata) metadata).getLastFileTimestamp().getTime() > hwmTime;
            }
        });
        intertidal = gatherStats(grouped, new Predicate() {
            public boolean evaluate(Object metadata) {
                long time = ((DatasetMetadata) metadata).getLastFileTimestamp().getTime();
                return time >= lwmTime && time <= hwmTime;
            }
        });
    }
    if (queueRange == null) {
        afterQEnd = null;
        beforeQStart = null;
        inQueue = null;
    } else {
        final long qStart = this.qStart.getTime();
        beforeQStart = gatherStats(grouped, new Predicate() {
            public boolean evaluate(Object metadata) {
                return ((DatasetMetadata) metadata).getLastFileTimestamp().getTime() < qStart;
            }
        });
        final long qEnd = this.qEnd.getTime();
        afterQEnd = gatherStats(grouped, new Predicate() {
            public boolean evaluate(Object metadata) {
                return ((DatasetMetadata) metadata).getLastFileTimestamp().getTime() > qEnd;
            }
        });
        inQueue = gatherStats(grouped, new Predicate() {
            public boolean evaluate(Object metadata) {
                long ts = ((DatasetMetadata) metadata).getLastFileTimestamp().getTime();
                return ts >= qStart && ts <= qEnd;
            }
        });
    }
    LOG.info("Performing queue entry integrity checks for " + getFacility().getFacilityName());
    problems = integrityCheck(grouped);
    return this;
}

From source file:net.sourceforge.fenixedu.domain.candidacyProcess.erasmus.ApprovedLearningAgreementDocumentFile.java

protected List<ApprovedLearningAgreementExecutedAction> getSentEmailAcceptedStudentActions() {
    List<ApprovedLearningAgreementExecutedAction> executedActionList = new ArrayList<ApprovedLearningAgreementExecutedAction>();

    CollectionUtils.select(getExecutedActionsSet(), new Predicate() {

        @Override//from   ww  w  .  j a  va  2  s  .c o m
        public boolean evaluate(Object arg0) {
            return ((ApprovedLearningAgreementExecutedAction) arg0).isSentEmailAcceptedStudent();
        };

    }, executedActionList);

    Collections.sort(executedActionList, Collections.reverseOrder(ExecutedAction.WHEN_OCCURED_COMPARATOR));

    return executedActionList;
}

From source file:de.hybris.platform.b2bacceleratorfacades.order.populators.B2BApprovalDataPopulator.java

protected Predicate applyApprovalStagePredicate(final String orderApprovalStage) {
    return new Predicate() {
        @Override//w ww  . j  a v a  2 s  . com
        public boolean evaluate(final Object object) {
            final B2BOrderHistoryEntryData orderHistoryEntryData = (B2BOrderHistoryEntryData) object;
            if (orderHistoryEntryData.getPreviousOrderVersionData() != null) {
                final String previousOrderStatus = orderHistoryEntryData.getPreviousOrderVersionData()
                        .getStatus().toString();
                return (previousOrderStatus.contains(orderApprovalStage));
            }
            return false;
        }
    };
}

From source file:edu.kit.dama.util.release.GenerateSourceRelease.java

public static void updatePom(File destination, ReleaseConfiguration config)
        throws IOException, XmlPullParserException {
    File pomfile = new File(destination, "pom.xml");

    FileUtils.copyFile(pomfile, new File(destination, "pom.original.xml"));
    MavenXpp3Reader mavenreader = new MavenXpp3Reader();
    FileReader reader = new FileReader(pomfile);
    Model model = mavenreader.read(reader);
    model.setPomFile(pomfile);//w  w  w .  j  a  v  a2s. c  om

    if (config.isRemoveDevelopers()) {
        model.setDevelopers(new ArrayList<Developer>());
    }

    if (config.isRemoveDistributionManagement()) {
        model.setDistributionManagement(null);
    }

    if (config.isRemoveCiManagement()) {
        model.setCiManagement(null);
    }

    if (config.getScmConnection() != null || config.getScmUrl() != null) {
        Scm scm = new Scm();
        scm.setConnection(config.getScmConnection());
        scm.setUrl(config.getScmUrl());
        model.setScm(scm);
    }

    for (final String profile : config.getProfilesToRemove()) {

        Profile toRemove = (Profile) org.apache.commons.collections.CollectionUtils.find(model.getProfiles(),
                new Predicate() {
                    @Override
                    public boolean evaluate(Object o) {
                        return profile.equals(((Profile) o).getId());
                    }
                });

        if (toRemove != null) {
            model.getProfiles().remove(toRemove);
        }
    }

    for (final String plugin : config.getPluginsToRemove()) {

        Plugin toRemove = (Plugin) org.apache.commons.collections.CollectionUtils
                .find(model.getBuild().getPlugins(), new Predicate() {
                    @Override
                    public boolean evaluate(Object o) {
                        return plugin.equals(((Plugin) o).getArtifactId());
                    }
                });

        if (toRemove != null) {
            model.getBuild().getPlugins().remove(toRemove);
        }
    }

    for (final String module : config.getModulesToRemove()) {

        String toRemove = (String) org.apache.commons.collections.CollectionUtils.find(model.getModules(),
                new Predicate() {
                    @Override
                    public boolean evaluate(Object o) {
                        return module.equals((String) o);
                    }
                });

        if (toRemove != null) {
            model.getModules().remove(toRemove);
        }
    }

    for (String property : config.getPropertiesToRemove()) {
        model.getProperties().remove(property);
    }

    Set<Entry<String, String>> entries = config.getPropertiesToSet().entrySet();

    for (Entry<String, String> entry : entries) {
        model.getProperties().put(entry.getKey(), entry.getValue());
    }

    if (config.getLocalDependencies().length != 0) {
        //add local dependencies
        for (Dependency dependency : config.getLocalDependencies()) {
            String groupId = dependency.getGroupId();
            String artifactId = dependency.getArtifactId();
            String version = dependency.getVersion();
            String dependencyPath = groupId.replaceAll("\\.", File.separator) + File.separator + artifactId
                    + File.separator + version;
            String mavenRepoPath = MAVEN_REPOSITORY + File.separator + dependencyPath;
            String localRepoPath = config.getDestinationDirectory() + File.separator + "srcRelease"
                    + File.separator + "libs" + File.separator + dependencyPath;
            if (!new File(localRepoPath).mkdirs() && !new File(localRepoPath).exists()) {
                throw new IOException("Failed to create local repository path at " + localRepoPath);
            }
            String artifactFileName = artifactId + "-" + version + ".jar";
            String pomFileName = artifactId + "-" + version + ".pom";

            File artifact = new File(mavenRepoPath, artifactFileName);
            File pom = new File(mavenRepoPath, pomFileName);
            if (artifact.exists() && pom.exists()) {
                FileUtils.copyFile(artifact, new File(localRepoPath, artifactFileName));
                FileUtils.copyFile(pom, new File(localRepoPath, pomFileName));
            } else {
                throw new IOException("Dependency " + groupId + ":" + artifactId + ":" + version
                        + " not found at " + mavenRepoPath);
            }
        }

        //check local repo                
        boolean haveLocalRepo = false;
        for (Repository repository : model.getRepositories()) {
            String repoUrl = repository.getUrl();
            URL u = new URL(repoUrl);
            if ("file".equals(u.getProtocol())) {
                haveLocalRepo = true;
                break;
                /**
                 * <repository>
                 * <id>localRepository</id>
                 * <url>file://${basedir}/${root.relative.path}/libs</url>
                 * </repository>
                 */
            }
        }

        if (!haveLocalRepo) {
            //add local repo
            Repository localRepository = new Repository();
            localRepository.setId("localRepository");
            localRepository.setUrl("file://${basedir}/lib/");
            localRepository.setName("Local file repository");
            model.getRepositories().add(0, localRepository);
        }
    }

    // MavenProject project = new MavenProject(model);
    //check parent (fail if exists)
    //
    MavenXpp3Writer mavenwriter = new MavenXpp3Writer();
    mavenwriter.write(new FileOutputStream(new File(destination, "pom.xml")), model);
}

From source file:net.sourceforge.fenixedu.domain.candidacyProcess.CandidacyProcess.java

public List<IndividualCandidacyProcess> getChildsWithMissingRequiredDocuments() {
    List<IndividualCandidacyProcess> childs = new ArrayList<IndividualCandidacyProcess>();

    CollectionUtils.select(getChildProcessesSet(), new Predicate() {

        @Override// w  w w .  j av a  2  s.c  om
        public boolean evaluate(Object arg0) {
            IndividualCandidacyProcess process = (IndividualCandidacyProcess) arg0;
            return !process.isCandidacyCancelled() && process.isProcessMissingRequiredDocumentFiles();
        }

    }, childs);

    return childs;
}

From source file:gov.nih.nci.ncicb.tcga.dcc.datareports.service.DatareportsServiceImpl.java

public List<Predicate> genListPredicates(final Class clazz, final List<String> valueList, final String getter) {
    List<Predicate> predList = null;
    if (valueList != null) {
        predList = new LinkedList<Predicate>();
        for (final String strValue : valueList) {
            predList.add(new Predicate() {
                public boolean evaluate(Object o) {
                    try {
                        final Method m = GetterMethod.getGetter(clazz, getter);
                        final Object obj = m.invoke(clazz.cast(o));
                        final String str = obj == null ? "" : obj.toString();
                        return strValue.equalsIgnoreCase(str);
                    } catch (Exception e) {
                        logger.debug(FancyExceptionLogger.printException(e));
                        return true;
                    }//from   ww  w . j  a  va 2s  . co m
                }
            });
        }
    }
    return predList;
}

From source file:com.zuora.api.object.Dynamic.java

private static Element getElement(Dynamic object, final String name) {
    try {//from w  ww .j  a va 2  s.com
        return (Element) CollectionUtils.find(object.getAny(), new Predicate() {
            public boolean evaluate(Object object) {
                return object instanceof Element && ((Element) object).getLocalName().equals(name);
            }
        });
    } catch (UnsupportedOperationException e) {
        throw new UnsupportedOperationException("There is no property " + name, e);
    }
}

From source file:de.hybris.platform.integration.cis.payment.cronjob.DefaultCisFraudReportJob.java

@Override
public PerformResult perform(final CisFraudReportCronJobModel cronJob) {
    try {//w ww  . j av  a 2 s.  c om
        final CisFraudReportRequest request = new CisFraudReportRequest();
        final Date requestStartTime = getLastCronJobEndTime();
        final Date requestEndTime = new Date();
        final Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.HOUR, -24);

        if (requestStartTime.before(calendar.getTime())) {
            LOG.error("CyberSource report time range is only valid for the past 24 hours");
            return new PerformResult(CronJobResult.ERROR, CronJobStatus.ABORTED);
        }

        request.setStartDateTime(requestStartTime);
        request.setEndDateTime(requestEndTime);
        final RestResponse<CisFraudReportResult> response = getOndemandHystrixCommandFactory().newCommand(
                getHystrixCommandConfig(), new HystrixExecutable<RestResponse<CisFraudReportResult>>() {
                    @Override
                    public RestResponse<CisFraudReportResult> runEvent() {
                        return getFraudClient().generateFraudReport(cronJob.getCode(), request);
                    }

                    @Override
                    public RestResponse<CisFraudReportResult> fallbackEvent() {
                        return null;
                    }

                    @Override
                    public RestResponse<CisFraudReportResult> defaultEvent() {
                        return null;
                    }
                }).execute();

        if (response != null) {
            final List<CisFraudTransactionResult> transactionResults = response.getResult().getTransactions();

            if (CollectionUtils.isNotEmpty(transactionResults)) {
                //Retrieve all the transactionIds from each of the transaction results
                final List<String> transactionIds = (List<String>) CollectionUtils.collect(transactionResults,
                        new Transformer() {
                            @Override
                            public Object transform(final Object o) {
                                final CisFraudTransactionResult result = (CisFraudTransactionResult) o;

                                return result.getClientAuthorizationId();
                            }
                        });

                final List<PaymentTransactionEntryModel> transactionEntries = getPaymentTransactionEntryModels(
                        transactionIds);

                //For each transaction result, set the transaction from it's corresponding order and fire the business process event
                for (final CisFraudTransactionResult transactionResult : transactionResults) {
                    final PaymentTransactionEntryModel transactionEntry = (PaymentTransactionEntryModel) CollectionUtils
                            .find(transactionEntries, new Predicate() {
                                @Override
                                public boolean evaluate(final Object o) {
                                    return ((PaymentTransactionEntryModel) o).getCode()
                                            .equalsIgnoreCase(transactionResult.getClientAuthorizationId());
                                }
                            });

                    if (transactionEntry != null && transactionEntry.getPaymentTransaction() != null
                            && transactionEntry.getPaymentTransaction().getOrder() != null) {
                        final PaymentTransactionModel transaction = transactionEntry.getPaymentTransaction();
                        final String guid = transaction.getOrder().getGuid();

                        final PaymentTransactionEntryModel newTransactionEntry = getTransactionResultConverter()
                                .convert(transactionResult);
                        getPaymentService().setPaymentTransactionReviewResult(newTransactionEntry, guid);
                    }
                }
            }

            //Set the LastFraudReportEndTime for use the next time this cron job runs
            cronJob.setLastFraudReportEndTime(requestEndTime);
            getModelService().save(cronJob);

            return new PerformResult(CronJobResult.SUCCESS, CronJobStatus.FINISHED);
        }

        return new PerformResult(CronJobResult.ERROR, CronJobStatus.ABORTED);
    } catch (final Exception e) {
        LOG.warn(String.format("Error occurred while processing the fraud reports [%s]",
                e.getLocalizedMessage()));
        if (LOG.isDebugEnabled()) {
            LOG.debug("Error occurred while processing the fraud reports", e);
        }
        return new PerformResult(CronJobResult.ERROR, CronJobStatus.ABORTED);
    }
}

From source file:gov.nih.nci.firebird.selenium2.pages.sponsor.protocol.EditProtocolJavaScriptHelper.java

public Predicate getOnClosePredicate() {
    return new Predicate() {
        @Override/*from   w w w.j av  a 2  s  . com*/
        public boolean evaluate(Object object) {
            return !isFormModified() || Boolean.TRUE.equals(object);
        }
    };
}

From source file:com.perceptive.epm.perkolcentral.action.ajax.EmployeeDetailsAction.java

public String executeGetAllEmployees() throws ExceptionWrapper {
    try {//w w w. j a v  a2s  . c o  m
        Soundex sndx = new Soundex();
        DoubleMetaphone doubleMetaphone = new DoubleMetaphone();
        final StringEncoderComparator comparator1 = new StringEncoderComparator(doubleMetaphone);

        LoggingHelpUtil.printDebug("Page " + getPage() + " Rows " + getRows() + " Sorting Order " + getSord()
                + " Index Row :" + getSidx());
        LoggingHelpUtil.printDebug("Search :" + searchField + " " + searchOper + " " + searchString);

        // Calcalate until rows ware selected
        int to = (rows * page);

        // Calculate the first row to read
        int from = to - rows;
        LinkedHashMap<Long, EmployeeBO> employeeLinkedHashMap = new LinkedHashMap<Long, EmployeeBO>();

        employeeLinkedHashMap = employeeBL.getAllEmployees();
        ArrayList<EmployeeBO> allEmployees = new ArrayList<EmployeeBO>(employeeLinkedHashMap.values());
        //Handle search
        if (searchOper != null && !searchOper.trim().equalsIgnoreCase("") && searchString != null
                && !searchString.trim().equalsIgnoreCase("")) {
            if (searchOper.trim().equalsIgnoreCase("eq")) {
                CollectionUtils.filter(allEmployees, new Predicate() {
                    @Override
                    public boolean evaluate(Object o) {
                        return ((EmployeeBO) o).getEmployeeName().equalsIgnoreCase(searchString.trim()); //To change body of implemented methods use File | Settings | File Templates.
                    }
                });
            } else if (searchOper.trim().equalsIgnoreCase("slk")) {
                CollectionUtils.filter(allEmployees, new Predicate() {
                    @Override
                    public boolean evaluate(Object o) {
                        return (new StringEncoderComparator(new Soundex()).compare(
                                ((EmployeeBO) o).getEmployeeName().toLowerCase(),
                                searchString.trim().toLowerCase()) == 0
                                || new StringEncoderComparator(new DoubleMetaphone()).compare(
                                        ((EmployeeBO) o).getEmployeeName().toLowerCase(),
                                        searchString.trim().toLowerCase()) == 0
                                || new StringEncoderComparator(new Metaphone()).compare(
                                        ((EmployeeBO) o).getEmployeeName().toLowerCase(),
                                        searchString.trim().toLowerCase()) == 0
                                || new StringEncoderComparator(new RefinedSoundex()).compare(
                                        ((EmployeeBO) o).getEmployeeName().toLowerCase(),
                                        searchString.trim().toLowerCase()) == 0); //To change body of implemented methods use File | Settings | File Templates.
                    }
                });
            } else {
                //First check whether there is an exact match
                if (CollectionUtils.exists(allEmployees, new Predicate() {
                    @Override
                    public boolean evaluate(Object o) {
                        return (((EmployeeBO) o).getEmployeeName().toLowerCase()
                                .contains(searchString.trim().toLowerCase())); //To change body of implemented methods use File | Settings | File Templates.
                    }
                })) {
                    CollectionUtils.filter(allEmployees, new Predicate() {
                        @Override
                        public boolean evaluate(Object o) {
                            return (((EmployeeBO) o).getEmployeeName().toLowerCase()
                                    .contains(searchString.trim().toLowerCase()));
                        }
                    });
                } else {
                    ArrayList<String> matchedEmployeeIds = employeeBL.getLuceneUtil()
                            .getBestMatchEmployeeName(searchString.trim().toLowerCase());
                    allEmployees = new ArrayList<EmployeeBO>();
                    for (String id : matchedEmployeeIds) {
                        allEmployees.add(employeeBL.getAllEmployees().get(Long.valueOf(id)));
                    }
                }
            }

            /*{
            CollectionUtils.filter(allEmployees, new Predicate() {
                @Override
                public boolean evaluate(Object o) {
                    if (((EmployeeBO) o).getEmployeeName().toLowerCase().contains(searchString.trim().toLowerCase()))
                        return true;
                    else if(new StringEncoderComparator(new Soundex()).compare(((EmployeeBO) o).getEmployeeName().toLowerCase(), searchString.trim().toLowerCase()) == 0
                            || new StringEncoderComparator(new DoubleMetaphone()).compare(((EmployeeBO) o).getEmployeeName().toLowerCase(), searchString.trim().toLowerCase()) == 0)
                    {
                        return true;
                    }
                    else {
                        for (String empNameParts : ((EmployeeBO) o).getEmployeeName().trim().split(" ")) {
                            if (new StringEncoderComparator(new Soundex()).compare(empNameParts.toLowerCase(), searchString.trim().toLowerCase()) == 0
                                    || new StringEncoderComparator(new DoubleMetaphone()).compare(empNameParts.toLowerCase(), searchString.trim().toLowerCase()) == 0
                                //    || new StringEncoderComparator(new Metaphone()).compare(empNameParts.toLowerCase(), searchString.trim().toLowerCase()) == 0
                                //    || new StringEncoderComparator(new RefinedSoundex()).compare(empNameParts.toLowerCase(), searchString.trim().toLowerCase()) == 0
                                    ) {
                                return true;
                            }
                        }
                        return false;
                    }
                    
                    
                }
            });
            } */
        }
        //// Handle Order By
        if (sidx != null && !sidx.equals("")) {

            Collections.sort(allEmployees, new Comparator<EmployeeBO>() {
                public int compare(EmployeeBO e1, EmployeeBO e2) {
                    if (sidx.equalsIgnoreCase("employeeName"))
                        return sord.equalsIgnoreCase("asc")
                                ? e1.getEmployeeName().compareTo(e2.getEmployeeName())
                                : e2.getEmployeeName().compareTo(e1.getEmployeeName());
                    else if (sidx.equalsIgnoreCase("jobTitle"))
                        return sord.equalsIgnoreCase("asc") ? e1.getJobTitle().compareTo(e2.getJobTitle())
                                : e2.getJobTitle().compareTo(e1.getJobTitle());
                    else if (sidx.equalsIgnoreCase("manager"))
                        return sord.equalsIgnoreCase("asc") ? e1.getManager().compareTo(e2.getManager())
                                : e2.getManager().compareTo(e1.getManager());
                    else
                        return sord.equalsIgnoreCase("asc")
                                ? e1.getEmployeeName().compareTo(e2.getEmployeeName())
                                : e2.getEmployeeName().compareTo(e1.getEmployeeName());
                }
            });

        }
        //

        records = allEmployees.size();
        total = (int) Math.ceil((double) records / (double) rows);

        gridModel = new ArrayList<EmployeeBO>();
        to = to > records ? records : to;
        for (int iCounter = from; iCounter < to; iCounter++) {
            EmployeeBO employeeBO = allEmployees.get(iCounter);
            //new EmployeeBO((Employee) employeeLinkedHashMap.values().toArray()[iCounter]);
            gridModel.add(employeeBO);
        }

    } catch (Exception ex) {
        throw new ExceptionWrapper(ex);

    }
    return SUCCESS;
}