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:org.mifos.accounts.loan.struts.action.validate.ProductMixValidator.java

boolean isCustomerACoSigningClient(final CustomerBO customer, LoanBO loan) throws ServiceException {
    return CollectionUtils.find(getCosigningClientsForLoan(loan), new Predicate() {
        @Override/*from w  w  w .ja  va 2s . co  m*/
        public boolean evaluate(Object arg0) {
            return customer.getCustomerId().equals(((CustomerBO) arg0).getCustomerId());
        }
    }) != null;
}

From source file:org.mifos.reports.branchreport.BranchReportBO.java

public BranchReportClientSummaryBO getClientSummary(Predicate predicate) {
    return (BranchReportClientSummaryBO) CollectionUtils.find(clientSummaries, predicate);
}

From source file:org.mifos.reports.branchreport.helper.BranchReportClientSummaryBatchBOExtractor.java

private BranchReportClientSummaryBO getClientSummary(Predicate predicate) {
    return (BranchReportClientSummaryBO) CollectionUtils.find(clientSummaries, predicate);
}

From source file:org.mifos.reports.business.validator.ReportParameterValidatorFactory.java

@SuppressWarnings("unchecked")
public ReportParameterValidator<ReportParameterForm> getValidator(final String reportFilePath) {
    initValidators();// w  ww  .j ava 2  s  .  com
    return (ReportParameterValidator<ReportParameterForm>) CollectionUtils.find(validators, new Predicate() {
        @Override
        public boolean evaluate(Object validator) {
            return ((ReportParameterValidator<ReportParameterForm>) validator)
                    .isApplicableToReportFilePath(reportFilePath);
        }
    });
}

From source file:org.motechproject.server.event.impl.ExpectedCareMessageProgram.java

protected ScheduledMessage getMatchingScheduledMessage(List<ScheduledMessage> scheduledMessagesList,
        ScheduledMessagePredicate scheduledMessagePredicate) {
    return (ScheduledMessage) CollectionUtils.find(scheduledMessagesList, scheduledMessagePredicate);
}

From source file:org.netbeans.jmiimpl.omg.uml.modelmanagement.UmlPackageImpl.java

public UmlPackage getChildPackage(String name, boolean create) {
    org.omg.uml.modelmanagement.UmlPackage current = this;

    if (name != null && name.length() > 0) {
        String[] names = name.split("\\.");
        CorePackage core = ((org.omg.uml.UmlPackage) refOutermostPackage()).getCore();
        UmlPackageClass namespaceClass = ((ModelManagementPackage) refImmediatePackage()).getUmlPackage();

        for (int i = 0; i < names.length; i++) {
            final String s = names[i];
            final UmlPackage currentCopy = current;
            Object l = CollectionUtils.find(namespaceClass.refAllOfType(), new Predicate() {

                public boolean evaluate(Object object) {
                    return object != null && ((UmlPackage) object).getNamespace() == currentCopy
                            && ((UmlPackage) object).getName().equals(s);
                }//w  w  w .  j a  v  a2 s  .c o m
            });

            if (l == null) {
                if (create) {
                    // add Namespace and make it current
                    UmlPackage newUmlPackage = namespaceClass.createUmlPackage();
                    newUmlPackage.setName(s);
                    core.getANamespaceOwnedElement().add(current, newUmlPackage);
                    current = newUmlPackage;
                } else {
                    throw new RuntimeException("'" + name + "' not found and create disabled");
                }
            } else {
                current = (UmlPackage) l;
            }
        }
    }
    return current;
}

From source file:org.onebusaway.nyc.sms.actions.IndexAction.java

public String execute() throws Exception {

    if (_googleAnalytics == null)
        initAnalytics();/*  ww w  .j  a v a2s .  co  m*/

    SearchResultFactory _resultFactory = new SearchResultFactoryImpl(_nycTransitDataService, _realtimeService,
            _configurationService);

    String commandString = getCommand(_query);
    String queryString = getQuery(_query);

    if (queryString != null && !queryString.isEmpty()) {
        _lastQuery = queryString;
        _searchResults = _searchService.getSearchResults(queryString, _resultFactory);
    } else if (commandString != null && commandString.equals("R") && _lastQuery != null
            && !_lastQuery.isEmpty()) {
        _searchResults = _searchService.getSearchResults(_lastQuery, _resultFactory);
    } else if (_searchResults != null && "StopResult".equals(_searchResults.getResultType())
            && commandString != null && getRoutesInSearchResults().contains(commandString)) {
        // We are all set, let the existing stop results be processed given the route command string
    } else if (_searchResults != null && "StopResult".equals(_searchResults.getResultType())
            && commandString != null && StringUtils.isNumeric(commandString)) {
        // We are all set, let the existing stop results be processed given the number (which is the users choice of stop) command string
    } else if ((queryString == null || queryString.isEmpty()) && commandString != null && _searchResults != null
            && _searchResults.getSuggestions().size() > 0) {
        // We have suggestions with a command string for picking one of them or paginating
    } else if (queryString == null || queryString.isEmpty()) {
        _response = errorResponse("No results.");
        return SUCCESS;
    }

    while (true) {
        if (_searchResults.getMatches().size() > 0) {
            // route identifier search
            if (_searchResults.getMatches().size() == 1
                    && "RouteResult".equals(_searchResults.getResultType())) {
                RouteResult route = (RouteResult) _searchResults.getMatches().get(0);

                // If we get a route back, but there is no direction information in it,
                // this is a route in the bundle with no trips/stops/etc.
                // Show no results.
                if (route.getDirections() != null && route.getDirections().size() == 0) {
                    _response = errorResponse("No results.");
                    break;

                } else if (commandString != null && commandString.equals("C")) {
                    // find a unique set of service alerts for the route found
                    Set<String> alerts = new HashSet<String>();
                    for (RouteDirection direction : route.getDirections()) {
                        for (NaturalLanguageStringBean alert : direction.getSerivceAlerts()) {
                            alerts.add(alert.getValue());
                        }
                    }

                    // make the alerts into results
                    SearchResultCollection newResults = new SearchResultCollection();
                    for (String alert : alerts) {
                        newResults.addMatch(new ServiceAlertResult(alert));
                    }

                    if (newResults.getMatches().size() == 0) {
                        _response = errorResponse("No " + route.getShortName() + " alerts.");
                        break;
                    }

                    _searchResults = newResults;
                    continue;

                    // route schedule status
                } else {
                    _response = routeResponse(route);
                    break;
                }

                // paginated service alerts
            } else if ("ServiceAlertResult".equals(_searchResults.getResultType())) {
                if (commandString != null && commandString.equals("N")) {
                    _response = serviceAlertResponse(_searchResultsCursor);
                } else {
                    _response = serviceAlertResponse(0);
                }
                break;

                // one or more paginated stops
            } else if ("StopResult".equals(_searchResults.getResultType())) {
                if (commandString != null && commandString.equals("N")) {

                    _response = directionDisambiguationResponse();

                } else if (_searchResults.getMatches().size() > 1 && commandString != null
                        && getRoutesInSearchResults().contains(commandString)) {
                    // We presented a list of routes for nearby stops to the user and they chose a route.
                    // Filter the search results to those that contain the chosen route and have the user
                    // pick a direction.

                    // Filter the result set to only the ones containing the chosen route in each direction
                    // might have to do a quick fake search to get a filter object
                    SearchResultCollection justToGetAFilter = _searchService
                            .getSearchResults("00000 " + commandString, _resultFactory);
                    _searchResults.getRouteFilter().clear();
                    _searchResults.addRouteFilters(justToGetAFilter.getRouteFilter());

                    // Filter the stop results down to the provided route for only up to one stop in each direction
                    filterStopSearchResultsToRouteFilterAndDirection();

                    // If there is only one stop after filtering, choose it for the user and don't display the direction disambiguation screen
                    if (_searchResults.getMatches().size() == 1) {
                        commandString = "1";
                        continue;
                    }

                    _response = directionDisambiguationResponse();

                } else if (StringUtils.isNumeric(commandString)) {

                    StopResult selectedStop = (StopResult) _searchResults.getMatches()
                            .get(Integer.parseInt(commandString) - 1);
                    _searchResults.getMatches().clear();
                    _searchResults.getMatches().add(selectedStop);

                    if (_searchResults.getRouteFilter().size() > 0) {
                        RouteBean routeBean = (RouteBean) _searchResults.getRouteFilter().toArray()[0];
                        _lastQuery = selectedStop.getIdWithoutAgency() + " " + routeBean.getShortName();
                    } else {
                        _lastQuery = selectedStop.getIdWithoutAgency();
                    }

                    _response = singleStopResponse(null);
                    _searchResults = null;

                } else if (_searchResults.getMatches().size() > 1) {

                    // See if there is a stop in search results that matches our route if filter
                    StopResult aStopServingRouteInFilter = (StopResult) CollectionUtils
                            .find(_searchResults.getMatches(), new Predicate() {

                                @Override
                                public boolean evaluate(Object object) {
                                    StopResult stopResult = (StopResult) object;
                                    if (stopResult.matchesRouteIdFilter()) {
                                        return true;
                                    }
                                    return false;
                                }
                            });

                    // If there is a stop matching our route id filter and there is a route id filter (if filter is empty or null, everything in
                    // search results 'matches' the filter) present the direction disambiguation view.
                    if (aStopServingRouteInFilter != null && _searchResults.getRouteFilter() != null
                            && _searchResults.getRouteFilter().size() > 0) {
                        _response = directionDisambiguationResponse();

                        // If there is only one route served by the stops in our search results, set the command
                        // string as if the user had chosen this route. We are skipping asking them to do that.
                    } else if (getRoutesInSearchResults().size() == 1) {

                        commandString = getRoutesInSearchResults().first();
                        continue;

                        // There is more than one route served by the stops in our results and 
                        // either there is no route id filter or none of our search results match the filter, so present
                        // the multiple stop response
                    } else {
                        _response = multipleStopResponse();
                    }
                } else if (_searchResults.getMatches().size() == 1) {

                    StopResult stopResult = (StopResult) _searchResults.getMatches().get(0);

                    // Check for case where there is a route id filter, but no service for
                    // that route for the stop in question.
                    if (!stopResult.matchesRouteIdFilter()) {

                        // Search for nearby stops
                        SearchResultCollection nearbyStops = _searchService.findStopsNearPoint(
                                stopResult.getStop().getLat(), stopResult.getStop().getLon(), _resultFactory,
                                _searchResults.getRouteFilter());

                        // See if there is at least one stop of the nearby stops that serves the route in the filter
                        StopResult aNearbyStopServingRouteInFilter = (StopResult) CollectionUtils
                                .find(nearbyStops.getMatches(), new Predicate() {

                                    @Override
                                    public boolean evaluate(Object object) {
                                        StopResult stopResult = (StopResult) object;
                                        if (stopResult.matchesRouteIdFilter()) {
                                            return true;
                                        }
                                        return false;
                                    }
                                });

                        // If we found nearby stops that service the route(s) in the filter, add those stops to our
                        // search results and call the method that knows how to display them.
                        if (aNearbyStopServingRouteInFilter != null) {

                            _response = singleStopWrongFilterNearbyResponse();
                            _searchResults = nearbyStops;

                            // We can't find nearby stops that service the route in the filter
                            // so call the method that lets the user know that.
                        } else {
                            RouteBean routeBean = (RouteBean) _searchResults.getRouteFilter().toArray()[0];
                            _searchResults = _searchService.getSearchResults(stopResult.getIdWithoutAgency(),
                                    _resultFactory);
                            _lastQuery = stopResult.getIdWithoutAgency();
                            _response = singleStopResponse("No " + routeBean.getShortName() + " stops nearby");
                            _searchResults = null;
                        }
                    } else {
                        _response = singleStopResponse(null);
                        _searchResults = null;
                    }
                }
                break;

                // an exact match for a location--i.e. location isn't ambiguous
            } else if (_searchResults.getMatches().size() == 1
                    && "GeocodeResult".equals(_searchResults.getResultType())) {
                GeocodeResult geocodeResult = (GeocodeResult) _searchResults.getMatches().get(0);

                // we don't do anything with regions--too much information to show via SMS.
                if (geocodeResult.isRegion()) {
                    _response = errorResponse("Too general.");
                    break;

                    // find stops near the point/address/intersection the user provided
                } else {
                    _searchResults = _searchService.findStopsNearPoint(geocodeResult.getLatitude(),
                            geocodeResult.getLongitude(), _resultFactory, _searchResults.getRouteFilter());
                    _searchResults.setQueryLat(geocodeResult.getLatitude());
                    _searchResults.setQueryLon(geocodeResult.getLongitude());
                    continue;

                }
            }
        }

        // process suggestions: suggestions can be ambiguous locations, or 
        // multiple routes--e.g. X17 -> X17A,C,J
        if (_searchResults.getSuggestions().size() > 0) {
            if ("RouteResult".equals(_searchResults.getResultType())) {
                _response = didYouMeanResponse();

                // if we get a geocode result, the user is choosing among multiple
                // ambiguous addresses. we also recognize a numeric input that
                // represents which ambiguous location number the user wants to use.
            } else if ("GeocodeResult".equals(_searchResults.getResultType())) {
                if (commandString != null) {
                    if (commandString.equals("M")) {
                        _response = locationDisambiguationResponse(_searchResultsCursor);
                        break;

                        // choosing an ambiguous choice by number
                    } else if (StringUtils.isNumeric(commandString)) {
                        GeocodeResult chosenLocation = (GeocodeResult) _searchResults.getSuggestions()
                                .get(Integer.parseInt(commandString) - 1);

                        if (chosenLocation != null) {
                            _searchResults = _searchService.findStopsNearPoint(chosenLocation.getLatitude(),
                                    chosenLocation.getLongitude(), _resultFactory,
                                    _searchResults.getRouteFilter());
                            _searchResults.setQueryLat(chosenLocation.getLatitude());
                            _searchResults.setQueryLon(chosenLocation.getLongitude());
                            commandString = null;
                            continue;
                        }
                    }

                } else {
                    _response = locationDisambiguationResponse(0);
                    break;
                }
            }
        }

        break;
    }

    // no response generated--no results or unrecognized query
    if (StringUtils.isEmpty(_response)) {
        _response = errorResponse("No results.");

        if (_googleAnalytics != null) {
            try {
                _googleAnalytics.trackEvent("SMS", "No Results", _query);
            } catch (Exception e) {
                //discard
            }
        }
    }

    return SUCCESS;
}

From source file:org.onebusaway.nyc.sms.actions.IndexAction.java

private String routeResponse(RouteResult result) throws Exception {
    String header = result.getShortName() + "\n\n";

    String footer = "\nSend:\n";
    footer += "STOPCODE or INTERSECTION\n";
    footer += "Add '" + result.getShortName() + "' for best results\n";

    RouteDirection aDirectionWithServiceAlerts = (RouteDirection) CollectionUtils.find(result.getDirections(),
            new Predicate() {

                @Override/*from  w  w w .jav a 2s  .  c o  m*/
                public boolean evaluate(Object object) {
                    RouteDirection routeDirection = (RouteDirection) object;
                    if (routeDirection.getSerivceAlerts().size() > 0) {
                        return true;
                    }
                    return false;
                }
            });

    if (aDirectionWithServiceAlerts != null) {
        footer += "\nC " + result.getShortName() + " for *svc alert";
    }

    // find biggest headsign
    int routeDirectionTruncationLength = -1;
    for (RouteDirection direction : result.getDirections()) {
        routeDirectionTruncationLength = Math.max(routeDirectionTruncationLength,
                direction.getDestination().length());
    }

    // try to fit the entire headsign, but if we can't, start chopping from the longest one down
    String body = null;
    while (body == null || header.length() + body.length() + footer.length() >= MAX_SMS_CHARACTER_COUNT) {
        body = "";
        for (RouteDirection direction : result.getDirections()) {
            String headsign = direction.getDestination();

            String alertString = "";
            if (direction.getSerivceAlerts().size() > 0) {
                alertString = "*";
            }

            if (headsign.length() + alertString.length() > routeDirectionTruncationLength) {
                body += "to "
                        + headsign.substring(0, Math.min(routeDirectionTruncationLength, headsign.length()))
                        + "..." + alertString;
            } else {
                body += "to " + headsign + alertString;
            }
            body += "\n";

            if (direction.hasUpcomingScheduledService() == false) {
                body += "not scheduled\n";
            } else {
                body += "is scheduled\n";
            }
        }

        routeDirectionTruncationLength--;
    }

    if (routeDirectionTruncationLength <= 0) {
        throw new Exception("Couldn't fit any route names!?");
    }

    if (_googleAnalytics != null) {
        try {
            _googleAnalytics.trackEvent("SMS", "Route Response", _query);
        } catch (Exception e) {
            //discard
        }
    }

    return header + body + footer;
}

From source file:org.onebusaway.nyc.sms.actions.IndexAction.java

private String directionDisambiguationResponse() throws Exception {

    filterStopSearchResultsToRouteFilterAndDirection();

    RouteBean routeBean = (RouteBean) _searchResults.getRouteFilter().toArray()[0];

    String a = null;/*from  w w w.  ja v  a  2s.co  m*/
    if (routeBean.getShortName().toUpperCase().matches("^(A|E|I|O|U).*$")) {
        a = "an";
    } else {
        a = "a";
    }

    String header = "Pick " + a + " " + routeBean.getShortName() + " direction:\n\n";

    List<String> choices = new ArrayList<String>();
    List<String> choiceNumbers = new ArrayList<String>();

    for (SearchResult searchResult : _searchResults.getMatches()) {
        StopResult stopResult = (StopResult) searchResult;

        RouteAtStop routeAtStopInFilter = (RouteAtStop) CollectionUtils.find(stopResult.getRoutesAvailable(),
                new Predicate() {

                    @Override
                    public boolean evaluate(Object object) {
                        RouteAtStop routeAtStop = (RouteAtStop) object;
                        if (routeAtStop.getRoute().equals(_searchResults.getRouteFilter().toArray()[0])) {
                            return true;
                        }
                        return false;
                    }
                });

        String destination = routeAtStopInFilter.getDirections().get(0).getDestination();

        int choiceNumber = _searchResults.getMatches().indexOf(searchResult) + 1;
        choiceNumbers.add(String.valueOf(choiceNumber));
        choices.add(choiceNumber + ") " + destination);
    }

    String footer = "Send:\n";
    footer += StringUtils.join(choiceNumbers, " or ");

    // find biggest choice
    int choiceTruncationLength = -1;
    for (String choice : choices) {
        choiceTruncationLength = Math.max(choiceTruncationLength, choice.length());
    }

    // try to fit the entire choice, but if we can't, start chopping from the longest one down
    String body = null;
    while (body == null || header.length() + body.length() + footer.length() >= MAX_SMS_CHARACTER_COUNT) {
        body = "";
        for (String choice : choices) {

            if (choice.length() > choiceTruncationLength) {
                body += choice.substring(0, Math.min(choiceTruncationLength, choice.length())) + "...";
            } else {
                body += choice;
            }
            body += "\n\n";
        }

        choiceTruncationLength--;
    }

    if (choiceTruncationLength <= 0) {
        throw new Exception("Couldn't fit any direction choice names!?");
    }

    if (_googleAnalytics != null) {
        try {
            _googleAnalytics.trackEvent("SMS", "Direction Disambiguation Response",
                    ((RouteBean) (_searchResults.getRouteFilter().toArray()[0])).getShortName());
        } catch (Exception e) {
            //discard
        }
    }

    return header + body + footer;
}

From source file:org.opencastproject.metadata.dublincore.DublinCoreCatalog.java

private boolean hasPropertyValue(EName property, final String language) {
    if (LANGUAGE_ANY.equals(language)) {
        return getValuesAsList(property).size() > 0;
    } else {/*from w w w  .ja va 2s. co m*/
        return CollectionUtils.find(getValuesAsList(property), new Predicate() {
            @Override
            public boolean evaluate(Object o) {
                return equalLanguage(((CatalogEntry) o).getAttribute(XML_LANG_ATTR), language);
            }
        }) != null;
    }
}