List of usage examples for com.google.common.collect Multimap keys
Multiset<K> keys();
From source file:io.redlink.sdk.impl.analysis.model.RDFStructureParser.java
public Collection<Enhancement> parseEnhancements() throws EnhancementParserException { Multimap<Enhancement, String> relations = ArrayListMultimap.create(); Map<String, Enhancement> enhancementsByUri = Maps.newHashMap(); try {/* w w w . j av a 2 s . c o m*/ RepositoryConnection conn = repository.getConnection(); try { conn.begin(); parseTextAnnotations(conn, relations, enhancementsByUri); parseEntityAnnotations(conn, relations, enhancementsByUri); for (Enhancement e : relations.keys()) { Collection<String> relationsUris = relations.get(e); Collection<Enhancement> relationsEnhans = Sets.newHashSet(); for (String uri : relationsUris) { relationsEnhans.add(enhancementsByUri.get(uri)); } e.setRelations(relationsEnhans); } conn.commit(); } finally { conn.close(); } } catch (RepositoryException e) { throw new EnhancementParserException("Error querying the RDF Model obtained as Service Response", e); } return enhancementsByUri.values(); }
From source file:org.opennms.web.controller.admin.thresholds.ThresholdController.java
private void addStandardEditingBits(ModelAndView modelAndView) { Map<String, String> dsTypes = new LinkedHashMap<String, String>(); dsTypes.put("node", "Node"); dsTypes.put("if", "Interface"); // "interface" is a wrong word Collection<OnmsResourceType> resourceTypes = m_resourceDao.getResourceTypes(); Multimap<String, String> genericDsTypes = TreeMultimap.create(); for (OnmsResourceType resourceType : resourceTypes) { if (resourceType instanceof GenericIndexResourceType) // Put these in by label to sort them, we'll get them out in a moment {/*from ww w .j ava 2 s . co m*/ genericDsTypes.put(resourceType.getLabel(), resourceType.getName()); } } // Now get the resource types out of the TreeMultimap for (String rtLabel : genericDsTypes.keys()) { Collection<String> rtNames = genericDsTypes.get(rtLabel); for (String rtName : rtNames) { if (rtNames.size() > 1) { dsTypes.put(rtName, rtLabel + " [" + rtName + "]"); } else { dsTypes.put(rtName, rtLabel); } } } // Finally, set the sorted resource types into the model modelAndView.addObject("dsTypes", dsTypes); Collection<String> thresholdTypes = new ArrayList<String>(); thresholdTypes.add("high"); thresholdTypes.add("low"); thresholdTypes.add("relativeChange"); thresholdTypes.add("absoluteChange"); thresholdTypes.add("rearmingAbsoluteChange"); modelAndView.addObject("thresholdTypes", thresholdTypes); Collection<String> filterOperators = new ArrayList<String>(); filterOperators.add("and"); filterOperators.add("or"); modelAndView.addObject("filterOperators", filterOperators); modelAndView.addObject("saveButtonTitle", SAVE_BUTTON_TITLE); modelAndView.addObject("cancelButtonTitle", CANCEL_BUTTON_TITLE); modelAndView.addObject("addFilterButtonTitle", ADDFILTER_BUTTON_TITLE); modelAndView.addObject("editButtonTitle", EDIT_BUTTON_TITLE); modelAndView.addObject("deleteButtonTitle", DELETE_BUTTON_TITLE); modelAndView.addObject("updateButtonTitle", UPDATE_BUTTON_TITLE); modelAndView.addObject("moveUpButtonTitle", MOVEUP_BUTTON_TITLE); modelAndView.addObject("moveDownButtonTitle", MOVEDOWN_BUTTON_TITLE); }
From source file:org.eclipse.sirius.ui.debug.SiriusDebugView.java
private void addShowResourceSetTopologyAction() { addAction("Show ResourceSet Topology", new Runnable() { @Override/* w w w . j a v a 2 s . com*/ public void run() { for (Session s : SessionManager.INSTANCE.getSessions()) { ResourceSetTopologyAnalyzer rsta = new ResourceSetTopologyAnalyzer( s.getTransactionalEditingDomain().getResourceSet()); Multimap<EStructuralFeature, Reference> result = rsta.analyze(); StringBuilder sb = new StringBuilder(); sb.append("Found " + result.keys().size() + " distinct kinds of cross-resource references:\n"); for (EStructuralFeature esf : result.keys()) { sb.append("- "); appendFeatureName(sb, esf); sb.append("\n"); for (Reference ref : result.get(esf)) { sb.append(" - ").append(renderResource(ref.sourceResource)).append(" => ") .append(renderResource(ref.targetResource)).append(" [" + ref.count + "]") .append("\n"); } } setText(sb.toString()); } } private final void appendFeatureName(StringBuilder out, EStructuralFeature esf) { out.append(esf.getEContainingClass().getEPackage().getName()).append("::") .append(esf.getEContainingClass().getName()).append(".").append(esf.getName()); } private final String renderResource(Resource res) { if (res == null) { return "(no resource)"; } else if (res.getURI() == null) { return "(resource with no URI)"; } else { return res.getURI().toString(); } } }); }
From source file:org.opentripplanner.api.resource.SimpleIsochrone.java
/** @return a map from contour (isochrone) thresholds in seconds to geometries. */ private Map<Integer, Geometry> makeContours() throws Exception { Map<Vertex, Double> points = makePoints(); if (points == null || points.isEmpty()) { LOG.error("No destinations were reachable."); return null; }/*from w ww . j ava 2 s . co m*/ /* Set up transforms into projected coordinates (necessary for buffering in meters) */ /* We could avoid projection by equirectangular approximation */ CoordinateReferenceSystem wgs = DefaultGeographicCRS.WGS84; CoordinateReferenceSystem crs = CRS.decode(crsCode); MathTransform toMeters = CRS.findMathTransform(wgs, crs, false); MathTransform fromMeters = CRS.findMathTransform(crs, wgs, false); GeometryFactory geomf = JTSFactoryFinder.getGeometryFactory(); /* One list of geometries for each contour */ Multimap<Integer, Geometry> bufferLists = ArrayListMultimap.create(); for (int c = 0; c < nContours; ++c) { int thresholdSeconds = (c + 1) * contourSpacingMinutes * 60; for (Map.Entry<Vertex, Double> vertexSeconds : points.entrySet()) { double remainingSeconds = thresholdSeconds - vertexSeconds.getValue(); if (remainingSeconds > 60) { // avoid degenerate geometries double remainingMeters = remainingSeconds * request.walkSpeed; Geometry point = geomf.createPoint(vertexSeconds.getKey().getCoordinate()); point = JTS.transform(point, toMeters); Geometry buffer = point.buffer(remainingMeters); bufferLists.put(thresholdSeconds, buffer); } } } /* Union the geometries at each contour threshold. */ Map<Integer, Geometry> contours = Maps.newHashMap(); for (Integer threshold : bufferLists.keys()) { Collection<Geometry> buffers = bufferLists.get(threshold); Geometry geom = geomf.buildGeometry(buffers); // make geometry collection geom = geom.union(); // combine all individual buffers in this contour into one if (!resultsProjected) geom = JTS.transform(geom, fromMeters); contours.put(threshold, geom); } return contours; }
From source file:org.opentripplanner.api.resource.analyst.SimpleIsochrone.java
/** @return a map from contour (isochrone) thresholds in seconds to geometries. */ private Map<Integer, Geometry> makeContours() throws Exception { Map<Vertex, Double> points = makePoints(); if (points == null || points.isEmpty()) { LOG.error("No destinations were reachable."); return null; }// w ww.ja va 2s . c om /* Set up transforms into projected coordinates (necessary for buffering in meters) */ /* We could avoid projection by equirectangular approximation */ CoordinateReferenceSystem wgs = DefaultGeographicCRS.WGS84; CoordinateReferenceSystem crs = CRS.decode(crsCode); MathTransform toMeters = CRS.findMathTransform(wgs, crs, false); MathTransform fromMeters = CRS.findMathTransform(crs, wgs, false); GeometryFactory geomf = JTSFactoryFinder.getGeometryFactory(); /* One list of geometries for each contour */ Multimap<Integer, Geometry> bufferLists = ArrayListMultimap.create(); for (int c = 0; c < nContours; ++c) { int thresholdSeconds = (c + 1) * contourSpacingMinutes * 60; for (Map.Entry<Vertex, Double> vertexSeconds : points.entrySet()) { double remainingSeconds = thresholdSeconds - vertexSeconds.getValue(); if (remainingSeconds > 60) { // avoid degenerate geometries double remainingMeters = remainingSeconds * request.getWalkSpeed(); Geometry point = geomf.createPoint(vertexSeconds.getKey().getCoordinate()); point = JTS.transform(point, toMeters); Geometry buffer = point.buffer(remainingMeters); bufferLists.put(thresholdSeconds, buffer); } } } /* Union the geometries at each contour threshold. */ Map<Integer, Geometry> contours = Maps.newHashMap(); for (Integer threshold : bufferLists.keys()) { Collection<Geometry> buffers = bufferLists.get(threshold); Geometry geom = geomf.buildGeometry(buffers); // make geometry collection geom = geom.union(); // combine all individual buffers in this contour into one if (!resultsProjected) geom = JTS.transform(geom, fromMeters); contours.put(threshold, geom); } return contours; }
From source file:org.gatein.wsrp.producer.handlers.PortletManagementHandler.java
public DestroyPortletsResponse destroyPortlets(DestroyPortlets destroyPortlets) throws InconsistentParameters, InvalidRegistration, MissingParameters, ModifyRegistrationRequired, OperationFailed, OperationNotSupported, ResourceSuspended { WSRP2ExceptionFactory.throwOperationFailedIfValueIsMissing(destroyPortlets, "DestroyPortlets"); List<String> handles = destroyPortlets.getPortletHandles(); WSRP2ExceptionFactory.throwMissingParametersIfValueIsMissing(handles, "portlet handles to be destroyed", "DestroyPortlets"); handles = WSRPUtils.replaceByEmptyListIfNeeded(handles); Registration registration = producer .getRegistrationOrFailIfInvalid(destroyPortlets.getRegistrationContext()); List<org.gatein.pc.api.PortletContext> portletContexts = new ArrayList<org.gatein.pc.api.PortletContext>( handles.size());/*ww w . ja va 2s.com*/ for (String handle : handles) { portletContexts.add(org.gatein.pc.api.PortletContext.createPortletContext(handle)); } try { RegistrationLocal.setRegistration(registration); List<DestroyCloneFailure> failuresList = producer.getPortletInvoker().destroyClones(portletContexts); int failuresNumber = failuresList.size(); List<FailedPortlets> failedPortlets; if (failuresNumber > 0) { // for each reason of failure, record the associated portlet handles, expecting one portlet handle per message Multimap<String, String> reasonToHandles = HashMultimap.create(failuresNumber, 1); for (DestroyCloneFailure failure : failuresList) { reasonToHandles.put(failure.getMessage(), failure.getPortletId()); } // create a FailedPortlets object for each reason failedPortlets = new ArrayList<FailedPortlets>(reasonToHandles.size()); for (String reason : reasonToHandles.keys()) { failedPortlets.add(WSRPTypeFactory.createFailedPortlets(reasonToHandles.get(reason), ErrorCodes.Codes.OPERATIONFAILED, reason)); } } else { failedPortlets = null; } return WSRPTypeFactory.createDestroyPortletsResponse(failedPortlets); } catch (PortletInvokerException e) { throw WSRP2ExceptionFactory.throwWSException(OperationFailed.class, "Failed to destroy clones", e); } finally { RegistrationLocal.setRegistration(null); } }
From source file:com.flexive.core.storage.genericSQL.GenericTreeStorageSpreaded.java
private void checkUniqueBounds(FxTreeMode mode, Multimap<BigInteger, CheckedNodeInfo> infos, String name) throws FxTreeException { // check for unique left/right tree bounds for (Entry<BigInteger> entry : infos.keys().entrySet()) { if (entry.getCount() > 1) { throw new FxTreeException(LOG, "ex.tree.check.failed", mode, "Duplicate boundaries (" + name + ") for nodes " + infos.get(entry.getElement())); }//from ww w .j a v a 2 s . c om } }
From source file:es.usc.citius.composit.core.composition.optimization.FunctionalDominanceOptimizer.java
public Collection<Collection<Operation<E>>> functionalOutputDominance(Collection<Operation<E>> operations, ServiceMatchNetwork<E, T> network, int level) { Multimap<Set<E>, Operation<E>> providers = HashMultimap.create(); Set<Operation<E>> consumers = new HashSet<Operation<E>>(); for (Operation<E> o : operations) { // Check operations that consumes the outputs of this op. for (E output : o.getSignature().getOutputs()) { for (E target : network.getTargetElementsMatchedBy(output).keySet()) { consumers.addAll(Sets.newHashSet(network.getOperationsWithInput(target))); }/*from w w w . j a va 2s . c om*/ } // Remove all the consumers that are not in the subsequent layers consumers.retainAll(network.getOperationsAfterLevel(level)); // Compute all the inputs matched by operation o Set<E> inputsMatched = new HashSet<E>(); for (Operation<E> consumer : consumers) { inputsMatched.addAll( network.partialMatch(o.getSignature().getOutputs(), consumer.getSignature().getInputs()) .getTargetElements()); } providers.get(inputsMatched).add(o); } // Now, build a new multi map moving all dominated elements Multimap<Set<E>, Operation<E>> nonDominatedProviders = HashMultimap.create(); // Inefficient subset elimination algorithm O(n^2) for (Set<E> m1 : providers.keys()) { // Check whether m1 is dominated or not boolean dominated = false; for (Set<E> m2 : providers.keys()) { if (m2.size() > m1.size()) { // m1 could be dominated by m2 if (m2.containsAll(m1)) { // m2 dominates m1 dominated = true; break; } } } if (!dominated) { // Copy nonDominatedProviders.get(m1).addAll(providers.get(m1)); } } return nonDominatedProviders.asMap().values(); }
From source file:grakn.core.graql.executor.WriteExecutor.java
/** * Produce a valid ordering of the properties by using the given dependency information. * This method uses a topological sort (Kahn's algorithm) in order to find a valid ordering. *///from w w w.j a va2 s. c o m private ImmutableList<Writer> sortedWriters() { ImmutableList.Builder<Writer> sorted = ImmutableList.builder(); // invertedDependencies is intended to just be a 'view' on dependencies, so when dependencies is modified // we should always also modify invertedDependencies (and vice-versa). Multimap<Writer, Writer> dependencies = HashMultimap.create(this.dependencies); Multimap<Writer, Writer> invertedDependencies = HashMultimap.create(); Multimaps.invertFrom(dependencies, invertedDependencies); Queue<Writer> writerWithoutDependencies = new ArrayDeque<>( Sets.filter(writers, property -> dependencies.get(property).isEmpty())); Writer property; // Retrieve the next property without any dependencies while ((property = writerWithoutDependencies.poll()) != null) { sorted.add(property); // We copy this into a new list because the underlying collection gets modified during iteration Collection<Writer> dependents = Lists.newArrayList(invertedDependencies.get(property)); for (Writer dependent : dependents) { // Because the property has been removed, the dependent no longer needs to depend on it dependencies.remove(dependent, property); invertedDependencies.remove(property, dependent); boolean hasNoDependencies = dependencies.get(dependent).isEmpty(); if (hasNoDependencies) { writerWithoutDependencies.add(dependent); } } } if (!dependencies.isEmpty()) { // This means there must have been a loop. Pick an arbitrary remaining var to display Variable var = dependencies.keys().iterator().next().var(); throw GraqlSemanticException.insertRecursive(printableRepresentation(var)); } return sorted.build(); }
From source file:com.github.pms1.tppt.p2.FeatureXmlComparator.java
private void comparePlugins2(Map<String, Multimap<String, Element>> baseline, Map<String, Multimap<String, Element>> current, ElementDeltaReporter elementDeltaReporter, DeltaReporter deltaReporter) {//from w w w . jav a 2 s . com for (String id : Sets.union(baseline.keySet(), current.keySet())) { Multimap<String, Element> b = baseline.get(id); if (b == null) b = HashMultimap.create(); else b = HashMultimap.create(b); Multimap<String, Element> c = current.get(id); if (c == null) c = HashMultimap.create(); else c = HashMultimap.create(c); AttributesDeltaReporter r = new AttributesDeltaReporter() { @Override public void removed(String key) { deltaReporter.fileDelta("Plugin {0} attribute {1} removed", id, key); } @Override public void changed(String key, String left, String right) { if (key.equals("version")) { deltaReporter.pluginVersionDelta(id, left, right); } else { deltaReporter.fileDelta("Plugin {0} attribute {1} changed {2} -> {3}", id, key, left, right); } } @Override public void added(String key, String value) { deltaReporter.fileDelta("Plugin {0} attribute {1} / {2} added", id, key, value); } }; Set<String> intersection = new HashSet<>(b.keys()); intersection.retainAll(c.keys()); for (String v : intersection) { Collection<Element> be = b.get(v); Collection<Element> ce = c.get(v); if (be.size() == 1 && ce.size() == 1) { compareAttributes(Iterables.getOnlyElement(be), Iterables.getOnlyElement(ce), r); b.removeAll(v); c.removeAll(v); } } if (b.size() == 1 && c.size() == 1) { compareAttributes(Iterables.getOnlyElement(b.values()), Iterables.getOnlyElement(c.values()), r); } else { for (Element e : b.values()) deltaReporter.fileDelta("Plugin removed: {0}", domRenderer.render(e)); for (Element e : c.values()) deltaReporter.fileDelta("Plugin added: {0}", domRenderer.render(e)); } } }