List of usage examples for java.util ListIterator previous
E previous();
From source file:org.apache.poi.ss.format.CellNumberFormatter.java
private void writeInteger(StringBuffer result, StringBuffer output, List<Special> numSpecials, Set<StringMod> mods, boolean showCommas) { int pos = result.indexOf(".") - 1; if (pos < 0) { if (exponent != null && numSpecials == integerSpecials) pos = result.indexOf("E") - 1; else//from w w w . j a va2s .com pos = result.length() - 1; } int strip; for (strip = 0; strip < pos; strip++) { char resultCh = result.charAt(strip); if (resultCh != '0' && resultCh != ',') break; } ListIterator<Special> it = numSpecials.listIterator(numSpecials.size()); boolean followWithComma = false; Special lastOutputIntegerDigit = null; int digit = 0; while (it.hasPrevious()) { char resultCh; if (pos >= 0) resultCh = result.charAt(pos); else { // If result is shorter than field, pretend there are leading zeros resultCh = '0'; } Special s = it.previous(); followWithComma = showCommas && digit > 0 && digit % 3 == 0; boolean zeroStrip = false; if (resultCh != '0' || s.ch == '0' || s.ch == '?' || pos >= strip) { zeroStrip = s.ch == '?' && pos < strip; output.setCharAt(s.pos, (zeroStrip ? ' ' : resultCh)); lastOutputIntegerDigit = s; } if (followWithComma) { mods.add(insertMod(s, zeroStrip ? " " : ",", StringMod.AFTER)); followWithComma = false; } digit++; --pos; } StringBuffer extraLeadingDigits = new StringBuffer(); if (pos >= 0) { // We ran out of places to put digits before we ran out of digits; put this aside so we can add it later ++pos; // pos was decremented at the end of the loop above when the iterator was at its end extraLeadingDigits = new StringBuffer(result.substring(0, pos)); if (showCommas) { while (pos > 0) { if (digit > 0 && digit % 3 == 0) extraLeadingDigits.insert(pos, ','); digit++; --pos; } } mods.add(insertMod(lastOutputIntegerDigit, extraLeadingDigits, StringMod.BEFORE)); } }
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 ww w.j av a 2s . co 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.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 a v a2s. 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.zenoss.zep.index.impl.EventIndexDaoImplIT.java
@Test public void testArchiveMissingInDb() throws ZepException { List<EventSummary> created = Lists.newArrayList(); for (int i = 0; i < 10; i++) { String summary = String.format("Event Archive %03d", i); EventSummary event = createArchiveClosed( Event.newBuilder(EventTestUtils.createSampleEvent()).setSummary(summary).build()); created.add(event);/*from www . ja v a 2s .c om*/ } this.eventArchiveIndexDao.indexMany(created); // Delete the first 3 events from the database (but don't delete from index) List<String> summariesToDelete = Lists.newArrayList(); for (int i = 0; i < 3; i++) { summariesToDelete.add(created.get(i).getOccurrence(0).getSummary()); } Map<String, List<String>> args = Collections.singletonMap("_summaries", summariesToDelete); this.simpleJdbcTemplate.update("DELETE FROM event_archive WHERE summary IN (:_summaries)", args); EventSort sort = EventSort.newBuilder().setField(Field.EVENT_SUMMARY).build(); EventSummaryRequest req = EventSummaryRequest.newBuilder().addSort(sort).build(); EventSummaryResult result = this.eventArchiveIndexDao.list(req); assertContainsEvents(result, created.subList(3, 10)); // Test sorting descending by summary sort = EventSort.newBuilder().setField(Field.EVENT_SUMMARY).setDirection(Direction.DESCENDING).build(); req = EventSummaryRequest.newBuilder().addSort(sort).build(); result = this.eventArchiveIndexDao.list(req); List<EventSummary> subList = created.subList(3, 10); assertContainsEvents(result, subList); ListIterator<EventSummary> it = subList.listIterator(subList.size()); int i = 0; while (it.hasPrevious()) { assertEquals(result.getEvents(i), it.previous()); ++i; } }
From source file:com.projity.pm.graphic.model.transform.NodeCacheTransformer.java
private void groupList(List list, List destList, ListIterator groupIterator, Node parentGroup, NodeTransformer composition, boolean preserveHierarchy) { NodeGroup group = (NodeGroup) groupIterator.next(); NodeSorter sorter = group.getSorter(); GraphicNodeComparator gcomp = new GraphicNodeComparator(sorter, composition); sorter.sortList(list, gcomp, preserveHierarchy); GraphicNode last = null;//from ww w . j ava 2s . c o m List nodes = null; GraphicNode current; for (ListIterator i = list.listIterator(); i.hasNext();) { current = (GraphicNode) i.next(); if (last == null) { nodes = new LinkedList(); } else if (gcomp.compare(last, current) != 0) { handleGroup(destList, groupIterator, parentGroup, group, last, nodes, composition, preserveHierarchy); nodes = new LinkedList(); } nodes.add(current); last = current; } if (nodes != null && nodes.size() > 0) { handleGroup(destList, groupIterator, parentGroup, group, last, nodes, composition, preserveHierarchy); } groupIterator.previous(); }
From source file:org.zkoss.poi.ss.format.CellNumberFormatter.java
private void writeInteger(StringBuffer result, StringBuffer output, List<Special> numSpecials, Set<StringMod> mods, boolean showCommas, boolean fraction) {//20100924, henrichen@zkoss.org: fraction has special treatment about zero //20100914, henrichen@zkoss.org: repect the current locale final char comma = Formatters.getGroupingSeparator(locale); final String commaStr = "" + comma; final String dot = "" + Formatters.getDecimalSeparator(locale); int pos = result.indexOf(dot) - 1; if (pos < 0) { if (exponent != null && numSpecials == integerSpecials) pos = result.indexOf("E") - 1; else/*w ww. ja v a 2s . co m*/ pos = result.length() - 1; } int strip; for (strip = 0; strip < pos; strip++) { char resultCh = result.charAt(strip); if (resultCh != '0' && resultCh != comma) break; } //20100924, henrichen@zkoss.org: handle all zero case final char posCh = !fraction && strip == pos && pos >= 0 ? result.charAt(pos) : '\000'; final boolean allZeros = posCh == '0' || posCh == comma; ListIterator<Special> it = numSpecials.listIterator(numSpecials.size()); boolean followWithComma = false; Special lastOutputIntegerDigit = null; int digit = 0; while (it.hasPrevious()) { char resultCh; if (pos >= 0) resultCh = result.charAt(pos); else { // If result is shorter than field, pretend there are leading zeros resultCh = '0'; } Special s = it.previous(); followWithComma = showCommas && digit > 0 && digit % 3 == 0; boolean zeroStrip = false; if (resultCh != '0' || s.ch == '0' || s.ch == '?' || pos >= strip) { zeroStrip = s.ch == '?' && (pos < strip || allZeros); //20100924, henrichen@zkoss.org: handle all zero case output.setCharAt(s.pos, (zeroStrip ? ' ' : resultCh)); lastOutputIntegerDigit = s; } if (followWithComma) { //20100914, henrichen@zkoss.org: repect the current locale //mods.add(insertMod(s, zeroStrip ? " " : ",", StringMod.AFTER)); mods.add(insertMod(s, zeroStrip ? " " : commaStr, StringMod.AFTER)); followWithComma = false; } digit++; --pos; } StringBuffer extraLeadingDigits = new StringBuffer(); if (pos >= 0) { // We ran out of places to put digits before we ran out of digits; put this aside so we can add it later ++pos; // pos was decremented at the end of the loop above when the iterator was at its end extraLeadingDigits = new StringBuffer(result.substring(0, pos)); if (showCommas) { while (pos > 0) { if (digit > 0 && digit % 3 == 0) //20100914, henrichen@zkoss.org: repect the current locale //extraLeadingDigits.insert(pos, ','); extraLeadingDigits.insert(pos, comma); digit++; --pos; } } mods.add(insertMod(lastOutputIntegerDigit, extraLeadingDigits, StringMod.BEFORE)); } }
From source file:org.slc.sli.dashboard.manager.impl.PopulationManagerImpl.java
/** * /*w w w. j a v a 2 s .c o m*/ * Finds the chronologically (strictly) earlier date on the list as compared * to the anchorDate. Note that this method assumes the dates list has been * chronologically sorted, the anchorDate is contained on it, and it has no * "null" entries. The input parameters themselves can be null, in which * case null is returned. * * @param dates * @param anchorDate */ @SuppressWarnings({ "unchecked", "rawtypes" }) private Date findPrevDate(List<Date> dates, Date anchorDate) { if (anchorDate == null || dates == null) { return null; } Date prevDate = null; ListIterator<Date> li = dates.listIterator(dates.indexOf(anchorDate)); while (li.hasPrevious()) { Date d = li.previous(); if (d.before(anchorDate)) { prevDate = d; break; } } return prevDate; }
From source file:mondrian.rolap.RolapStar.java
/** * Adds an {@link AggStar} to this star. * * <p>Internally the AggStars are added in sort order, smallest row count * to biggest, so that the most efficient AggStar is encountered first; * ties do not matter./*from www. j a va 2s. co m*/ */ public void addAggStar(AggStar aggStar) { // Add it before the first AggStar which is larger, if there is one. int size = aggStar.getSize(); ListIterator<AggStar> lit = aggStars.listIterator(); while (lit.hasNext()) { AggStar as = lit.next(); if (as.getSize() >= size) { lit.previous(); lit.add(aggStar); return; } } // There is no larger star. Add at the end of the list. aggStars.add(aggStar); }
From source file:com.xmobileapp.rockplayer.LastFmEventImporter.java
/********************************************** * //from w ww.j a va 2s. c o m * insertListInListByDate * @param singleArtistEventList * **********************************************/ public void insertListInListByDate(LinkedList<ArtistEvent> singleArtistEventList) { /* * If this artist List is empty just return */ if (singleArtistEventList.isEmpty()) return; /* * If the big list is empty just add this one to it */ if (artistEventList.isEmpty()) { artistEventList.addAll(singleArtistEventList); return; } /* * Insert the items (normal case) */ ListIterator<ArtistEvent> artistEventListIterator = artistEventList.listIterator(0); ListIterator<ArtistEvent> singleArtistEventListIterator = singleArtistEventList.listIterator(0); ArtistEvent artistEvent; ArtistEvent singleArtistEvent; while (singleArtistEventListIterator.hasNext()) { /* * Not yet at the end of the big list */ if (artistEventListIterator.hasNext()) { singleArtistEvent = singleArtistEventListIterator.next(); artistEvent = artistEventListIterator.next(); while (singleArtistEvent.dateInMillis > artistEvent.dateInMillis) { if (artistEventListIterator.hasNext()) artistEvent = artistEventListIterator.next(); else { if (artistEventListIterator.previousIndex() >= MAX_EVENT_LIST_SIZE) { return; } else { break; // TODO: add missing items to the big list } } } artistEventListIterator.previous(); artistEventListIterator.add(singleArtistEvent); } /* * At the end of the big list (but not of the 'small' list */ else { if (artistEventListIterator.previousIndex() >= MAX_EVENT_LIST_SIZE) return; singleArtistEvent = singleArtistEventListIterator.next(); artistEventListIterator.add(singleArtistEvent); artistEventListIterator.next(); } } /* * Keep the list size in check */ while (artistEventList.size() > MAX_EVENT_LIST_SIZE) artistEventList.removeLast(); }
From source file:org.rifidi.emulator.reader.thingmagic.commandobjects.CloseCommand.java
public CloseCommand(String command, ThingMagicReaderSharedResources tmsr) throws CommandCreationException { this.tmsr = tmsr; this.command = command; List<String> tokens = new ArrayList<String>(); /*//from w w w . ja va 2s . c o m * This regex looks for a Word, or a series of spaces on either side of * any single comparison operator or comma, or a single parentheses * (opening or closing). At the last ... any dangling spaces not * attached to the above groups and then anything else as a single * group. * * This makes it really easy to parse the command string as it becomes * really predictable tokens. */ Pattern tokenizer = Pattern.compile( // anything less... "[^\\s\\w]+|" + // groups we are looking for... "\\w+|" + "\\s+", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher tokenFinder = tokenizer.matcher(command.toLowerCase().trim()); while (tokenFinder.find()) { String temp = tokenFinder.group(); /* * no need to add empty strings at tokens. */ // TODO: Figure out why we are getting empty stings as tokens. if (temp.equals("")) continue; tokens.add(temp); } ListIterator<String> tokenIterator = tokens.listIterator(); String token = tokenIterator.next(); if (!token.equals("close")) throw new CommandCreationException("Error 0100: syntax error at '" + token + "'"); try { token = tokenIterator.next(); if (!token.matches(WHITE_SPACE)) throw new CommandCreationException("Error 0100: syntax error at '" + token + "'"); token = tokenIterator.next(); if (token.matches(A_WORD)) { cursorName = token; logger.debug("Cursor name is " + cursorName); } else { throw new CommandCreationException("Error 0100: syntax error at '" + token + "'"); } // check if the command correctly ends in a semicolon if (tokenIterator.hasNext()) { token = tokenIterator.next(); if (token.matches(WHITE_SPACE)) { token = tokenIterator.next(); } if (!token.equals(";")) { throw new CommandCreationException("Error 0100: syntax error at '" + token + "'"); } } else { throw new CommandCreationException("Error 0100: syntax error at '\n'"); } } catch (NoSuchElementException e) { /* * if we get here... we run out of tokens prematurely... Our job now * is to walk backwards to find the last non space tokens and throw * an exception saying that there is an syntax error at that point. */ /* * look for the last offending command block that is not a series of * whitespaces. */ token = tokenIterator.previous(); while (token.matches(WHITE_SPACE)) { token = tokenIterator.previous(); } logger.debug("Premature end of token list detected."); throw new CommandCreationException("Error 0100: syntax error at '" + token + "'"); } if (!tmsr.getCursorCommandRegistry().containsKey(cursorName)) { throw new CommandCreationException("Error 0100: DELETE: Cursor does not exist\n"); } }