Example usage for org.apache.commons.collections Transformer Transformer

List of usage examples for org.apache.commons.collections Transformer Transformer

Introduction

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

Prototype

Transformer

Source Link

Usage

From source file:tds.itempreview.ConfigBuilder.java

private Collection<IGrouping<String, IrisITSDocument>> groupDocumentsByParentFolder(
        Collection<IrisITSDocument> itsDocuments) {
    Transformer groupTransformer = new Transformer() {

        @Override//from  w ww. ja  va 2  s . co m
        public Object transform(Object itsDocument) {
            return ((IITSDocument) itsDocument).getFolderName();
        }
    };

    List<IGrouping<String, IrisITSDocument>> returnList = IGrouping
            .<String, IrisITSDocument>createGroups(itsDocuments, groupTransformer);

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

    return returnList;
}

From source file:tds.itempreview.ConfigLoader.java

private void setFilePaths(final String configBasePath, Config config) {
    for (Page configPage : config.getPages()) {
        if (configPage.getPassage() != null)
            setFilePath(configBasePath, configPage.getPassage());
        if (configPage.getItems() != null)
            CollectionUtils.transform(configPage.getItems(), new Transformer() {
                @Override/*  w  w  w  . j ava 2  s. com*/
                public Object transform(Object ic) {
                    setFilePath(configBasePath, (Item) ic);
                    return ic;
                }
            });
    }
}

From source file:tds.itempreview.ConfigLoader.java

private void setHttpPaths(final String rootPath, Config config) {
    for (Page configPage : config.getPages()) {
        if (configPage.getPassage() != null)
            setHttpPath(rootPath, configPage.getPassage());
        if (configPage.getItems() != null)
            CollectionUtils.transform(configPage.getItems(), new Transformer() {

                @Override// w w  w  .  j ava  2  s  .  co  m
                public Object transform(Object ic) {
                    setHttpPath(rootPath, (Item) ic);
                    return ic;
                }
            });
    }
}

From source file:tds.itempreview.ConfigLoader.java

private void encryptPaths(Config config) {
    for (Page configPage : config.getPages()) {
        configPage.setEncrypted(true);//from w ww.j  a v  a2  s .c om
        if (configPage.getPassage() != null)
            encryptPath(configPage.getPassage());
        if (configPage.getItems() != null)
            CollectionUtils.transform(configPage.getItems(), new Transformer() {

                @Override
                public Object transform(Object configContent) {
                    encryptPath((Content) configContent);
                    return configContent;
                }
            });
    }
}

From source file:tds.itemrenderer.webcontrols.PageLayout.java

@SuppressWarnings("unchecked")
protected void bindResponseControl_MC(IItemRender itemRender, ITSContent itsContent, UIComponent control) {
    final char delimiter = ',';

    // logic for figuring our answer template
    List<ItemRenderMCOption> renderOptions = new ArrayList<ItemRenderMCOption>();

    // check if there are any MC options
    if (itsContent.getOptions() != null) {
        for (ITSOption option : itsContent.getOptions()) {
            ItemRenderMCOption renderMCOption = new ItemRenderMCOption(
                    "Response_MC_" + itemRender.getPosition(), option.getKey());
            renderMCOption.setText(option.getValue());
            renderMCOption.setFeedback(option.getFeedback());
            renderMCOption.setSound(option.getSound());
            renderMCOption.setDisabled(itemRender.getDisabled());

            // get the answer key
            String answerString = itemRender.getItem().getAnswerKey();

            // set the correct answer on the option
            if (!StringUtils.isEmpty(answerString)) {
                String[] answerKeys = StringUtils.split(answerString, delimiter);

                for (String answerKey : answerKeys) {
                    // check if matching answer key
                    if (StringUtils.equals(option.getKey(), answerKey)) {
                        renderMCOption.setAnswer(true);
                        break;
                    }/*from   w  w  w.j  av a 2 s .  co  m*/
                }
            }

            // check for a response
            if (!StringUtils.isEmpty(itemRender.getResponse())) {
                // check if multiple response
                if (StringUtils.equalsIgnoreCase(itemRender.getItem().getFormat(), "MS")) {
                    String[] responseKeys = StringUtils.split(itemRender.getResponse(), delimiter);

                    // go through all the response keys to see if they match option key
                    for (String responseKey : responseKeys) {
                        // check if matching response key
                        if (StringUtils.equals(option.getKey(), responseKey)) {
                            renderMCOption.setSelected(true);
                            break;
                        }
                    }
                } else {
                    // check if response key matches option key
                    renderMCOption.setSelected(StringUtils.equals(option.getKey(), itemRender.getResponse()));
                }
            }
            renderOptions.add(renderMCOption);
        }
    }

    // perform data binding
    if (control instanceof ITemplateAnswer) {
        ITemplateAnswer templateAnswer = (ITemplateAnswer) control;
        templateAnswer.setOptions(renderOptions);
    }
    // TODO Shiva: Finish the loops below
    /*
     * else if (control instanceof ITemplateAnswerMC) { ITemplateAnswerMC
     * templateAnswer = control as ITemplateAnswerMC;
     * templateAnswer.Options.DataSource = renderOptions;
     * templateAnswer.Options.DataBind(); }
     */
    else if (control instanceof ITemplateAnswerTable) {

        ITemplateAnswerTable templateAnswer = (ITemplateAnswerTable) control;
        templateAnswer.setOptions((List<Object>) CollectionUtils.collect(renderOptions, new Transformer() {
            @Override
            public Object transform(Object input) {
                return input;
            }
        }));
    }
    /*
     * else if (control is ITemplateAnswerRepeater) { ITemplateAnswerRepeater
     * templateAnswer = control as ITemplateAnswerRepeater;
     * templateAnswer.Options.DataSource = renderOptions;
     * templateAnswer.Options.DataBind(); }
     */
    else {
        addError(ErrorCategories.Template,
                "Cannot bind data to the answer template '{0}' because it inherits from unknown interface. Failed to load item {1}.",
                control.getClientId(), itemRender.getItem().getItemKey());
    }
}

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 w w  . j av a 2 s. co  m*/
        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  w  w .j ava  2s  .co m*/
 *     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.services.AccommodationsService.java

public List<Accommodations> getApprovedOrig(OpportunityInstance oppInstance, String testKey,
        boolean isGuestSession) throws ReturnStatusException {

    List<OpportunityAccommodation> oppAccs = null;
    List<Accommodations> segmentAccsList = null;
    // get all the test and segment accommodations
    TestProperties testProps = null;/*from  w  w  w  . j a  va2 s  .c om*/
    try {
        // FW Performance Changes - switched from _ibRepository to new ItemBankService which utilizes caching and other optimizations
        testProps = itemBankService.getTestProperties(testKey);

        segmentAccsList = getTestSegments(testProps, isGuestSession); // get the
                                                                      // approved
                                                                      // accommodation
                                                                      // types/codes
                                                                      // from the
                                                                      // DB

        oppAccs = _oppRepository.getOpportunityAccommodations(oppInstance, testKey);

        Transformer groupTransformer = new Transformer() {
            @Override
            public Object transform(Object itsDocument) {
                return ((OpportunityAccommodation) itsDocument).getSegmentPosition();
            }
        };
        List<IGrouping<String, OpportunityAccommodation>> oppAccsLookup = IGrouping
                .<String, OpportunityAccommodation>createGroups(oppAccs, groupTransformer);
        Collections.sort(oppAccsLookup, new Comparator<IGrouping<String, OpportunityAccommodation>>() {
            @Override
            public int compare(IGrouping<String, OpportunityAccommodation> o1,
                    IGrouping<String, OpportunityAccommodation> o2) {
                return o1.getKey().compareTo(o2.getKey());
            }
        });

        // take all the approved accommodations and make a dictionary lookup by
        // segment position
        // var oppAccsLookup = oppAccs.OrderBy(OA =>
        // OA.SegmentPosition).GroupBy(OA
        // => OA.SegmentPosition).ToDictionary(OA => OA.Key);
        List<Accommodations> accommodationsList = new ArrayList<Accommodations>();
        for (Accommodations accommodations : segmentAccsList) {
            // check if there are any approved accommodations for this segment

            if (oppAccsLookup.contains(accommodations.getPosition())) {
                // for this test segments accommodation lookup the approved
                // accommodations

                OpportunityAccommodation codes = oppAccsLookup.get(accommodations.getPosition()).get(0);

                List<String> list = new ArrayList<String>();
                list.add(codes.getAccCode());
                // return only the approved subset

                // return accommodations.getSubset(codes);
                try {
                    accommodationsList.add(accommodations.getSubset(list));
                } catch (ReadOnlyException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else {
                // return empty subset
                // return accommodations.getSubset(new List<String>());
                accommodationsList.add(accommodations.getSubset(new ArrayList<String>()));
            }
        }
        return accommodationsList;
    } catch (ReadOnlyException e) {
        _logger.error(e.getMessage());
        throw new ReturnStatusException(e);
    }
}

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

public List<Accommodations> getApproved(OpportunityInstance oppInstance, String testKey, boolean isGuestSession)
        throws ReturnStatusException {
    List<OpportunityAccommodation> oppAccs = null;
    List<Accommodations> segmentAccsList = null;
    // get all the test and segment accommodations
    TestProperties testProps = null;//  w  w  w  .j a v  a2 s. com
    try {
        // FW Performance Changes - switched from _ibRepository to new ItemBankService which utilizes caching and other optimizations
        testProps = itemBankService.getTestProperties(testKey);
        segmentAccsList = getTestSegments(testProps, isGuestSession);
        oppAccs = _oppRepository.getOpportunityAccommodations(oppInstance, testKey);
        Transformer groupTransformer = new Transformer() {
            @Override
            public Object transform(Object itsDocument) {
                return ((OpportunityAccommodation) itsDocument).getSegmentPosition();
            }
        };
        List<IGrouping<Integer, OpportunityAccommodation>> oppAccsLookup = IGrouping
                .<Integer, OpportunityAccommodation>createGroups(oppAccs, groupTransformer);
        //Collections.sort (oppAccsLookup, new Comparator<IGrouping<String, OpportunityAccommodation>> ()
        //{
        //  @Override
        //  public int compare (IGrouping<String, OpportunityAccommodation> o1, IGrouping<String, OpportunityAccommodation> o2) {
        //    return o1.getKey ().compareTo (o2.getKey ());
        //  }
        //});

        // take all the approved accommodations and make a dictionary lookup by
        // segment position
        // var oppAccsLookup = oppAccs.OrderBy(OA =>
        // OA.SegmentPosition).GroupBy(OA
        // => OA.SegmentPosition).ToDictionary(OA => OA.Key);
        List<Accommodations> accommodationsList = new ArrayList<Accommodations>();
        for (Accommodations accommodations : segmentAccsList) {

            // check if there are any approved accommodations for this segment
            IGrouping<Integer, OpportunityAccommodation> a = findOppAcctLookupEntry(oppAccsLookup,
                    accommodations.getPosition());
            if (a != null) {
                // for this test segments accommodation lookup the approved
                // accommodations

                List<String> listAcc = getAccCodes(a);

                try {
                    accommodations.selectCodes(listAcc);
                    accommodationsList.add(accommodations.getSubset(listAcc));
                } catch (ReadOnlyException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else {
                // return empty subset
                // return accommodations.getSubset(new List<String>());
                accommodationsList.add(accommodations.getSubset(new ArrayList<String>()));
            }
        }
        return accommodationsList;
    } catch (ReadOnlyException e) {
        _logger.error(e.getMessage());
        throw new ReturnStatusException(e);
    } catch (Exception ex) {
        throw new ReturnStatusException(ex);
    }
}

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

private void setTesteeDefaults(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  ww  w  .  j av  a 2  s.  c o  m
        allRTSAccCodes = _testeeRepository.getAccommodations(testee);
        // get all the RTS accommodations that match this tests subject
        Collection<RTSAccommodation> subjectRTSAccCodes = (List<RTSAccommodation>) CollectionUtils
                .select(allRTSAccCodes, new Predicate() {
                    @Override
                    public boolean evaluate(Object object) {
                        RTSAccommodation rtsAttr = (RTSAccommodation) object;
                        return (rtsAttr.getAccFamily() == null
                                || rtsAttr.getAccFamily().equalsIgnoreCase(accFamily));
                    }
                });

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

        if (subjectRTSAccCodes != null)
            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<AccommodationType, AccommodationValue>> subjectAccValuesGroupedByType = IGrouping
                .<AccommodationType, AccommodationValue>createGroups(subjectAccValues, groupTransformer);
        Collections.sort(subjectAccValuesGroupedByType,
                new Comparator<IGrouping<AccommodationType, AccommodationValue>>() {
                    @Override
                    public int compare(IGrouping<AccommodationType, AccommodationValue> o1,
                            IGrouping<AccommodationType, AccommodationValue> o2) {
                        if (o1.getKey() == o2.getKey())
                            return 0;
                        else
                            return 1;
                        // return o1.getKey ().Comparable (o2.getKey ());
                    }
                });

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

        // select the new defaults for this type
        for (IGrouping<AccommodationType, AccommodationValue> subjectAccValuesGroup : subjectAccValuesGroupedByType) {
            AccommodationType subjectAccType = subjectAccValuesGroup.getKey();

            // 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);
    }
}