List of usage examples for java.util ListIterator set
void set(E e);
From source file:org.apache.fop.layoutmgr.table.ActiveCell.java
/** * Modifies the cell's element list by putting filler elements, so that the cell's or * row's explicit height is always reached. * * TODO this will work properly only for the first break. Then the limitation * explained on http://wiki.apache.org/xmlgraphics-fop/TableLayout/KnownProblems * occurs. The list of elements needs to be re-adjusted after each break. *//*from w w w. j ava 2s .c o m*/ private void handleExplicitHeight(MinOptMax cellBPD, MinOptMax rowBPD) { int minBPD = Math.max(cellBPD.getMin(), rowBPD.getMin()); if (minBPD > 0) { ListIterator iter = elementList.listIterator(); int cumulateLength = 0; boolean prevIsBox = false; while (iter.hasNext() && cumulateLength < minBPD) { KnuthElement el = (KnuthElement) iter.next(); if (el.isBox()) { prevIsBox = true; cumulateLength += el.getWidth(); } else if (el.isGlue()) { if (prevIsBox) { elementList.add(iter.nextIndex() - 1, new FillerPenalty(minBPD - cumulateLength)); } prevIsBox = false; cumulateLength += el.getWidth(); } else { prevIsBox = false; if (cumulateLength + el.getWidth() < minBPD) { iter.set(new FillerPenalty((KnuthPenalty) el, minBPD - cumulateLength)); } } } } int optBPD = Math.max(minBPD, Math.max(cellBPD.getOpt(), rowBPD.getOpt())); if (pgu.getContentLength() < optBPD) { elementList.add(new FillerBox(optBPD - pgu.getContentLength())); } }
From source file:de.unijena.bioinf.FragmentationTreeConstruction.computation.FragmentationPatternAnalysis.java
/** * Step 6: Decomposition/* w w w. j a v a 2s. com*/ * Decompose each peak as well as the parent peak */ public ProcessedInput performDecomposition(ProcessedInput input) { final FormulaConstraints constraints = input.getMeasurementProfile().getFormulaConstraints(); final Ms2Experiment experiment = input.getExperimentInformation(); final Deviation parentDeviation = input.getMeasurementProfile().getAllowedMassDeviation(); // sort again... final ArrayList<ProcessedPeak> processedPeaks = new ArrayList<ProcessedPeak>(input.getMergedPeaks()); Collections.sort(processedPeaks, new ProcessedPeak.MassComparator()); final ProcessedPeak parentPeak = processedPeaks.get(processedPeaks.size() - 1); // decompose peaks final PeakAnnotation<DecompositionList> decompositionList = input .getOrCreatePeakAnnotation(DecompositionList.class); final MassToFormulaDecomposer decomposer = decomposers.getDecomposer(constraints.getChemicalAlphabet()); final Ionization ion = experiment.getPrecursorIonType().getIonization(); final Deviation fragmentDeviation = input.getMeasurementProfile().getAllowedMassDeviation(); final List<MolecularFormula> pmds = decomposer.decomposeToFormulas( experiment.getPrecursorIonType().subtractIonAndAdduct(parentPeak.getOriginalMz()), parentDeviation, constraints); // add adduct to molecular formula of the ion - because the adduct might get lost during fragmentation { final MolecularFormula adduct = experiment.getPrecursorIonType().getAdduct(); final ListIterator<MolecularFormula> iter = pmds.listIterator(); while (iter.hasNext()) { final MolecularFormula f = iter.next(); iter.set(f.add(adduct)); } } decompositionList.set(parentPeak, DecompositionList.fromFormulas(pmds)); int j = 0; for (ProcessedPeak peak : processedPeaks.subList(0, processedPeaks.size() - 1)) { peak.setIndex(j++); decompositionList.set(peak, DecompositionList.fromFormulas( decomposer.decomposeToFormulas(peak.getUnmodifiedMass(), fragmentDeviation, constraints))); } parentPeak.setIndex(processedPeaks.size() - 1); assert parentPeak == processedPeaks.get(processedPeaks.size() - 1); // important: for each two peaks which are within 2*massrange: // => make decomposition list disjoint final Deviation window = fragmentDeviation.multiply(2); for (int i = 1; i < processedPeaks.size() - 1; ++i) { if (window.inErrorWindow(processedPeaks.get(i).getMz(), processedPeaks.get(i - 1).getMz())) { final HashSet<MolecularFormula> right = new HashSet<MolecularFormula>( decompositionList.get(processedPeaks.get(i)).getFormulas()); final ArrayList<MolecularFormula> left = new ArrayList<MolecularFormula>( decompositionList.get(processedPeaks.get(i - 1)).getFormulas()); final double leftMass = ion.subtractFromMass(processedPeaks.get(i - 1).getMass()); final double rightMass = ion.subtractFromMass(processedPeaks.get(i).getMass()); final Iterator<MolecularFormula> leftIter = left.iterator(); while (leftIter.hasNext()) { final MolecularFormula leftFormula = leftIter.next(); if (right.contains(leftFormula)) { if (Math.abs(leftFormula.getMass() - leftMass) < Math .abs(leftFormula.getMass() - rightMass)) { right.remove(leftFormula); } else { leftIter.remove(); } } } decompositionList.set(processedPeaks.get(i - 1), DecompositionList.fromFormulas(left)); decompositionList.set(processedPeaks.get(i), DecompositionList.fromFormulas(right)); } } return postProcess(PostProcessor.Stage.AFTER_DECOMPOSING, input); }
From source file:com.predic8.membrane.core.interceptor.rewrite.RewriteInterceptor.java
@Override public Outcome handleRequest(Exchange exc) throws Exception { logMappings();//from www . ja v a2s. c o m ListIterator<String> it = exc.getDestinations().listIterator(); while (it.hasNext()) { String dest = it.next(); String pathQuery = URLUtil.getPathQuery(router.getUriFactory(), dest); int pathBegin = -1; int authorityBegin = dest.indexOf("//"); if (authorityBegin != -1) pathBegin = dest.indexOf("/", authorityBegin + 2); String schemaHostPort = pathBegin == -1 ? null : dest.substring(0, pathBegin); log.debug("pathQuery: " + pathQuery); log.debug("schemaHostPort: " + schemaHostPort); Mapping mapping = findFirstMatchingRegEx(pathQuery); if (mapping == null) continue; Type do_ = mapping.getDo(); log.debug("match found: " + mapping.from); log.debug("replacing with: " + mapping.to); log.debug("for type: " + do_); String newDest = replace(pathQuery, mapping); if (do_ == Type.REDIRECT_PERMANENT || do_ == Type.REDIRECT_TEMPORARY) { exc.setResponse(Response.redirect(newDest, do_ == Type.REDIRECT_PERMANENT).build()); return Outcome.RETURN; } if (!newDest.contains("://") && schemaHostPort != null) { // prepend schema, host and port from original uri newDest = schemaHostPort + newDest; } it.set(newDest); } Mapping mapping = findFirstMatchingRegEx(exc.getRequest().getUri()); if (mapping != null && mapping.do_ == Type.REWRITE) { String newDest = replace(exc.getRequest().getUri(), mapping); if (newDest.contains("://")) { newDest = URLUtil.getPathQuery(router.getUriFactory(), newDest); } exc.getRequest().setUri(newDest); } return Outcome.CONTINUE; }
From source file:org.objectweb.proactive.core.body.ft.protocols.cic.managers.FTManagerCIC.java
private void filterQueue(BlockingRequestQueue queue, CheckpointInfoCIC cic) { CircularArrayList<Request> internalQueue = ((BlockingRequestQueueImpl) queue).getInternalQueue(); ListIterator<Request> itQueue = internalQueue.listIterator(); while (itQueue.hasNext()) { Request current = (itQueue.next()); MessageInfoCIC mi = (MessageInfoCIC) current.getMessageInfo(); if (mi == null) { // is request an awaited or a non ft ? if (current instanceof AwaitedRequest) { // current is an awaited request that is not updated this.awaitedRequests.add((AwaitedRequest) current); }//from ww w . ja v a 2 s. co m } else if (mi.isOrphanFor <= cic.checkpointIndex) { // current is an orpahn request // System.out.println("" + this.ownerID + " is filtering some orphan requests ..."); AwaitedRequest ar = new AwaitedRequest(current.getSourceBodyID()); itQueue.set(ar); this.awaitedRequests.add(ar); } } }
From source file:org.cruk.genologics.api.cache.GenologicsAPICache.java
/** * Join point for the {@code GenologicsAPI.loadAll} method. * Examines the cache for objects already loaded and only fetches those * that are not already seen (or, for stateful objects, those whose requested * state is later than that in the cache). * * @param <E> The type of LIMS entity referred to. * @param pjp The join point object.//from w w w . jav a 2 s .c o m * * @return The list of entities retrieved. * * @throws Throwable if there is an error. * * @see GenologicsAPI#loadAll(Collection) */ public <E extends Locatable> List<E> loadAll(ProceedingJoinPoint pjp) throws Throwable { @SuppressWarnings("unchecked") Collection<LimsLink<E>> links = (Collection<LimsLink<E>>) pjp.getArgs()[0]; List<E> results = new ArrayList<E>(links == null ? 0 : links.size()); if (links != null && !links.isEmpty()) { Ehcache cache = null; List<LimsLink<E>> toFetch = new ArrayList<LimsLink<E>>(links.size()); List<E> alreadyCached = new ArrayList<E>(links.size()); Boolean cacheable = null; String className = null; Boolean stateful = null; CacheStatefulBehaviour callBehaviour = behaviourOverride.get(); if (callBehaviour == null) { callBehaviour = behaviour; } behaviourLock.lock(); try { Iterator<LimsLink<E>> linkIterator = links.iterator(); // Loop through the links requested and accumulate two lists of links: // those that are not in the cache and need to be fetched and those that // have already been fetched. While doing this, assemble in "results" those // entities already in the cache that don't need to be fetch. This list will // have nulls inserted where the entity needs to be fetched. while (linkIterator.hasNext()) { LimsLink<E> link = linkIterator.next(); if (link == null) { throw new IllegalArgumentException("link contains a null"); } if (link.getUri() == null) { throw new IllegalArgumentException("A link in the collection has no URI set."); } if (className == null) { className = ClassUtils.getShortClassName(link.getEntityClass()); cacheable = isCacheable(link.getEntityClass()); stateful = isStateful(link.getEntityClass()); } E entity = null; if (!cacheable) { // Fetch always. toFetch.add(link); } else { if (cache == null) { cache = getCache(link.getEntityClass()); } String key = keyFromLocatable(link); Element wrapper = cache.get(key); if (wrapper == null) { toFetch.add(link); } else { long version = versionFromLocatable(link); switch (callBehaviour) { case ANY: entity = getFromWrapper(wrapper); alreadyCached.add(entity); break; case LATEST: if (version != NO_STATE_VALUE && version > wrapper.getVersion()) { toFetch.add(link); } else { entity = getFromWrapper(wrapper); alreadyCached.add(entity); } break; case EXACT: if (version != NO_STATE_VALUE && version != wrapper.getVersion()) { toFetch.add(link); } else { entity = getFromWrapper(wrapper); alreadyCached.add(entity); } break; } } } results.add(entity); } } finally { behaviourLock.unlock(); } if (logger.isWarnEnabled()) { if (cache.getCacheConfiguration().getMaxEntriesLocalHeap() < links.size()) { logger.warn( "{} {}s are requested, but the cache will only hold {}. Repeated fetches of this collection will always call through to the API.", links.size(), className, cache.getCacheConfiguration().getMaxEntriesLocalHeap()); } } if (logger.isDebugEnabled()) { if (alreadyCached.size() == links.size()) { logger.debug("All {} {}s requested are already in the cache.", links.size(), className); } else { logger.debug("Have {} {}s in the cache; {} to retrieve.", alreadyCached.size(), className, toFetch.size()); } } // If there is anything to fetch, perform the call to the API then // fill in the nulls in the "results" list from the entities returned // from the API. // The end result is that newly fetched items are put into the cache // and "results" is a fully populated list. if (!toFetch.isEmpty()) { assert cacheable != null : "No cacheable flag found"; assert stateful != null : "No stateful flag found"; Object[] args = { toFetch }; @SuppressWarnings("unchecked") List<E> fetched = (List<E>) pjp.proceed(args); ListIterator<E> resultIterator = results.listIterator(); ListIterator<E> fetchIterator = fetched.listIterator(); while (resultIterator.hasNext()) { E entity = resultIterator.next(); if (entity == null) { assert fetchIterator.hasNext() : "Run out of items in the fetched list."; entity = fetchIterator.next(); resultIterator.set(entity); if (cacheable) { if (!stateful) { // Entities without state will only have been fetched because they // were not in the cache. These should just be added. cache.put(createCacheElement(entity)); } else { // Stateful entities may already be in the cache but may have been // fetched because the requested version is newer or of a different // state. Some care needs to be taken to update its cached version // depending on how the cache normally behaves. String key = keyFromLocatable(entity); Element wrapper = cache.get(key); if (wrapper == null) { // Not already cached, so simply add this entity whatever // its state. cache.put(createCacheElement(entity)); } else { // As we have a stateful entity, there may be cause // to replace the object in the cache depending on how the // cache normally behaves. Typically this will be replacing the // existing with a newer version or replacing for a difference. // When we don't care about versions, the one already in the cache // can remain. long version = versionFromLocatable(entity); switch (behaviour) { case ANY: break; case LATEST: if (version > wrapper.getVersion()) { cache.put(createCacheElement(entity)); } break; case EXACT: if (version != wrapper.getVersion()) { cache.put(createCacheElement(entity)); } break; } } } } } } assert !fetchIterator.hasNext() : "Have further items fetched after populating results list."; } } return results; }
From source file:marytts.modules.phonemiser.AllophoneSet.java
/** * Syllabify a string of allophones. If stress markers are provided, they are preserved; otherwise, primary stress will be * assigned to the initial syllable./*from w ww . ja va 2 s . co m*/ * <p> * The syllabification algorithm itself follows the <i>Core Syllabification Principle (CSP)</i> from <blockquote>G.N. Clements * (1990) "The role of the sonority cycle in core syllabification." In: J. Kingston & M.E. Beckman (Eds.), * <em>Papers in Laboratory Phonology I: Between the Grammar and Physics of Speech</em>, Ch. 17, pp. 283-333, Cambridge * University Press.</blockquote> * * @param phoneString * phoneString * @return a syllabified string; individual allophones are separated by spaces, and syllables, by dashes. * @throws IllegalArgumentException * if the <b>phoneString</b> is empty or contains a symbol that satisfies none of the following conditions: * <ol> * <li>the symbol corresponds to an Allophone, or</li> <li>the symbol is a stress symbol (cf. {@link Stress}), or * </li> <li>the symbol is a syllable boundary (<code>-</code>)</li> * </ol> * */ public String syllabify(String phoneString) throws IllegalArgumentException { // Before we process, a sanity check: if (phoneString.trim().isEmpty()) { throw new IllegalArgumentException("Cannot syllabify empty phone string"); } // First, split phoneString into a List of allophone Strings... List<String> allophoneStrings = splitIntoAllophoneList(phoneString, true); // ...and create from it a List of generic Objects List<Object> phonesAndSyllables = new ArrayList<Object>(allophoneStrings); // Create an iterator ListIterator<Object> iterator = phonesAndSyllables.listIterator(); // First iteration (left-to-right): // CSP (a): Associate each [+syllabic] segment to a syllable node. Syllable currentSyllable = null; while (iterator.hasNext()) { String phone = (String) iterator.next(); try { // either it's an Allophone Allophone allophone = getAllophone(phone); if (allophone.isSyllabic()) { // if /6/ immediately follows a non-diphthong vowel, it should be appended instead of forming its own syllable boolean appendR = false; if (allophone.getFeature("ctype").equals("r")) { // it's an /6/ if (iterator.previousIndex() > 1) { Object previousPhoneOrSyllable = phonesAndSyllables.get(iterator.previousIndex() - 1); if (previousPhoneOrSyllable == currentSyllable) { // the /6/ immediately follows the current syllable if (!currentSyllable.getLastAllophone().isDiphthong()) { // the vowel immediately preceding the /6/ is not a diphthong appendR = true; } } } } if (appendR) { iterator.remove(); currentSyllable.appendAllophone(allophone); } else { currentSyllable = new Syllable(allophone); iterator.set(currentSyllable); } } } catch (IllegalArgumentException e) { // or a stress or boundary marker if (!getIgnoreChars().contains(phone)) { throw e; } } } // Second iteration (right-to-left): // CSP (b): Given P (an unsyllabified segment) preceding Q (a syllabified segment), adjoin P to the syllable containing Q // iff P has lower sonority rank than Q (iterative). currentSyllable = null; boolean foundPrimaryStress = false; iterator = phonesAndSyllables.listIterator(phonesAndSyllables.size()); while (iterator.hasPrevious()) { Object phoneOrSyllable = iterator.previous(); if (phoneOrSyllable instanceof Syllable) { currentSyllable = (Syllable) phoneOrSyllable; } else if (currentSyllable == null) { // haven't seen a Syllable yet in this iteration continue; } else { String phone = (String) phoneOrSyllable; try { // it's an Allophone -- prepend to the Syllable Allophone allophone = getAllophone(phone); if (allophone.sonority() < currentSyllable.getFirstAllophone().sonority()) { iterator.remove(); currentSyllable.prependAllophone(allophone); } } catch (IllegalArgumentException e) { // it's a provided stress marker -- assign it to the Syllable switch (phone) { case Stress.PRIMARY: iterator.remove(); currentSyllable.setStress(Stress.PRIMARY); foundPrimaryStress = true; break; case Stress.SECONDARY: iterator.remove(); currentSyllable.setStress(Stress.SECONDARY); break; case "-": iterator.remove(); // TODO handle syllable boundaries break; default: throw e; } } } } // Third iteration (left-to-right): // CSP (c): Given Q (a syllabified segment) followed by R (an unsyllabified segment), adjoin R to the syllable containing // Q iff has a lower sonority rank than Q (iterative). Syllable initialSyllable = currentSyllable; currentSyllable = null; iterator = phonesAndSyllables.listIterator(); while (iterator.hasNext()) { Object phoneOrSyllable = iterator.next(); if (phoneOrSyllable instanceof Syllable) { currentSyllable = (Syllable) phoneOrSyllable; } else { String phone = (String) phoneOrSyllable; try { // it's an Allophone -- append to the Syllable Allophone allophone; try { allophone = getAllophone(phone); } catch (IllegalArgumentException e) { // or a stress or boundary marker -- remove if (getIgnoreChars().contains(phone)) { iterator.remove(); continue; } else { throw e; } } if (currentSyllable == null) { // haven't seen a Syllable yet in this iteration iterator.remove(); if (initialSyllable == null) { // haven't seen any syllable at all initialSyllable = new Syllable(allophone); iterator.add(initialSyllable); } else { initialSyllable.prependAllophone(allophone); } } else { // append it to the last seen Syllable iterator.remove(); currentSyllable.appendAllophone(allophone); } } catch (IllegalArgumentException e) { throw e; } } } // if primary stress was not provided, assign it to initial syllable if (!foundPrimaryStress) { initialSyllable.setStress(Stress.PRIMARY); } // join Syllables with dashes and return the String return StringUtils.join(phonesAndSyllables, " - "); }
From source file:com.apptentive.android.sdk.module.messagecenter.view.MessageCenterActivityContent.java
private void prepareMessages(final List<MessageCenterListItem> originalItems) { messages.clear();//from ww w . ja v a 2 s .c o m unsendMessagesCount = 0; // Loop through each message item retrieved from database for (MessageCenterListItem item : originalItems) { if (item instanceof ApptentiveMessage) { ApptentiveMessage apptentiveMessage = (ApptentiveMessage) item; Double createdAt = apptentiveMessage.getCreatedAt(); if (apptentiveMessage.isOutgoingMessage() && createdAt == null) { unsendMessagesCount++; } /* * Find proper location to insert into the messages list of the listview. */ ListIterator<MessageCenterListItem> listIterator = messages.listIterator(); ApptentiveMessage next = null; while (listIterator.hasNext()) { next = (ApptentiveMessage) listIterator.next(); Double nextCreatedAt = next.getCreatedAt(); // For unsent and dropped message, move the iterator to the end, and append there if (createdAt == null || createdAt <= Double.MIN_VALUE) { continue; } // next message has not received by server or received, but has a later created_at time if (nextCreatedAt == null || nextCreatedAt > createdAt) { break; } } if (next == null || next.getCreatedAt() == null || createdAt == null || next.getCreatedAt() <= createdAt || createdAt <= Double.MIN_VALUE) { listIterator.add(item); } else { // Add in front of the message that has later created_at time listIterator.set(item); listIterator.add(next); } } } // Finally, add greeting message messages.add(0, interaction.getGreeting()); }
From source file:com.apptentive.android.sdk.module.engagement.interaction.fragment.MessageCenterFragment.java
private void prepareMessages(final List<MessageCenterListItem> originalItems) { listItems.clear();//www. j av a2 s. c o m unsentMessagesCount = 0; // Loop through each message item retrieved from database for (MessageCenterListItem item : originalItems) { if (item instanceof ApptentiveMessage) { ApptentiveMessage apptentiveMessage = (ApptentiveMessage) item; Double createdAt = apptentiveMessage.getCreatedAt(); if (apptentiveMessage.isOutgoingMessage() && createdAt == null) { unsentMessagesCount++; } /* * Find proper location to insert into the listItems list of the listview. */ ListIterator<MessageCenterListItem> listIterator = listItems.listIterator(); ApptentiveMessage next = null; while (listIterator.hasNext()) { next = (ApptentiveMessage) listIterator.next(); Double nextCreatedAt = next.getCreatedAt(); // For unsent and dropped message, move the iterator to the end, and append there if (createdAt == null || createdAt <= Double.MIN_VALUE) { continue; } // next message has not received by server or received, but has a later created_at time if (nextCreatedAt == null || nextCreatedAt > createdAt) { break; } } if (next == null || next.getCreatedAt() == null || createdAt == null || next.getCreatedAt() <= createdAt || createdAt <= Double.MIN_VALUE) { listIterator.add(item); } else { // Add in front of the message that has later created_at time listIterator.set(item); listIterator.add(next); } } } messagingActionHandler.sendEmptyMessage(MSG_ADD_GREETING); }
From source file:cz.cesnet.shongo.connector.device.CiscoMCUConnector.java
/** * Populates the results list - puts the original objects instead of item stubs. * <p/>/* w w w . j a va2 s.co m*/ * If there was a previous call to the same command, the changed items are just stubs in the new result set. To use * the results, this method populates all the stubs and puts the objects from the previous call in their place. * * @param results list of results, some of which may be stubs; gets modified so that it contains no stubs * @param currentRevision the revision of this results * @param lastRevision the revision of the previous call of the same command * @param command the command called to get the supplied results * @param enumField the field name from which the supplied results where taken within the command result */ private void populateResultsFromCache(List<Map<String, Object>> results, Integer currentRevision, Integer lastRevision, Command command, String enumField) throws CommandException { // we got just the difference since lastRevision (or full set if this is the first issue of the command) final String cacheId = getCommandCacheId(command); if (lastRevision != null) { // fill the values that have not changed since lastRevision ListIterator<Map<String, Object>> iterator = results.listIterator(); while (iterator.hasNext()) { Map<String, Object> item = iterator.next(); if (isItemDead(item)) { // from the MCU API: "The device will also never return a dead record if listAll is set to true." // unfortunately, the buggy MCU still reports some items as dead even though listAll = true, so we // must remove them by ourselves (according to the API, a dead item should not have been ever // listed when listAll = true) iterator.remove(); } else if (!hasItemChanged(item)) { ResultsCache cache = resultsCache.get(cacheId); Map<String, Object> it = cache.getItem(item); if (it == null) { throw new CommandException( "Item reported as not changed by the device, but was not found in the cache: " + item); } iterator.set(it); } } } // store the results and the revision number for the next time ResultsCache rc = resultsCache.get(cacheId); if (rc == null) { rc = new ResultsCache(); resultsCache.put(cacheId, rc); } rc.store(currentRevision, results); }