List of usage examples for java.util List listIterator
ListIterator<E> listIterator(int index);
From source file:com.epam.catgenome.manager.gene.GffManager.java
private void loadExonsBackwards(int centerPosition, int viewPortSize, Chromosome chromosome, int intronLength, int featuresStart, final IntervalTree<Block> intervalTree, final AbstractFeatureReader<GeneFeature, LineIterator> featureReader) throws IOException { int totalLength = 0; // check if some of exons, got by forward lookup are good for backwards Iterator<IntervalTree.Node<Block>> nodeIterator = intervalTree.overlappers(featuresStart, centerPosition); while (nodeIterator.hasNext()) { Block exon = nodeIterator.next().getValue(); totalLength += calculateExonLength(exon, centerPosition, false); }//from ww w.j a v a2 s . c om int i = 0; boolean lastChunk = false; while (totalLength < viewPortSize / 2) { if (lastChunk) { break; } int firstIndex = centerPosition - EXON_SEARCH_CHUNK_SIZE * (i + 1); final int lastIndex = centerPosition - 1 - EXON_SEARCH_CHUNK_SIZE * i; if (firstIndex < featuresStart) { firstIndex = featuresStart; lastChunk = true; // this is the last chunk to be traversed } CloseableIterator<GeneFeature> iterator = Utils.query(featureReader, chromosome, firstIndex, lastIndex); // instead traversing the whole file, read it by small chunks, 100000 bps // long. Hopefully, the desired window will be covered by first/second chunk if (iterator.hasNext()) { List<GeneFeature> featuresChunk = iterator.toList(); ListIterator<GeneFeature> listIterator = featuresChunk.listIterator(featuresChunk.size() - 1); while (listIterator.hasPrevious() && totalLength < viewPortSize / 2) { GeneFeature feature = listIterator.previous(); totalLength = processExon(intervalTree, totalLength, feature, intronLength, centerPosition, false); } } i++; } }
From source file:de.fosd.jdime.matcher.cost_model.CostModelMatcher.java
/** * Finds the lowest pair of (possibly different) ancestors of <code>a</code> and <code>b</code> that are part of the * same sibling group./* w w w .j a v a 2 s .c o m*/ * * @param a * the first <code>Artifact</code> * @param b * the second <code>Artifact</code> * @param matchings * the current <code>CMMatching</code> * @param parameters * the <code>CMParameters</code> to use * @return the ancestor of the first <code>Artifact</code> in the first position, that of the second in the second * position */ private Tuple<T, T> lca(T a, T b, CMMatchings<T> matchings, CMParameters<T> parameters) { return parameters.lcaCache.computeIfAbsent(Tuple.of(a, b), ab -> { Tuple<T, T> ba = Tuple.of(b, a); if (parameters.lcaCache.containsKey(ba)) { Tuple<T, T> baLCS = parameters.lcaCache.get(ba); return Tuple.of(baLCS.y, baLCS.x); } if (siblings(a, matchings, parameters).contains(b)) { return ab; } List<T> aPath = pathToRoot(a); List<T> bPath = pathToRoot(b); ListIterator<T> aIt = aPath.listIterator(aPath.size()); ListIterator<T> bIt = bPath.listIterator(bPath.size()); T l, r; do { l = aIt.previous(); r = bIt.previous(); } while (l == r && (aIt.hasPrevious() && bIt.hasPrevious())); return Tuple.of(l, r); }); }
From source file:org.apache.cayenne.unit.di.server.SchemaBuilder.java
private void dropSchema(DataNode node, DataMap map) throws Exception { List<DbEntity> list = dbEntitiesInInsertOrder(node, map); try (Connection conn = dataSourceFactory.getSharedDataSource().getConnection();) { DatabaseMetaData md = conn.getMetaData(); List<String> allTables = new ArrayList<String>(); try (ResultSet tables = md.getTables(null, null, "%", null)) { while (tables.next()) { // 'toUpperCase' is needed since most databases // are case insensitive, and some will convert names to // lower // case // (PostgreSQL) String name = tables.getString("TABLE_NAME"); if (name != null) allTables.add(name.toUpperCase()); }/*from www . j a va 2 s. c om*/ } unitDbAdapter.willDropTables(conn, map, allTables); // drop all tables in the map try (Statement stmt = conn.createStatement();) { ListIterator<DbEntity> it = list.listIterator(list.size()); while (it.hasPrevious()) { DbEntity ent = it.previous(); if (!allTables.contains(ent.getName().toUpperCase())) { continue; } for (String dropSql : node.getAdapter().dropTableStatements(ent)) { try { logger.info(dropSql); stmt.execute(dropSql); } catch (SQLException sqe) { logger.warn("Can't drop table " + ent.getName() + ", ignoring...", sqe); } } } } unitDbAdapter.droppedTables(conn, map); } }
From source file:net.sf.jasperreports.engine.export.tabulator.Tabulator.java
protected void layoutElements(List<? extends JRPrintElement> elementList, Table table, FrameCell parentCell, PrintElementIndex parentIndex, int xOffset, int yOffset, Bounds elementBounds) { if (log.isTraceEnabled()) { log.trace("laying out " + elements.size() + " elements for parent " + parentCell + " at offsets " + xOffset + ", " + yOffset); }/*ww w .ja v a 2s . c om*/ // iterating the list in reverse order so that background band elements come last for (ListIterator<? extends JRPrintElement> it = elementList.listIterator(elementList.size()); it .hasPrevious();) { JRPrintElement element = it.previous(); if (filter != null && !filter.isToExport(element)) { if (log.isTraceEnabled()) { log.trace("element " + element.getUUID() + " skipped by filter " + element); } continue; } if (element.getWidth() <= 0 || element.getHeight() <= 0) { if (log.isDebugEnabled()) { log.debug("element " + element.getUUID() + " skipped, size " + element.getWidth() + ", " + element.getHeight()); } continue; } if (elementBounds != null && !elementBounds.contains(element.getX(), element.getX() + element.getWidth(), element.getY(), element.getY() + element.getHeight())) { if (log.isDebugEnabled()) { log.debug("element " + element.getUUID() + " at [" + element.getX() + "," + (element.getX() + element.getWidth()) + "),[" + element.getY() + "," + (element.getY() + element.getHeight()) + ") does not fit inside bounds " + elementBounds); } continue; } placeElement(table, parentCell, xOffset, yOffset, element, parentIndex, it.nextIndex(), true); } }
From source file:org.commonjava.maven.ext.core.impl.DependencyManipulator.java
/** * This will load the remote overrides. It will first try to load any overrides that might have * been prepopulated by the REST scanner, failing that it will load from a remote POM file. * * @return the loaded overrides/*www . j a v a 2 s . c o m*/ * @throws ManipulationException if an error occurs. */ private Map<ArtifactRef, String> loadRemoteOverrides() throws ManipulationException { final DependencyState depState = session.getState(DependencyState.class); final RESTState restState = session.getState(RESTState.class); final List<ProjectVersionRef> gavs = depState.getRemoteBOMDepMgmt(); // While in theory we are only mapping ProjectRef -> NewVersion if we store key as ProjectRef we can't then have // org.foo:foobar -> 1.2.0.redhat-2 // org.foo:foobar -> 2.0.0.redhat-2 // Which is useful for strictAlignment scenarios (although undefined for non-strict). Map<ArtifactRef, String> restOverrides = depState.getRemoteRESTOverrides(); Map<ArtifactRef, String> bomOverrides = new LinkedHashMap<>(); Map<ArtifactRef, String> mergedOverrides = new LinkedHashMap<>(); if (gavs != null) { final ListIterator<ProjectVersionRef> iter = gavs.listIterator(gavs.size()); // Iterate in reverse order so that the first GAV in the list overwrites the last while (iter.hasPrevious()) { final ProjectVersionRef ref = iter.previous(); Map<ArtifactRef, String> rBom = effectiveModelBuilder.getRemoteDependencyVersionOverrides(ref); // We don't normalise the BOM list here as ::applyOverrides can handle multiple GA with different V // for strict override. However, it is undefined if strict is not enabled. bomOverrides.putAll(rBom); } } if (depState.getPrecedence() == DependencyPrecedence.BOM) { mergedOverrides = bomOverrides; if (mergedOverrides.isEmpty()) { String msg = restState.isEnabled() ? "dependencySource for restURL" : "dependencyManagement"; logger.warn("No dependencies found for dependencySource {}. Has {} been configured? ", depState.getPrecedence(), msg); } } if (depState.getPrecedence() == DependencyPrecedence.REST) { mergedOverrides = restOverrides; if (mergedOverrides.isEmpty()) { logger.warn("No dependencies found for dependencySource {}. Has restURL been configured? ", depState.getPrecedence()); } } else if (depState.getPrecedence() == DependencyPrecedence.RESTBOM) { mergedOverrides = bomOverrides; removeDuplicateArtifacts(mergedOverrides, restOverrides); mergedOverrides.putAll(restOverrides); } else if (depState.getPrecedence() == DependencyPrecedence.BOMREST) { mergedOverrides = restOverrides; removeDuplicateArtifacts(mergedOverrides, bomOverrides); mergedOverrides.putAll(bomOverrides); } logger.info("Remote precedence is {}", depState.getPrecedence()); logger.debug("Final remote override list is {}", mergedOverrides); return mergedOverrides; }
From source file:net.solarnetwork.node.setup.obr.OBRProvisionTask.java
private void downloadPlugins(List<Plugin> plugins) throws InterruptedException { assert plugins != null; LOG.debug("Starting install of {} plugins", plugins.size()); if (!directory.exists() && !directory.mkdirs()) { throw new RuntimeException("Unable to create plugin directory: " + directory.toString()); }// www. ja v a 2 s . c om // This method will manually download the bundle for each resolved plugin, // then install it and start it in the running OSGi platform. We don't // make use of the OBR RepositoryAdmin to do this because on SolarNode // the bundle's runtime area is held only in RAM (not persisted to disk) // but we want these downloaded bundles to be persisted to disk. Thus we // just do a bit of work here to download and start the bundles ourselves. List<Bundle> installedBundles = new ArrayList<Bundle>(plugins.size()); // iterate backwards, to work our way up through deps to requested plugin for (ListIterator<Plugin> itr = plugins.listIterator(plugins.size()); itr.hasPrevious();) { Plugin plugin = itr.previous(); assert plugin instanceof OBRResourcePlugin; LOG.debug("Starting install of plugin: {}", plugin.getUID()); status.setStatusMessage("Starting install of plugin " + plugin.getUID()); OBRResourcePlugin obrPlugin = (OBRResourcePlugin) plugin; Resource resource = obrPlugin.getResource(); URL resourceURL = resource.getURL(); String pluginFileName = StringUtils.getFilename(resourceURL.getPath()); File outputFile = new File(directory, pluginFileName); String bundleSymbolicName = resource.getSymbolicName(); // download to tmp file first, then we'll rename File tmpOutputFile = new File(directory, "." + pluginFileName); LOG.debug("Downloading plugin {} => {}", resourceURL, tmpOutputFile); try { FileCopyUtils.copy(resourceURL.openStream(), new FileOutputStream(tmpOutputFile)); } catch (IOException e) { throw new RuntimeException("Unable to download plugin " + bundleSymbolicName, e); } moveTemporaryDownloadedPluginFile(resource, outputFile, tmpOutputFile); installDownloadedPlugin(resource, outputFile, installedBundles); LOG.debug("Installed plugin: {}", plugin.getUID()); status.markPluginInstalled(plugin); } if (!installedBundles.isEmpty()) { Set<Bundle> toRefresh = findFragmentHostsForBundles(installedBundles); toRefresh.addAll(installedBundles); status.setStatusMessage("Refreshing OSGi framework."); FrameworkWiring fw = bundleContext.getBundle(0).adapt(FrameworkWiring.class); fw.refreshBundles(toRefresh); for (ListIterator<Bundle> itr = installedBundles.listIterator(); itr.hasNext();) { Bundle b = itr.next(); boolean fragment = isFragment(b); status.setStatusMessage("Starting plugin: " + b.getSymbolicName()); try { if (!fragment && !(b.getState() == Bundle.ACTIVE || b.getState() == Bundle.STARTING)) { b.start(); } // bundles are in reverse order of plugins Plugin p = plugins.get(plugins.size() - itr.nextIndex()); status.markPluginStarted(p); } catch (BundleException e) { throw new RuntimeException( "Unable to start plugin " + b.getSymbolicName() + " version " + b.getVersion(), e); } } } if (status.isRestartRequired() && systemService == null) { LOG.debug("Install of {} plugins complete; manual restart required", plugins.size()); status.setStatusMessage("Install of " + plugins.size() + " plugins complete; manual restart required"); } else if (status.isRestartRequired()) { LOG.debug("Install of {} plugins complete; restarting now", plugins.size()); status.setStatusMessage("Install of " + plugins.size() + " plugins complete; restarting now"); performRestart(); } else { LOG.debug("Install of {} plugins complete", plugins.size()); status.setStatusMessage("Install of " + plugins.size() + " plugins complete"); } }
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 ww w . ja va 2 s . 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: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// w w w .j a v a2s . c om 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.apache.fop.layoutmgr.AbstractBreaker.java
/** * Gets the next block list (sequence) and adds it to a list of block lists * if it's not empty.//w ww . jav a 2 s.co m * * @param childLC LayoutContext to use * @param nextSequenceStartsOn indicates on what page the next sequence * should start * @param positionAtIPDChange last element on the part before an IPD change * @param restartAtLM the layout manager from which to restart, if IPD * change occurs between two LMs * @param firstElements elements from non-restartable LMs on the new page * @return the page on which the next content should appear after a hard * break */ protected int getNextBlockList(LayoutContext childLC, int nextSequenceStartsOn, Position positionAtIPDChange, LayoutManager restartAtLM, List<KnuthElement> firstElements) { updateLayoutContext(childLC); //Make sure the span change signal is reset childLC.signalSpanChange(Constants.NOT_SET); BlockSequence blockList; List<KnuthElement> returnedList; if (firstElements == null) { returnedList = getNextKnuthElements(childLC, alignment); } else if (positionAtIPDChange == null) { /* * No restartable element found after changing IPD break. Simply add the * non-restartable elements found after the break. */ returnedList = firstElements; /* * Remove the last 3 penalty-filler-forced break elements that were added by * the Knuth algorithm. They will be re-added later on. */ ListIterator iter = returnedList.listIterator(returnedList.size()); for (int i = 0; i < 3; i++) { iter.previous(); iter.remove(); } } else { returnedList = getNextKnuthElements(childLC, alignment, positionAtIPDChange, restartAtLM); returnedList.addAll(0, firstElements); } if (returnedList != null) { if (returnedList.isEmpty()) { nextSequenceStartsOn = handleSpanChange(childLC, nextSequenceStartsOn); return nextSequenceStartsOn; } blockList = new BlockSequence(nextSequenceStartsOn, getCurrentDisplayAlign()); //Only implemented by the PSLM nextSequenceStartsOn = handleSpanChange(childLC, nextSequenceStartsOn); Position breakPosition = null; if (ElementListUtils.endsWithForcedBreak(returnedList)) { KnuthPenalty breakPenalty = (KnuthPenalty) ListUtil.removeLast(returnedList); breakPosition = breakPenalty.getPosition(); log.debug("PLM> break - " + getBreakClassName(breakPenalty.getBreakClass())); switch (breakPenalty.getBreakClass()) { case Constants.EN_PAGE: nextSequenceStartsOn = Constants.EN_ANY; break; case Constants.EN_COLUMN: //TODO Fix this when implementing multi-column layout nextSequenceStartsOn = Constants.EN_COLUMN; break; case Constants.EN_ODD_PAGE: nextSequenceStartsOn = Constants.EN_ODD_PAGE; break; case Constants.EN_EVEN_PAGE: nextSequenceStartsOn = Constants.EN_EVEN_PAGE; break; default: throw new IllegalStateException("Invalid break class: " + breakPenalty.getBreakClass()); } } blockList.addAll(returnedList); BlockSequence seq; seq = blockList.endBlockSequence(breakPosition); if (seq != null) { blockLists.add(seq); } } return nextSequenceStartsOn; }
From source file:org.apache.cloudstack.api.response.QuotaResponseBuilderImpl.java
@Override public QuotaBalanceResponse createQuotaBalanceResponse(List<QuotaBalanceVO> quotaBalance, Date startDate, Date endDate) {/*w w w . j a v a 2 s. co m*/ if (quotaBalance == null || quotaBalance.isEmpty()) { throw new InvalidParameterValueException("The request period does not contain balance entries."); } Collections.sort(quotaBalance, new Comparator<QuotaBalanceVO>() { public int compare(QuotaBalanceVO o1, QuotaBalanceVO o2) { o1 = o1 == null ? new QuotaBalanceVO() : o1; o2 = o2 == null ? new QuotaBalanceVO() : o2; return o2.getUpdatedOn().compareTo(o1.getUpdatedOn()); // desc } }); boolean have_balance_entries = false; //check that there is at least one balance entry for (Iterator<QuotaBalanceVO> it = quotaBalance.iterator(); it.hasNext();) { QuotaBalanceVO entry = it.next(); if (entry.isBalanceEntry()) { have_balance_entries = true; break; } } //if last entry is a credit deposit then remove that as that is already //accounted for in the starting balance after that entry, note the sort is desc if (have_balance_entries) { ListIterator<QuotaBalanceVO> li = quotaBalance.listIterator(quotaBalance.size()); // Iterate in reverse. while (li.hasPrevious()) { QuotaBalanceVO entry = li.previous(); if (s_logger.isDebugEnabled()) { s_logger.debug("createQuotaBalanceResponse: Entry=" + entry); } if (entry.getCreditsId() > 0) { li.remove(); } else { break; } } } int quota_activity = quotaBalance.size(); QuotaBalanceResponse resp = new QuotaBalanceResponse(); BigDecimal lastCredits = new BigDecimal(0); boolean consecutive = true; for (Iterator<QuotaBalanceVO> it = quotaBalance.iterator(); it.hasNext();) { QuotaBalanceVO entry = it.next(); if (s_logger.isDebugEnabled()) { s_logger.debug("createQuotaBalanceResponse: All Credit Entry=" + entry); } if (entry.getCreditsId() > 0) { if (consecutive) { lastCredits = lastCredits.add(entry.getCreditBalance()); } resp.addCredits(entry); it.remove(); } else { consecutive = false; } } if (quota_activity > 0 && quotaBalance.size() > 0) { // order is desc last item is the start item QuotaBalanceVO startItem = quotaBalance.get(quotaBalance.size() - 1); QuotaBalanceVO endItem = quotaBalance.get(0); resp.setStartDate(startDate); resp.setStartQuota(startItem.getCreditBalance()); resp.setEndDate(endDate); if (s_logger.isDebugEnabled()) { s_logger.debug("createQuotaBalanceResponse: Start Entry=" + startItem); s_logger.debug("createQuotaBalanceResponse: End Entry=" + endItem); } resp.setEndQuota(endItem.getCreditBalance().add(lastCredits)); } else if (quota_activity > 0) { // order is desc last item is the start item resp.setStartDate(startDate); resp.setStartQuota(new BigDecimal(0)); resp.setEndDate(endDate); resp.setEndQuota(new BigDecimal(0).add(lastCredits)); } else { resp.setStartDate(startDate); resp.setEndDate(endDate); resp.setStartQuota(new BigDecimal(0)); resp.setEndQuota(new BigDecimal(0)); } resp.setCurrency(QuotaConfig.QuotaCurrencySymbol.value()); resp.setObjectName("balance"); return resp; }