List of usage examples for com.google.common.collect Multimaps index
public static <K, V> ImmutableListMultimap<K, V> index(Iterator<V> values, Function<? super V, K> keyFunction)
From source file:com.rk.grid.server.ExecutionServer.java
private final <T> void submitBatch(Collection<ITask<T>> batch, ProxyJobResultHandler<T> proxyHandler) { if (batch.size() == 0) return;//w ww. j a v a 2s . c om ListMultimap<String, ITask<T>> tasksByService = Multimaps.index(batch, new Function<ITask<T>, String>() { public String apply(ITask<T> task) { return task.getInvocationNamespace(); } }); Map<String, Collection<ITask<T>>> tasksByServiceMap = tasksByService.asMap(); for (String requiredService : tasksByServiceMap.keySet()) { if (this.executorMap.containsKey(requiredService)) { ITaskExecutor taskExecutor = this.executorMap.get(requiredService); try { IResultHandler<T> delegate = proxyHandler.newDelegate(); taskExecutor.execute(tasksByServiceMap.get(requiredService), delegate); } catch (Exception e) { e.printStackTrace(); proxyHandler.onError(e); } } else { System.out.println("XXX" + requiredService); proxyHandler.onRejection(tasksByServiceMap.get(requiredService)); } } }
From source file:info.gehrels.voting.web.BallotIterableDiffCalculator.java
private static <T extends Candidate> Multimap<Long, Ballot<T>> asIdToBallotsMulitmap( Iterable<Ballot<T>> castBallots) { return Multimaps.index(castBallots, GET_ID_FROM_BALLOT_FUNCTION); }
From source file:com.yodle.vantage.component.dao.IssueDao.java
public Map<String, Collection<Issue>> getIssuesDirectlyAffectingVersions(String component) { List<Map<String, Object>> rs = jdbcTemplate .queryForList(//from www . j a v a 2 s.c o m "MATCH (c:Component {name:{1}})<-[:VERSION_OF]-(v:Version)<-[:PRECEDES|:AFFECTS*]-(i:Issue)" + "MATCH (i)-[:AFFECTS]->(av:Version)" + "WHERE NOT (v)<-[:PRECEDES|:FIXED_BY*]-(i)" + "OPTIONAL MATCH (i)-[:FIXED_BY]->(fv:Version)" + "RETURN c.name, v.version, i.id, i.level, i.message, av.version, fv.version", component); ImmutableListMultimap<String, Map<String, Object>> grouped = Multimaps.index(rs, (row -> (String) row.get("v.version"))); return Multimaps.transformValues(grouped, (this::toIssue)).asMap(); }
From source file:com.google.cloud.bigtable.dataflowimport.HBaseResultToMutationFn.java
private Put processRowWithDeleteMarkers(byte[] rowKey, List<Cell> cells) throws IOException { Put put = new Put(rowKey); // Group cells by column family, since DeleteMarkers do not apply across families. Map<String, Collection<Cell>> dataCellsByFamilyMap = Multimaps .index(Iterables.filter(cells, Predicates.not(IS_DELETE_MARKER_FILTER)), COLUMN_FAMILY_EXTRACTOR) .asMap();//from w ww. java2 s . co m Map<String, Collection<Cell>> deleteMarkersByFamilyMap = Multimaps .index(Iterables.filter(cells, IS_DELETE_MARKER_FILTER), COLUMN_FAMILY_EXTRACTOR).asMap(); for (Map.Entry<String, Collection<Cell>> e : dataCellsByFamilyMap.entrySet()) { processOneColumnFamily(put, e.getValue(), deleteMarkersByFamilyMap.get(e.getKey())); } return put; }
From source file:org.immutables.sequence.Entries.java
public static <K, V> Entries<K, V> index(Iterable<V> values, Function<? super V, K> keyFunction) { return from(new Iterable<Entry<K, V>>() { @Override/*from w w w. jav a2s. co m*/ public Iterator<Entry<K, V>> iterator() { return Multimaps.index(values, v -> keyFunction.apply(v)).entries().iterator(); } }); }
From source file:org.eclipse.emf.compare.diagram.sirius.internal.SiriusDiffPostProcessor.java
/** * {@inheritDoc}/*from w w w .j a v a2 s.c o m*/ */ public void postRequirements(Comparison comparison, Monitor monitor) { /* * Any added/deleted DSemanticDecorator must require the corresponding getTarget() addition/removal */ Iterable<ReferenceChange> allContainmentRefChanges = Iterables.filter( Iterables.filter(comparison.getDifferences(), ReferenceChange.class), CONTAINMENT_REFERENCE_CHANGE); Iterable<ReferenceChange> addedOrRemovedSemanticDecorators = Iterables.filter(allContainmentRefChanges, valueIsKindOf(ViewpointPackage.eINSTANCE.getDSemanticDecorator())); Multimap<EObject, ReferenceChange> diffsByValue = Multimaps.index(allContainmentRefChanges, getReferenceChangeValue()); /* * Any added or removed semantic decorator should have a dependency to the corresponding * addition/removal of semantic element. */ for (ReferenceChange referenceChange : addedOrRemovedSemanticDecorators) { DSemanticDecorator value = (DSemanticDecorator) referenceChange.getValue(); if (value.getTarget() != null) { EObject semanticTarget = value.getTarget(); addRequiresToDecoratedElement(diffsByValue, referenceChange, semanticTarget); } /* * A DNode should always have its actualMapping reference set. */ if (value instanceof DNode) { NodeMapping map = ((DNode) value).getActualMapping(); if (map != null) { for (ReferenceChange actualMappingChange : Iterables.filter(comparison.getDifferences(map), ReferenceChange.class)) { if (actualMappingChange.getReference() == DiagramPackage.eINSTANCE.getDNode_ActualMapping() && fromSide(referenceChange.getSource()).apply(actualMappingChange)) { referenceChange.getRequires().add(actualMappingChange); } } } } } /* * Any added or removed gmf Node should have a dependency to the corresponding addition/removal of a * DSemantic decorator. */ Iterable<ReferenceChange> addedOrRemovedGmfView = Iterables.filter(allContainmentRefChanges, valueIsKindOf(NotationPackage.eINSTANCE.getView())); for (ReferenceChange referenceChange : addedOrRemovedGmfView) { View value = (View) referenceChange.getValue(); /* * beware here, GMF do som trick in getElement() and will return it's container element if the * element is null.. */ if (value.getElement() != null) { EObject semanticTarget = value.getElement(); addRequiresToDecoratedElement(diffsByValue, referenceChange, semanticTarget); } } }
From source file:org.gradle.model.internal.manage.schema.extract.StructStrategy.java
public <R> ModelSchemaExtractionResult<R> extract(final ModelSchemaExtractionContext<R> extractionContext, final ModelSchemaCache cache) { ModelType<R> type = extractionContext.getType(); Class<? super R> clazz = type.getRawClass(); if (clazz.isAnnotationPresent(Managed.class)) { validateType(type, extractionContext); Iterable<Method> methods = Arrays.asList(clazz.getMethods()); if (!clazz.isInterface()) { methods = filterIgnoredMethods(methods); }/* w w w. j a v a 2s . c o m*/ ImmutableListMultimap<String, Method> methodsByName = Multimaps.index(methods, new Function<Method, String>() { public String apply(Method method) { return method.getName(); } }); ensureNoOverloadedMethods(extractionContext, methodsByName); List<ModelProperty<?>> properties = Lists.newLinkedList(); List<Method> handled = Lists.newArrayListWithCapacity(clazz.getMethods().length); ReturnTypeSpecializationOrdering returnTypeSpecializationOrdering = new ReturnTypeSpecializationOrdering(); for (String methodName : methodsByName.keySet()) { if (methodName.startsWith("get") && !methodName.equals("get")) { ImmutableList<Method> getterMethods = methodsByName.get(methodName); // The overload check earlier verified that all methods for are equivalent for our purposes // So, taking the first one with the most specialized return type is fine. Method sampleMethod = returnTypeSpecializationOrdering.max(getterMethods); boolean abstractGetter = Modifier.isAbstract(sampleMethod.getModifiers()); if (sampleMethod.getParameterTypes().length != 0) { throw invalidMethod(extractionContext, "getter methods cannot take parameters", sampleMethod); } Character getterPropertyNameFirstChar = methodName.charAt(3); if (!Character.isUpperCase(getterPropertyNameFirstChar)) { throw invalidMethod(extractionContext, "the 4th character of the getter method name must be an uppercase character", sampleMethod); } ModelType<?> returnType = ModelType.returnType(sampleMethod); String propertyNameCapitalized = methodName.substring(3); String propertyName = StringUtils.uncapitalize(propertyNameCapitalized); String setterName = "set" + propertyNameCapitalized; ImmutableList<Method> setterMethods = methodsByName.get(setterName); boolean isWritable = !setterMethods.isEmpty(); if (isWritable) { Method setter = setterMethods.get(0); if (!abstractGetter) { throw invalidMethod(extractionContext, "setters are not allowed for non-abstract getters", setter); } validateSetter(extractionContext, returnType, setter); handled.addAll(setterMethods); } if (abstractGetter) { ImmutableSet<ModelType<?>> declaringClasses = ImmutableSet .copyOf(Iterables.transform(getterMethods, new Function<Method, ModelType<?>>() { public ModelType<?> apply(Method input) { return ModelType.of(input.getDeclaringClass()); } })); boolean unmanaged = Iterables.any(getterMethods, new Predicate<Method>() { public boolean apply(Method input) { return input.getAnnotation(Unmanaged.class) != null; } }); properties.add(ModelProperty.of(returnType, propertyName, isWritable, declaringClasses, unmanaged)); } handled.addAll(getterMethods); } } Iterable<Method> notHandled = Iterables.filter(methodsByName.values(), Predicates.not(Predicates.in(handled))); // TODO - should call out valid getters without setters if (!Iterables.isEmpty(notHandled)) { throw invalidMethods(extractionContext, "only paired getter/setter methods are supported", notHandled); } Class<R> concreteClass = type.getConcreteClass(); Class<? extends R> implClass = classGenerator.generate(concreteClass); final ModelStructSchema<R> schema = ModelSchema.struct(type, properties, implClass); extractionContext.addValidator(new Action<ModelSchemaExtractionContext<R>>() { @Override public void execute(ModelSchemaExtractionContext<R> validatorModelSchemaExtractionContext) { ensureCanBeInstantiated(extractionContext, schema); } }); Iterable<ModelSchemaExtractionContext<?>> propertyDependencies = Iterables.transform(properties, new Function<ModelProperty<?>, ModelSchemaExtractionContext<?>>() { public ModelSchemaExtractionContext<?> apply(final ModelProperty<?> property) { return toPropertyExtractionContext(extractionContext, property, cache); } }); return new ModelSchemaExtractionResult<R>(schema, propertyDependencies); } else { return null; } }
From source file:org.mondo.collaboration.security.lens.correspondence.EObjectCorrespondence.java
public static Map<Object, Collection<EObject>> applyObjectToUniqueIdentifier(ModelIndexer indexer, UniqueIDScheme objectToUniqueIdentifier) { return Multimaps.index(indexer.getAllEObjects(), objectToUniqueIdentifier).asMap(); }
From source file:de.faustedition.reasoning.InscriptionPrecedenceResource.java
@Override protected void doInit() throws ResourceException { super.doInit(); final VerseInterval verseInterval = VerseManager.fromRequestAttibutes(getRequestAttributes()); final Multimap<String, GraphVerseInterval> intervalIndex = Multimaps .index(verseManager.forInterval(verseInterval), new Function<GraphVerseInterval, String>() { @Override// w w w . j ava2s. co m public String apply(@Nullable GraphVerseInterval input) { //final String sigil = transcriptManager.materialUnitForTranscript(input.getTranscript(textRepo)).toString(); final String sigil = ((Document) (transcriptManager .materialUnitForTranscript(input.getTranscript(textRepo)))).getSource().toString(); return sigil; } }); inscriptions = Sets.newHashSet(); for (String sigil : Ordering.natural().immutableSortedCopy(intervalIndex.keySet())) { final Inscription inscription = new Inscription(sigil); for (VerseInterval interval : intervalIndex.get(sigil)) { inscription.addInterval(interval.getStart(), interval.getEnd()); } Preconditions.checkState(!inscription.isEmpty()); inscriptions.add(inscription); //long materialUnitId = intervalIndex.get(sigil).iterator().next().getTranscript(textRepo).getMaterialUnitId(); //Node node = graphDb.getNodeById(materialUnitId); Node node = transcriptManager.materialUnitForTranscript( intervalIndex.get(sigil).iterator().next().getTranscript(textRepo)).node; nodeMap.put(inscription, node); } for (Inscription subject : inscriptions) { for (Inscription object : inscriptions) { if (InscriptionRelations.syntagmaticallyPrecedesByFirstLine(subject, object)) { // if (InscriptionRelations.syntagmaticallyPrecedesByAverage(subject, object)) { syntagmaticPrecedence.relate(subject, object); } if (InscriptionRelations.exclusivelyContains(subject, object)) { exclusiveContainment.relate(subject, object); } if (InscriptionRelations.paradigmaticallyContains(subject, object)) { paradigmaticContainment.relate(subject, object); } } } try { explicitPrecedence = new GraphBasedRelation<Inscription>(nodeMap, new FaustURI(new URI("faust://secondary/gruss2011"))); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } List<Premise<Inscription>> premises = new ArrayList<Premise<Inscription>>(); // premises.addAll(premisesFromGeneticSources()); premises.addAll(premisesFromInference()); precedence = new PremiseBasedRelation<Inscription>(premises); // precedence = new LastPremiseRelation<Inscription> (premises); Relation<Inscription> test = Util .wrapTransitive(new PremiseBasedRelation<Inscription>(premisesFromInference()), inscriptions); Relation<Inscription> check = Util .wrapTransitive(new PremiseBasedRelation<Inscription>(premisesFromGeneticSources()), inscriptions); logger.info("Genetic graph statistics: "); logger.info(" Coverage: " + Statistics.completeness(precedence, check, inscriptions) * 100 + ", Recall: " + Statistics.recall(precedence, check, inscriptions) * 100 + ", Accuracy : " + Statistics.correctness(precedence, check, inscriptions) * 100 ); }
From source file:com.google.testing.compile.Parser.java
private static ImmutableListMultimap<Diagnostic.Kind, Diagnostic<? extends JavaFileObject>> sortDiagnosticsByKind( Iterable<Diagnostic<? extends JavaFileObject>> diagnostics) { return Multimaps.index(diagnostics, input -> input.getKind()); }