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

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

Introduction

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

Prototype

public static Object find(Collection collection, Predicate predicate) 

Source Link

Document

Finds the first element in the given collection which matches the given predicate.

Usage

From source file:de.hybris.platform.acceleratorservices.cronjob.SiteMapMediaJob.java

protected SiteMapGenerator getGeneratorForSiteMapPage(final SiteMapPageEnum siteMapPageEnum) {

    return (SiteMapGenerator) CollectionUtils.find(getGenerators(), new Predicate() {
        @Override/* w ww .  j ava2s. c o m*/
        public boolean evaluate(final Object o) {
            return ((SiteMapGenerator) o).getSiteMapPageEnum().equals(siteMapPageEnum);
        }
    });
}

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

private static Element getElement(Dynamic object, final String name) {
    try {/*from w w w. j a v a 2  s . c o m*/
        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 . jav 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:com.netthreads.mavenize.Pommel.java

/**
 * Process pom files with defined old and new dependency mappings.
 * //w ww. j a  va  2  s. c om
 * @param pomFiles
 * @param mappings 
 */
private void processDependencyMappings(List<File> files, List<Mapping> mappings) {
    for (File file : files) {
        String pomPath = file.getAbsolutePath();

        try {
            // Read pom
            Model model = readPom(pomPath);

            List<Dependency> dependencies = model.getDependencies();

            // Save us writing back poms we didn't update.
            boolean sticky = false;

            for (Dependency dependency : dependencies) {
                // Check each dependency
                Predicate searchPredicate = new DependencyPredicate(dependency.getGroupId(),
                        dependency.getArtifactId(), dependency.getVersion());
                Mapping target = (Mapping) CollectionUtils.find(mappings, searchPredicate);

                if (target != null) {
                    logger.debug(dependency.getGroupId() + ", " + dependency.getArtifactId() + " : "
                            + target.getDependencyTarget().getGroupId() + ", "
                            + target.getDependencyTarget().getArtifactId());

                    DependencyTarget dependencyTarget = target.getDependencyTarget();
                    dependency.setGroupId(dependencyTarget.getGroupId());
                    dependency.setArtifactId(dependencyTarget.getArtifactId());
                    dependency.setVersion(dependencyTarget.getVersion());
                    String scope = dependencyTarget.getScope();
                    if (scope != null) {
                        dependency.setScope(scope);
                    }

                    sticky = true; // Must write back
                }
            }

            // If altered then save back
            if (sticky) {
                logger.info("Writing " + file.getAbsolutePath());
                writePom(model, file);
            }

        } catch (Exception ex) {
            logger.error("Couldn't read pom, " + pomPath);
        }
    }

}

From source file:de.hybris.platform.b2b.services.impl.DefaultB2BOrderServiceTest.java

@Test
public void testOrderComment() throws Exception {
    final OrderModel order = createOrder(1);

    final B2BCommentModel b2BCommentModel = modelService.create(B2BCommentModel.class);
    b2BCommentModel.setCode("QuoteRequest");
    b2BCommentModel.setComment("Requesting 5% discount.");
    b2BCommentModel.setModifiedDate(new Date());

    final Date modifiedDate = DateUtils.addDays(b2BCommentModel.getModifiedDate(), 10);
    order.setQuoteExpirationDate(modifiedDate);
    order.setB2bcomments(Collections.singletonList(b2BCommentModel));
    modelService.save(order);/*from  w w  w  .j a  v  a 2 s .  co  m*/

    final OrderModel retrievedOrder = b2bOrderService.getOrderForCode(order.getCode());
    final List<B2BCommentModel> retrievedComments = (List<B2BCommentModel>) retrievedOrder.getB2bcomments();

    Assert.assertNotNull(CollectionUtils.find(retrievedComments,
            new BeanPropertyValueEqualsPredicate(B2BCommentModel.CODE, "QuoteRequest")));

    Assert.assertTrue(order.getQuoteExpirationDate().equals(modifiedDate));
}

From source file:net.sourceforge.fenixedu.dataTransferObject.CurricularCourseScopesForPrintDTO.java

private DegreeCurricularPlanForPrintDTO getSelectedCurricularPlan(final InfoCurricularCourseScope scope) {
    DegreeCurricularPlanForPrintDTO selectedCurricularPlan = (DegreeCurricularPlanForPrintDTO) CollectionUtils
            .find(getDegreeCurricularPlans(), new Predicate() {

                @Override/*from  w  w  w  .j  a v a  2 s.c  o m*/
                public boolean evaluate(Object arg0) {
                    DegreeCurricularPlanForPrintDTO degreeCurricularPlanForPrintDTO = (DegreeCurricularPlanForPrintDTO) arg0;
                    if (degreeCurricularPlanForPrintDTO.name
                            .equals(scope.getInfoCurricularCourse().getInfoDegreeCurricularPlan().getName())) {
                        return true;
                    }

                    return false;
                }
            });

    if (selectedCurricularPlan == null) {
        InfoDegreeCurricularPlan degreeCurricularPlan = scope.getInfoCurricularCourse()
                .getInfoDegreeCurricularPlan();
        selectedCurricularPlan = new DegreeCurricularPlanForPrintDTO(degreeCurricularPlan.getName(),
                degreeCurricularPlan.getInfoDegree().getNome(), degreeCurricularPlan.getAnotation());
        this.getDegreeCurricularPlans().add(selectedCurricularPlan);
    }

    return selectedCurricularPlan;
}

From source file:com.linkedin.pinot.common.data.Schema.java

@JsonIgnore(true)
public MetricFieldSpec getMetricSpec(final String metricName) {
    return (MetricFieldSpec) CollectionUtils.find(metricFieldSpecs, new Predicate() {
        @Override//from  w w  w. j a v a  2 s  .  c  o m
        public boolean evaluate(Object object) {
            if (object instanceof MetricFieldSpec) {
                MetricFieldSpec spec = (MetricFieldSpec) object;
                return spec.getName().equals(metricName);
            }

            return false;
        }
    });
}

From source file:edu.kit.dama.mdm.admin.UserPropertyCollection.java

/**
 * Set the value of property with key pKey to pValue. If there is no property
 * with the provided key, a new property is added. If the provided value is
 * null, the property with the provided key will be removed.
 *
 * @param pKey The property key. This value must not be null.
 * @param pValue The property value. If pValue is null, the property will be
 * removed.//from  www.j a  v a 2 s  .  co m
 *
 * @return TRUE if a property has been modified/added/removed, FALSE if the
 * removal failed.
 */
public boolean setStringProperty(final String pKey, String pValue) {
    if (pKey == null) {
        throw new IllegalArgumentException("Argument pKey must not be null");
    }
    boolean result = true;

    if (pValue == null) {
        LOGGER.debug("Provided property value is null. Removing property.");
        return removeProperty(pKey);
    }

    LOGGER.debug("Setting property with key {} to value {}", new Object[] { pKey, pValue });
    UserProperty existingProp = (UserProperty) CollectionUtils.find(properties, new Predicate() {
        @Override
        public boolean evaluate(Object o) {
            return ((UserProperty) o).getPropertyKey().equals(pKey);
        }
    });
    if (existingProp == null) {
        LOGGER.debug("Adding new property");
        properties.add(new UserProperty(pKey, pValue));
    } else {
        LOGGER.debug("Updating existing property");
        existingProp.setPropertyValue(pValue);
    }
    return result;
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.department.ReadTeacherProfessorshipsByExecutionYearAction.java

private void prepareConstants(User userView, InfoTeacher infoTeacher, HttpServletRequest request)
        throws FenixServiceException {

    List executionYears = ReadNotClosedExecutionYears.run();

    InfoExecutionYear infoExecutionYear = (InfoExecutionYear) CollectionUtils.find(executionYears,
            new Predicate() {
                @Override/*from  ww w . j a  v  a  2 s.  co m*/
                public boolean evaluate(Object arg0) {
                    InfoExecutionYear infoExecutionYearElem = (InfoExecutionYear) arg0;
                    if (infoExecutionYearElem.getState().equals(PeriodState.CURRENT)) {
                        return true;
                    }
                    return false;
                }
            });

    Department department = infoTeacher.getTeacher().getCurrentWorkingDepartment();
    InfoDepartment teacherDepartment = InfoDepartment.newInfoFromDomain(department);

    if (userView == null || !userView.getPerson().hasRole(RoleType.CREDITS_MANAGER)) {

        final Collection<Department> departmentList = userView.getPerson().getManageableDepartmentCreditsSet();
        request.setAttribute("isDepartmentManager", Boolean.valueOf(departmentList.contains(department)));

    } else {
        request.setAttribute("isDepartmentManager", Boolean.FALSE);
    }

    request.setAttribute("teacherDepartment", teacherDepartment);
    request.setAttribute("executionYear", infoExecutionYear);
    request.setAttribute("executionYears", executionYears);
}

From source file:com.linkedin.pinot.common.data.Schema.java

@JsonIgnore(true)
public DimensionFieldSpec getDimensionSpec(final String dimensionName) {
    return (DimensionFieldSpec) CollectionUtils.find(dimensionFieldSpecs, new Predicate() {
        @Override//from   w ww.  jav  a2s .c  o m
        public boolean evaluate(Object object) {
            if (object instanceof DimensionFieldSpec) {
                DimensionFieldSpec spec = (DimensionFieldSpec) object;
                return spec.getName().equals(dimensionName);
            }
            return false;
        }
    });
}