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:net.sourceforge.fenixedu.domain.Person.java

public Professorship getProfessorshipByExecutionCourse(final ExecutionCourse executionCourse) {
    return (Professorship) CollectionUtils.find(getProfessorshipsSet(), new Predicate() {
        @Override//from   w w w  .j  a  va2 s.co m
        public boolean evaluate(final Object arg0) {
            final Professorship professorship = (Professorship) arg0;
            return professorship.getExecutionCourse() == executionCourse;
        }
    });
}

From source file:nl.strohalm.cyclos.taglibs.CustomFieldTag.java

private void renderSelect(final StringBuilder sb) throws JspException {

    final boolean hasChildren = CollectionUtils.isNotEmpty(field.getChildren());
    final boolean hasParent = field.getParent() != null;

    // We show the empty label in 2 situations: search or required fields
    String emptyLabel = "";
    if (search || field.getValidation().isRequired()) {
        if (search) {
            emptyLabel = StringUtils.trimToEmpty(field.getAllSelectedLabel());
            if (StringUtils.isEmpty(emptyLabel)) {
                emptyLabel = messageHelper.message("global.search.all");
            }//from   w  ww  . j  a  va 2s  . c om
        } else {
            emptyLabel = messageHelper.message("global.select.empty");
        }
    }

    final CustomFieldPossibleValue selected = getPossibleValue();
    final Collection<CustomFieldPossibleValue> possibleValues = removeDisabledValues(selected,
            field.getPossibleValues(false));

    // We will render a MultiDropDown control if we are on search for enumerated fields, and the field has no relationships
    if (!hasChildren && !hasParent && search && field.getType() == CustomField.Type.ENUMERATED
            && field.getPossibleValues(false).size() > 2) {
        // MultiDropDown
        final StringWriter temp = new StringWriter();
        pageContext.pushBody(temp);
        final MultiDropDownTag multiSelect = new MultiDropDownTag();
        multiSelect.setPageContext(pageContext);
        multiSelect.setName(valueName);
        multiSelect.setSingleField(true);
        multiSelect.doStartTag();
        multiSelect.setEmptyLabel(emptyLabel);
        final OptionTag option = new OptionTag();
        final List<String> values = Arrays.asList(StringUtils.trimToEmpty(getStringValue()).split(","));
        for (final CustomFieldPossibleValue possibleValue : possibleValues) {
            final String idAsString = String.valueOf(possibleValue.getId());
            option.setParent(multiSelect);
            option.setPageContext(pageContext);
            option.setValue(idAsString);
            option.setText(possibleValue.getValue());
            option.setSelected(values.contains(idAsString));
            option.doStartTag();
            option.doEndTag();
        }
        multiSelect.doEndTag();
        pageContext.popBody();
        sb.append(temp.toString());
    } else {
        // Normal select or search for booleans
        final String id = "custom_field_select_" + field.getId();
        sb.append("<select id=\"").append(id).append("\"");
        sb.append(" fieldId=\"").append(field.getId()).append("\"");
        sb.append(" fieldName=\"").append(field.getInternalName()).append("\" name=\"").append(valueName)
                .append('"');
        if (search) {
            sb.append(" fieldEmptyLabel=\"").append(StringEscapeUtils.escapeHtml(emptyLabel)).append('"');
        }
        final Validation validation = field.getValidation();
        final List<String> classes = new ArrayList<String>();
        if (validation != null && validation.isRequired() && !search) {
            classes.add("required");
        }
        if (!enabled) {
            classes.add("InputBoxDisabled");
            sb.append(" disabled");
        }
        sb.append(" class=\"").append(StringUtils.join(classes.iterator(), ' ')).append("\">\n");
        sb.append("<option value=''>");
        sb.append(StringEscapeUtils.escapeHtml(emptyLabel));
        sb.append("</option>\n");
        Long initialOptionId = null;
        if (field.getType() == CustomField.Type.ENUMERATED) {
            // Render each possible value as an enumerated value
            CustomFieldPossibleValue value = selected;
            // When the value is not a PossibleValue, try to find it as String
            if (value == null) {
                final String valueAsString = getStringValue();
                if (StringUtils.isNotEmpty(valueAsString)) {
                    // The value as string is the possible value id
                    final Long possibleValueId = IdConverter.instance().valueOf(valueAsString);
                    value = (CustomFieldPossibleValue) CollectionUtils.find(field.getPossibleValues(false),
                            new Predicate() {
                                @Override
                                public boolean evaluate(final Object obj) {
                                    final CustomFieldPossibleValue pv = (CustomFieldPossibleValue) obj;
                                    return pv.getId().equals(possibleValueId);
                                }
                            });
                }
            }

            // As child fields have their options loaded via AJAX, the form.reset() method doesn't return it to the initial state.
            // Store the options
            if (value != null && field.getParent() != null) {
                initialOptionId = value.getId();
            }

            // Check whether the default value will be used
            boolean useDefault = false;
            if (!isSearch()) {
                if (this.value == null) {
                    useDefault = true;
                } else if (this.value instanceof CustomFieldValue) {
                    // Use on new values only
                    final CustomFieldValue fieldValue = (CustomFieldValue) this.value;
                    useDefault = fieldValue.isTransient();
                }
            }

            // When a field has children, store it's current value on the page scope, so that child fields can filter their possible values
            if (hasChildren) {
                pageContext.setAttribute("valueForField_" + field.getId(), value);
            }

            // Write the options
            for (final CustomFieldPossibleValue possibleValue : possibleValues) {
                final String idAsString = String.valueOf(possibleValue.getId());
                sb.append("<option");
                if (ObjectUtils.equals(value, possibleValue)
                        || (useDefault && possibleValue.isDefaultValue())) {
                    sb.append(" selected");
                }
                sb.append(" value=\"").append(idAsString).append("\">");
                sb.append(ensureHtml(possibleValue.getValue())).append("</option>\n");
            }
        } else {
            // Render the options for a boolean
            sb.append("<option value='true'");
            if (value != null && "true".equalsIgnoreCase(value.toString())) {
                sb.append(" selected");
            }
            sb.append(">").append(messageHelper.message("global.yes")).append("</option>\n");
            sb.append("<option value='false'");
            if (value != null && "false".equalsIgnoreCase(value.toString())) {
                sb.append(" selected");
            }
            sb.append(">").append(messageHelper.message("global.no")).append("</option>\n");
        }
        sb.append("</select>\n");
        if (hasChildren) {
            sb.append("<script>\n");
            sb.append("$('").append(id).append("').onchange = function() {\n");
            for (final CustomField child : field.getChildren()) {
                final String childId = "custom_field_select_" + child.getId();
                sb.append("updateCustomFieldChildValues('").append(field.getNature()).append("', '").append(id)
                        .append("', '").append(childId).append("');\n");
            }
            sb.append("");
            sb.append("}\n");
            sb.append("Event.observe(self, 'loadi', $('").append(id).append("').onchange);\n");
            sb.append("</script>\n");
        }
        if (field.getParent() != null) {
            sb.append("<script>\n");
            if (initialOptionId != null) {
                // Write the initial value id, so the form.reset will work
                sb.append("$('").append(id).append("').initialOptionId = \"").append(initialOptionId)
                        .append("\";\n");
            }
            // Write the initial options, so they will be correct on form.reset
            sb.append("$('").append(id).append("').initialOptions = [");
            boolean first = true;
            for (final CustomFieldPossibleValue possibleValue : possibleValues) {
                if (first) {
                    first = false;
                } else {
                    sb.append(", ");
                }
                sb.append("new Option(\"").append(StringEscapeUtils.escapeJavaScript(possibleValue.getValue()))
                        .append("\",\"").append(possibleValue.getId()).append("\")");
            }
            sb.append("];\n");
            sb.append("</script>\n");
        }
    }
}

From source file:nl.strohalm.cyclos.taglibs.ProfileTag.java

private String generateProfileField() {
    if (elementId <= 0) {
        return "";
    }/* w ww . j  a v a2  s  .  c om*/
    final ElementVO element = elementService.getElementVO(elementId);
    boolean canGoToProfile = false;
    final Object foundGroup = CollectionUtils.find(permissionService.getAllVisibleGroups(), new Predicate() {
        @Override
        public boolean evaluate(final Object group) {
            return ((Group) group).getId().equals(element.getGroupId());
        }
    });

    if (foundGroup != null) {
        canGoToProfile = true;
    }

    if (StringUtils.isEmpty(text)) {
        // The text will be the name or the user name based on the local settings.
        final LocalSettings localSettings = settingsService.getLocalSettings();
        final MemberResultDisplay memberResultDisplay = localSettings.getMemberResultDisplay();
        if (pattern != null) {
            text = pattern.replaceAll("username", element.getUsername()).replaceAll("name", element.getName());
        } else {
            if (memberResultDisplay == MemberResultDisplay.NAME) {
                text = element.getName();
            } else if (memberResultDisplay == MemberResultDisplay.USERNAME) {
                text = element.getUsername();
            }
        }
    }

    // truncate
    text = TruncateTag.truncate(text, fieldLength);

    String profile;

    if (canGoToProfile && !onlyShowLabel) {

        profile = "<a class=\"$linkClass\" $attribute=\"$id\">$text</a>";

        // $attribute, $class, $id and $text
        String linkClass = "";
        String attribute = "";
        switch (element.getNature()) {
        case ADMIN:
            linkClass = "adminProfileLink";
            attribute = "adminId";
            break;
        case MEMBER:
            linkClass = "profileLink";
            attribute = "memberId";
            break;
        case OPERATOR:
            linkClass = "operatorProfileLink";
            attribute = "operatorId";
            break;
        default:
            throw new IllegalArgumentException("Unexpected element identifier " + elementId);
        }

        if (!StringUtils.isEmpty(styleClass)) {
            linkClass += " " + styleClass;
        }

        profile = profile.replace("$linkClass", linkClass);
        profile = profile.replace("$attribute", attribute);
        profile = profile.replace("$id", elementId.toString());
        profile = profile.replace("$text", text);

    } else {
        profile = text;
    }
    return profile;
}

From source file:nl.strohalm.cyclos.webservices.payments.PaymentWebServiceImpl.java

private Collection<MemberCustomField> getMemberCustomFields(final Member member,
        final List<String> fieldInternalNames) {
    Collection<MemberCustomField> fields = new HashSet<MemberCustomField>();

    for (final String internalName : fieldInternalNames) {
        MemberCustomFieldValue mcfv = (MemberCustomFieldValue) CollectionUtils.find(member.getCustomValues(),
                new Predicate() {
                    @Override/*from w ww. j  ava  2 s.co m*/
                    public boolean evaluate(final Object object) {
                        MemberCustomFieldValue mcfv = (MemberCustomFieldValue) object;
                        return mcfv.getField().getInternalName().equals(internalName);
                    }
                });
        if (mcfv == null) {
            webServiceHelper.trace(
                    String.format("Required field '%1$s' was not found for member %2$s", internalName, member));
            return null;
        } else {
            fields.add(memberCustomFieldServiceLocal.load(mcfv.getField().getId()));
        }
    }

    return fields;
}

From source file:op.care.prescription.DlgDiscontinue.java

/**
 * Creates new form DlgDiscontinue/*from ww  w . j a va2  s  .  c  o  m*/
 */
private void cmbArztAbKeyPressed(KeyEvent e) {
    final String searchKey = String.valueOf(e.getKeyChar());
    GP doc = (GP) CollectionUtils.find(listAerzte, new Predicate() {
        @Override
        public boolean evaluate(Object o) {
            return o != null && ((GP) o).getName().toLowerCase().charAt(0) == searchKey.toLowerCase().charAt(0);
        }
    });
    if (doc != null) {
        cmbArztAb.setSelectedItem(doc);
    }
}

From source file:op.care.prescription.DlgOnDemand.java

private void cmbDocONKeyPressed(KeyEvent e) {
    final String searchKey = String.valueOf(e.getKeyChar());
    GP doc = (GP) CollectionUtils.find(listAerzte, new Predicate() {
        @Override/*from  w ww . ja v  a 2 s.  c  om*/
        public boolean evaluate(Object o) {
            return o != null && ((GP) o).getName().toLowerCase().charAt(0) == searchKey.toLowerCase().charAt(0);
        }
    });
    if (doc != null) {
        cmbDocON.setSelectedItem(doc);
    }
}

From source file:org.andromda.cartridges.database.metafacades.ColumnLogicImpl.java

/**
 * Gets the association end that has the foreign identifier
 * flag set (if there is one).//from   ww w  . j a va 2s . c om
 * 
 * @return the foreign identifier association end or null if
 * on can't be found.
 */
private EntityAssociationEnd getForeignIdentifierEnd() {

    EntityAssociationEnd end = (EntityAssociationEnd) CollectionUtils.find(this.getOwner().getAssociationEnds(),
            new Predicate() {

                public boolean evaluate(Object object) {

                    AssociationEndFacade end = (AssociationEndFacade) object;
                    boolean valid = false;

                    if ((end != null) && EntityAssociationEnd.class.isAssignableFrom(end.getClass())) {

                        valid = ((EntityAssociationEnd) end).isForeignIdentifier();

                    }

                    return valid;

                }

            });

    return end;

}

From source file:org.andromda.cartridges.database.metafacades.TableLogicImpl.java

/**
 * @see org.andromda.cartridges.database.metafacades.Table#getIdentifierForeignKeyColumns()
 *//*from   w ww  .  ja  v a 2 s  . co m*/
@Override
protected Collection handleGetIdentifierForeignKeyColumns() {

    Collection columns = null;
    final EntityAssociationEnd end = (EntityAssociationEnd) CollectionUtils.find(this.getAssociationEnds(),
            new Predicate() {

                @Override
                public boolean evaluate(final Object object) {

                    boolean valid = false;

                    if (EntityAssociationEnd.class.isAssignableFrom(object.getClass())) {

                        valid = ((EntityAssociationEnd) object).isForeignIdentifier();

                    }

                    return valid;

                }

            });

    if ((end != null) && EntityAssociationEnd.class.isAssignableFrom(end.getClass())) {

        columns = ((Table) end.getType()).getIdentifiers();

    }

    return columns;

}

From source file:org.apache.ambari.server.controller.ganglia.GangliaPropertyProviderTest.java

private boolean isUrlParamsEquals(URIBuilder actualUri, URIBuilder expectedUri) {
    for (final NameValuePair expectedParam : expectedUri.getQueryParams()) {
        NameValuePair actualParam = (NameValuePair) CollectionUtils.find(actualUri.getQueryParams(),
                new Predicate() {

                    @Override//w  ww. ja va  2 s. c  om
                    public boolean evaluate(Object arg0) {
                        if (!(arg0 instanceof NameValuePair))
                            return false;

                        NameValuePair otherObj = (NameValuePair) arg0;
                        return otherObj.getName().equals(expectedParam.getName());
                    }
                });

        List<String> actualParamList = new ArrayList<String>(Arrays.asList(actualParam.getValue().split(",")));
        List<String> expectedParamList = new ArrayList<String>(
                Arrays.asList(expectedParam.getValue().split(",")));

        Collections.sort(actualParamList);
        Collections.sort(expectedParamList);

        if (!actualParamList.equals(expectedParamList))
            return false;
    }

    return true;
}

From source file:org.apache.ambari.server.controller.internal.AbstractProviderModule.java

@Override
public boolean isGangliaCollectorHostLive(String clusterName) throws SystemException {

    HostResponse gangliaCollectorHost = null;

    try {// w w w.ja  v  a  2  s .c om
        HostRequest hostRequest = new HostRequest(null, clusterName, Collections.<String, String>emptyMap());
        Set<HostResponse> hosts = managementController.getHosts(Collections.singleton(hostRequest));

        final String gangliaCollectorHostName = getGangliaCollectorHostName(clusterName);

        gangliaCollectorHost = (HostResponse) CollectionUtils.find(hosts,
                new org.apache.commons.collections.Predicate() {

                    @Override
                    public boolean evaluate(Object hostResponse) {
                        return ((HostResponse) hostResponse).getHostname().equals(gangliaCollectorHostName);
                    }
                });
    } catch (AmbariException e) {
        LOG.debug("Error checking of Ganglia server host live status: ", e);
        return false;
    }

    //Cluster without Ganglia
    if (gangliaCollectorHost == null)
        return false;

    return !gangliaCollectorHost.getHostState().equals(HostState.HEARTBEAT_LOST.name());
}