Example usage for java.util ListIterator previousIndex

List of usage examples for java.util ListIterator previousIndex

Introduction

In this page you can find the example usage for java.util ListIterator previousIndex.

Prototype

int previousIndex();

Source Link

Document

Returns the index of the element that would be returned by a subsequent call to #previous .

Usage

From source file:org.netflux.core.task.compose.SplitTask.java

@Override
protected RecordMetadata computeMetadata(String outputPortName, InputPort changedInputPort,
        RecordMetadata newMetadata) {/*from   w w w. j a  va2 s.  c om*/
    int insertionPoint = Integer.MAX_VALUE;
    RecordMetadata inputMetadata = this.inputPorts.get("input").getMetadata();

    if (inputMetadata != null && inputMetadata.getFieldCount() > 0) {
        List<FieldMetadata> fieldMetadata = new LinkedList<FieldMetadata>(inputMetadata.getFieldMetadata());
        ListIterator<FieldMetadata> fieldMetadataIterator = fieldMetadata.listIterator();
        while (fieldMetadataIterator.hasNext()) {
            FieldMetadata currentFieldMetadata = fieldMetadataIterator.next();
            if (this.fieldNamesToSplitAsSet.contains(currentFieldMetadata.getName())) {
                insertionPoint = Math.min(insertionPoint, fieldMetadataIterator.previousIndex());
                fieldMetadataIterator.remove();
            }
        }

        List<FieldMetadata> splittedMetadata = new LinkedList<FieldMetadata>();
        Iterator<String> splittedFieldNameIterator = this.splittedFieldNames.iterator();
        for (String fieldName : this.fieldNamesToSplit.get(0)) {
            // FIXME: Do this properly: getFieldMetadata should throw an Exception
            if (inputMetadata.getFieldIndex(fieldName) != -1) {
                FieldMetadata currentSplittedMetadata = inputMetadata.getFieldMetadata(fieldName).clone();
                currentSplittedMetadata.setName(splittedFieldNameIterator.next());
                splittedMetadata.add(currentSplittedMetadata);
            } else {
                splittedMetadata.clear();
                insertionPoint = fieldMetadata.size();
                break;
            }
        }

        fieldMetadata.addAll(insertionPoint, splittedMetadata);

        return new RecordMetadata(fieldMetadata);
    } else {
        List<FieldMetadata> emptyMetadata = Collections.emptyList();
        return new RecordMetadata(emptyMetadata);
    }
}

From source file:org.openconcerto.openoffice.ODSingleXMLDocument.java

/**
 * Slice the body into parts. Since some content have no part (e.g. comment), they can be added
 * to the previous or next range. If <code>overlapping</code> is <code>true</code> they will be
 * added to both, else only to the next range.
 * //from  w ww .  ja  v a 2s. c om
 * @param parts parts definition.
 * @param body the element to slice.
 * @param overlapping <code>true</code> if ranges can overlap.
 * @return the start (inclusive, {@link Point#x}) and end (exclusive, {@link Point#y}) for each
 *         {@link ContentPart}.
 */
static private Point[] getBounds(final Map<Tuple2<Namespace, String>, ContentPart> parts, final Element body,
        final boolean overlapping) {
    @SuppressWarnings("unchecked")
    final List<Content> content = body.getContent();
    final int contentSize = content.size();
    if (contentSize == 0)
        return new Point[] { new Point(0, 0), new Point(0, 0), new Point(0, 0) };

    // start from the beginning until we leave the prologue
    ContentPart contentPart = null;
    ListIterator<Content> thisChildrenIter = content.listIterator(0);
    final int prologueStart = 0;
    int nullsStartIndex = -1;
    while ((contentPart == null || contentPart == ContentPart.PROLOGUE) && thisChildrenIter.hasNext()) {
        contentPart = getPart(parts, thisChildrenIter.next());
        if (contentPart != null) {
            nullsStartIndex = -1;
        } else if (nullsStartIndex < 0) {
            nullsStartIndex = thisChildrenIter.previousIndex();
        }
    }
    final int nullsEnd = contentPart == null || contentPart == ContentPart.PROLOGUE
            ? thisChildrenIter.nextIndex()
            : thisChildrenIter.previousIndex();
    final int nullsStart = nullsStartIndex < 0 ? nullsEnd : nullsStartIndex;
    assert nullsStart >= 0 && nullsStart <= nullsEnd;
    final int mainStart = nullsStart;
    final int prologueStop = overlapping ? nullsEnd : nullsStart;

    final int epilogueEnd = contentSize;
    final int[] lastNulls = getLastNulls(parts, content, contentSize);
    final int lastNullsStart = lastNulls[0];
    final int lastNullsEnd = lastNulls[1];
    assert lastNullsStart >= mainStart && lastNullsStart <= lastNullsEnd;
    final int epilogueStart = lastNullsStart;
    final int mainEnd = overlapping ? lastNullsEnd : lastNullsStart;

    final Point[] res = new Point[] { new Point(prologueStart, prologueStop), new Point(mainStart, mainEnd),
            new Point(epilogueStart, epilogueEnd) };
    assert res.length == ContentPart.values().length;
    return res;
}

From source file:org.pentaho.metadata.query.impl.sql.graph.MqlGraph.java

/**
 * Attempts to find next valid solution to the graph depending on what type of <code>PathType</code> is desired.
 * /*from w w  w . j av a 2  s.c o m*/
 * @param searchTechnique
 *          Indicates type of search that should be performed
 * @param prevSolution
 *          Previous solution to allow this search to continue from that point
 * @return The resulting solution
 * @throws ConsistencyException
 *           When determine that graph is impossible to satisfy
 */
private Solution searchForNextSolution(PathType searchTechnique, Solution prevSolution)
        throws ConsistencyException {
    // A left move equates to setting a requirement to false and a right move is equivalent to true.
    // Try setting to "false" first to reduce the number of tables for most searches.
    // For the "any relevant" search use "true" first which is quicker
    SearchDirection firstDirection;
    SearchDirection secondDirection;
    if (searchTechnique == PathType.ANY_RELEVANT) {
        firstDirection = SearchDirection.RIGHT;
        secondDirection = SearchDirection.LEFT;
    } else {
        firstDirection = SearchDirection.LEFT;
        secondDirection = SearchDirection.RIGHT;
    }

    // if this is a subsequent search after a solution was already found, we need
    // to return to the location where the last move in the first direction was made
    List<SearchDirection> searchPath = new LinkedList<SearchDirection>();
    List<Arc> searchArcs = new LinkedList<Arc>();
    if (prevSolution != null) {
        // check for situation where we have already traversed all possible paths
        boolean prevContainsFirstDirection = false;
        for (SearchDirection direction : prevSolution.searchPath) {
            if (direction == firstDirection) {
                prevContainsFirstDirection = true;
                break;
            }
        }
        if (!prevContainsFirstDirection) {
            return null;
        }

        ListIterator<SearchDirection> pathIter = prevSolution.searchPath
                .listIterator(prevSolution.searchPath.size());

        // continue to move back in search path until we find an arc that can
        // be assigned the second direction
        boolean foundSecondDir = false;
        while (pathIter.hasPrevious() && !foundSecondDir) {

            // reset the search function for next search operation
            reset(requiredTables);
            propagate();
            searchPath.clear();
            searchArcs.clear();

            // locate the last move that has an alternative
            while (pathIter.hasPrevious()) {
                SearchDirection direction = pathIter.previous();

                if (direction == firstDirection) {
                    break;
                }
            }

            // recreate path up to point where we can try a different direction
            Iterator<Arc> arcIter = prevSolution.getSearchArcs().iterator();
            if (pathIter.hasPrevious()) {
                Iterator<SearchDirection> redoIter = prevSolution.getSearchPath().iterator();
                int lastIdx = pathIter.previousIndex();
                for (int idx = 0; idx <= lastIdx; idx++) {

                    // all of these operations should work without issue
                    SearchDirection direction = redoIter.next();
                    Arc arc = arcIter.next();
                    if (!attemptArcAssignment(arc, direction)) {
                        throw new ConsistencyException(arc);
                    }

                    // add movement to newly constructed search path
                    searchPath.add(direction);
                    searchArcs.add(arc);
                }
            }

            // before any searching will begin, make sure the path we are going down shouldn't
            // just be skipped
            int rating = getRatingForCurrentState(searchTechnique);

            // current state isn't any better, return it as next solution
            if (rating >= prevSolution.getRating()) {
                return new Solution(arcs, rating, searchPath, searchArcs, true);
            }

            // retrieve arc which we are going to move second direction
            Arc arc = arcIter.next();

            // if we can't move the second direction here, continue
            // to move back in search path until we find an arc that can
            // be assigned the second direction
            if (attemptArcAssignment(arc, secondDirection)) {
                // update new search path
                searchPath.add(secondDirection);
                searchArcs.add(arc);

                // before any searching will begin, make sure the path we are going down shouldn't
                // just be skipped
                rating = getRatingForCurrentState(searchTechnique);

                // current state isn't any better, return it as next solution
                if (rating >= prevSolution.getRating()) {
                    return new Solution(arcs, rating, searchPath, searchArcs, true);
                }

                // set second direction flag so search will continue
                foundSecondDir = true;
            }
        }

        // if we weren't able to make another movement, there are not more solutions
        if (searchPath.size() == 0) {
            return null;
        }
    }

    // dump current state of graph
    if (logger.isDebugEnabled()) {
        logger.debug("-- Graph State Before Search --");
        dumpStateToLog();
    }

    // look for arcs that are not bound
    int rating = -1;
    for (Arc a : arcs) {
        if (!a.isRequirementKnown()) {
            // try the first direction
            if (attemptArcAssignment(a, firstDirection)) {
                searchPath.add(firstDirection);
            } else if (attemptArcAssignment(a, secondDirection)) { // if first direction fails, try the second
                searchPath.add(secondDirection);
            } else { // If arc cannot be assigned a requirement value, throw an exception
                throw new ConsistencyException(a);
            }

            // record arc that was altered in search path
            searchArcs.add(a);

            // make sure solution is getting better
            if (prevSolution != null) {
                rating = getRatingForCurrentState(searchTechnique);

                // current state isn't any better, return it as next solution
                if (rating >= prevSolution.getRating()) {
                    return new Solution(arcs, rating, searchPath, searchArcs, true);
                }
            }
        }
    }

    // compute rating if never computed
    if (rating < 0) {
        rating = getRatingForCurrentState(searchTechnique);
    }
    // return solution to graph problem
    return new Solution(arcs, rating, searchPath, searchArcs, false);
}

From source file:org.pentaho.pms.mql.graph.MqlGraph.java

/**
 * Attempts to find next valid solution to the graph depending on what type of <code>PathType</code> is desired.
 *
 * @param searchTechnique Indicates type of search that should be performed
 * @param prevSolution    Previous solution to allow this search to continue from that point
 * @return The resulting solution//from   w w w  . j a va  2 s . c o  m
 * @throws ConsistencyException When determine that graph is impossible to satisfy
 */
private Solution searchForNextSolution(PathType searchTechnique, Solution prevSolution)
        throws ConsistencyException {
    // A left move equates to setting a requirement to false and a right move is equivalent to true.
    // Try setting to "false" first to reduce the number of tables for most searches.
    // For the "any relevant" search use "true" first which is quicker
    SearchDirection firstDirection;
    SearchDirection secondDirection;
    if (searchTechnique == PathType.ANY_RELEVANT) {
        firstDirection = SearchDirection.RIGHT;
        secondDirection = SearchDirection.LEFT;
    } else {
        firstDirection = SearchDirection.LEFT;
        secondDirection = SearchDirection.RIGHT;
    }

    // if this is a subsequent search after a solution was already found, we need
    // to return to the location where the last move in the first direction was made
    List<SearchDirection> searchPath = new LinkedList<SearchDirection>();
    List<Arc> searchArcs = new LinkedList<Arc>();
    if (prevSolution != null) {
        // check for situation where we have already traversed all possible paths
        boolean prevContainsFirstDirection = false;
        for (SearchDirection direction : prevSolution.searchPath) {
            if (direction == firstDirection) {
                prevContainsFirstDirection = true;
                break;
            }
        }
        if (!prevContainsFirstDirection) {
            return null;
        }

        ListIterator<SearchDirection> pathIter = prevSolution.searchPath
                .listIterator(prevSolution.searchPath.size());

        // continue to move back in search path until we find an arc that can
        // be assigned the second direction
        boolean foundSecondDir = false;
        while (pathIter.hasPrevious() && !foundSecondDir) {

            // reset the search function for next search operation
            reset(requiredTables);
            propagate();
            searchPath.clear();
            searchArcs.clear();

            // locate the last move that has an alternative
            while (pathIter.hasPrevious()) {
                SearchDirection direction = pathIter.previous();

                if (direction == firstDirection) {
                    break;
                }
            }

            // recreate path up to point where we can try a different direction
            Iterator<Arc> arcIter = prevSolution.getSearchArcs().iterator();
            if (pathIter.hasPrevious()) {
                Iterator<SearchDirection> redoIter = prevSolution.getSearchPath().iterator();
                int lastIdx = pathIter.previousIndex();
                for (int idx = 0; idx <= lastIdx; idx++) {

                    // all of these operations should work without issue
                    SearchDirection direction = redoIter.next();
                    Arc arc = arcIter.next();
                    if (!attemptArcAssignment(arc, direction)) {
                        throw new ConsistencyException(arc);
                    }

                    // add movement to newly constructed search path
                    searchPath.add(direction);
                    searchArcs.add(arc);
                }
            }

            // before any searching will begin, make sure the path we are going down shouldn't
            // just be skipped
            int rating = getRatingForCurrentState(searchTechnique);

            // current state isn't any better, return it as next solution
            if (rating >= prevSolution.getRating()) {
                return new Solution(arcs, rating, searchPath, searchArcs, true);
            }

            // retrieve arc which we are going to move second direction
            Arc arc = arcIter.next();

            // if we can't move the second direction here, continue
            // to move back in search path until we find an arc that can
            // be assigned the second direction
            if (attemptArcAssignment(arc, secondDirection)) {
                // update new search path
                searchPath.add(secondDirection);
                searchArcs.add(arc);

                // before any searching will begin, make sure the path we are going down shouldn't
                // just be skipped
                rating = getRatingForCurrentState(searchTechnique);

                // current state isn't any better, return it as next solution
                if (rating >= prevSolution.getRating()) {
                    return new Solution(arcs, rating, searchPath, searchArcs, true);
                }

                // set second direction flag so search will continue
                foundSecondDir = true;
            }
        }

        // if we weren't able to make another movement, there are not more solutions
        if (searchPath.size() == 0) {
            return null;
        }
    }

    // dump current state of graph
    if (logger.isDebugEnabled()) {
        logger.debug("-- Graph State Before Search --");
        dumpStateToLog();
    }

    // look for arcs that are not bound
    int rating = -1;
    for (Arc a : arcs) {
        if (!a.isRequirementKnown()) {
            // try the first direction
            if (attemptArcAssignment(a, firstDirection)) {
                searchPath.add(firstDirection);
            } else if (attemptArcAssignment(a, secondDirection)) { // if first direction fails, try the second
                searchPath.add(secondDirection);
            } else { // If arc cannot be assigned a requirement value, throw an exception
                throw new ConsistencyException(a);
            }

            // record arc that was altered in search path
            searchArcs.add(a);

            // make sure solution is getting better
            if (prevSolution != null) {
                rating = getRatingForCurrentState(searchTechnique);

                // current state isn't any better, return it as next solution
                if (rating >= prevSolution.getRating()) {
                    return new Solution(arcs, rating, searchPath, searchArcs, true);
                }
            }
        }
    }

    // compute rating if never computed
    if (rating < 0) {
        rating = getRatingForCurrentState(searchTechnique);
    }

    // return solution to graph problem
    return new Solution(arcs, rating, searchPath, searchArcs, false);
}

From source file:org.rhq.enterprise.server.plugins.alertSnmp.SnmpSenderTest.java

private void assertExpectedPdu(PDU pdu, PduExpectedValues expectedValues) {
    Vector variableBindings = pdu.getVariableBindings();

    assertTrue(variableBindings.size() == 9, "Variable bindings should contain 9 variable bindings and not "
            + variableBindings.size() + ": " + variableBindings);

    @SuppressWarnings("unchecked")
    ListIterator<VariableBinding> variableBindingsIterator = variableBindings.listIterator();

    VariableBinding variableBinding = variableBindingsIterator.next();
    assertEquals(variableBinding.getOid(), SnmpConstants.sysUpTime);

    variableBinding = variableBindingsIterator.next();
    assertEquals(variableBinding.getOid(), SnmpConstants.snmpTrapOID);
    assertEquals(variableBinding.getVariable(), expectedValues.getSnmpTrapOid());

    OID oidPrefix = new OID(TEST_VARIABLE_BINDING_PREFIX);
    while (variableBindingsIterator.hasNext()) {
        variableBinding = variableBindingsIterator.next();

        assertVariableBindingIsPrefixed(variableBinding, oidPrefix);
        assertVariableBindingHasStringValue(variableBinding);

        switch (variableBindingsIterator.previousIndex()) {
        case 2:/*from w  w w.  java2s  . c  o m*/
            assertEquals(variableBinding.getVariable(),
                    new OctetString(expectedValues.getAlertDefinitionName()));
            break;
        case 3:
            assertEquals(variableBinding.getVariable(), new OctetString(expectedValues.getResourceName()));
            break;
        case 4:
            assertEquals(variableBinding.getVariable(), new OctetString(expectedValues.getPlatformName()));
            break;
        case 5:
            assertEquals(variableBinding.getVariable(), new OctetString(expectedValues.getAlertConditions()));
            break;
        case 6:
            assertEquals(variableBinding.getVariable(),
                    new OctetString(expectedValues.getAlertPriority().toString().toLowerCase()));
            break;
        case 7:
            assertEquals(variableBinding.getVariable(), new OctetString(expectedValues.getAlertUrl()));
            break;
        case 8:
            assertEquals(variableBinding.getVariable(), new OctetString(
                    expectedValues.getPlatformName() + "::" + expectedValues.getResourceName() + "::"));
            break;
        default:
            throw new RuntimeException("Unexpected index: " + variableBindingsIterator.previousIndex());
        }
    }
}

From source file:org.sakaiproject.tool.assessment.ui.listener.evaluation.TotalScoreListener.java

public void prepareAgentResult(PublishedAssessmentData p, Iterator iter, ArrayList agents, Map userRoles) {

    TotalScoresBean bean = (TotalScoresBean) ContextUtil.lookupBean("totalScores");
    while (iter.hasNext()) {
        AgentResults results = new AgentResults();
        AssessmentGradingData gdata = (AssessmentGradingData) iter.next();

        // no need to initialize itemSet 'cos we don't need to use it in totalScoresPage. So I am
        // stuffing it with an empty HashSet - daisyf
        gdata.setItemGradingSet(new HashSet());
        //gdata.setItemGradingSet(gradingService.getItemGradingSet(gdata.getAssessmentGradingId().toString()));
        try {//w  ww . j  a v  a2s.c o m
            BeanUtils.copyProperties(results, gdata);
        } catch (Exception e) {
            log.warn(e.getMessage());
        }

        results.setAssessmentGradingId(gdata.getAssessmentGradingId());
        if (gdata.getTotalAutoScore() != null) {
            if (gdata.getForGrade()) {
                results.setTotalAutoScore(gdata.getTotalAutoScore().toString());
                results.setForGrade(Boolean.TRUE);
            } else {
                results.setTotalAutoScore("-");
                results.setForGrade(Boolean.FALSE);
            }
        } else
            results.setTotalAutoScore("0.0");

        if (gdata.getTotalOverrideScore() != null)
            results.setTotalOverrideScore(gdata.getTotalOverrideScore().toString());
        else
            results.setTotalOverrideScore("0.0");

        if (gdata.getFinalScore() != null) {
            results.setFinalScore(gdata.getFinalScore().toString());
            results.setScoreSummation(gdata.getFinalScore());
            results.setSubmissionCount(1);
        } else
            results.setFinalScore("0.0");

        if (gdata.getTimeElapsed() != null)
            results.setTimeElapsed(gdata.getTimeElapsed());
        else
            results.setTimeElapsed(Integer.valueOf(0));

        results.setComments(FormattedText.convertFormattedTextToPlaintext(gdata.getComments()));

        results.setIsLate(gdata.getIsLate());

        Date dueDate = null;
        PublishedAccessControl ac = (PublishedAccessControl) p.getAssessmentAccessControl();
        if (ac != null)
            dueDate = ac.getDueDate();
        /*
        if (dueDate == null || gdata.getSubmittedDate() == null || gdata.getSubmittedDate().before(dueDate)) {   
          results.setIsLate(Boolean.FALSE);
        }
        else {
          results.setIsLate(Boolean.TRUE);
          // The mock up has been updated. For a late submission, the "LATE" will be displayed
          // under Submission Date column instead of Status column. Therefore, we will not treat
          // LATE_SUBMISSION as a status. Comment out the following line for this reason.
          //results.setStatus(AssessmentGradingIfc.LATE_SUBMISSION);
        }
        */

        if (gdata.getIsAutoSubmitted() != null && gdata.getIsAutoSubmitted().equals(Boolean.TRUE)) {
            results.setIsAutoSubmitted(true);
        } else {
            results.setIsAutoSubmitted(false);
        }

        // For assessments accept late submission, if 
        // 1. student starts taking it after the due date
        // 2. the assessment is submitted by auto-submit (not student)
        // we want to display LATE instead of AUTO-SUBMIT on the total scores page
        // That's why we set this info here
        if (dueDate != null && gdata.getAttemptDate() != null && gdata.getAttemptDate().after(dueDate)) {
            results.setIsAttemptDateAfterDueDate(true);
        } else {
            results.setIsAttemptDateAfterDueDate(false);
        }

        AgentFacade agent = new AgentFacade(gdata.getAgentId());
        results.setLastName(agent.getLastName());
        results.setFirstName(agent.getFirstName());
        results.setEmail(agent.getEmail());
        if (results.getLastName() != null && results.getLastName().length() > 0)
            results.setLastInitial(results.getLastName().substring(0, 1));
        else if (results.getFirstName() != null && results.getFirstName().length() > 0)
            results.setLastInitial(results.getFirstName().substring(0, 1));
        else
            results.setLastInitial("Anonymous");
        results.setIdString(agent.getIdString());
        results.setAgentEid(agent.getEidString());
        results.setAgentDisplayId(agent.getDisplayIdString());
        log.debug("testing agent getEid agent.getFirstname= " + agent.getFirstName());
        log.debug("testing agent getEid agent.getid= " + agent.getIdString());
        log.debug("testing agent getEid agent.geteid = " + agent.getEidString());
        log.debug("testing agent getDisplayId agent.getdisplayid = " + agent.getDisplayIdString());

        results.setRole((String) userRoles.get(gdata.getAgentId()));

        if (bean.getAllSubmissions().equals("4") && bean.getScoringOption().equals("4") && agents.size() > 0) {
            ListIterator<AgentResults> it = agents.listIterator();
            boolean updated = false;
            while (it.hasNext()) {
                AgentResults ar = (AgentResults) it.next();
                if (ar.getAgentId().equals(results.getAgentId())) {
                    agents.remove(it.previousIndex());
                    ar.setSubmissionCount((ar.getSubmissionCount()) + 1);
                    ar.setScoreSummation(ar.getScoreSummation() + gdata.getFinalScore());
                    ar.setAssessmentGradingId(results.getAssessmentGradingId());
                    agents.add(ar);
                    updated = true;
                }
            } //end of while loop
            if (!updated)
                agents.add(results);
        } else {
            agents.add(results);
        }
    }

    if (bean.getAllSubmissions().equals("4") && bean.getScoringOption().equals("4") && agents.size() > 0) {
        Iterator it = agents.iterator();
        while (it.hasNext()) {
            AgentResults ar = (AgentResults) it.next();
            Double averageScore = ar.getScoreSummation() / ar.getSubmissionCount();
            ar.setFinalScore(averageScore.toString());
            ar.setComments(null);
            ar.setSubmittedDate(new Date());
            ar.setStatus(null);
            ar.setItemGradingSet(null);

        }
    }
}

From source file:org.squale.squaleweb.transformer.ResultListTransformer.java

/**
 * @param pObject le tableau de ProjectDTO  transformer en formulaires.
 * @param pForm le formulaire  remplir.//w  w  w . j  a va2s  .c o  m
 * @throws WTransformerException si un pb apparat.
 */
public void objToForm(Object[] pObject, WActionForm pForm) throws WTransformerException {
    List tre = (List) pObject[0];
    // On supprime les objets nuls
    tre.remove(null);
    // Concersion en liste de String
    List values = SqualeWebActionUtils.getAsStringsList((List) pObject[1]);
    ArrayList result = new ArrayList();
    ResultListForm form = (ResultListForm) pForm;
    ListIterator it = tre.listIterator();
    ResultForm resultForm = null;
    // On rcupre les rgles
    while (it.hasNext()) {
        resultForm = new ResultForm();
        Object currentTre = it.next();
        // sous forme de TRE ou sous forme de QualityResultDTO
        if (currentTre instanceof String) {
            resultForm.setName((String) currentTre);
        } else {
            QualityRuleDTO rule = (QualityRuleDTO) currentTre;
            resultForm.setName(rule.getName());
            // Dans ce cas on renseigne aussi l'id de la rgle
            resultForm.setId("" + rule.getId());
        }
        try {
            String value = (String) values.get(it.previousIndex());
            // Cas o la rgle n'a pa de note
            if (value == null || value.startsWith("-")) {
                value = "-";
            }
            // formatage HTML
            value = value.replaceAll(" ", "&nbsp;");
            resultForm.setCurrentMark(value.replaceAll("\n", "<br/>"));
        } catch (Exception e) {
            // TODO voir comment ce code est activ
            // l'accs  it.previousIndex() est trange
            LOGGER.debug(e, e);
        }
        result.add(resultForm);
    }
    form.setList(result);
}

From source file:org.squale.squaleweb.transformer.ResultListTransformer.java

/**
 * @param pObject le tableau de ProjectDTO  transformer en formulaires.
 * @param pForm le formulaire  remplir./*w w w.  j a v a  2 s  .com*/
 * @param pLanguage le langage de programmation du projet
 * @throws WTransformerException si un pb apparat.
 */
public static void objToFormWithLanguage(Object[] pObject, WActionForm pForm, String pLanguage)
        throws WTransformerException {
    List tre = (List) pObject[0];
    // On supprime les objets nuls
    tre.remove(null);
    // Concersion en liste de String
    List values = SqualeWebActionUtils.getAsStringsList((List) pObject[1]);
    ArrayList result = new ArrayList();
    ResultListForm form = (ResultListForm) pForm;
    ListIterator it = tre.listIterator();
    ResultForm resultForm = null;
    // On rcupre les rgles
    while (it.hasNext()) {
        resultForm = new ResultForm();
        Object currentTre = it.next();
        // sous forme de TRE ou sous forme de QualityResultDTO
        if (currentTre instanceof String) {
            String name = (String) currentTre;
            if (WebMessages.existString(currentTre + "." + pLanguage)) {
                name = name + "." + pLanguage;
            }
            resultForm.setName((String) name);
        } else {
            QualityRuleDTO rule = (QualityRuleDTO) currentTre;
            String ruleName = rule.getName();
            if (WebMessages.existString(ruleName + "." + pLanguage)) {
                ruleName = ruleName + "." + pLanguage;
            }
            resultForm.setName(ruleName);
            // Dans ce cas on renseigne aussi l'id de la rgle
            resultForm.setId("" + rule.getId());
        }
        try {
            String value = (String) values.get(it.previousIndex());
            // Cas o la rgle n'a pa de note
            if (value == null || value.startsWith("-")) {
                value = "-";
            }
            // formatage HTML
            value = value.replaceAll(" ", "&nbsp;");
            resultForm.setCurrentMark(value.replaceAll("\n", "<br/>"));
        } catch (Exception e) {
            // TODO voir comment ce code est activ
            // l'accs  it.previousIndex() est trange
            LOGGER.debug(e, e);
        }
        result.add(resultForm);
    }
    form.setList(result);
}

From source file:org.squashtest.tm.domain.campaign.Iteration.java

/***
 * Method which returns the position of a test case in the current iteration
 *
 * @param testCaseId// w w  w.  j a  va2s  .co  m
 *            the id of the test case we're looking for
 * @return the position of the test case (int)
 * @throws UnknownEntityException
 *             if not found.
 */
public int findTestCaseIndexInTestPlan(long testCaseId) {
    ListIterator<IterationTestPlanItem> iterator = testPlans.listIterator();
    while (iterator.hasNext()) {
        IterationTestPlanItem itemTestPlan = iterator.next();

        if (!itemTestPlan.isTestCaseDeleted()
                && itemTestPlan.getReferencedTestCase().getId().equals(testCaseId)) {
            return iterator.previousIndex();
        }
    }

    throw new UnknownEntityException(testCaseId, TestCase.class);

}

From source file:org.squashtest.tm.domain.campaign.Iteration.java

/***
 * Method which returns the position of an item test plan in the current iteration
 *
 * @param testPlanId//from  w w  w  . j a  v  a2s  .  c om
 *            the id of the test plan we're looking for
 * @return the position of the test plan (int)
 * @throws UnknownEntityException
 *             if not found.
 */
public int findItemIndexInTestPlan(long testPlanId) {

    ListIterator<IterationTestPlanItem> iterator = testPlans.listIterator();
    while (iterator.hasNext()) {
        IterationTestPlanItem itemTestPlan = iterator.next();

        if (itemTestPlan.getId().equals(testPlanId)) {

            return iterator.previousIndex();
        }
    }

    throw new UnknownEntityException(testPlanId, IterationTestPlanItem.class);

}