List of usage examples for com.google.common.base Predicates instanceOf
@GwtIncompatible("Class.isInstance") public static Predicate<Object> instanceOf(Class<?> clazz)
From source file:vazkii.botania.common.entity.EntityMagicMissile.java
public boolean getTarget() { EntityLivingBase target = getTargetEntity(); if (target != null && target.getHealth() > 0 && !target.isDead && worldObj.loadedEntityList.contains(target)) return true; if (target != null) setTarget(null);// w w w . j av a 2 s .c om double range = 12; List entities = worldObj.getEntitiesWithinAABB( Entity.class, new AxisAlignedBB(posX - range, posY - range, posZ - range, posX + range, posY + range, posZ + range), Predicates.instanceOf(isEvil() ? EntityPlayer.class : IMob.class)); while (entities.size() > 0) { Entity e = (Entity) entities.get(worldObj.rand.nextInt(entities.size())); if (!(e instanceof EntityLivingBase) || e.isDead) { // Just in case... entities.remove(e); continue; } target = (EntityLivingBase) e; setTarget(target); break; } return target != null; }
From source file:bear.core.Stage.java
public Address findRemoteEnvironment() { return Iterables.find(addresses, Predicates.instanceOf(SshAddress.class)); }
From source file:org.apache.brooklyn.entity.nosql.etcd.EtcdClusterImpl.java
protected void onServerPoolMemberChanged(Entity member) { synchronized (memberMutex) { log.debug("For {}, considering membership of {} which is in locations {}", new Object[] { this, member, member.getLocations() }); Map<Entity, String> nodes = sensors().get(ETCD_CLUSTER_NODES); if (belongsInServerPool(member)) { if (nodes == null) { nodes = Maps.newLinkedHashMap(); }/*from w ww. j av a 2 s . c o m*/ String name = Preconditions.checkNotNull(getNodeName(member)); // Wait until node has been installed DynamicTasks .queueIfPossible( DependentConfiguration.attributeWhenReady(member, EtcdNode.ETCD_NODE_INSTALLED)) .orSubmitAndBlock(this).andWaitForSuccess(); // Check for first node in the cluster. Duration timeout = config().get(BrooklynConfigKeys.START_TIMEOUT); Entity firstNode = sensors().get(DynamicCluster.FIRST); if (member.equals(firstNode)) { nodes.put(member, name); recalculateClusterAddresses(nodes); log.info("Adding first node {}: {}; {} to cluster", new Object[] { this, member, name }); ((EntityInternal) member).sensors().set(EtcdNode.ETCD_NODE_HAS_JOINED_CLUSTER, Boolean.TRUE); } else { int retry = 3; // TODO use a configurable Repeater instead? while (retry-- > 0 && member.sensors().get(EtcdNode.ETCD_NODE_HAS_JOINED_CLUSTER) == null && !nodes.containsKey(member)) { Optional<Entity> anyNodeInCluster = Iterables.tryFind(nodes.keySet(), Predicates.and(Predicates.instanceOf(EtcdNode.class), EntityPredicates .attributeEqualTo(EtcdNode.ETCD_NODE_HAS_JOINED_CLUSTER, Boolean.TRUE))); if (anyNodeInCluster.isPresent()) { DynamicTasks.queueIfPossible(DependentConfiguration.builder() .attributeWhenReady(anyNodeInCluster.get(), Startable.SERVICE_UP) .timeout(timeout).build()).orSubmitAndBlock(this).andWaitForSuccess(); Entities.invokeEffectorWithArgs(this, anyNodeInCluster.get(), EtcdNode.JOIN_ETCD_CLUSTER, name, getNodeAddress(member)) .blockUntilEnded(timeout); nodes.put(member, name); recalculateClusterAddresses(nodes); log.info("Adding node {}: {}; {} to cluster", new Object[] { this, member, name }); ((EntityInternal) member).sensors().set(EtcdNode.ETCD_NODE_HAS_JOINED_CLUSTER, Boolean.TRUE); } else { log.info("Waiting for first node in cluster {}", this); Time.sleep(Duration.seconds(15)); } } } } else { if (nodes != null && nodes.containsKey(member)) { Optional<Entity> anyNodeInCluster = Iterables.tryFind(nodes.keySet(), Predicates.and( Predicates.instanceOf(EtcdNode.class), EntityPredicates .attributeEqualTo(EtcdNode.ETCD_NODE_HAS_JOINED_CLUSTER, Boolean.TRUE), Predicates.not(Predicates.equalTo(member)))); if (anyNodeInCluster.isPresent()) { Entities.invokeEffectorWithArgs(this, anyNodeInCluster.get(), EtcdNode.LEAVE_ETCD_CLUSTER, getNodeName(member)).blockUntilEnded(); } nodes.remove(member); recalculateClusterAddresses(nodes); log.info("Removing node {}: {}; {} from cluster", new Object[] { this, member, getNodeName(member) }); ((EntityInternal) member).sensors().set(EtcdNode.ETCD_NODE_HAS_JOINED_CLUSTER, Boolean.FALSE); } } ServiceNotUpLogic.updateNotUpIndicatorRequiringNonEmptyMap(this, ETCD_CLUSTER_NODES); log.debug("Done {} checkEntity {}", this, member); } }
From source file:org.obm.sync.calendar.Event.java
public Collection<Attendee> getContactAttendees() { return Collections2.filter(attendees, Predicates.instanceOf(ContactAttendee.class)); }
From source file:org.eclipse.tracecompass.internal.analysis.os.linux.ui.views.cpuusage.CpuUsageView.java
/** * Signal handler for when a cpu is selected * * @param signal/*w w w. j a va 2 s . co m*/ * the cpu being selected * @since 2.0 */ @TmfSignalHandler public void cpuSelect(TmfCpuSelectedSignal signal) { final @Nullable CpuUsageXYViewer xyViewer = fXYViewer; final @Nullable CpuUsageComposite treeViewer = fTreeViewer; if (xyViewer != null && treeViewer != null) { Object data = getData(CPU_USAGE_FOLLOW_CPU); if (data == null) { data = new TreeSet<Integer>(); } if (data instanceof Set<?>) { Set<?> set = (Set<?>) data; int core = signal.getCore(); if (core >= 0) { xyViewer.addCpu(core); treeViewer.addCpu(core); if (Iterables.all(set, Predicates.instanceOf(Integer.class))) { @SuppressWarnings("unchecked") Set<Integer> intSet = (Set<Integer>) set; intSet.add(core); } } else { xyViewer.clearCpu(); treeViewer.clearCpu(); ((Set<?>) data).clear(); } saveData(CPU_USAGE_FOLLOW_CPU, data); } else { Activator.getDefault().logError("The followed cores should have been store in a Set"); //$NON-NLS-1$ } } }
From source file:com.vmware.appfactory.notification.controller.NotificationApiController.java
/** * Get the number of waiting capture tasks. * * @return//from w w w . java 2 s. com */ private int getWaitingCaptureTaskCount() { // Now compute the number of waiting capture tasks. Iterable<TaskState> waitingCaptureStates = Iterables.filter( _conversionsQueue.getTasks(MetaStatusPredicate.WAITING), Predicates.instanceOf(AbstractCaptureState.class)); return Iterables.size(waitingCaptureStates); }
From source file:org.obm.sync.calendar.Event.java
public Collection<Attendee> getResourceAttendees() { return Collections2.filter(attendees, Predicates.instanceOf(ResourceAttendee.class)); }
From source file:clocker.docker.policy.ContainerHeadroomEnricher.java
private void recalculate() { Integer maxContainers = null; List<DockerAwarePlacementStrategy> strategies = entity.config() .get(DockerInfrastructure.PLACEMENT_STRATEGIES); Optional<DockerAwarePlacementStrategy> lookup = Iterables.tryFind(strategies, Predicates.instanceOf(MaxContainersPlacementStrategy.class)); if (lookup.isPresent()) { maxContainers = ((MaxContainersPlacementStrategy) lookup.get()).config() .get(MaxContainersPlacementStrategy.DOCKER_CONTAINER_CLUSTER_MAX_SIZE); }//from w w w. j a va 2 s .com if (maxContainers == null) { maxContainers = entity.config().get(MaxContainersPlacementStrategy.DOCKER_CONTAINER_CLUSTER_MAX_SIZE); } if (maxContainers == null) { maxContainers = MaxContainersPlacementStrategy.DEFAULT_MAX_CONTAINERS; } boolean tooColdEnabled = Boolean.TRUE.equals(config().get(CLUSTER_TOO_COLD_ENABLED)); // Calculate cluster state Integer containers = entity.sensors().get(DockerInfrastructure.DOCKER_CONTAINER_COUNT); Integer hosts = entity.sensors().get(DockerInfrastructure.DOCKER_HOST_COUNT); if (containers == null || hosts == null) return; int possible = maxContainers * hosts; int available = possible - containers; // Calculate headroom Integer headroom = config().get(CONTAINER_HEADROOM); Double percent = config().get(CONTAINER_HEADROOM_PERCENTAGE); if (headroom == null) { headroom = (int) Math.ceil(percent * possible); } // Calculate requirements int needed = headroom - available; double utilisation = (double) containers / (double) possible; if (LOG.isDebugEnabled()) { LOG.debug("Headroom enricher: {} containers on {} hosts, {} available and {} needed", new Object[] { containers, hosts, available, needed }); } double lowThreshold = (double) (possible - (headroom + maxContainers)) / (double) possible; lowThreshold = Math.max(0d, lowThreshold); double highThreshold = (double) (possible - headroom) / (double) possible; highThreshold = Math.max(0d, highThreshold); // Emit current status of the pool as sensor data emit(CONTAINERS_NEEDED, needed); emit(DOCKER_CONTAINER_UTILISATION, utilisation); // Emit pool hot or cold sensors if headroom requirements not met Map<String, Object> properties = ImmutableMap.<String, Object>of(AutoScalerPolicy.POOL_CURRENT_SIZE_KEY, hosts, AutoScalerPolicy.POOL_CURRENT_WORKRATE_KEY, utilisation, AutoScalerPolicy.POOL_LOW_THRESHOLD_KEY, lowThreshold, AutoScalerPolicy.POOL_HIGH_THRESHOLD_KEY, highThreshold); if (needed > 0) { lastPublished = DOCKER_CONTAINER_CLUSTER_HOT; emit(DOCKER_CONTAINER_CLUSTER_HOT, properties); } else if (tooColdEnabled && available > (headroom + maxContainers)) { lastPublished = DOCKER_CONTAINER_CLUSTER_COLD; emit(DOCKER_CONTAINER_CLUSTER_COLD, properties); } else { // Only emit ok if we weren't previously if (lastPublished != null && lastPublished != DOCKER_CONTAINER_CLUSTER_OK) { lastPublished = DOCKER_CONTAINER_CLUSTER_OK; emit(DOCKER_CONTAINER_CLUSTER_OK, properties); } } }
From source file:org.apache.impala.analysis.SortInfo.java
/** * Create a tuple descriptor for the single tuple that is materialized, sorted, and * output by the sort node. Done by materializing slot refs in the order-by and given * result expressions. Those slot refs in the ordering and result exprs are substituted * with slot refs into the new tuple. This simplifies the sorting logic for total and * top-n sorts. The substitution map is returned. * TODO: We could do something more sophisticated than simply copying input slot refs - * e.g. compute some order-by expressions. *//*w w w.j a va2 s . c om*/ public ExprSubstitutionMap createSortTupleInfo(List<Expr> resultExprs, Analyzer analyzer) { // sourceSlots contains the slots from the sort input to materialize. Set<SlotRef> sourceSlots = Sets.newHashSet(); TreeNode.collect(resultExprs, Predicates.instanceOf(SlotRef.class), sourceSlots); TreeNode.collect(orderingExprs_, Predicates.instanceOf(SlotRef.class), sourceSlots); // The descriptor for the tuples on which the sort operates. TupleDescriptor sortTupleDesc = analyzer.getDescTbl().createTupleDescriptor("sort"); sortTupleDesc.setIsMaterialized(true); List<Expr> sortTupleExprs = Lists.newArrayList(); // substOrderBy is the mapping from slot refs in the sort node's input to slot refs in // the materialized sort tuple. Each slot ref in the input gets cloned and builds up // the tuple operated on and returned by the sort node. ExprSubstitutionMap substOrderBy = new ExprSubstitutionMap(); for (SlotRef origSlotRef : sourceSlots) { SlotDescriptor origSlotDesc = origSlotRef.getDesc(); SlotDescriptor materializedDesc = analyzer.copySlotDescriptor(origSlotDesc, sortTupleDesc); SlotRef cloneRef = new SlotRef(materializedDesc); substOrderBy.put(origSlotRef, cloneRef); sortTupleExprs.add(origSlotRef); } // The ordering exprs still point to the old slot refs and need to be replaced with // ones that point to the slot refs into the sort's output tuple. substituteOrderingExprs(substOrderBy, analyzer); // Update the tuple descriptor used to materialize the input of the sort. setMaterializedTupleInfo(sortTupleDesc, sortTupleExprs); return substOrderBy; }
From source file:org.eclipse.sirius.diagram.sequence.ui.tool.internal.util.RequestQuery.java
/** * Checks if the current request is a creation request for a new create * message.//from w w w . j a v a 2 s .com * * @return true if the current request is a creation request for a new * create message */ public boolean isCreateMessageCreation() { return isSequenceMessageCreation(Predicates.instanceOf(CreationMessageMapping.class)); }