List of usage examples for com.google.common.base Predicates and
public static <T> Predicate<T> and(Predicate<? super T> first, Predicate<? super T> second)
From source file:com.ardor3d.example.canvas.RotatingCubeGame.java
private void registerInputTriggers() { logicalLayer.registerTrigger(new InputTrigger(new KeyHeldCondition(Key.W), new TriggerAction() { public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) { moveForward(source, tpf);//from w w w. j av a 2 s.c o m } })); logicalLayer.registerTrigger(new InputTrigger(new KeyHeldCondition(Key.S), new TriggerAction() { public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) { moveBack(source, tpf); } })); logicalLayer.registerTrigger(new InputTrigger(new KeyHeldCondition(Key.A), new TriggerAction() { public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) { turnLeft(source, tpf); } })); logicalLayer.registerTrigger(new InputTrigger(new KeyHeldCondition(Key.D), new TriggerAction() { public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) { turnRight(source, tpf); } })); logicalLayer.registerTrigger(new InputTrigger(new KeyHeldCondition(Key.Q), new TriggerAction() { public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) { moveLeft(source, tpf); } })); logicalLayer.registerTrigger(new InputTrigger(new KeyHeldCondition(Key.E), new TriggerAction() { public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) { moveRight(source, tpf); } })); logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.ESCAPE), new TriggerAction() { public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) { exit.exit(); } })); logicalLayer .registerTrigger(new InputTrigger(new KeyPressedCondition(toggleRotationKey), new TriggerAction() { public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) { toggleRotation(); } })); logicalLayer.registerTrigger(new InputTrigger(new KeyReleasedCondition(Key.U), new TriggerAction() { public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) { toggleRotation(); } })); logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.ZERO), new TriggerAction() { public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) { resetCamera(source); } })); logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.NINE), new TriggerAction() { public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) { lookAtZero(source); } })); final Predicate<TwoInputStates> mouseMovedAndOneButtonPressed = Predicates.and( TriggerConditions.mouseMoved(), Predicates.or(TriggerConditions.leftButtonDown(), TriggerConditions.rightButtonDown())); logicalLayer.registerTrigger(new InputTrigger(mouseMovedAndOneButtonPressed, new TriggerAction() { public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) { final MouseState mouseState = inputStates.getCurrent().getMouseState(); turn(source, mouseState.getDx() * tpf * -MOUSE_TURN_SPEED); rotateUpDown(source, mouseState.getDy() * tpf * -MOUSE_TURN_SPEED); } })); logicalLayer.registerTrigger(new InputTrigger( new MouseButtonCondition(ButtonState.DOWN, ButtonState.DOWN, ButtonState.UNDEFINED), new TriggerAction() { public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) { moveForward(source, tpf); } })); logicalLayer.registerTrigger(new InputTrigger(new AnyKeyCondition(), new TriggerAction() { public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) { final InputState current = inputStates.getCurrent(); System.out .println("Key character pressed: " + current.getKeyboardState().getKeyEvent().getKeyChar()); } })); }
From source file:org.apache.brooklyn.entity.nosql.riak.RiakClusterImpl.java
protected void onServerPoolMemberChanged(final Entity member) { synchronized (mutex) { log.trace("For {}, considering membership of {} which is in locations {}", new Object[] { this, member, member.getLocations() }); Map<Entity, String> nodes = getAttribute(RIAK_CLUSTER_NODES); if (belongsInServerPool(member)) { // TODO can we discover the nodes by asking the riak cluster, rather than assuming what we add will be in there? // TODO and can we do join as part of node starting? if (nodes == null) { nodes = Maps.newLinkedHashMap(); }/*from w ww . jav a 2 s.com*/ String riakName = getRiakName(member); Preconditions.checkNotNull(riakName); // flag a first node to be the first node in the riak cluster. Boolean firstNode = getAttribute(IS_FIRST_NODE_SET); if (!Boolean.TRUE.equals(firstNode)) { sensors().set(IS_FIRST_NODE_SET, Boolean.TRUE); nodes.put(member, riakName); sensors().set(RIAK_CLUSTER_NODES, nodes); ((EntityInternal) member).sensors().set(RiakNode.RIAK_NODE_HAS_JOINED_CLUSTER, Boolean.TRUE); log.info("Added initial Riak node {}: {}; {} to new cluster", new Object[] { this, member, getRiakName(member) }); } else { // TODO: be wary of erroneous nodes but are still flagged 'in cluster' // add the new node to be part of the riak cluster. Optional<Entity> anyNodeInCluster = Iterables.tryFind(nodes.keySet(), Predicates.and( Predicates.instanceOf(RiakNode.class), EntityPredicates.attributeEqualTo(RiakNode.RIAK_NODE_HAS_JOINED_CLUSTER, true))); if (anyNodeInCluster.isPresent()) { if (!nodes.containsKey(member) && member.getAttribute(RiakNode.RIAK_NODE_HAS_JOINED_CLUSTER) == null) { String anyNodeName = anyNodeInCluster.get().getAttribute(RiakNode.RIAK_NODE_NAME); Entities.invokeEffectorWithArgs(this, member, RiakNode.JOIN_RIAK_CLUSTER, anyNodeName) .blockUntilEnded(); nodes.put(member, riakName); sensors().set(RIAK_CLUSTER_NODES, nodes); log.info("Added Riak node {}: {}; {} to cluster", new Object[] { this, member, getRiakName(member) }); } } else { log.error("isFirstNodeSet, but no cluster members found to add {}", member.getId()); } } } else { if (nodes != null && nodes.containsKey(member)) { DependentConfiguration.attributeWhenReady(member, RiakNode.RIAK_NODE_HAS_JOINED_CLUSTER, Predicates.equalTo(false)).blockUntilEnded(Duration.TWO_MINUTES); @SuppressWarnings("unchecked") Optional<Entity> anyNodeInCluster = Iterables.tryFind(nodes.keySet(), Predicates.and(Predicates.instanceOf(RiakNode.class), EntityPredicates.attributeEqualTo(RiakNode.RIAK_NODE_HAS_JOINED_CLUSTER, true), Predicates.not(Predicates.equalTo(member)))); if (anyNodeInCluster.isPresent()) { Entities.invokeEffectorWithArgs(this, anyNodeInCluster.get(), RiakNode.REMOVE_FROM_CLUSTER, getRiakName(member)).blockUntilEnded(); } nodes.remove(member); sensors().set(RIAK_CLUSTER_NODES, nodes); log.info("Removed Riak node {}: {}; {} from cluster", new Object[] { this, member, getRiakName(member) }); } } ServiceNotUpLogic.updateNotUpIndicatorRequiringNonEmptyMap(this, RIAK_CLUSTER_NODES); calculateClusterAddresses(); } }
From source file:org.apache.beam.sdk.io.LocalFileSystem.java
private MatchResult matchOne(String spec) throws IOException { File file = Paths.get(spec).toFile(); if (file.exists()) { return MatchResult.create(Status.OK, ImmutableList.of(toMetadata(file))); }//from w w w. ja va 2 s .c om File parent = file.getAbsoluteFile().getParentFile(); if (!parent.exists()) { return MatchResult.create(Status.NOT_FOUND, Collections.<Metadata>emptyList()); } // Method getAbsolutePath() on Windows platform may return something like // "c:\temp\file.txt". FileSystem.getPathMatcher() call below will treat // '\' (backslash) as an escape character, instead of a directory // separator. Replacing backslash with double-backslash solves the problem. // We perform the replacement on all platforms, even those that allow // backslash as a part of the filename, because Globs.toRegexPattern will // eat one backslash. String pathToMatch = file.getAbsolutePath().replaceAll(Matcher.quoteReplacement("\\"), Matcher.quoteReplacement("\\\\")); final PathMatcher matcher = java.nio.file.FileSystems.getDefault().getPathMatcher("glob:" + pathToMatch); // TODO: Avoid iterating all files: https://issues.apache.org/jira/browse/BEAM-1309 Iterable<File> files = com.google.common.io.Files.fileTreeTraverser().preOrderTraversal(parent); Iterable<File> matchedFiles = Iterables.filter(files, Predicates.and(com.google.common.io.Files.isFile(), new Predicate<File>() { @Override public boolean apply(File input) { return matcher.matches(input.toPath()); } })); List<Metadata> result = Lists.newLinkedList(); for (File match : matchedFiles) { result.add(toMetadata(match)); } if (result.isEmpty()) { // TODO: consider to return Status.OK for globs. return MatchResult.create(Status.NOT_FOUND, new FileNotFoundException(String.format("No files found for spec: %s.", spec))); } else { return MatchResult.create(Status.OK, result); } }
From source file:com.eucalyptus.compute.common.internal.vm.VmInstances.java
/** * List instances in any state that match the given parameters. *//*from w w w. j av a 2 s . c om*/ public static List<VmInstance> list(@Nullable final OwnerFullName ownerFullName, final Criterion criterion, final Map<String, String> aliases, @Nullable final Predicate<? super VmInstance> predicate, final boolean outerJoins) { return list(new Supplier<List<VmInstance>>() { @Override public List<VmInstance> get() { return Entities.query(VmInstance.named(ownerFullName, null), false, criterion, aliases, outerJoins); } }, Predicates.and(RestrictedTypes.filterByOwner(ownerFullName), checkPredicate(predicate))); }
From source file:forge.quest.BoosterUtils.java
private static void populateBalancedFilters(final List<Predicate<CardRules>> colorFilters, final List<Byte> preferredColors, final List<PaperCard> cardPool, final boolean includeArtifacts) { final List<Byte> otherColors = new ArrayList<>(possibleColors); otherColors.removeAll(preferredColors); int colorBias = FModel.getQuestPreferences().getPrefInt(QPref.STARTING_POOL_COLOR_BIAS); double preferredBias = 0; if (preferredColors.isEmpty()) { colorBias = 0;/*from ww w . j a va2 s.c o m*/ } else { preferredBias = (double) colorBias / preferredColors.size(); } int usedMulticolor = 0, usedPhyrexian = 0; for (int i = 0; i < MAX_BIAS; i++) { if (i < colorBias) { int index = (int) ((double) i / preferredBias); for (@SuppressWarnings("unused") Byte ignored : otherColors) { //Add artifacts here if there's no colorless selection if (i % 8 == 0 && !preferredColors.contains(MagicColor.COLORLESS) && includeArtifacts) { colorFilters.add(CardRulesPredicates.Presets.IS_ARTIFACT); } else if (i % 5 == 0) { //If colorless is the only color selected, add a small chance to get Phyrexian mana cost cards. if (preferredColors.contains(MagicColor.COLORLESS) && preferredColors.size() == 1) { Predicate<CardRules> predicateRules = CardRulesPredicates.cost(StringOp.CONTAINS_IC, "p/"); Predicate<PaperCard> predicateCard = Predicates.compose(predicateRules, PaperCard.FN_GET_RULES); int size = Iterables.size(Iterables.filter(cardPool, predicateCard)); int totalSize = cardPool.size(); double phyrexianAmount = (double) size / totalSize; phyrexianAmount *= 125; if (usedPhyrexian < Math.min(1, phyrexianAmount)) { colorFilters.add(predicateRules); usedPhyrexian++; continue; } } //Try to get multicolored cards that fit into the preferred colors. Predicate<CardRules> predicateRules = Predicates.and( CardRulesPredicates.isColor(preferredColors.get(index)), CardRulesPredicates.Presets.IS_MULTICOLOR); Predicate<PaperCard> predicateCard = Predicates.compose(predicateRules, PaperCard.FN_GET_RULES); //Adjust for the number of multicolored possibilities. This prevents flooding of non-selected //colors if multicolored cards aren't in the selected sets. The more multi-colored cards in the //sets, the more that will be selected. if (usedMulticolor / 8 < Iterables.size(Iterables.filter(cardPool, predicateCard))) { colorFilters.add(predicateRules); usedMulticolor++; } else { //Exceeded multicolor-specific ratio, so here we add a more generic filter. colorFilters.add(CardRulesPredicates.isColor(preferredColors.get(index))); } } else { colorFilters.add(CardRulesPredicates.isMonoColor(preferredColors.get(index))); } } } else { for (Byte color : otherColors) { if (i % 6 == 0) { colorFilters.add(Predicates.and(CardRulesPredicates.isColor(color), CardRulesPredicates.Presets.IS_MULTICOLOR)); } else { colorFilters.add(CardRulesPredicates.isMonoColor(color)); } } } } }
From source file:uk.ac.liverpool.narrative.BranchingStoryGenerator.java
private static void usage() { System.out.print("\n\nAlgorithms: \n"); for (Class<? extends BranchingSearch> c : algos) { System.out.print(" " + c.getSimpleName() + "\t\t["); Set<Method> mm = ReflectionUtils.getAllMethods(c, Predicates .and(ReflectionUtils.withModifier(Modifier.PUBLIC), ReflectionUtils.withPrefix("set"))); for (Method m : mm) { System.out.print(m.getName() + " "); }/* w w w. j a va 2 s. com*/ System.out.println("]"); } System.out.print("\n\nFilters: "); for (Class<? extends Filter> c : filters) { System.out.print(" " + c.getSimpleName()); } System.out.println(); }
From source file:org.apache.aurora.scheduler.async.preemptor.PendingTaskProcessor.java
private List<TaskGroupKey> fetchIdlePendingGroups(StoreProvider store) { Multiset<TaskGroupKey> taskGroupCounts = HashMultiset .create(FluentIterable.from(store.getTaskStore().fetchTasks(Query.statusScoped(PENDING))) .filter(Predicates.and(isIdleTask, Predicates.not(hasCachedSlot))) .transform(Functions.compose(ASSIGNED_TO_GROUP_KEY, SCHEDULED_TO_ASSIGNED))); return getPreemptionSequence(taskGroupCounts); }
From source file:org.eclipse.sirius.diagram.business.api.query.DDiagramElementQuery.java
/** * Check if this {@link DDiagramElement} is directly collapsed. * /* www. j ava2s. c om*/ * @return true if the given element is directly collapsed. */ public boolean isCollapsed() { return Iterables.any(element.getGraphicalFilters(), Predicates.and(Predicates.instanceOf(CollapseFilter.class), Predicates.not(Predicates.instanceOf(IndirectlyCollapseFilter.class)))); }
From source file:org.eclipse.sirius.diagram.sequence.ui.business.internal.migration.SequenceDiagramRepresentationsFileMigrationParticipant.java
private void migrateGMFBoundsOfCollapsedBorderedNode(List<Diagram> sequenceDiagrams) { for (Diagram diagram : sequenceDiagrams) { // 1-Add new IndirectlyCollapseFilter migrateChildrenOfCollapsedNode(diagram); // 2-Set width and height of graphical filters of collapsed nodes // (directly or not) with GMF size and set GMF bounds. Iterator<Node> viewIterator = Iterators.filter(Iterators.filter(diagram.eAllContents(), Node.class), Predicates.and(isNode, isCollapsedNode)); while (viewIterator.hasNext()) { Node node = viewIterator.next(); DNode dNode = (DNode) node.getElement(); LayoutConstraint layoutConstraint = node.getLayoutConstraint(); if (layoutConstraint instanceof Bounds) { Bounds bounds = (Bounds) layoutConstraint; // The GMF node size must be stored in collapse filter (to // can // set this size when this node is expanded). for (GraphicalFilter graphicalFilter : dNode.getGraphicalFilters()) { if (graphicalFilter instanceof CollapseFilter) { ((CollapseFilter) graphicalFilter).setWidth(bounds.getWidth()); ((CollapseFilter) graphicalFilter).setHeight(bounds.getHeight()); }//from w w w .j a va 2 s.c o m } // Set new collapsed GMF bounds SequenceCollapseUpdater scbu = new SequenceCollapseUpdater(); scbu.collapseBounds(node, dNode); } } } }
From source file:org.eclipse.sirius.diagram.ui.tools.internal.layout.provider.PinnedElementsLayoutProvider.java
/** * Finds the "real" children of the specified edit part that needs to be * laid out./* w ww .ja va2 s .co m*/ */ private Collection<IGraphicalEditPart> getChildrenOfInterest(final IGraphicalEditPart gep) { final Iterable<IGraphicalEditPart> rawChildren = Iterables.filter(gep.getChildren(), IGraphicalEditPart.class); // Ignore these, which are technically children edit parts but not // "inside" the container. final Predicate<Object> invalidChildKind = Predicates.or( Predicates.instanceOf(IDiagramBorderNodeEditPart.class), Predicates.instanceOf(IDiagramNameEditPart.class)); // These are OK. final Predicate<Object> validChildKind = Predicates.or(Predicates.instanceOf(IDiagramNodeEditPart.class), Predicates.instanceOf(IDiagramContainerEditPart.class), Predicates.instanceOf(IDiagramListEditPart.class)); final Predicate<Object> isProperChild = Predicates.and(validChildKind, Predicates.not(invalidChildKind)); final Collection<IGraphicalEditPart> result = Lists .newArrayList(Iterables.filter(rawChildren, isProperChild)); // Containers have an intermediate level of children edit parts. We // ignore these "wrapper" parts, but must look inside for proper // children of the container. for (IGraphicalEditPart part : Iterables.filter(rawChildren, Predicates.not(isProperChild))) { if (part instanceof DNodeContainerViewNodeContainerCompartmentEditPart || part instanceof DNodeContainerViewNodeContainerCompartment2EditPart) { result.addAll(getChildrenOfInterest(part)); } } return result; }