List of usage examples for com.google.common.base Predicates equalTo
public static <T> Predicate<T> equalTo(@Nullable T target)
From source file:org.eclipse.sirius.diagram.sequence.business.internal.util.SubEventsHelper.java
private Iterable<ISequenceEvent> getSequenceEventsToFilter(ISequenceEvent self, ISequenceEvent child, final Range range, final Collection<Lifeline> lifelines) { Set<ISequenceEvent> result = Sets.newHashSet(self.getSubEvents()); Predicate<ISequenceEvent> inRangePredicate = new Predicate<ISequenceEvent>() { public boolean apply(ISequenceEvent input) { Range inputRange = input.getVerticalRange(); return range.includesAtLeastOneBound(inputRange) || new ISequenceEventQuery(input).isReflectiveMessage() && inputRange.includesAtLeastOneBound(range); }// ww w . ja va 2 s. c om }; Predicate<ISequenceEvent> inCoverage = new Predicate<ISequenceEvent>() { public boolean apply(ISequenceEvent input) { Collection<Lifeline> inputCoverage = Lists.newArrayList(getCoverage(input)); return Iterables.removeAll(inputCoverage, lifelines); } }; @SuppressWarnings("unchecked") Predicate<ISequenceEvent> predicateFilter = Predicates.and(Predicates.not(Predicates.equalTo(child)), inRangePredicate, inCoverage); return Iterables.filter(result, predicateFilter); }
From source file:org.immutables.value.processor.meta.ValueType.java
public Set<ValueAttribute> computeConstructorArguments() { return ImmutableSet.copyOf(attributes() .filter(Predicates.compose(Predicates.not(Predicates.equalTo(-1)), ToConstructorArgumentOrder.FUNCTION)) .toSortedList(Ordering.natural().onResultOf(ToConstructorArgumentOrder.FUNCTION))); }
From source file:brooklyn.entity.mesos.task.marathon.MarathonTaskImpl.java
@Override public void start(Collection<? extends Location> locs) { addLocations(locs);// w ww . j av a2s . com List<Location> locations = MutableList.copyOf(Locations.getLocationsCheckingAncestors(locs, this)); super.start(locations); ServiceStateLogic.setExpectedState(this, Lifecycle.STARTING); // Only start new application for managed tasks boolean managed = Optional.fromNullable(sensors().get(MANAGED)).or(true); if (managed) { Entity entity = getRunningEntity(); entity.sensors().set(DockerContainer.CONTAINER, this); entity.sensors().set(MesosAttributes.MESOS_CLUSTER, getMesosCluster()); MarathonFramework marathon = (MarathonFramework) sensors().get(FRAMEWORK); marathon.sensors().get(MesosFramework.FRAMEWORK_TASKS).addMember(this); String id = sensors().get(APPLICATION_ID); Map<String, Object> flags = getMarathonFlags(entity); try { LOG.debug("Starting task {} on {} with flags: {}", new Object[] { id, marathon, Joiner.on(",").withKeyValueSeparator("=").join(flags) }); marathon.startApplication(id, flags); } catch (Exception e) { ServiceStateLogic.setExpectedState(this, Lifecycle.ON_FIRE); throw Exceptions.propagate(e); } // Waiting for TASK_RUNNING status and get hostname Task<?> running = DependentConfiguration.attributeWhenReady(this, MesosTask.TASK_STATE, Predicates.equalTo(MesosTask.TaskState.TASK_RUNNING.toString())); DynamicTasks.queueIfPossible(running).orSubmitAndBlock(this).asTask() .getUnchecked(Duration.FIVE_MINUTES); Task<?> hostname = DependentConfiguration.attributeWhenReady(this, Attributes.HOSTNAME, Predicates.notNull()); DynamicTasks.queueIfPossible(hostname).orSubmitAndBlock(this).asTask() .getUnchecked(Duration.FIVE_MINUTES); LOG.info("Task {} running on {} successfully", id, getHostname()); String containerId = null; MesosSlave slave = getMesosCluster().getMesosSlave(getHostname()); String ps = slave.execCommand(BashCommands.sudo("docker ps --no-trunc --filter=name=mesos-* -q")); Iterable<String> containers = Iterables.filter( Splitter.on(CharMatcher.anyOf("\r\n")).omitEmptyStrings().split(ps), StringPredicates.matchesRegex("[a-z0-9]{64}")); for (String each : containers) { String env = slave.execCommand(BashCommands .sudo("docker inspect --format='{{range .Config.Env}}{{println .}}{{end}}' " + each)); Optional<String> found = Iterables.tryFind(Splitter.on(CharMatcher.anyOf("\r\n")).split(env), Predicates.equalTo("MARATHON_APP_ID=" + sensors().get(APPLICATION_ID))); if (found.isPresent()) { containerId = each; break; } } sensors().set(DockerContainer.CONTAINER_ID, containerId); entity.sensors().set(DockerContainer.CONTAINER_ID, containerId); // Set network configuration if using Calico SDN if (SdnUtils.isSdnProvider(getMesosCluster(), "CalicoModule")) { CalicoModule provider = ((CalicoModule) getMesosCluster().sensors().get(MesosCluster.SDN_PROVIDER)); List<String> networks = Lists.newArrayList(entity.getApplicationId()); Collection<String> extra = entity.config().get(SdnAttributes.NETWORK_LIST); if (extra != null) networks.addAll(extra); sensors().set(SdnAttributes.ATTACHED_NETWORKS, networks); entity.sensors().set(SdnAttributes.ATTACHED_NETWORKS, networks); Set<String> addresses = Sets.newHashSet(); for (String networkId : networks) { SdnUtils.createNetwork(provider, networkId); InetAddress address = provider.attachNetwork(slave, entity, containerId, networkId); addresses.add(address.getHostAddress().toString()); if (networkId.equals(entity.getApplicationId())) { sensors().set(Attributes.SUBNET_ADDRESS, address.getHostAddress()); sensors().set(Attributes.SUBNET_HOSTNAME, address.getHostAddress()); entity.sensors().set(Attributes.SUBNET_ADDRESS, address.getHostAddress()); entity.sensors().set(Attributes.SUBNET_HOSTNAME, address.getHostAddress()); } } sensors().set(DockerContainer.CONTAINER_ADDRESSES, addresses); entity.sensors().set(DockerContainer.CONTAINER_ADDRESSES, addresses); } // Look up mapped ports for entity DockerUtils.getContainerPorts(entity); createLocation(flags); } ServiceStateLogic.setExpectedState(this, Lifecycle.RUNNING); }
From source file:dagger2.internal.codegen.BindingGraphValidator.java
/** * Validates a members injection binding, returning false (and reporting the error) if it wasn't * valid.// ww w. j ava 2 s .com */ private boolean validateMembersInjectionBinding(MembersInjectionBinding binding, final Deque<ResolvedRequest> path, final Builder<BindingGraph> reportBuilder) { return binding.key().type().accept(new SimpleTypeVisitor6<Boolean, Void>() { @Override protected Boolean defaultAction(TypeMirror e, Void p) { reportBuilder.addItem("Invalid members injection request.", path.peek().request().requestElement()); return false; } @Override public Boolean visitDeclared(DeclaredType type, Void ignored) { // If the key has type arguments, validate that each type argument is declared. // Otherwise the type argument may be a wildcard (or other type), and we can't // resolve that to actual types. If the arg was an array, validate the type // of the array. for (TypeMirror arg : type.getTypeArguments()) { boolean declared; switch (arg.getKind()) { case ARRAY: declared = MoreTypes.asArray(arg).getComponentType() .accept(new SimpleTypeVisitor6<Boolean, Void>() { @Override protected Boolean defaultAction(TypeMirror e, Void p) { return false; } @Override public Boolean visitDeclared(DeclaredType t, Void p) { for (TypeMirror arg : t.getTypeArguments()) { if (!arg.accept(this, null)) { return false; } } return true; } @Override public Boolean visitArray(ArrayType t, Void p) { return t.getComponentType().accept(this, null); } @Override public Boolean visitPrimitive(PrimitiveType t, Void p) { return true; } }, null); break; case DECLARED: declared = true; break; default: declared = false; } if (!declared) { ImmutableList<String> printableDependencyPath = FluentIterable.from(path) .transform(REQUEST_FROM_RESOLVED_REQUEST).transform(dependencyRequestFormatter) .filter(Predicates.not(Predicates.equalTo(""))).toList().reverse(); reportBuilder.addItem( String.format(MEMBERS_INJECTION_WITH_UNBOUNDED_TYPE, arg.toString(), type.toString(), Joiner.on('\n').join(printableDependencyPath)), path.peek().request().requestElement()); return false; } } TypeElement element = MoreElements.asType(type.asElement()); // Also validate that the key is not the erasure of a generic type. // If it is, that means the user referred to Foo<T> as just 'Foo', // which we don't allow. (This is a judgement call -- we *could* // allow it and instantiate the type bounds... but we don't.) if (!MoreTypes.asDeclared(element.asType()).getTypeArguments().isEmpty() && types.isSameType(types.erasure(element.asType()), type)) { ImmutableList<String> printableDependencyPath = FluentIterable.from(path) .transform(REQUEST_FROM_RESOLVED_REQUEST).transform(dependencyRequestFormatter) .filter(Predicates.not(Predicates.equalTo(""))).toList().reverse(); reportBuilder.addItem( String.format(ErrorMessages.MEMBERS_INJECTION_WITH_RAW_TYPE, type.toString(), Joiner.on('\n').join(printableDependencyPath)), path.peek().request().requestElement()); return false; } return true; // valid } }, null); }
From source file:clocker.mesos.entity.task.marathon.MarathonTaskImpl.java
@Override public void start(Collection<? extends Location> locs) { addLocations(locs);/* w w w.j a v a 2 s .c o m*/ List<Location> locations = MutableList.copyOf(Locations.getLocationsCheckingAncestors(locs, this)); super.start(locations); ServiceStateLogic.setExpectedState(this, Lifecycle.STARTING); // Only start new application for managed tasks boolean managed = Optional.fromNullable(sensors().get(MANAGED)).or(true); if (managed) { Entity entity = getRunningEntity(); entity.sensors().set(DockerContainer.CONTAINER, this); entity.sensors().set(MesosAttributes.MESOS_CLUSTER, getMesosCluster()); MarathonFramework marathon = (MarathonFramework) sensors().get(FRAMEWORK); marathon.sensors().get(MesosFramework.FRAMEWORK_TASKS).addMember(this); String id = sensors().get(APPLICATION_ID); Map<String, Object> flags = getMarathonFlags(entity); try { LOG.debug("Starting task {} on {} with flags: {}", new Object[] { id, marathon, Joiner.on(",").withKeyValueSeparator("=").join(flags) }); marathon.startApplication(id, flags); } catch (Exception e) { ServiceStateLogic.setExpectedState(this, Lifecycle.ON_FIRE); throw Exceptions.propagate(e); } // Waiting for TASK_RUNNING status and get hostname Task<?> running = DependentConfiguration.attributeWhenReady(this, MesosTask.TASK_STATE, Predicates.equalTo(MesosTask.TaskState.TASK_RUNNING.toString())); DynamicTasks.queueIfPossible(running).orSubmitAndBlock(this).asTask() .getUnchecked(Duration.FIVE_MINUTES); Task<?> hostname = DependentConfiguration.attributeWhenReady(this, Attributes.HOSTNAME, Predicates.notNull()); DynamicTasks.queueIfPossible(hostname).orSubmitAndBlock(this).asTask() .getUnchecked(Duration.FIVE_MINUTES); LOG.info("Task {} running on {} successfully", id, getHostname()); String containerId = null; MesosSlave slave = getMesosCluster().getMesosSlave(getHostname()); String ps = slave.execCommand(BashCommands.sudo("docker ps --no-trunc --filter=name=mesos-* -q")); Iterable<String> containers = Iterables.filter( Splitter.on(CharMatcher.anyOf("\r\n")).omitEmptyStrings().split(ps), StringPredicates.matchesRegex("[a-z0-9]{64}")); for (String each : containers) { String env = slave.execCommand(BashCommands .sudo("docker inspect --format='{{range .Config.Env}}{{println .}}{{end}}' " + each)); Optional<String> found = Iterables.tryFind(Splitter.on(CharMatcher.anyOf("\r\n")).split(env), Predicates.equalTo("MARATHON_APP_ID=" + sensors().get(APPLICATION_ID))); if (found.isPresent()) { containerId = each; break; } } sensors().set(DockerContainer.DOCKER_CONTAINER_ID, containerId); entity.sensors().set(DockerContainer.DOCKER_CONTAINER_ID, containerId); // Set network configuration if using Calico SDN if (SdnUtils.isSdnProvider(getMesosCluster(), "CalicoModule")) { CalicoModule provider = ((CalicoModule) getMesosCluster().sensors().get(MesosCluster.SDN_PROVIDER)); List<String> networks = Lists.newArrayList(entity.getApplicationId()); Collection<String> extra = entity.config().get(SdnAttributes.NETWORK_LIST); if (extra != null) networks.addAll(extra); sensors().set(SdnAttributes.ATTACHED_NETWORKS, networks); entity.sensors().set(SdnAttributes.ATTACHED_NETWORKS, networks); Set<String> addresses = Sets.newHashSet(); for (String networkId : networks) { SdnUtils.createNetwork(provider, networkId); InetAddress address = provider.attachNetwork(slave, entity, containerId, networkId); addresses.add(address.getHostAddress().toString()); if (networkId.equals(entity.getApplicationId())) { sensors().set(Attributes.SUBNET_ADDRESS, address.getHostAddress()); sensors().set(Attributes.SUBNET_HOSTNAME, address.getHostAddress()); entity.sensors().set(Attributes.SUBNET_ADDRESS, address.getHostAddress()); entity.sensors().set(Attributes.SUBNET_HOSTNAME, address.getHostAddress()); } } sensors().set(DockerContainer.CONTAINER_ADDRESSES, addresses); entity.sensors().set(DockerContainer.CONTAINER_ADDRESSES, addresses); } // Look up mapped ports for entity DockerUtils.getContainerPorts(entity); createLocation(flags); } ServiceStateLogic.setExpectedState(this, Lifecycle.RUNNING); }
From source file:com.twitter.aurora.scheduler.thrift.SchedulerThriftInterface.java
@Override public Response getJobs(@Nullable String maybeNullRole) { Optional<String> ownerRole = Optional.fromNullable(maybeNullRole); // Ensure we only return one JobConfiguration for each JobKey. Map<IJobKey, IJobConfiguration> jobs = Maps.newHashMap(); // Query the task store, find immediate jobs, and synthesize a JobConfiguration for them. // This is necessary because the ImmediateJobManager doesn't store jobs directly and // ImmediateJobManager#getJobs always returns an empty Collection. Query.Builder scope = ownerRole.isPresent() ? Query.roleScoped(ownerRole.get()) : Query.unscoped(); Multimap<IJobKey, IScheduledTask> tasks = Tasks .byJobKey(Storage.Util.weaklyConsistentFetchTasks(storage, scope.active())); jobs.putAll(Maps.transformEntries(tasks.asMap(), new Maps.EntryTransformer<IJobKey, Collection<IScheduledTask>, IJobConfiguration>() { @Override//from w ww . ja v a2 s . c o m public IJobConfiguration transformEntry(IJobKey jobKey, Collection<IScheduledTask> tasks) { // Pick an arbitrary task for each immediate job. The chosen task might not be the most // recent if the job is in the middle of an update or some shards have been selectively // created. TaskConfig firstTask = tasks.iterator().next().getAssignedTask().getTask().newBuilder(); return IJobConfiguration.build( new JobConfiguration().setKey(jobKey.newBuilder()).setOwner(firstTask.getOwner()) .setTaskConfig(firstTask).setInstanceCount(tasks.size())); } })); // Get cron jobs directly from the manager. Do this after querying the task store so the real // template JobConfiguration for a cron job will overwrite the synthesized one that could have // been created above. Predicate<IJobConfiguration> configFilter = ownerRole.isPresent() ? Predicates.compose(Predicates.equalTo(ownerRole.get()), JobKeys.CONFIG_TO_ROLE) : Predicates.<IJobConfiguration>alwaysTrue(); jobs.putAll(Maps.uniqueIndex(FluentIterable.from(cronJobManager.getJobs()).filter(configFilter), JobKeys.FROM_CONFIG)); return new Response().setResponseCode(OK).setResult(Result .getJobsResult(new GetJobsResult().setConfigs(IJobConfiguration.toBuildersSet(jobs.values())))); }
From source file:org.apache.cassandra.cql.QueryProcessor.java
private static void validateSchemaAgreement() throws SchemaDisagreementException { // unreachable hosts don't count towards disagreement Map<String, List<String>> versions = Maps.filterKeys(StorageProxy.describeSchemaVersions(), Predicates.not(Predicates.equalTo(StorageProxy.UNREACHABLE))); if (versions.size() > 1) throw new SchemaDisagreementException(); }
From source file:com.palantir.atlasdb.keyvalue.cassandra.CQLKeyValueService.java
@Override public Map<Cell, Value> get(String tableName, Map<Cell, Long> timestampByCell) { try {/*from ww w . j a v a2 s.c o m*/ long firstTs = timestampByCell.values().iterator().next(); if (Iterables.all(timestampByCell.values(), Predicates.equalTo(firstTs))) { StartTsResultsCollector collector = new StartTsResultsCollector(firstTs); loadWithTs(tableName, timestampByCell.keySet(), firstTs, false, collector, readConsistency); return collector.collectedResults; } SetMultimap<Long, Cell> cellsByTs = HashMultimap.create(); Multimaps.invertFrom(Multimaps.forMap(timestampByCell), cellsByTs); Builder<Cell, Value> builder = ImmutableMap.builder(); for (long ts : cellsByTs.keySet()) { StartTsResultsCollector collector = new StartTsResultsCollector(ts); loadWithTs(tableName, cellsByTs.get(ts), ts, false, collector, readConsistency); builder.putAll(collector.collectedResults); } return builder.build(); } catch (Throwable t) { throw Throwables.throwUncheckedException(t); } }
From source file:org.apache.druid.segment.StringDimensionIndexer.java
@Override public DimensionSelector makeDimensionSelector(final DimensionSpec spec, final IncrementalIndexRowHolder currEntry, final IncrementalIndex.DimensionDesc desc) { final ExtractionFn extractionFn = spec.getExtractionFn(); final int dimIndex = desc.getIndex(); final int maxId = getCardinality(); class IndexerDimensionSelector implements DimensionSelector, IdLookup { private final ArrayBasedIndexedInts indexedInts = new ArrayBasedIndexedInts(); private int[] nullIdIntArray; @Override/* w w w .j a v a 2s . c o m*/ public IndexedInts getRow() { final Object[] dims = currEntry.get().getDims(); int[] indices; if (dimIndex < dims.length) { indices = (int[]) dims[dimIndex]; } else { indices = null; } int[] row = null; int rowSize = 0; // usually due to currEntry's rowIndex is smaller than the row's rowIndex in which this dim first appears if (indices == null || indices.length == 0) { if (hasMultipleValues) { row = IntArrays.EMPTY_ARRAY; rowSize = 0; } else { final int nullId = getEncodedValue(null, false); if (nullId > -1) { if (nullIdIntArray == null) { nullIdIntArray = new int[] { nullId }; } row = nullIdIntArray; rowSize = 1; } else { // doesn't contain nullId, then empty array is used // Choose to use ArrayBasedIndexedInts later, instead of special "empty" IndexedInts, for monomorphism row = IntArrays.EMPTY_ARRAY; rowSize = 0; } } } if (row == null && indices != null && indices.length > 0) { row = indices; rowSize = indices.length; } indexedInts.setValues(row, rowSize); return indexedInts; } @Override public ValueMatcher makeValueMatcher(final String value) { if (extractionFn == null) { final int valueId = lookupId(value); if (valueId >= 0 || value == null) { return new ValueMatcher() { @Override public boolean matches() { Object[] dims = currEntry.get().getDims(); if (dimIndex >= dims.length) { return value == null; } int[] dimsInt = (int[]) dims[dimIndex]; if (dimsInt == null || dimsInt.length == 0) { return value == null; } for (int id : dimsInt) { if (id == valueId) { return true; } } return false; } @Override public void inspectRuntimeShape(RuntimeShapeInspector inspector) { // nothing to inspect } }; } else { return BooleanValueMatcher.of(false); } } else { // Employ caching BitSet optimization return makeValueMatcher(Predicates.equalTo(value)); } } @Override public ValueMatcher makeValueMatcher(final Predicate<String> predicate) { final BitSet checkedIds = new BitSet(maxId); final BitSet matchingIds = new BitSet(maxId); final boolean matchNull = predicate.apply(null); // Lazy matcher; only check an id if matches() is called. return new ValueMatcher() { @Override public boolean matches() { Object[] dims = currEntry.get().getDims(); if (dimIndex >= dims.length) { return matchNull; } int[] dimsInt = (int[]) dims[dimIndex]; if (dimsInt == null || dimsInt.length == 0) { return matchNull; } for (int id : dimsInt) { if (checkedIds.get(id)) { if (matchingIds.get(id)) { return true; } } else { final boolean matches = predicate.apply(lookupName(id)); checkedIds.set(id); if (matches) { matchingIds.set(id); return true; } } } return false; } @Override public void inspectRuntimeShape(RuntimeShapeInspector inspector) { // nothing to inspect } }; } @Override public int getValueCardinality() { return maxId; } @Override public String lookupName(int id) { if (id >= maxId) { throw new ISE("id[%d] >= maxId[%d]", id, maxId); } final String strValue = getActualValue(id, false); return extractionFn == null ? strValue : extractionFn.apply(strValue); } @Override public boolean nameLookupPossibleInAdvance() { return true; } @Nullable @Override public IdLookup idLookup() { return extractionFn == null ? this : null; } @Override public int lookupId(String name) { if (extractionFn != null) { throw new UnsupportedOperationException( "cannot perform lookup when applying an extraction function"); } return getEncodedValue(name, false); } @SuppressWarnings("deprecation") @Nullable @Override public Object getObject() { IncrementalIndexRow key = currEntry.get(); if (key == null) { return null; } Object[] dims = key.getDims(); if (dimIndex >= dims.length) { return null; } return convertUnsortedEncodedKeyComponentToActualList((int[]) dims[dimIndex]); } @SuppressWarnings("deprecation") @Override public Class classOfObject() { return Object.class; } @Override public void inspectRuntimeShape(RuntimeShapeInspector inspector) { // nothing to inspect } } return new IndexerDimensionSelector(); }
From source file:com.eucalyptus.reporting.ReportingDataVerifier.java
private static Address findAddress(final String uuid) { return Iterables.getFirst(Iterables.filter( Iterables.concat(Addresses.getInstance().listValues(), Addresses.getInstance().listDisabledValues()), Predicates.compose(Predicates.equalTo(uuid), naturalId())), null); }