List of usage examples for com.google.common.collect Maps filterValues
@CheckReturnValue public static <K, V> BiMap<K, V> filterValues(BiMap<K, V> unfiltered, final Predicate<? super V> valuePredicate)
From source file:ninja.leaping.permissionsex.backend.memory.MemorySubjectData.java
@Override public Map<Set<Entry<String, String>>, Map<String, Integer>> getAllPermissions() { return Maps.filterValues( Maps.transformValues(contexts, dataEntry -> dataEntry == null ? null : dataEntry.permissions), o -> o != null);//from ww w . ja va 2 s.c o m }
From source file:org.apache.brooklyn.location.jclouds.JCloudsPropertiesBuilder.java
public JCloudsPropertiesBuilder setCustomJcloudsProperties() { Map<String, Object> extra = Maps.filterKeys(conf.getAllConfig(), Predicates.containsPattern("^jclouds\\.")); if (extra.size() > 0) { String provider = getProviderFromConfig(conf); LOG.debug("Configuring custom jclouds property overrides for {}: {}", provider, Sanitizer.sanitize(extra)); }/*from www . ja v a 2 s. c o m*/ properties.putAll(Maps.filterValues(extra, Predicates.notNull())); return this; }
From source file:gg.uhc.uhc.modules.death.DeathStandsModule.java
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void on(EntityDamageEvent event) { if (event.getEntityType() != EntityType.ARMOR_STAND) return;/*from w w w . j av a 2 s .co m*/ if (!isProtectedArmourStand(event.getEntity())) return; // always cancel events, we choose when to break the stand event.setCancelled(true); ArmorStand stand = (ArmorStand) event.getEntity(); Location loc = stand.getLocation(); World world = stand.getWorld(); // for the first 2 seconds don't allow breaking // to avoid accidental breaks after kill if (event.getEntity().getTicksLived() < 40) { world.playEffect(stand.getEyeLocation(), Effect.WITCH_MAGIC, 0); return; } // drop each of it's worn items for (ItemStack stack : Maps.filterValues(getItems(stand), Predicates.not(EMPTY_ITEM)).values()) { world.dropItemNaturally(loc, stack); } // kill the stand now stand.remove(); }
From source file:ninja.leaping.permissionsex.backend.file.FileDataStore.java
@Override public Set<String> getRegisteredTypes() { return ImmutableSet .copyOf(Iterables/*from w ww . j a v a 2s. c o m*/ .transform( Maps.filterValues(getSubjectsNode().getChildrenMap(), input -> input != null && input.hasMapChildren()).keySet(), Object::toString)); }
From source file:ninja.leaping.permissionsex.backend.memory.MemoryOptionSubjectData.java
@Override public Map<Set<Entry<String, String>>, Map<String, Integer>> getAllPermissions() { return Maps.filterValues(Maps.transformValues(contexts, new Function<DataEntry, Map<String, Integer>>() { @Nullable//from w w w .j a v a2 s . c o m @Override public Map<String, Integer> apply(@Nullable DataEntry dataEntry) { return dataEntry == null ? null : dataEntry.permissions; } }), Predicates.notNull()); }
From source file:com.isotrol.impe3.web20.impl.MigrationServiceImpl.java
private MemberEntity fillMember(MemberEntity entity, MemberDTO dto) { final Calendar date = Calendar.getInstance(); date.setTime(dto.getDate());//from w w w .j a v a 2 s. c o m entity.setDate(date); entity.setDisplayName(dto.getDisplayName()); entity.setEmail(dto.getEmail()); entity.setMemberCode(dto.getCode()); entity.setName(dto.getName()); entity.setBlocked(dto.isBlocked()); final Set<String> profiles = entity.getProfiles(); profiles.clear(); final Set<String> dtopf = dto.getProfiles(); if (dtopf != null) { profiles.addAll(Sets.filter(dtopf, notNull())); } final Map<String, String> properties = entity.getProperties(); properties.clear(); final Map<String, String> dtopr = dto.getProperties(); if (dtopr != null) { properties.putAll(Maps.filterKeys(Maps.filterValues(dtopr, notNull()), notNull())); } return entity; }
From source file:org.cinchapi.concourse.server.storage.temp.Limbo.java
/** * Calculate the browsable view of {@code key} at {@code timestamp} using * prior {@code context} as if it were also a part of the Buffer. * //from w ww . j a v a 2 s . co m * @param key * @param timestamp * @param context * @return a possibly empty Map of data */ public Map<TObject, Set<Long>> browse(String key, long timestamp, Map<TObject, Set<Long>> context) { Iterator<Write> it = iterator(); while (it.hasNext()) { Write write = it.next(); if (write.getKey().toString().equals(key) && write.getVersion() <= timestamp) { Set<Long> records = context.get(write.getValue().getTObject()); if (records == null) { records = Sets.newLinkedHashSet(); context.put(write.getValue().getTObject(), records); } if (write.getType() == Action.ADD) { records.add(write.getRecord().longValue()); } else { records.remove(write.getRecord().longValue()); } } else if (write.getVersion() > timestamp) { break; } else { continue; } } return Maps.newTreeMap((SortedMap<TObject, Set<Long>>) Maps.filterValues(context, emptySetFilter)); }
From source file:dagger.internal.codegen.ComponentValidator.java
/** * Validates the given component subject. Also validates any referenced subcomponents that aren't * already included in the {@code validatedSubcomponents} set. *//*from w ww .j av a2 s .co m*/ public ComponentValidationReport validate(final TypeElement subject, Set<? extends Element> validatedSubcomponents, Set<? extends Element> validatedSubcomponentBuilders) { ValidationReport.Builder<TypeElement> builder = ValidationReport.about(subject); ComponentDescriptor.Kind componentKind = ComponentDescriptor.Kind.forAnnotatedElement(subject).get(); if (!subject.getKind().equals(INTERFACE) && !(subject.getKind().equals(CLASS) && subject.getModifiers().contains(ABSTRACT))) { builder.addError(String.format("@%s may only be applied to an interface or abstract class", componentKind.annotationType().getSimpleName()), subject); } ImmutableList<DeclaredType> builders = enclosedBuilders(subject, componentKind.builderAnnotationType()); if (builders.isEmpty()) { final String subjectName = subject.getQualifiedName().toString(); builder.addError( String.format(ErrorMessages.builderMsgsFor(componentKind).noBuilderPresent(), subjectName)); } if (builders.size() > 1) { builder.addError(String.format(ErrorMessages.builderMsgsFor(componentKind).moreThanOne(), builders), subject); } Optional<AnnotationMirror> reusableAnnotation = getAnnotationMirror(subject, Reusable.class); if (reusableAnnotation.isPresent()) { builder.addError(COMPONENT_ANNOTATED_REUSABLE, subject, reusableAnnotation.get()); } DeclaredType subjectType = MoreTypes.asDeclared(subject.asType()); SetMultimap<Element, ExecutableElement> referencedSubcomponents = LinkedHashMultimap.create(); getLocalAndInheritedMethods(subject, types, elements).stream() .filter(method -> method.getModifiers().contains(ABSTRACT)).forEachOrdered(method -> { ExecutableType resolvedMethod = asExecutable(types.asMemberOf(subjectType, method)); List<? extends TypeMirror> parameterTypes = resolvedMethod.getParameterTypes(); List<? extends VariableElement> parameters = method.getParameters(); TypeMirror returnType = resolvedMethod.getReturnType(); // abstract methods are ones we have to implement, so they each need to be validated // first, check the return type. if it's a subcomponent, validate that method as such. Optional<AnnotationMirror> subcomponentAnnotation = checkForAnnotations(returnType, FluentIterable.from(componentKind.subcomponentKinds()).transform(Kind::annotationType) .toSet()); Optional<AnnotationMirror> subcomponentBuilderAnnotation = checkForAnnotations(returnType, FluentIterable.from(componentKind.subcomponentKinds()) .transform(Kind::builderAnnotationType).toSet()); if (subcomponentAnnotation.isPresent()) { referencedSubcomponents.put(MoreTypes.asElement(returnType), method); validateSubcomponentMethod(builder, ComponentDescriptor.Kind.forAnnotatedElement(MoreTypes.asTypeElement(returnType)) .get(), method, parameters, parameterTypes, returnType, subcomponentAnnotation); } else if (subcomponentBuilderAnnotation.isPresent()) { referencedSubcomponents.put(MoreTypes.asElement(returnType).getEnclosingElement(), method); validateSubcomponentBuilderMethod(builder, method, parameters, returnType, validatedSubcomponentBuilders); } else { // if it's not a subcomponent... switch (parameters.size()) { case 0: // no parameters means that it is a provision method // basically, there are no restrictions here. \o/ break; case 1: // one parameter means that it's a members injection method TypeMirror onlyParameter = Iterables.getOnlyElement(parameterTypes); if (!(returnType.getKind().equals(VOID) || types.isSameType(returnType, onlyParameter))) { builder.addError( "Members injection methods may only return the injected type or void.", method); } break; default: // this isn't any method that we know how to implement... builder.addError( "This method isn't a valid provision method, members injection method or " + "subcomponent factory method. Dagger cannot implement this method", method); break; } } }); Maps.filterValues(referencedSubcomponents.asMap(), methods -> methods.size() > 1) .forEach((subcomponent, methods) -> builder.addError(String.format( ErrorMessages.SubcomponentBuilderMessages.INSTANCE.moreThanOneRefToSubcomponent(), subcomponent, methods), subject)); AnnotationMirror componentMirror = getAnnotationMirror(subject, componentKind.annotationType()).get(); if (componentKind.isTopLevel()) { validateComponentDependencies(builder, getComponentDependencies(componentMirror)); } builder.addSubreport( moduleValidator.validateReferencedModules(subject, componentMirror, componentKind.moduleKinds())); // Make sure we validate any subcomponents we're referencing, unless we know we validated // them already in this pass. // TODO(sameb): If subcomponents refer to each other and both aren't in // 'validatedSubcomponents' (e.g, both aren't compiled in this pass), // then this can loop forever. ImmutableSet.Builder<Element> allSubcomponents = ImmutableSet.<Element>builder() .addAll(referencedSubcomponents.keySet()); for (Element subcomponent : Sets.difference(referencedSubcomponents.keySet(), validatedSubcomponents)) { ComponentValidationReport subreport = subcomponentValidator.validate(MoreElements.asType(subcomponent), validatedSubcomponents, validatedSubcomponentBuilders); builder.addItems(subreport.report().items()); allSubcomponents.addAll(subreport.referencedSubcomponents()); } return new AutoValue_ComponentValidator_ComponentValidationReport(allSubcomponents.build(), builder.build()); }
From source file:org.voltcore.agreement.MeshArbiter.java
/** * Process the fault message, and if necessary start arbitration. * @param hsIds pre-failure mesh ids/*from www . j a v a2s .c om*/ * @param fm a {@link FaultMessage} * @return a map where the keys are the sites we need to disconnect from, and * the values the last know safe zookeeper transaction ids for the sites * we need to disconnect from. A map with entries indicate that an * arbitration resolutions has been reached, while a map without entries * indicate either a stale message, or that an agreement has not been * reached */ public Map<Long, Long> reconfigureOnFault(Set<Long> hsIds, FaultMessage fm) { boolean proceed = false; do { Discard ignoreIt = mayIgnore(hsIds, fm); if (Discard.DoNot == ignoreIt) { m_inTrouble.put(fm.failedSite, fm.witnessed || fm.decided); m_recoveryLog.info("Agreement, Processing " + fm); proceed = true; } else { ignoreIt.log(fm); } fm = (FaultMessage) m_mailbox.recv(justFailures); } while (fm != null); if (!proceed) { return ImmutableMap.of(); } m_inTroubleCount = m_inTrouble.size(); // we are here if failed site was not previously recorded // or it was previously recorded but it became witnessed from unwitnessed m_seeker.startSeekingFor(Sets.difference(hsIds, m_failedSites), m_inTrouble); discoverGlobalFaultData_send(hsIds); if (discoverGlobalFaultData_rcv(hsIds)) { Map<Long, Long> lastTxnIdByFailedSite = extractGlobalFaultData(hsIds); if (lastTxnIdByFailedSite.isEmpty()) { return ImmutableMap.of(); } Set<Long> witnessed = Maps.filterValues(m_inTrouble, equalTo(Boolean.TRUE)).keySet(); Set<Long> notClosed = Sets.difference(witnessed, lastTxnIdByFailedSite.keySet()); if (!notClosed.isEmpty()) { m_recoveryLog.warn("Agreement, witnessed but not decided: [" + CoreUtils.hsIdCollectionToString(notClosed) + "] seeker: " + m_seeker); } notifyOnKill(hsIds, lastTxnIdByFailedSite); m_failedSites.addAll(lastTxnIdByFailedSite.keySet()); m_failedSitesCount = m_failedSites.size(); m_recoveryLog .info("Agreement, Adding " + CoreUtils.hsIdCollectionToString(lastTxnIdByFailedSite.keySet()) + " to failed sites history"); clearInTrouble(lastTxnIdByFailedSite.keySet()); m_seeker.clear(); return lastTxnIdByFailedSite; } else { return ImmutableMap.of(); } }
From source file:org.onosproject.store.primitives.resources.impl.AtomixLeaderElectorState.java
/** * Applies an {@link AtomixLeaderElectorCommands.Evict} commit. * @param commit evict commit//from www . jav a2s .co m */ public void evict(Commit<? extends Evict> commit) { try { List<Change<Leadership>> changes = Lists.newArrayList(); NodeId nodeId = commit.operation().nodeId(); Set<String> topics = Maps.filterValues(elections, e -> e.candidates().contains(nodeId)).keySet(); topics.forEach(topic -> { Leadership oldLeadership = leadership(topic); elections.compute(topic, (k, v) -> v.evict(nodeId, termCounter(topic)::incrementAndGet)); Leadership newLeadership = leadership(topic); if (!Objects.equal(oldLeadership, newLeadership)) { changes.add(new Change<>(oldLeadership, newLeadership)); } }); notifyLeadershipChanges(changes); } catch (Exception e) { log.error("State machine operation failed", e); throw Throwables.propagate(e); } finally { commit.close(); } }