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.yes.cart.report.impl.ReportServiceImpl.java

ReportDescriptor getReportDescriptorbyId(final String reportId) {

    Assert.notNull(reportId, "ReportId must be not null");

    return (ReportDescriptor) CollectionUtils.find(reportDescriptors, new Predicate() {
        public boolean evaluate(final Object o) {
            return reportId.equalsIgnoreCase(((ReportDescriptor) o).getReportId());
        }//  www  . j  av  a 2 s  . co  m
    });

}

From source file:org.zanata.tmx.TMXParserTest.java

private TransMemoryUnit findInCollection(Collection<TransMemoryUnit> col, final String tuid) {
    return (TransMemoryUnit) CollectionUtils.find(col, new Predicate() {
        @Override/*w  ww  .  j ava  2  s  . c  om*/
        public boolean evaluate(Object o) {
            return ((TransMemoryUnit) o).getTransUnitId().equals(tuid);
        }
    });
}

From source file:qtiscoringengine.ISECustomExpression.java

@Override
protected DataElement exprEvaluate(VariableBindings vb, QTIRubric rubric, List<DataElement> paramValues) {
    String response = vb.getVariable(_responseIdentifier).toString();

    ResponseInfo rinfo = new ResponseInfo(_itemFormat, "", response, _rubric, RubricContentType.ContentString,
            null, false) {/* w  w w .j  a  v a2s  . c  o m*/
        {
            setOutgoingBindings(Arrays.asList(VarBinding.ALL)); // We alwyas ask
                                                                // for ALL from
                                                                // expressions and
                                                                // leave it to the
                                                                // QTI executive
                                                                // to decide which
                                                                // ones to expose
                                                                // to the caller
                                                                // IncomingBindings = GetIncomingBindings(_incomingIdentifiers) // These
                                                                // are bindings we can pass from QTI to ISE .. **TODO**
        }
    };

    ItemScore score = _itemScorer.ScoreItem(rinfo, null);

    rubric.getResponseProcessingState().add(score);

    if (score.getScoreInfo().getRationale().getBindings() != null) {
        for (final VarBinding binding : score.getScoreInfo().getRationale().getBindings()) {
            // Look through the bindOutput declarations to see whether this binding
            // from ISE needs to be bound to a QTI variable and to which one
            NameMapping bindOutputDirective = (NameMapping) CollectionUtils.find(_outgoingIdentifiers,
                    new Predicate() {

                        @Override
                        public boolean evaluate(Object object) {
                            NameMapping x = (NameMapping) object;
                            return StringUtils.equals(x.sourceId, binding.getName());
                        }
                    });

            if (bindOutputDirective.targetId != null && vb.getVariable(bindOutputDirective.targetId) != null) // this
                                                                                                              // is
                                                                                                              // added
                                                                                                              // so
                                                                                                              // that
                                                                                                              // only
                                                                                                              // variables
                                                                                                              // declared
                                                                                                              // in
                                                                                                              // the
                                                                                                              // QTI
                                                                                                              // rubric
                                                                                                              // will
                                                                                                              // be
                                                                                                              // bound
                                                                                                              // and
                                                                                                              // we
                                                                                                              // can
                                                                                                              // exclude
                                                                                                              // all
                                                                                                              // the
                                                                                                              // internal
                                                                                                              // native
                                                                                                              // scoring
                                                                                                              // engine
                                                                                                              // bindings
            {
                vb.setVariable(bindOutputDirective.targetId, DataElement.create(binding.getValue(),
                        rubric.getOutcomeVariableBaseType(bindOutputDirective.targetId)));
            }
        }
    }
    if (score.getScoreInfo().getRationale().getPropositions() != null) {
        for (final Proposition proposition : score.getScoreInfo().getRationale().getPropositions()) {
            // Look through the bindOutput declarations to see whether this binding
            // from ISE needs to be bound to a QTI variable and to which one
            NameMapping bindOutputDirective = (NameMapping) CollectionUtils.find(_outgoingIdentifiers,
                    new Predicate() {
                        @Override
                        public boolean evaluate(Object object) {
                            NameMapping x = (NameMapping) object;
                            return StringUtils.equals(x.sourceId, proposition.getName());
                        }
                    });

            if (bindOutputDirective.targetId != null && vb.getVariable(bindOutputDirective.targetId) != null) // this
                                                                                                              // is
                                                                                                              // added
                                                                                                              // so
                                                                                                              // that
                                                                                                              // only
                                                                                                              // variables
                                                                                                              // declared
                                                                                                              // in
                                                                                                              // the
                                                                                                              // QTI
                                                                                                              // rubric
                                                                                                              // will
                                                                                                              // be
                                                                                                              // bound
                                                                                                              // and
                                                                                                              // we
                                                                                                              // can
                                                                                                              // exclude
                                                                                                              // all
                                                                                                              // the
                                                                                                              // internal
                                                                                                              // native
                                                                                                              // scoring
                                                                                                              // engine
                                                                                                              // propositions
            {
                vb.setVariable(bindOutputDirective.targetId,
                        DataElement.create(
                                TDSStringUtils.getCSharpBooleanToString(
                                        proposition.getState() == PropositionState.Asserted),
                                BaseType.Boolean));
            }
        }
    }

    return score.getScoreInfo().getStatus() == ScoringStatus.Scored
            ? DataElement.create("true", BaseType.Boolean)
            : DataElement.create("false", BaseType.Boolean);
}

From source file:ru.jcorp.smartstreets.helpers.Bundle.java

private static SmartMapNode getPointByName(SmartMap map, final String pointName) {
    return (SmartMapNode) CollectionUtils.find(map.getNodes(), new Predicate() {
        @Override//from w w w. j  a  v a 2  s  . co  m
        public boolean evaluate(Object object) {
            SmartMapNode node = (SmartMapNode) object;
            return StringUtils.equals(node.getTitle(), pointName);
        }
    });
}

From source file:structure.Index.java

/**
 *
 * @param id// w  w  w. j a  v  a2  s  .co m
 * @return
 */
public Entity getEntityById(final String id) {
    return (Entity) CollectionUtils.find(index, new Predicate() {
        @Override
        public boolean evaluate(Object arg0) {
            return ((Entity) arg0).getId().equals(id);
        }
    });
}

From source file:tds.itemrenderer.data.AccLookup.java

@JsonIgnore
public String getCode(String type) {
    return (String) CollectionUtils.find(getCodes(type), new Predicate() {
        @Override//from   ww w.ja  v a2  s . c  om
        public boolean evaluate(Object arg0) {
            return true;
        }
    });
}

From source file:tds.itemrenderer.data.apip.APIPXml.java

public APIPAccessElement getRelatedElementInfo(final String id) {
    /*/* w ww  .j  a  va  2 s  .  co  m*/
     * return (from accessElement in AccessElements where
     * accessElement.ContentLinkInfo.ITSLinkIdentifierRef == id select
     * accessElement).FirstOrDefault();
     */
    return (APIPAccessElement) CollectionUtils
            .find(CollectionUtils.select(getAccessElements(), new Predicate() {

                @Override
                public boolean evaluate(Object accessElement) {
                    return StringUtils.equals(
                            ((APIPAccessElement) accessElement).getContentLinkInfo().getItsLinkIdentifierRef(),
                            id);
                }
            }), new Predicate() {
                // this will make it return the first element.
                // TODO Shiva: would not it have been simpler to check using plain java
                // code.
                @Override
                public boolean evaluate(Object arg0) {
                    return true;
                }
            });
}

From source file:tds.itemrenderer.data.ITSContent.java

private ITSAttachment findBrailleAttachment(List<String> brailleSubTypeCodes, boolean isFindTranscript) {
    ITSAttachment brailleAttachment = null;
    // need to check these in order in case the content has both Math specific and No Math Code Needed versions
    for (String subTypeCode : brailleSubTypeCodes) {
        final String subTypeCodeFinal = subTypeCode + (isFindTranscript ? "_transcript" : "");

        brailleAttachment = (ITSAttachment) CollectionUtils.find(_attachments, new Predicate() {
            @Override//from  www.  j  av  a2 s.com
            public boolean evaluate(Object attachment) {
                return StringUtils.equalsIgnoreCase(subTypeCodeFinal,
                        ((ITSAttachment) attachment).getSubType());
            }
        });

        if (brailleAttachment != null) {
            return brailleAttachment;
        }
    }

    return null;
}

From source file:tds.itemscoringengine.itemscorers.QTIRubricScorer.java

public ItemScore scoreItem(ResponseInfo responseInfo) {
    ItemScore score = new ItemScore(-1, -1, ScoringStatus.NotScored, "overall", new ScoreRationale(),
            responseInfo.getContextToken()); // We
    // Shiva: I added the follow null check on the response as it makes it
    // easier to test it on the web
    // interface with a REST client.
    String response = responseInfo.getStudentResponse();
    if (response != null) {
        response = response.trim();/* www  . j  a va2  s .  c  om*/
        responseInfo.setStudentResponse(response);
    }

    // Max
    // score
    // is
    long startTime = System.currentTimeMillis();
    Map<String, String> identifiersAndResponses = new HashMap<String, String>();
    // first try to retrieve the item response, and the identifier
    try {
        XmlReader reader = new XmlReader(new StringReader(responseInfo.getStudentResponse()));
        Document doc = reader.getDocument();

        List<Element> responseNodes = new XmlElement(doc.getRootElement())
                .selectNodes("//itemResponse/response");
        for (Element elem : responseNodes) {
            String identifier = elem.getAttribute("id").getValue();
            List<String> responses = new ArrayList<String>();
            List<Element> valueNodes = new XmlElement(elem).selectNodes("value");
            for (Element valElem : valueNodes) {
                responses.add(new XmlElement(valElem).getInnerText());
            }

            identifiersAndResponses.put(identifier, StringUtils.join(responses, ","));
        }

    } catch (final Exception e) {
        e.printStackTrace();
        _logger.error("Error loading responses " + e.getMessage());
        score.getScoreInfo().setStatus(ScoringStatus.ScoringError);
        score.getScoreInfo().getRationale().setMsg("Error loading response. Message: " + e.getMessage());
        score.getScoreInfo().getRationale().setException(e);
        return score;
    }

    if (identifiersAndResponses.size() == 0) {
        // This could be a response from a grid/ti/eq item being scored using a
        // QTI version of our proprietary rubrics
        // Check if this is a TI/GI/SIM/EQ and unfortunately, there is no clean
        // way to figure this out other than resorting to this hack
        response = responseInfo.getStudentResponse();

        if (!StringUtils.isEmpty(response) && ((response.toUpperCase().startsWith("<RESPONSESPEC>")
                || response.toUpperCase().startsWith("<RESPONSETABLE>")) || // TI
                (response.toUpperCase().startsWith("<RESPONSE>")) || // EQ
                (response.toUpperCase().contains("<ANSWERSET>"))) // GI
        ) {
            identifiersAndResponses.put("RESPONSE", responseInfo.getStudentResponse());
        } else {
            _logger.error("No responses found");
            score.getScoreInfo().getRationale().setMsg("No responses found");
            return score;
        }
    }

    try {
        if (wasThereErrorWithRubric()) {
            _logger.error(String.format("Error validating rubric. File %s. Message %s",
                    responseInfo.getRubric().toString(), getErrorMessageIfAny()));
            score.getScoreInfo().getRationale().setMsg(getErrorMessageIfAny());
            return score;
        }

        // now score the item
        String[] scoreArr = null;
        List<String[]> bindings = _rubric.evaluate(identifiersAndResponses);
        for (String[] binding : bindings) {
            if ("score".equalsIgnoreCase(binding[0]))
                scoreArr = binding;
        }

        // error check the score result
        if (scoreArr == null) {
            score.getScoreInfo().setStatus(ScoringStatus.ScoringError);
            score.getScoreInfo().getRationale()
                    .setMsg("There was no SCORE identifier specified for the identifiers "
                            + StringUtils.join(identifiersAndResponses.keySet(), ','));
            return score;
        }
        if (scoreArr.length < 4 || StringUtils.isEmpty(scoreArr[3])) {
            score.getScoreInfo().setStatus(ScoringStatus.ScoringError);
            score.getScoreInfo().getRationale().setMsg("There was no score specified for the identifiers "
                    + StringUtils.join(identifiersAndResponses.keySet(), ','));
            return score;
        }

        // try to parse the actual score value -- note the score value is
        // hardcoded to be at index 3
        _Ref<Double> dScore = new _Ref<>();
        if (JavaPrimitiveUtils.doubleTryParse(scoreArr[3], dScore)) {
            // note: we truncate the double score to be an int
            score.getScoreInfo().setPoints((int) Math.ceil(Math.max(dScore.get(), 0)));
            score.getScoreInfo().setStatus(ScoringStatus.Scored);
            score.getScoreInfo().getRationale().setMsg("successfully scored");

            // populate the requested outgoing bindings
            if (responseInfo.getOutgoingBindings() != null) {
                if (responseInfo.getOutgoingBindings().contains(VarBinding.ALL)) // All
                                                                                 // bindings
                                                                                 // requested
                {
                    score.getScoreInfo().getRationale().setBindings(new ArrayList<VarBinding>());

                    CollectionUtils.collect(bindings, new Transformer() {

                        @Override
                        public Object transform(Object arg0) {
                            final String[] variable = (String[]) arg0;
                            return new VarBinding() {
                                {
                                    setName(variable[0]);
                                    setType(variable[1]);
                                    setValue(variable[3]);
                                }
                            };
                        }
                    }, score.getScoreInfo().getRationale().getBindings());

                } else // Specific bindings requested
                {
                    score.getScoreInfo().getRationale().setBindings(new ArrayList<VarBinding>());
                    for (final VarBinding outgoingBinding : responseInfo.getOutgoingBindings()) {

                        final String[] binding = (String[]) CollectionUtils.find(bindings, new Predicate() {

                            @Override
                            public boolean evaluate(Object arg0) {
                                return StringUtils.equals(((String[]) arg0)[0], outgoingBinding.getName());
                            }
                        });

                        if (binding != null)
                            score.getScoreInfo().getRationale().getBindings().add(new VarBinding() {
                                {
                                    setName(binding[0]);
                                    setType(binding[1]);
                                    setValue(binding[3]);
                                }
                            });

                    }
                }
            }

            // populate any subscores that might have been recorded as internal
            // scoring state
            for (Object stateObj : _rubric.getResponseProcessingState()) {
                ItemScore subScore = (ItemScore) stateObj;
                if (subScore != null) {
                    if (score.getScoreInfo().getSubScores() == null)
                        score.getScoreInfo().setSubScores(new ArrayList<ItemScoreInfo>());

                    // remove any bindings from the subscore that is not requested as an
                    // outgoing binding
                    if (responseInfo.getOutgoingBindings() == null) {
                        // No bindings requested - clear everything
                        // TODO: Recursively go through the subscore's children to clear
                        // those bindings also.
                        subScore.getScoreInfo().getRationale().getBindings().clear();
                    } else if (responseInfo.getOutgoingBindings().contains(VarBinding.ALL)) {
                        // All bindings requested
                        // don't remove anything. let them all through
                    } else {
                        // specific bindings requested. Remove anything not explicitly
                        // asked for.
                        // TODO: Recursively go through the subscore's children to filter
                        // them also
                        VarBinding[] subScoreBindings = subScore.getScoreInfo().getRationale().getBindings()
                                .toArray(new VarBinding[subScore.getScoreInfo().getRationale().getBindings()
                                        .size()]);

                        for (int counter1 = 0; counter1 < subScoreBindings.length; ++counter1) {
                            final VarBinding subScoreBinding = subScoreBindings[counter1];
                            if (!CollectionUtils.exists(responseInfo.getOutgoingBindings(), new Predicate() {

                                @Override
                                public boolean evaluate(Object arg0) {
                                    return StringUtils.equals(((VarBinding) arg0).getName(),
                                            subScoreBinding.getName());
                                }
                            })) {
                                subScore.getScoreInfo().getRationale().getBindings().remove(counter1);
                                --counter1;
                            }
                        }

                    }
                    score.getScoreInfo().getSubScores().add(subScore.getScoreInfo());
                }

            }
            // note: ScoreLatency is miliseconds
            score.setScoreLatency(System.currentTimeMillis() - startTime);
            return score;

        } else {
            score.getScoreInfo().setStatus(ScoringStatus.ScoringError);
            score.getScoreInfo().getRationale().setMsg("Error changing score to int, score array values='"
                    + StringUtils.join(scoreArr, ',') + "'.");
            return score;
        }

    } catch (final Exception e) {
        e.printStackTrace();
        _logger.error("Error : " + e.getMessage());
        score.getScoreInfo().setPoints(-1);
        score.getScoreInfo().setStatus(ScoringStatus.ScoringError);
        score.getScoreInfo().getRationale().setMsg("Error processing rubric. Message: " + e.getMessage());
        score.getScoreInfo().getRationale().setException(e);
        return score;
    }
}

From source file:tds.student.services.LoginService.java

@SuppressWarnings("unchecked")
public void setRTSAccommodations(long testee, final String accFamily, Accommodations accommodations)
        throws ReturnStatusException {
    // get all accommodations from RTS that are preselected for this student
    List<RTSAccommodation> allRTSAccCodes = null;
    try {/*from w w w. j  av a 2s  .  c  om*/
        allRTSAccCodes = _testeeRepository.getAccommodations(testee);
        // List<RTSAccommodation> subjectRTSAccCodes = allRTSAccCodes.FindAll(RTS
        // =>
        // RTS.AccFamily == null || RTS.AccFamily == accFamily);
        // TODO
        // get all the RTS accommodations that match this tests subject
        // (accommodation family)
        List<RTSAccommodation> subjectRTSAccCodes = (List<RTSAccommodation>) CollectionUtils
                .find(allRTSAccCodes, new Predicate() {
                    @Override
                    public boolean evaluate(Object object) {
                        RTSAccommodation rtsAttr = (RTSAccommodation) object;
                        return rtsAttr.getAccFamily().equalsIgnoreCase(accFamily);
                    }
                });

        // get all the test accommodations for this subject's codes
        List<AccommodationValue> subjectAccValues = new ArrayList<AccommodationValue>();

        for (RTSAccommodation subjectRTSAccCode : subjectRTSAccCodes) {
            AccommodationValue accValue = accommodations.getValue(subjectRTSAccCode.getAccCode());
            if (accValue != null)
                subjectAccValues.add(accValue);
        }
        // TODO
        Transformer groupTransformer = new Transformer() {

            @Override
            public Object transform(Object itsDocument) {
                return ((AccommodationValue) itsDocument).getParentType();
            }
        };

        List<IGrouping<String, AccommodationValue>> subjectAccValuesGroupedByType = IGrouping
                .<String, AccommodationValue>createGroups(subjectAccValues, groupTransformer);

        Collections.sort(subjectAccValuesGroupedByType,
                new Comparator<IGrouping<String, AccommodationValue>>() {
                    @Override
                    public int compare(IGrouping<String, AccommodationValue> o1,
                            IGrouping<String, AccommodationValue> o2) {
                        return o1.getKey().compareTo(o2.getKey());
                    }
                });

        // group the test accommodations by type
        // var subjectAccValuesGroupedByType = subjectAccValues.GroupBy(value =>
        // value.ParentType);

        // select the new defaults for this type
        for (IGrouping<String, AccommodationValue> subjectAccValuesGroup : subjectAccValuesGroupedByType) {
            AccommodationValue defaultAccValue = subjectAccValuesGroup.get(0);

            // deselect the current default value
            // AccommodationValue defaultAccValue = subjectAccType.getDefault();

            if (defaultAccValue != null) {
                defaultAccValue.setIsDefault(false);
            }

            // select new default values
            for (AccommodationValue accValue : subjectAccValuesGroup) {
                accValue.setIsDefault(true);
            }
        }
    } catch (ReturnStatusException e) {
        _logger.error(e.getMessage());
        throw new ReturnStatusException(e);
    }
}