List of usage examples for com.google.common.base Predicates not
public static <T> Predicate<T> not(Predicate<T> predicate)
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;// w w w . j ava 2 s . c om 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:com.facebook.buck.cxx.Omnibus.java
protected static OmnibusSpec buildSpec(final CxxPlatform cxxPlatform, final Iterable<? extends NativeLinkTarget> includedRoots, final Iterable<? extends NativeLinkable> excludedRoots) { // A map of targets to native linkable objects. We maintain this, so that we index our // bookkeeping around `BuildTarget` and avoid having to guarantee that all other types are // hashable./*w ww . ja v a 2 s . c o m*/ final Map<BuildTarget, NativeLinkable> nativeLinkables = new LinkedHashMap<>(); // The nodes which should *not* be included in the omnibus link. final Set<BuildTarget> excluded = new LinkedHashSet<>(); // Process all the roots included in the omnibus link. final Map<BuildTarget, NativeLinkTarget> roots = new LinkedHashMap<>(); Map<BuildTarget, NativeLinkable> rootDeps = new LinkedHashMap<>(); for (NativeLinkTarget root : includedRoots) { roots.put(root.getBuildTarget(), root); for (NativeLinkable dep : NativeLinkables.getNativeLinkables(cxxPlatform, root.getNativeLinkTargetDeps(cxxPlatform), Linker.LinkableDepType.SHARED).values()) { Linker.LinkableDepType linkStyle = NativeLinkables .getLinkStyle(dep.getPreferredLinkage(cxxPlatform), Linker.LinkableDepType.SHARED); Preconditions.checkState(linkStyle != Linker.LinkableDepType.STATIC); // We only consider deps which aren't *only* statically linked. if (linkStyle == Linker.LinkableDepType.SHARED) { rootDeps.put(dep.getBuildTarget(), dep); nativeLinkables.put(dep.getBuildTarget(), dep); } } } // Process all roots excluded from the omnibus link, and add them to our running list of // excluded nodes. for (NativeLinkable root : excludedRoots) { nativeLinkables.put(root.getBuildTarget(), root); excluded.add(root.getBuildTarget()); } // Perform the first walk starting from the native linkable nodes immediately reachable via the // included roots. We'll accomplish two things here: // 1. Build up the map of node names to their native linkable objects. // 2. Perform an initial discovery of dependency nodes to exclude from the omnibus link. new AbstractBreadthFirstTraversal<BuildTarget>(rootDeps.keySet()) { @Override public ImmutableSet<BuildTarget> visit(BuildTarget target) { NativeLinkable nativeLinkable = Preconditions.checkNotNull(nativeLinkables.get(target)); ImmutableMap<BuildTarget, NativeLinkable> deps = Maps .uniqueIndex(getDeps(nativeLinkable, cxxPlatform), HasBuildTarget::getBuildTarget); nativeLinkables.putAll(deps); if (nativeLinkable.getPreferredLinkage(cxxPlatform) == NativeLinkable.Linkage.SHARED) { excluded.add(target); } return deps.keySet(); } }.start(); // Do another walk to flesh out the transitively excluded nodes. new AbstractBreadthFirstTraversal<BuildTarget>(excluded) { @Override public Iterable<BuildTarget> visit(BuildTarget target) { NativeLinkable nativeLinkable = Preconditions.checkNotNull(nativeLinkables.get(target)); ImmutableMap<BuildTarget, NativeLinkable> deps = Maps .uniqueIndex(getDeps(nativeLinkable, cxxPlatform), HasBuildTarget::getBuildTarget); nativeLinkables.putAll(deps); excluded.add(target); return deps.keySet(); } }.start(); // And then we can do one last walk to create the actual graph which contain only root and body // nodes to include in the omnibus link. final MutableDirectedGraph<BuildTarget> graphBuilder = new MutableDirectedGraph<>(); final Set<BuildTarget> deps = new LinkedHashSet<>(); new AbstractBreadthFirstTraversal<BuildTarget>(Sets.difference(rootDeps.keySet(), excluded)) { @Override public Iterable<BuildTarget> visit(BuildTarget target) { graphBuilder.addNode(target); Set<BuildTarget> keep = new LinkedHashSet<>(); for (BuildTarget dep : Iterables.transform(getDeps(target, roots, nativeLinkables, cxxPlatform), HasBuildTarget::getBuildTarget)) { if (excluded.contains(dep)) { deps.add(dep); } else { keep.add(dep); graphBuilder.addEdge(target, dep); } } return keep; } }.start(); DirectedAcyclicGraph<BuildTarget> graph = new DirectedAcyclicGraph<>(graphBuilder); // Since we add all undefined root symbols into the omnibus library, we also need to include // any excluded root deps as deps of omnibus, as they may fulfill these undefined symbols. // Also add any excluded nodes that are also root dependencies. deps.addAll(Sets.intersection(rootDeps.keySet(), excluded)); return ImmutableOmnibusSpec.builder().graph(graph).roots(roots) .body(FluentIterable.from(graph.getNodes()).filter(Predicates.not(roots.keySet()::contains)) .toMap(Functions.forMap(nativeLinkables))) .deps(Maps.asMap(deps, Functions.forMap(nativeLinkables))) .excluded(Maps.asMap(excluded, Functions.forMap(nativeLinkables))).build(); }
From source file:clocker.docker.location.DockerContainerLocation.java
@Override public int execCommands(Map<String, ?> props, String summaryForLogging, List<String> commands, Map<String, ?> env) { Iterable<String> filtered = Iterables.filter(commands, DockerCallbacks.FILTER); for (String commandString : filtered) { parseDockerCallback(commandString); }//from w ww. j a v a 2 s .c o m boolean entitySsh = Boolean.TRUE.equals(entity.config().get(DockerContainer.DOCKER_USE_SSH)); boolean dockerSsh = Boolean.TRUE.equals(getOwner().config().get(DockerContainer.DOCKER_USE_SSH)); if (entitySsh && dockerSsh) { return super.execCommands(props, summaryForLogging, commands, env); } else { Map<String, ?> nonPortProps = Maps.filterKeys(props, Predicates.not(Predicates.containsPattern("port"))); return hostMachine.execCommands(nonPortProps, summaryForLogging, getDockerExecCommand(commands, env)); } }
From source file:org.apache.brooklyn.entity.brooklynnode.effector.BrooklynClusterUpgradeEffectorBody.java
protected Collection<Entity> createNodes(int nodeCnt) { DynamicCluster cluster = (DynamicCluster) entity(); //1. Create the nodes Collection<Entity> newNodes = cluster.resizeByDelta(nodeCnt); //2. Wait for them to be RUNNING (or at least STARTING to have completed) // (should already be the case, because above is synchronous and, we think, it will fail if start does not succeed) DynamicTasks.queue(EntityTasks.requiringAttributeEventually(newNodes, Attributes.SERVICE_STATE_ACTUAL, Predicates.not(Predicates.equalTo(Lifecycle.STARTING)), Duration.minutes(30))); //3. Set HOT_STANDBY in case it is not enabled on the command line ... // TODO support via EntitySpec DynamicTasks.queue(Effectors.invocation(BrooklynNode.SET_HIGH_AVAILABILITY_MODE, MutableMap.of(SetHighAvailabilityModeEffector.MODE, HighAvailabilityMode.HOT_STANDBY), newNodes)) .asTask().getUnchecked();/*from ww w . j a v a 2 s. c o m*/ //... and wait until all of the nodes change state // TODO fail quicker if state changes to FAILED DynamicTasks.queue(EntityTasks.requiringAttributeEventually(newNodes, BrooklynNode.MANAGEMENT_NODE_STATE, Predicates.equalTo(ManagementNodeState.HOT_STANDBY), Duration.FIVE_MINUTES)); // TODO also check that the nodes created all report the original master, in case persistence changes it //5. Just in case check if all of the nodes are SERVICE_UP (which would rule out ON_FIRE as well) Collection<Entity> failedNodes = Collections2.filter(newNodes, EntityPredicates.attributeEqualTo(BrooklynNode.SERVICE_UP, Boolean.FALSE)); if (!failedNodes.isEmpty()) { throw new IllegalStateException("Nodes " + failedNodes + " are not " + BrooklynNode.SERVICE_UP + " though successfully in " + ManagementNodeState.HOT_STANDBY); } return newNodes; }
From source file:org.eclipse.sirius.diagram.sequence.business.internal.operation.VerticalSpaceExpansion.java
private void categorizeMessages(Set<Message> messages) { messagesToResize = Sets.newHashSet(); messagesToShift = Sets.newHashSet(); for (Message ise : Iterables.filter(messages, Predicates.not(Predicates.in(eventsToIgnore)))) { if (containsInsertionPoint(ise)) { messagesToResize.add(ise);/*from ww w . jav a2 s. c o m*/ } else if (isStrictlyBelowInsertionPoint(ise) || isConnectedToAMovedExecutionByASingleEnd(ise)) { messagesToShift.add(ise); } } }
From source file:com.twitter.aurora.scheduler.periodic.Preempter.java
/** * Creates a static filter that will identify tasks that may preempt the provided task. * A task may preempt another task if the following conditions hold true: * - The resources reserved for {@code preemptableTask} are sufficient to satisfy the task. * - The tasks are owned by the same user and the priority of {@code preemptableTask} is lower * OR {@code preemptableTask} is non-production and the compared task is production. * * @param preemptableTask Task to possibly preempt. * @return A filter that will compare the priorities and resources required by other tasks * with {@code preemptableTask}./*w ww . j ava2 s .c o m*/ */ private Predicate<AssignedTask> preemptionFilter(AssignedTask preemptableTask) { Predicate<AssignedTask> preemptableIsProduction = preemptableTask.getTask().isProduction() ? Predicates.<AssignedTask>alwaysTrue() : Predicates.<AssignedTask>alwaysFalse(); Predicate<AssignedTask> priorityFilter = greaterPriorityFilter(GET_PRIORITY.apply(preemptableTask)); return Predicates.or(Predicates.and(Predicates.not(preemptableIsProduction), IS_PRODUCTION), Predicates.and(isOwnedBy(getRole(preemptableTask)), priorityFilter)); }
From source file:clocker.docker.location.strategy.affinity.AffinityRules.java
private Predicate<Entity> predicate(String rule) { Preconditions.checkNotNull(rule, "rule"); Queue<String> tokens = Queues .newArrayDeque(Splitter.on(CharMatcher.WHITESPACE).omitEmptyStrings().splitToList(rule)); boolean same = true; Predicate<Entity> predicate = Predicates.alwaysTrue(); // Check first token for special values String first = tokens.peek(); if (first.equalsIgnoreCase(NOT)) { same = false;/*ww w. j a v a2s .co m*/ tokens.remove(); } // Check verb String verb = tokens.peek(); if (verb == null) { throw new IllegalStateException("Affinity rule verb not specified: " + rule); } else { if (Iterables.contains(VERBS, verb.toUpperCase(Locale.ENGLISH))) { tokens.remove(); } else { throw new IllegalStateException("Affinity rule parser found unexpected verb token: " + verb); } } // Check paramater and instantiate if required final String parameter = tokens.peek(); if (parameter == null) { if (verb.equalsIgnoreCase(EMPTY)) { allowEmpty = same; tokens.remove(); if (tokens.isEmpty()) { return predicate; } else { throw new IllegalStateException("Affinity rule has extra tokens: " + rule); } } else if (verb.equalsIgnoreCase(TYPE)) { predicate = new Predicate<Entity>() { @Override public boolean apply(@Nullable Entity input) { return input.getEntityType().getName().equalsIgnoreCase(entity.getEntityType().getName()) || input.getEntityType().getSimpleName() .equalsIgnoreCase(entity.getEntityType().getSimpleName()); } }; } else if (verb.equalsIgnoreCase(ID)) { predicate = EntityPredicates.idEqualTo(entity.getId()); } else if (verb.equalsIgnoreCase(APPLICATION)) { predicate = EntityPredicates.applicationIdEqualTo(entity.getApplicationId()); } else { throw new IllegalStateException("Affinity rule parameter not specified: " + rule); } } else { tokens.remove(); if (verb.equalsIgnoreCase(TYPE)) { predicate = new Predicate<Entity>() { @Override public boolean apply(@Nullable Entity input) { return input.getEntityType().getName().equalsIgnoreCase(parameter) || input.getEntityType().getSimpleName().equalsIgnoreCase(parameter); } }; } else if (verb.equalsIgnoreCase(NAME)) { predicate = new Predicate<Entity>() { @Override public boolean apply(@Nullable Entity input) { return input.getDisplayName().toLowerCase(Locale.ENGLISH) .contains(parameter.toLowerCase(Locale.ENGLISH)); } }; } else if (verb.equalsIgnoreCase(ID)) { predicate = EntityPredicates.idEqualTo(parameter); } else if (verb.equalsIgnoreCase(APPLICATION)) { predicate = EntityPredicates.applicationIdEqualTo(parameter); } else if (verb.equalsIgnoreCase(PREDICATE)) { try { Class<?> clazz = Class.forName(parameter); if (Reflections.hasNoArgConstructor(clazz)) { predicate = (Predicate<Entity>) Reflections.invokeConstructorWithArgs(clazz); } else { throw new IllegalStateException("Could not instantiate predicate: " + parameter); } } catch (ClassNotFoundException e) { throw new IllegalStateException("Could not find predicate: " + parameter); } } } // Check for left-over tokens if (tokens.peek() != null) { throw new IllegalStateException("Affinity rule has extra tokens: " + rule); } // Create predicate and return if (same) { return predicate; } else { return Predicates.not(predicate); } }
From source file:com.google.devtools.build.lib.rules.objc.CrosstoolCompilationSupport.java
@Override CompilationSupport registerLinkActions(ObjcProvider objcProvider, J2ObjcMappingFileProvider j2ObjcMappingFileProvider, J2ObjcEntryClassProvider j2ObjcEntryClassProvider, ExtraLinkArgs extraLinkArgs, Iterable<Artifact> extraLinkInputs, DsymOutputType dsymOutputType) throws InterruptedException { Iterable<Artifact> prunedJ2ObjcArchives = computeAndStripPrunedJ2ObjcArchives(j2ObjcEntryClassProvider, j2ObjcMappingFileProvider, objcProvider); ImmutableList<Artifact> bazelBuiltLibraries = Iterables.isEmpty(prunedJ2ObjcArchives) ? objcProvider.getObjcLibraries() : substituteJ2ObjcPrunedLibraries(objcProvider); Artifact inputFileList = intermediateArtifacts.linkerObjList(); ImmutableSet<Artifact> forceLinkArtifacts = getForceLoadArtifacts(objcProvider); Iterable<Artifact> objFiles = Iterables.concat(bazelBuiltLibraries, objcProvider.get(IMPORTED_LIBRARY), objcProvider.getCcLibraries()); // Clang loads archives specified in filelists and also specified as -force_load twice, // resulting in duplicate symbol errors unless they are deduped. objFiles = Iterables.filter(objFiles, Predicates.not(Predicates.in(forceLinkArtifacts))); registerObjFilelistAction(objFiles, inputFileList); LinkTargetType linkType = (objcProvider.is(Flag.USES_CPP)) ? LinkTargetType.OBJCPP_EXECUTABLE : LinkTargetType.OBJC_EXECUTABLE; ObjcVariablesExtension extension = new ObjcVariablesExtension.Builder().setRuleContext(ruleContext) .setObjcProvider(objcProvider).setConfiguration(ruleContext.getConfiguration()) .setIntermediateArtifacts(intermediateArtifacts).setFrameworkNames(frameworkNames(objcProvider)) .setLibraryNames(libraryNames(objcProvider)) .setForceLoadArtifacts(getForceLoadArtifacts(objcProvider)) .setAttributeLinkopts(attributes.linkopts()) .addVariableCategory(VariableCategory.EXECUTABLE_LINKING_VARIABLES).build(); Artifact binaryToLink = getBinaryToLink(); CppLinkAction executableLinkAction = new CppLinkActionBuilder(ruleContext, binaryToLink) .setMnemonic("ObjcLink").addActionInputs(bazelBuiltLibraries) .addActionInputs(objcProvider.getCcLibraries()) .addTransitiveActionInputs(objcProvider.get(IMPORTED_LIBRARY)) .addTransitiveActionInputs(objcProvider.get(STATIC_FRAMEWORK_FILE)) .addTransitiveActionInputs(objcProvider.get(DYNAMIC_FRAMEWORK_FILE)) .setCrosstoolInputs(CppHelper.getToolchain(ruleContext).getLink()) .addActionInputs(prunedJ2ObjcArchives).addActionInput(inputFileList).setLinkType(linkType) .setLinkStaticness(LinkStaticness.FULLY_STATIC).addVariablesExtension(extension) .setFeatureConfiguration(getFeatureConfiguration(ruleContext)).build(); ruleContext.registerAction(executableLinkAction); return this; }
From source file:org.cloudsmith.geppetto.graph.catalog.CatalogGraphProducer.java
/** * Produces the graph data structure (RootGraph, Vertexes, Edges). * /*from w w w .ja v a 2 s . co m*/ */ private RootGraph produceRootGraph(ICancel cancel, Catalog catalog, String catalogName, final IPath root) { RootGraph g = new RootGraph(catalogName, "RootGraph", "root"); // Iterate the catalog // What to do with these? Are they of any value? // catalog.getClasses(); // list of classnames // catalog.getTags(); // don't know if these have any value... Map<String, Vertex> vertexMap = Maps.newHashMap(); Map<CatalogResource, Vertex> resourceVertexMap = Maps.newHashMap(); for (CatalogResource r : catalog.getResources()) { StringBuilder builder = new StringBuilder(); builder.append(r.getType().toLowerCase()); builder.append("["); builder.append(r.getTitle().toLowerCase()); builder.append("]"); Vertex v = createVertexFor(r, root); g.addVertex(v); vertexMap.put(builder.toString(), v); resourceVertexMap.put(r, v); } for (CatalogResource r : catalog.getResources()) { final Vertex source = resourceVertexMap.get(r); for (CatalogResourceParameter p : Iterables.filter(getParameterIterable(r), Predicates.not(regularParameterPredicate))) { String aName = p.getName(); String style = null; if ("subscribe".equals(aName)) style = CatalogGraphStyles.STYLE_SubscribeEdge; else if ("before".equals(aName)) style = CatalogGraphStyles.STYLE_BeforeEdge; else if ("notify".equals(aName)) style = CatalogGraphStyles.STYLE_NotifyEdge; else style = CatalogGraphStyles.STYLE_RequireEdge; for (String ref : p.getValue()) { Vertex target = vertexMap.get(ref.toLowerCase()); if (target == null) { target = createVertexForMissingResource(ref); vertexMap.put(ref.toLowerCase(), target); // keep it if there are more references g.addVertex(target); } Edge edge = new Edge(aName, style, source, target); g.addEdge(edge); } } } for (CatalogEdge e : catalog.getEdges()) { Vertex source = vertexMap.get(e.getSource().toLowerCase()); Vertex target = vertexMap.get(e.getTarget().toLowerCase()); Edge edge = new Edge("", STYLE_ResourceEdge, source, target); g.addEdge(edge); } return g; }
From source file:uk.co.unclealex.executable.generator.scan.ExecutableAnnotationInformationFinderImpl.java
/** * Check to see if the command class is instantiable and return any declared * Guice Modules.// w ww .j av a2 s .com * * @param clazz * The command class. * @param executable * The {@link Executable} annotation that has been found. * @return The array of Guice modules declared by the annotation. * @throws CommandNotInstantiableExecutableScanException * Thrown if the command class cannot be instantiatied. * @throws NonGuiceModulesReferencedException Thrown if non-Guice {@link Module}s are found. */ @SuppressWarnings("unchecked") protected Class<? extends Module>[] extractGuiceModules(Class<?> clazz, Method annotatedMethod, Executable executable) throws CommandNotInstantiableExecutableScanException, NonGuiceModulesReferencedException { Class<?>[] guiceModules = executable.value(); List<Class<?>> nonGuiceModules = Lists.newArrayList( Iterables.filter(Arrays.asList(guiceModules), Predicates.not(new IsGuiceModulePredicate()))); if (!nonGuiceModules.isEmpty()) { throw new NonGuiceModulesReferencedException(clazz, annotatedMethod, nonGuiceModules); } Predicate<Constructor<?>> isInstantiablePredicate = new IsDefaultConstructor(); if (guiceModules.length != 0) { isInstantiablePredicate = Predicates.or(isInstantiablePredicate, IsConstructorAnnotated.with(javax.inject.Inject.class)); isInstantiablePredicate = Predicates.or(isInstantiablePredicate, IsConstructorAnnotated.with(com.google.inject.Inject.class)); } if (!Iterables.any(Arrays.asList(clazz.getConstructors()), isInstantiablePredicate)) { throw new CommandNotInstantiableExecutableScanException(clazz); } return (Class<? extends Module>[]) guiceModules; }