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

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

Introduction

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

Prototype

public static Collection collect(Iterator inputIterator, final Transformer transformer,
        final Collection outputCollection) 

Source Link

Document

Transforms all elements from the inputIterator with the given transformer and adds them to the outputCollection.

Usage

From source file:qtiscoringengine.QTIRubric.java

@SuppressWarnings("unchecked")
public List<String> getOutcomeVariables() {
    return (List<String>) CollectionUtils.collect(_outcomeDeclarations, new Transformer() {
        @Override/*from   w w  w . j  a v a2 s.co  m*/
        public Object transform(Object arg0) {
            return ((OutcomeDeclaration) arg0).getIdentifier();
        }
    }, new ArrayList<String>());
}

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();/*from w ww .  ja v  a  2  s. com*/
        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.performance.services.impl.ItemBankServiceImpl.java

/**
 * <p>/*w ww . jav a  2s.  c  om*/
 *     NOTE: Caching is NOT implemented because the call to itemBankDao.getTestGrades() has a date check in the SQL that utilizes now()
 * </p>
 */
public List<String> getGrades() throws ReturnStatusException {

    List<TestGrade> testGrades = itemBankDao.getTestGrades(getTdsSettings().getClientName(), null,
            getTdsSettings().getSessionType());

    Collections.<TestGrade>sort(testGrades, new Comparator<TestGrade>() {
        @Override
        public int compare(TestGrade o1, TestGrade o2) {
            int compare = Integer.compare(o1.getInteger(), o2.getInteger());
            if (compare == 0)
                return o1.getText().compareTo(o2.getText());
            return compare;
        }
    });
    return (List<String>) ((CollectionUtils.collect(testGrades, new Transformer() {
        public Object transform(Object each) {
            return ((TestGrade) each).getText();
        }
    }, new ArrayList<String>())));
}

From source file:tds.student.sql.repository.ItemBankRepository.java

/**
 * This has been replaced by ItemBankService.getGrades.
 *
 * @deprecated use {@link #ItemBankService.getGrades()} instead.
 *///  ww w .  j a v a  2 s  . c  o  m
public List<String> getGrades() throws ReturnStatusException {

    List<TestGrade> testGrades = new ArrayList<TestGrade>();

    try (SQLConnection connection = getSQLConnection()) {

        String testKey = null;
        SingleDataResultSet firstResultSet = _studentDll.IB_GetTestGrades_SP(connection,
                getTdsSettings().getClientName(), testKey, getTdsSettings().getSessionType());

        ReturnStatusException.getInstanceIfAvailable(firstResultSet);
        Iterator<DbResultRecord> records = firstResultSet.getRecords();
        while (records.hasNext()) {
            DbResultRecord record = records.next();
            TestGrade testGrade = new TestGrade(record.<String>get("grade"));
            if (testGrades.contains(testGrade))
                continue;
            testGrades.add(testGrade);
        }
    } catch (SQLException e) {
        _logger.error(e.getMessage());
        throw new ReturnStatusException(e);
    }

    Collections.<TestGrade>sort(testGrades, new Comparator<TestGrade>() {
        @Override
        public int compare(TestGrade o1, TestGrade o2) {
            int compare = Integer.compare(o1.getInteger(), o2.getInteger());
            if (compare == 0)
                return o1.getText().compareTo(o2.getText());
            return compare;
        }
    });
    return (List<String>) ((CollectionUtils.collect(testGrades, new Transformer() {
        public Object transform(Object each) {
            return ((TestGrade) each).getText();
        }
    }, new ArrayList<String>())));
}

From source file:tds.student.sql.repositorysp.ItemBankRepository.java

public List<String> getGrades() throws ReturnStatusException {
    final String CMD_GET_TEST_GRADES = "BEGIN; SET NOCOUNT ON; exec IB_GetTestGrades ${clientName}, ${testKey}, ${sessiontype}; end;";

    List<TestGrade> testGrades = new ArrayList<TestGrade>();

    try (SQLConnection connection = getSQLConnection()) {
        // build parameters
        SqlParametersMaps parametersQuery = new SqlParametersMaps();

        parametersQuery.put("clientname", getTdsSettings().getClientName());
        parametersQuery.put("testKey", null);
        parametersQuery.put("sessiontype", getTdsSettings().getSessionType());

        SingleDataResultSet firstResultSet = executeStatement(connection, CMD_GET_TEST_GRADES, parametersQuery,
                false).getResultSets().next();

        ReturnStatusException.getInstanceIfAvailable(firstResultSet);
        Iterator<DbResultRecord> records = firstResultSet.getRecords();
        while (records.hasNext()) {
            DbResultRecord record = records.next();
            TestGrade testGrade = new TestGrade(record.<String>get("grade"));
            if (testGrades.contains(testGrade))
                continue;
            testGrades.add(testGrade);//from www .java2  s  . c  om
        }
    } catch (SQLException e) {
        _logger.error(e.getMessage());
        throw new ReturnStatusException(e);
    }

    Collections.<TestGrade>sort(testGrades, new Comparator<TestGrade>() {
        @Override
        public int compare(TestGrade o1, TestGrade o2) {
            int compare = Integer.compare(o1.getInteger(), o2.getInteger());
            if (compare == 0)
                return o1.getText().compareTo(o2.getText());
            return compare;
        }
    });
    return (List<String>) ((CollectionUtils.collect(testGrades, new Transformer() {
        public Object transform(Object each) {
            return ((TestGrade) each).getText();
        }
    }, new ArrayList<String>())));
}

From source file:tds.student.web.StudentContext.java

public static void saveSegmentsAccommodations(List<Accommodations> segmentsAccommodations) {
    // saveSegmentsAccLookupAccommodations(segmentsAccommodations.Select(A =>
    // A.GetCollection()));
    List<AccLookup> accLookUpList = new ArrayList<AccLookup>();
    CollectionUtils.collect(segmentsAccommodations, new Transformer() {
        @Override//w  w w  .j  a  v a2s .  c o  m
        public Object transform(Object input) {
            Accommodations accommodations = (Accommodations) input;
            AccLookup lookup = new AccLookup(accommodations.getPosition(), accommodations.getId());

            for (AccommodationType accType : accommodations.getTypes()) {
                for (AccommodationValue accValue : accType.getValues()) {
                    lookup.add(accType.getName(), accValue.getCode());
                }
            }

            return lookup;
        }
    }, accLookUpList);
    saveSegmentsAccLookupAccommodations(accLookUpList);
}