List of usage examples for com.google.common.collect SetMultimap put
boolean put(@Nullable K key, @Nullable V value);
From source file:omero.cmd.graphs.Preprocessor.java
/** * Preprocess the list of requests.//from w w w . ja va 2 s .c o m */ protected void process() { boolean modified = false; for (final Predicate<Request> isRelevant : predicatesForRequests()) { final SetMultimap<TargetType, GraphModifyTarget> targets = HashMultimap.create(); /* direct references */ for (final Request relevantRequest : Collections2.filter(this.requests, isRelevant)) { final GraphModify gm = (GraphModify) relevantRequest; final TargetType targetType = TargetType.byName.get(gm.type); targets.put(targetType, new GraphModifyTarget(targetType, gm.id)); } /* indirect references */ for (final Entry<TargetType, TargetType> relationship : Preprocessor.targetTypeHierarchy) { final TargetType containerType = relationship.getKey(); final TargetType containedType = relationship.getValue(); final Set<GraphModifyTarget> containers = targets.get(containerType); this.hierarchyNavigator.prepareLookups(containedType, containers); for (final GraphModifyTarget container : containers) { targets.putAll(containedType, this.hierarchyNavigator.doLookup(containedType, container)); } } /* review the referenced FS images */ this.hierarchyNavigator.prepareLookups(TargetType.FILESET, targets.get(TargetType.IMAGE)); while (!targets.get(TargetType.IMAGE).isEmpty()) { final GraphModifyTarget image = targets.get(TargetType.IMAGE).iterator().next(); /* find the image's fileset */ final Set<GraphModifyTarget> containers = this.hierarchyNavigator.doLookup(TargetType.FILESET, image); final Iterator<GraphModifyTarget> filesetIterator = GraphModifyTarget .filterByType(containers, TargetType.FILESET).iterator(); final GraphModifyTarget fileset; if (!filesetIterator.hasNext()) { /* pre-FS image */ targets.get(TargetType.IMAGE).remove(image); continue; } fileset = filesetIterator.next(); if (filesetIterator.hasNext()) { throw new IllegalStateException("image is contained in multiple filesets"); } /* check that all the fileset's images are referenced */ final Set<GraphModifyTarget> filesetImages = this.hierarchyNavigator.doLookup(TargetType.IMAGE, fileset); final boolean completeFileset = targets.get(TargetType.IMAGE).containsAll(filesetImages); /* this iteration will handle this fileset sufficiently, so do not revisit it */ targets.get(TargetType.IMAGE).removeAll(filesetImages); /* this preprocessing is applied only when all of a fileset's images are referenced */ if (!(completeFileset)) { continue; } /* okay, list the fileset as a target among the requests, after all of its images and their containers */ final Set<GraphModifyTarget> prohibitedPrefixes = new HashSet<GraphModifyTarget>(filesetImages); for (final GraphModifyTarget filesetImage : filesetImages) { prohibitedPrefixes.addAll(getAllContainers(filesetImage)); } /* and, once listed, neither the fileset nor its images need subsequent requests */ final Set<GraphModifyTarget> prohibitedSuffixes = new HashSet<GraphModifyTarget>(filesetImages); prohibitedSuffixes.add(fileset); /* adjust the list of requests accordingly */ transform(isRelevant, fileset, prohibitedPrefixes, prohibitedSuffixes); modified = true; } } if (modified && log.isDebugEnabled()) { StringBuilder sb = new StringBuilder(); sb.append(requestToString(requests.get(0))); for (int i = 1; i < requests.size(); i++) { sb.append(","); sb.append(requestToString(requests.get(i))); } log.debug("transformed to: {}", sb); } }
From source file:org.terasology.holdings.HoldingSystem.java
/** * Responsible for tick update - see if we should review thresholds (like making a new queen) * * @param delta time step since last update *///w ww. j a v a2 s. c om public void update(float delta) { // Do a time check to see if we should even bother calculating stuff (really only needed every second or so) // Keep a ms counter handy, delta is in seconds tick += delta * 1000; if (tick - classLastTick < 5000) { return; } classLastTick = tick; // Prep a list of the holdings we know about ArrayList<EntityRef> holdingEntities = new ArrayList<EntityRef>(4); // Go fetch all the Holdings. // TODO: Do we have a helper method for this? I forgot and it is late :P for (EntityRef holdingEntity : entityManager.getEntitiesWith(HoldingComponent.class)) { holdingEntities.add(holdingEntity); } // Prep a fancy multi map of the Holdings and which if any Spawnables belong to each SetMultimap<EntityRef, EntityRef> spawnableEntitiesByHolding = HashMultimap.create(); // Loop through all Spawnables and assign them to a Holding if one exists that is also the Spawnables parent (its Spawner) for (EntityRef spawnableEntity : entityManager.getEntitiesWith(SpawnableComponent.class)) { for (EntityRef holdingEntity : holdingEntities) { // Check the spawnable's parent (a reference to a Spawner entity) against the holding (which we cheat-know to also be a Spawner) if (spawnableEntity.getComponent(SpawnableComponent.class).parent == holdingEntity) { // Map this Spawnable to its Holding spawnableEntitiesByHolding.put(holdingEntity, spawnableEntity); break; } } } // For each Holding check if there are enough Spawnables to create a queen for (EntityRef holdingEntity : holdingEntities) { Set<EntityRef> holdingSpawnables = spawnableEntitiesByHolding.get(holdingEntity); int spawnableCount = holdingSpawnables.size(); HoldingComponent holdComp = holdingEntity.getComponent(HoldingComponent.class); logger.info("Processing a holding with a spawnableCount of {} and threshold of {}", spawnableCount, holdComp.queenThreshold); if (spawnableCount > holdComp.queenThreshold && holdComp.queenMax > holdComp.queenCurrent) { EntityRef queenInWaiting = null; // See if we have a candidate queen to crown for (EntityRef queenCandidate : holdingSpawnables) { // Come up with some criteria - for now just pick the first one queenInWaiting = queenCandidate; } if (queenInWaiting == null) { logger.info("We failed to find a worthy queen :-("); continue; } // After success make sure to increment the threshold and queen count (queen count never decrements, queens could disappear in the future) holdComp.queenThreshold += 10; holdComp.queenCurrent++; // Then prep the "crown" in the shape of a shiny new SpawnerComponent ;-) SpawnerComponent newSpawnerComp = new SpawnerComponent(); newSpawnerComp.types.add("Oreon"); newSpawnerComp.maxMobsPerSpawner = 50; newSpawnerComp.timeBetweenSpawns = 1000; /* // Make the queen a unique color (in this case, black) TODO: With Oreons instead make the filling purple? MeshComponent mesh = queenInWaiting.getComponent(MeshComponent.class); if (mesh != null) { mesh.color.set(new Color4f(0, 0, 0, 1)); } */ queenInWaiting.addComponent(newSpawnerComp); logger.info("Queen prepped, id {} and spawnercomp {}", queenInWaiting, queenInWaiting.getComponent(SpawnerComponent.class)); } else { logger.info("Haven't reached the threshold yet or queenMax {} is not greater than queenCurrent {}", holdComp.queenMax, holdComp.queenCurrent); } } }
From source file:org.sosy_lab.cpachecker.cpa.value.refiner.utils.ErrorPathClassifier.java
/** * This method creates a successor relation from the root to the target state. * * @param target the state to which the successor relation should be built. * @return the successor relation from the root state to the given target state *///from w w w .j av a 2 s . c o m private SetMultimap<ARGState, ARGState> buildSuccessorRelation(ARGState target) { Deque<ARGState> todo = new ArrayDeque<>(); todo.add(target); ARGState itpTreeRoot = null; SetMultimap<ARGState, ARGState> successorRelation = LinkedHashMultimap.create(); // build the tree, bottom-up, starting from the target states while (!todo.isEmpty()) { final ARGState currentState = todo.removeFirst(); if (currentState.getParents().iterator().hasNext()) { ARGState parentState = currentState.getParents().iterator().next(); todo.add(parentState); successorRelation.put(parentState, currentState); } else if (itpTreeRoot == null) { itpTreeRoot = currentState; } } return successorRelation; }
From source file:org.robotframework.ide.eclipse.main.plugin.model.RobotSuiteFile.java
public SetMultimap<LibrarySpecification, String> getImportedLibraries() { final Optional<RobotSettingsSection> section = findSection(RobotSettingsSection.class); final SetMultimap<String, String> toImport = HashMultimap.create(); if (section.isPresent()) { toImport.putAll(section.get().getLibrariesPathsOrNamesWithAliases()); }//from w w w . j a va2s . c o m final SetMultimap<LibrarySpecification, String> imported = HashMultimap.create(); for (final LibrarySpecification spec : getProject().getLibrariesSpecifications()) { if (toImport.containsKey(spec.getName())) { imported.putAll(spec, toImport.get(spec.getName())); toImport.removeAll(spec.getName()); } else if (spec.isAccessibleWithoutImport()) { imported.put(spec, ""); } } for (final String toImportPathOrName : toImport.keySet()) { try { final LibrarySpecification spec = findSpecForPath(toImportPathOrName); if (spec != null) { imported.putAll(spec, toImport.get(toImportPathOrName)); } } catch (final PathResolvingException e) { // ok we won't provide any spec, since we can't resolve uri } } return imported; }
From source file:com.android.tools.idea.npw.NewModuleWizardState.java
/** * Updates the dependencies stored in the parameters map, to include support libraries required by the extra features selected. *///from w ww.jav a 2 s. c o m public void updateDependencies() { @SuppressWarnings("unchecked") SetMultimap<String, String> dependencies = (SetMultimap<String, String>) get(ATTR_DEPENDENCIES_MULTIMAP); if (dependencies == null) { dependencies = HashMultimap.create(); } RepositoryUrlManager urlManager = RepositoryUrlManager.get(); // Support Library Object fragmentsExtra = get(ATTR_FRAGMENTS_EXTRA); Object navigationDrawerExtra = get(ATTR_NAVIGATION_DRAWER_EXTRA); if ((fragmentsExtra != null && Boolean.parseBoolean(fragmentsExtra.toString())) || (navigationDrawerExtra != null && Boolean.parseBoolean(navigationDrawerExtra.toString()))) { dependencies.put(SdkConstants.GRADLE_COMPILE_CONFIGURATION, urlManager.getLibraryStringCoordinate(SupportLibrary.SUPPORT_V4, true)); } // AppCompat Library Object actionBarExtra = get(ATTR_ACTION_BAR_EXTRA); if (actionBarExtra != null && Boolean.parseBoolean(actionBarExtra.toString())) { dependencies.put(SdkConstants.GRADLE_COMPILE_CONFIGURATION, urlManager.getLibraryStringCoordinate(SupportLibrary.APP_COMPAT_V7, true)); } // GridLayout Library Object gridLayoutExtra = get(ATTR_GRID_LAYOUT_EXTRA); if (gridLayoutExtra != null && Boolean.parseBoolean(gridLayoutExtra.toString())) { dependencies.put(SdkConstants.GRADLE_COMPILE_CONFIGURATION, urlManager.getLibraryStringCoordinate(SupportLibrary.GRID_LAYOUT_V7, true)); } put(ATTR_DEPENDENCIES_MULTIMAP, dependencies); }
From source file:com.addthis.hydra.query.FileRefSource.java
public SetMultimap<Integer, FileReference> getWithShortCircuit() throws InterruptedException { SetMultimap<Integer, FileReference> fileRefMap = HashMultimap.create(); long end = System.nanoTime() + MAX_WAIT_NANOS; long remaining = MAX_WAIT_NANOS; while (true) { if (semaphore.tryWriteLock(remaining, TimeUnit.NANOSECONDS) == 0) { lateFileRefFinds = ConcurrentHashMultiset.create(); shortCircuited = true;/* w w w.ja v a2s . com*/ log.warn("Timed out waiting for mesh file list: {}. After waiting {}", this, MAX_WAIT_NANOS); return fileRefMap; } FileReference fileReference = references.poll(); while (fileReference != null) { if (fileReference == END_SIGNAL) { log.debug("Finished collecting file refs for: {}", this); return fileRefMap; } fileRefMap.put(getTaskId(fileReference), fileReference); fileReference = references.poll(); } remaining = end - System.nanoTime(); } }
From source file:brooklyn.event.feed.jmx.JmxFeed.java
protected JmxFeed(Builder builder) { super();//from ww w . j av a 2s . co m if (builder.helper != null) { JmxHelper helper = builder.helper; setConfig(HELPER, helper); setConfig(OWN_HELPER, false); setConfig(JMX_URI, helper.getUrl()); } setConfig(JMX_CONNECTION_TIMEOUT, builder.jmxConnectionTimeout); SetMultimap<String, JmxAttributePollConfig<?>> attributePolls = HashMultimap .<String, JmxAttributePollConfig<?>>create(); for (JmxAttributePollConfig<?> config : builder.attributePolls) { @SuppressWarnings({ "rawtypes", "unchecked" }) JmxAttributePollConfig<?> configCopy = new JmxAttributePollConfig(config); if (configCopy.getPeriod() < 0) configCopy.period(builder.period, builder.periodUnits); attributePolls.put(configCopy.getObjectName().getCanonicalName() + configCopy.getAttributeName(), configCopy); } setConfig(ATTRIBUTE_POLLS, attributePolls); SetMultimap<List<?>, JmxOperationPollConfig<?>> operationPolls = HashMultimap .<List<?>, JmxOperationPollConfig<?>>create(); for (JmxOperationPollConfig<?> config : builder.operationPolls) { @SuppressWarnings({ "rawtypes", "unchecked" }) JmxOperationPollConfig<?> configCopy = new JmxOperationPollConfig(config); if (configCopy.getPeriod() < 0) configCopy.period(builder.period, builder.periodUnits); operationPolls.put(configCopy.buildOperationIdentity(), configCopy); } setConfig(OPERATION_POLLS, operationPolls); SetMultimap<NotificationFilter, JmxNotificationSubscriptionConfig<?>> notificationSubscriptions = HashMultimap .create(); for (JmxNotificationSubscriptionConfig<?> config : builder.notificationSubscriptions) { notificationSubscriptions.put(config.getNotificationFilter(), config); } setConfig(NOTIFICATION_SUBSCRIPTIONS, notificationSubscriptions); initUniqueTag(builder.uniqueTag, attributePolls, operationPolls, notificationSubscriptions); }
From source file:com.facebook.buck.cli.AuditOwnerCommand.java
/** * Guess target owners for deleted/missing files by finding first * BUCK file and assuming that all targets in this file used * missing file as input.// ww w . ja va 2 s.c o m */ private void guessOwnersForNonExistentFiles(DependencyGraph graph, SetMultimap<BuildRule, Path> owners, Set<String> nonExistentFiles) { ProjectFilesystem projectFilesystem = getProjectFilesystem(); for (String nonExistentFile : nonExistentFiles) { File file = projectFilesystem.getFileForRelativePath(nonExistentFile); File buck = findBuckFileFor(file); for (BuildRule rule : graph.getNodes()) { if (rule.getType() == ProjectConfigDescription.TYPE) { continue; } try { File ruleBuck = rule.getBuildTarget().getBuildFile(projectFilesystem); if (buck.getCanonicalFile().equals(ruleBuck.getCanonicalFile())) { owners.put(rule, Paths.get(nonExistentFile)); } } catch (IOException | BuildTargetException e) { throw Throwables.propagate(e); } } } }
From source file:de.bund.bfr.knime.openkrise.MyKrisenInterfacesNodeModel.java
private BufferedDataTable getStationTable(Connection conn, Map<Integer, String> stationIds, Collection<Delivery> deliveries, ExecutionContext exec, boolean useSerialAsId) throws CanceledExecutionException { SetMultimap<String, String> deliversTo = LinkedHashMultimap.create(); SetMultimap<String, String> receivesFrom = LinkedHashMultimap.create(); for (Delivery d : deliveries) { deliversTo.put(d.getSupplierId(), d.getRecipientId()); receivesFrom.put(d.getRecipientId(), d.getSupplierId()); }//from w w w . j a v a 2s.co m DataTableSpec spec = getStationSpec(conn, useSerialAsId); BufferedDataContainer container = exec.createDataContainer(spec); long index = 0; SelectJoinStep<Record> select = DSL.using(conn, SQLDialect.HSQLDB).select().from(STATION); if (set.isLotBased()) { select = select.join(PRODUKTKATALOG).on(STATION.ID.equal(PRODUKTKATALOG.STATION)).join(CHARGEN) .on(PRODUKTKATALOG.ID.equal(CHARGEN.ARTIKEL)); } for (Record r : select) { String stationId = stationIds.get(r.getValue(STATION.ID)); String district = clean(r.getValue(STATION.DISTRICT)); String state = clean(r.getValue(STATION.BUNDESLAND)); String country = clean(r.getValue(STATION.LAND)); String zip = clean(r.getValue(STATION.PLZ)); String company = r.getValue(STATION.NAME) == null || set.isAnonymize() ? getISO3166_2(country, state) + "#" + r.getValue(STATION.ID) : clean(r.getValue(STATION.NAME)); DataCell[] cells = new DataCell[spec.getNumColumns()]; fillCell(spec, cells, TracingColumns.ID, !set.isLotBased() ? createCell(stationId) : createCell(String.valueOf(r.getValue(CHARGEN.ID)))); fillCell(spec, cells, TracingColumns.STATION_ID, createCell(stationId)); fillCell(spec, cells, BackwardUtils.STATION_NODE, createCell(company)); fillCell(spec, cells, TracingColumns.NAME, !set.isLotBased() ? createCell(company) : createCell(r.getValue(PRODUKTKATALOG.BEZEICHNUNG))); fillCell(spec, cells, TracingColumns.STATION_NAME, createCell(company)); fillCell(spec, cells, TracingColumns.STATION_STREET, set.isAnonymize() ? DataType.getMissingCell() : createCell(r.getValue(STATION.STRASSE))); fillCell(spec, cells, TracingColumns.STATION_HOUSENO, set.isAnonymize() ? DataType.getMissingCell() : createCell(r.getValue(STATION.HAUSNUMMER))); fillCell(spec, cells, TracingColumns.STATION_ZIP, createCell(zip)); fillCell(spec, cells, TracingColumns.STATION_CITY, set.isAnonymize() ? DataType.getMissingCell() : createCell(r.getValue(STATION.ORT))); fillCell(spec, cells, TracingColumns.STATION_DISTRICT, set.isAnonymize() ? DataType.getMissingCell() : createCell(district)); fillCell(spec, cells, TracingColumns.STATION_STATE, set.isAnonymize() ? DataType.getMissingCell() : createCell(state)); fillCell(spec, cells, TracingColumns.STATION_COUNTRY, set.isAnonymize() ? DataType.getMissingCell() : createCell(country)); fillCell(spec, cells, BackwardUtils.STATION_VAT, set.isAnonymize() ? DataType.getMissingCell() : createCell(r.getValue(STATION.VATNUMBER))); fillCell(spec, cells, TracingColumns.STATION_TOB, createCell(r.getValue(STATION.BETRIEBSART))); fillCell(spec, cells, BackwardUtils.STATION_NUMCASES, createCell(r.getValue(STATION.ANZAHLFAELLE))); fillCell(spec, cells, BackwardUtils.STATION_DATESTART, createCell(r.getValue(STATION.DATUMBEGINN))); fillCell(spec, cells, BackwardUtils.STATION_DATEPEAK, createCell(r.getValue(STATION.DATUMHOEHEPUNKT))); fillCell(spec, cells, BackwardUtils.STATION_DATEEND, createCell(r.getValue(STATION.DATUMENDE))); fillCell(spec, cells, BackwardUtils.STATION_SERIAL, createCell(r.getValue(STATION.SERIAL))); fillCell(spec, cells, TracingColumns.STATION_SIMPLESUPPLIER, !receivesFrom.containsKey(stationId) && deliversTo.get(stationId).size() == 1 ? BooleanCell.TRUE : BooleanCell.FALSE); fillCell(spec, cells, TracingColumns.STATION_DEADSTART, !receivesFrom.containsKey(stationId) ? BooleanCell.TRUE : BooleanCell.FALSE); fillCell(spec, cells, TracingColumns.STATION_DEADEND, !deliversTo.containsKey(stationId) ? BooleanCell.TRUE : BooleanCell.FALSE); fillCell(spec, cells, TracingColumns.FILESOURCES, createCell(r.getValue(STATION.IMPORTSOURCES))); fillCell(spec, cells, BackwardUtils.STATION_COUNTY, set.isAnonymize() ? DataType.getMissingCell() : createCell(district)); if (set.isLotBased()) { fillCell(spec, cells, TracingColumns.LOT_NUMBER, createCell(r.getValue(CHARGEN.CHARGENNR))); fillCell(spec, cells, TracingColumns.PRODUCT_NUMBER, createCell(r.getValue(PRODUKTKATALOG.ARTIKELNUMMER))); } for (String column : spec.getColumnNames()) { if (column.startsWith("_")) { Result<Record1<String>> result; if (!set.isLotBased()) { String attribute = column.substring(1); result = DSL.using(conn, SQLDialect.HSQLDB).select(EXTRAFIELDS.VALUE).from(EXTRAFIELDS) .where(EXTRAFIELDS.TABLENAME.equal(STATION.getName()), EXTRAFIELDS.ID.equal(r.getValue(STATION.ID)), EXTRAFIELDS.ATTRIBUTE.equal(attribute)) .fetch(); } else { String table = column.substring(1, column.indexOf(".")); String attribute = column.substring(column.indexOf(".") + 1); result = DSL.using(conn, SQLDialect.HSQLDB).select(EXTRAFIELDS.VALUE).from(EXTRAFIELDS) .where(EXTRAFIELDS.TABLENAME.equal(table), EXTRAFIELDS.ID.equal(r.getValue(ID_COLUMNS.get(table))), EXTRAFIELDS.ATTRIBUTE.equal(attribute)) .fetch(); } fillCell(spec, cells, column, !result.isEmpty() ? createCell(result.get(0).value1()) : DataType.getMissingCell()); } } container.addRowToTable(new DefaultRow(RowKey.createRowKey(index++), cells)); exec.checkCanceled(); } container.close(); return container.getTable(); }
From source file:org.glowroot.central.repo.GaugeValueDao.java
private SetMultimap<Long, String> getRollupCaptureTimes(List<GaugeValue> gaugeValues) { SetMultimap<Long, String> rollupCaptureTimes = HashMultimap.create(); List<RollupConfig> rollupConfigs = configRepository.getRollupConfigs(); for (GaugeValue gaugeValue : gaugeValues) { String gaugeName = gaugeValue.getGaugeName(); long captureTime = gaugeValue.getCaptureTime(); long intervalMillis = rollupConfigs.get(0).intervalMillis(); long rollupCaptureTime = Utils.getRollupCaptureTime(captureTime, intervalMillis); rollupCaptureTimes.put(rollupCaptureTime, gaugeName); }//w w w. j a va 2 s. com return rollupCaptureTimes; }