List of usage examples for com.google.common.base Predicates in
public static <T> Predicate<T> in(Collection<? extends T> target)
From source file:org.immutables.value.processor.meta.ValueType.java
public List<ValueAttribute> getConstructorExcluded() { if (constructorExcluded == null) { constructorExcluded = FluentIterable.from(getSettableAttributes()) .filter(Predicates.not(Predicates.in(getConstructorArguments()))).toList(); }/*from www .ja v a 2s . c o m*/ return constructorExcluded; }
From source file:org.apache.aurora.scheduler.thrift.ReadOnlySchedulerImpl.java
@Override public Response getJobUpdateDiff(JobUpdateRequest mutableRequest) { IJobUpdateRequest request;//from w ww .j ava 2 s . com try { request = IJobUpdateRequest .build(new JobUpdateRequest(mutableRequest).setTaskConfig(configurationManager .validateAndPopulate(ITaskConfig.build(mutableRequest.getTaskConfig())).newBuilder())); } catch (TaskDescriptionException e) { return error(INVALID_REQUEST, e); } IJobKey job = request.getTaskConfig().getJob(); return storage.read(storeProvider -> { if (storeProvider.getCronJobStore().fetchJob(job).isPresent()) { return invalidRequest(NO_CRON); } JobDiff diff = JobDiff.compute(storeProvider.getTaskStore(), job, JobDiff.asMap(request.getTaskConfig(), request.getInstanceCount()), request.getSettings().getUpdateOnlyTheseInstances()); Map<Integer, ITaskConfig> replaced = diff.getReplacedInstances(); Map<Integer, ITaskConfig> replacements = Maps.asMap(diff.getReplacementInstances(), Functions.constant(request.getTaskConfig())); Map<Integer, ITaskConfig> add = Maps.filterKeys(replacements, Predicates.in(Sets.difference(replacements.keySet(), replaced.keySet()))); Map<Integer, ITaskConfig> remove = Maps.filterKeys(replaced, Predicates.in(Sets.difference(replaced.keySet(), replacements.keySet()))); Map<Integer, ITaskConfig> update = Maps.filterKeys(replaced, Predicates.in(Sets.intersection(replaced.keySet(), replacements.keySet()))); return ok( Result.getJobUpdateDiffResult(new GetJobUpdateDiffResult().setAdd(instancesToConfigGroups(add)) .setRemove(instancesToConfigGroups(remove)).setUpdate(instancesToConfigGroups(update)) .setUnchanged(instancesToConfigGroups(diff.getUnchangedInstances())))); }); }
From source file:com.continuuity.weave.yarn.YarnWeavePreparer.java
private Closeable saveLocalFiles(Map<String, LocalResource> localResources, Set<String> keys) throws IOException { Map<String, LocalFile> localFiles = Maps.transformEntries( Maps.filterKeys(localResources, Predicates.in(keys)), new Maps.EntryTransformer<String, LocalResource, LocalFile>() { @Override/*from w ww. jav a 2 s . co m*/ public LocalFile transformEntry(String key, LocalResource value) { try { return new DefaultLocalFile(key, ConverterUtils.getPathFromYarnURL(value.getResource()).toUri(), value.getTimestamp(), value.getSize(), value.getType() != LocalResourceType.FILE, value.getPattern()); } catch (URISyntaxException e) { throw Throwables.propagate(e); } } }); LOG.debug("Create and copy localFiles.json"); Location location = createTempLocation("localFiles", ".json"); Writer writer = new OutputStreamWriter(location.getOutputStream(), Charsets.UTF_8); try { new GsonBuilder().registerTypeAdapter(LocalFile.class, new LocalFileCodec()).create() .toJson(localFiles.values(), new TypeToken<List<LocalFile>>() { }.getType(), writer); } finally { writer.close(); } LOG.debug("Done localFiles.json"); localResources.put("localFiles.json", YarnUtils.createLocalResource(location)); return getCloseable(location); }
From source file:com.twitter.common.args.ArgScanner.java
/** * Applies argument values to fields based on their annotations. * * @param parserOracle ParserOracle available to parse raw args with. * @param verifiers Verifiers available to verify argument constraints with. * @param argsInfo Fields to apply argument values to. * @param args Unparsed argument values. * @param positionalArgs The unparsed positional arguments. * @return {@code true} if the given {@code args} were successfully applied to their * corresponding {@link com.twitter.common.args.Arg} fields. *//* w ww .j a va2 s . com*/ private boolean process(final ParserOracle parserOracle, Verifiers verifiers, ArgsInfo argsInfo, Map<String, String> args, List<String> positionalArgs) { if (!Sets.intersection(args.keySet(), ArgumentInfo.HELP_ARGS).isEmpty()) { printHelp(verifiers, argsInfo); return false; } Optional<? extends PositionalInfo<?>> positionalInfoOptional = argsInfo.getPositionalInfo(); checkArgument(positionalInfoOptional.isPresent() || positionalArgs.isEmpty(), "Positional arguments have been supplied but there is no Arg annotated to received them."); Iterable<? extends OptionInfo<?>> optionInfos = argsInfo.getOptionInfos(); final Set<String> argsFailedToParse = Sets.newHashSet(); final Set<String> argsConstraintsFailed = Sets.newHashSet(); Set<String> argAllShortNamesNoCollisions = getNoCollisions(optionInfos); final Map<String, OptionInfo<?>> argsByName = ImmutableMap.<String, OptionInfo<?>>builder() // Map by short arg name -> arg def. .putAll(Maps.uniqueIndex(Iterables.filter(optionInfos, Predicates.compose(Predicates.in(argAllShortNamesNoCollisions), GET_OPTION_INFO_NAME)), GET_OPTION_INFO_NAME)) // Map by canonical arg name -> arg def. .putAll(Maps.uniqueIndex(optionInfos, GET_CANONICAL_ARG_NAME)) // Map by negated short arg name (for booleans) .putAll(Maps.uniqueIndex(Iterables.filter(Iterables.filter(optionInfos, IS_BOOLEAN), Predicates.compose(Predicates.in(argAllShortNamesNoCollisions), GET_OPTION_INFO_NEGATED_NAME)), GET_OPTION_INFO_NEGATED_NAME)) // Map by negated canonical arg name (for booleans) .putAll(Maps.uniqueIndex(Iterables.filter(optionInfos, IS_BOOLEAN), GET_CANONICAL_NEGATED_ARG_NAME)) .build(); // TODO(William Farner): Make sure to disallow duplicate arg specification by short and // canonical names. // TODO(William Farner): Support non-atomic argument constraints. @OnlyIfSet, @OnlyIfNotSet, // @ExclusiveOf to define inter-argument constraints. Set<String> recognizedArgs = Sets.intersection(argsByName.keySet(), args.keySet()); for (String argName : recognizedArgs) { String argValue = args.get(argName); OptionInfo<?> optionInfo = argsByName.get(argName); try { optionInfo.load(parserOracle, argName, argValue); } catch (IllegalArgumentException e) { argsFailedToParse.add(argName + " - " + e.getMessage()); } } if (positionalInfoOptional.isPresent()) { PositionalInfo<?> positionalInfo = positionalInfoOptional.get(); positionalInfo.load(parserOracle, positionalArgs); } Set<String> commandLineArgumentInfos = Sets.newTreeSet(); Iterable<? extends ArgumentInfo<?>> allArguments = argsInfo.getOptionInfos(); if (positionalInfoOptional.isPresent()) { PositionalInfo<?> positionalInfo = positionalInfoOptional.get(); allArguments = Iterables.concat(optionInfos, ImmutableList.of(positionalInfo)); } for (ArgumentInfo<?> anArgumentInfo : allArguments) { Arg<?> arg = anArgumentInfo.getArg(); commandLineArgumentInfos.add(String.format("%s (%s): %s", anArgumentInfo.getName(), anArgumentInfo.getCanonicalName(), arg.uncheckedGet())); try { anArgumentInfo.verify(verifiers); } catch (IllegalArgumentException e) { argsConstraintsFailed.add(anArgumentInfo.getName() + " - " + e.getMessage()); } } ImmutableMultimap<String, String> warningMessages = ImmutableMultimap.<String, String>builder() .putAll("Unrecognized arguments", Sets.difference(args.keySet(), argsByName.keySet())) .putAll("Failed to parse", argsFailedToParse) .putAll("Value did not meet constraints", argsConstraintsFailed).build(); if (!warningMessages.isEmpty()) { printHelp(verifiers, argsInfo); StringBuilder sb = new StringBuilder(); for (Map.Entry<String, Collection<String>> warnings : warningMessages.asMap().entrySet()) { sb.append(warnings.getKey()).append(":\n\t").append(Joiner.on("\n\t").join(warnings.getValue())) .append("\n"); } throw new IllegalArgumentException(sb.toString()); } LOG.info("-------------------------------------------------------------------------"); LOG.info("Command line argument values"); for (String commandLineArgumentInfo : commandLineArgumentInfos) { LOG.info(commandLineArgumentInfo); } LOG.info("-------------------------------------------------------------------------"); return true; }
From source file:org.sosy_lab.cpachecker.cpa.value.refiner.ValueAnalysisRefiner.java
/** * This method returns an unsorted, non-empty collection of target states * found during the analysis.//from w ww. jav a2 s. c o m * * @param pReached the set of reached states * @return the target states */ private Collection<ARGState> getTargetStates(final ARGReachedSet pReached) { // obtain all target locations, excluding feasible ones // this filtering is needed to distinguish between multiple targets being available // because of stopAfterError=false (feasible) versus globalRefinement=true (new) Set<ARGState> targets = from(pReached.asReachedSet()).transform(AbstractStates.toState(ARGState.class)) .filter(AbstractStates.IS_TARGET_STATE).filter(Predicates.not(Predicates.in(feasibleTargets))) .toSet(); assert !targets.isEmpty(); logger.log(Level.FINEST, "number of targets found: " + targets.size()); targetCounter = targetCounter + targets.size(); return targets; }
From source file:org.eclipse.sirius.diagram.sequence.business.internal.layout.vertical.SequenceVerticalLayout.java
private Map<ISequenceEvent, Range> computeBasicRanges(Map<EventEnd, Integer> endLocations) { final Map<ISequenceEvent, Range> sequenceEventsToRange = new LinkedHashMap<ISequenceEvent, Range>(); Predicate<ISequenceEvent> notMoved = Predicates.not(Predicates.in(sequenceEventsToRange.keySet())); // CombinedFragments for (EventEnd sortedEnd : semanticOrdering) { Predicate<ISequenceEvent> frames = Predicates.and(notMoved, Predicates.or( Predicates.instanceOf(CombinedFragment.class), Predicates.instanceOf(InteractionUse.class))); for (ISequenceEvent ise : Iterables.filter(endToISequencEvents.get(sortedEnd), frames)) { computeFinalRange(endLocations, sequenceEventsToRange, ise); }/*from w w w . j a v a2s . c o m*/ } // Operands for (EventEnd sortedEnd : semanticOrdering) { Predicate<ISequenceEvent> operands = Predicates.and(notMoved, Predicates.instanceOf(Operand.class)); for (ISequenceEvent ise : Iterables.filter(endToISequencEvents.get(sortedEnd), operands)) { computeFinalRange(endLocations, sequenceEventsToRange, ise); } } // Other sequence events for (EventEnd sortedEnd : semanticOrdering) { for (ISequenceEvent ise : Iterables.filter(endToISequencEvents.get(sortedEnd), notMoved)) { computeFinalRange(endLocations, sequenceEventsToRange, ise); } } return sequenceEventsToRange; }
From source file:org.immutables.value.processor.meta.ValueType.java
public List<ValueAttribute> getConstructorOmited() { return FluentIterable.from(getImplementedAttributes()) .filter(Predicates.not(Predicates.in(getConstructorArguments()))).toList(); }
From source file:com.palantir.atlasdb.transaction.impl.SerializableTransaction.java
private void verifyCells(Transaction ro) { for (String table : cellsRead.keySet()) { final ConcurrentNavigableMap<Cell, byte[]> readsForTable = getReadsForTable(table); for (Iterable<Cell> batch : Iterables.partition(cellsRead.get(table), 1000)) { if (writesByTable.get(table) != null) { // We don't want to verify any reads that we wrote to cause we will just read our own values. // NB: If the value has changed between read and write, our normal SI checking handles this case batch = Iterables.filter(batch, Predicates.not(Predicates.in(writesByTable.get(table).keySet()))); }//from ww w . j a v a2 s. co m ImmutableSet<Cell> batchSet = ImmutableSet.copyOf(batch); Map<Cell, byte[]> currentBatch = ro.get(table, batchSet); ImmutableMap<Cell, byte[]> originalReads = Maps.toMap( Sets.intersection(batchSet, readsForTable.keySet()), Functions.forMap(readsForTable)); if (!areMapsEqual(currentBatch, originalReads)) { throw TransactionSerializableConflictException.create(table, getTimestamp(), System.currentTimeMillis() - timeCreated); } } } }
From source file:com.google.devtools.build.lib.rules.android.DexArchiveAspect.java
/** * Derives options to use in incremental dexing actions from the given context and dx flags, where * the latter typically come from a {@code dexopts} attribute on a top-level target. This method * only works reliably if the given dexopts were tokenized, e.g., using * {@link RuleContext#getTokenizedStringListAttr}. *///ww w. j a va2s .co m static ImmutableSet<String> incrementalDexopts(RuleContext ruleContext, Iterable<String> tokenizedDexopts) { return normalizeDexopts(ruleContext, Iterables.filter(tokenizedDexopts, Predicates.in(getAndroidConfig(ruleContext).getDexoptsSupportedInIncrementalDexing()))); }
From source file:com.google.devtools.build.lib.rules.objc.ProtoSupport.java
private Iterable<Artifact> getFilteredProtos() { // Filter the well known types from being sent to be generated, as these protos have already // been generated and linked in libprotobuf.a. return Iterables.filter(attributes.getProtoFiles(), Predicates.not(Predicates.in(attributes.getWellKnownTypeProtos()))); }