Java Code Examples for com.google.common.base.Predicates#not()

The following examples show how to use com.google.common.base.Predicates#not() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SimpleHelpMap.java    From Kettle with GNU General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public SimpleHelpMap(CraftServer server) {
    this.helpTopics = new TreeMap<String, HelpTopic>(HelpTopicComparator.topicNameComparatorInstance()); // Using a TreeMap for its explicit sorting on key
    this.topicFactoryMap = new HashMap<Class, HelpTopicFactory<Command>>();
    this.server = server;
    this.yaml = new HelpYamlReader(server);

    Predicate indexFilter = Predicates.not(Predicates.instanceOf(CommandAliasHelpTopic.class));
    if (!yaml.commandTopicsInMasterIndex()) {
        indexFilter = Predicates.and(indexFilter, Predicates.not(new IsCommandTopicPredicate()));
    }

    this.defaultTopic = new IndexHelpTopic("Index", null, null, Collections2.filter(helpTopics.values(), indexFilter), "Use /help [n] to get page n of help.");

    registerHelpTopicFactory(MultipleCommandAlias.class, new MultipleCommandAliasHelpTopicFactory());
}
 
Example 2
Source File: BlueTestResultContainerImpl.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@VisibleForTesting
public static Predicate<BlueTestResult> filterByStatus(String status) {
    String[] statusAtoms = StringUtils.split(status, ',');
    Predicate<BlueTestResult> predicate = Predicates.alwaysFalse();
    if (statusAtoms == null || statusAtoms.length == 0) {
        throw new BadRequestException("status not provided");
    }
    for (String statusString : statusAtoms) {
        Predicate<BlueTestResult> statusPredicate;
        try {
            if (statusString.startsWith("!")) {
                statusPredicate = Predicates.not(new StatusPredicate(Status.valueOf(statusString.toUpperCase().substring(1))));
            } else {
                statusPredicate  = new StatusPredicate(Status.valueOf(statusString.toUpperCase()));
            }
        } catch (IllegalArgumentException e) {
            throw new BadRequestException("bad status " + status, e);
        }
        predicate = Predicates.or(predicate, statusPredicate );
    }
    return predicate;
}
 
Example 3
Source File: Sets.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Returns an unmodifiable <b>view</b> of the difference of two sets. The
 * returned set contains all elements that are contained by {@code set1} and
 * not contained by {@code set2}. {@code set2} may also contain elements not
 * present in {@code set1}; these are simply ignored. The iteration order of
 * the returned set matches that of {@code set1}.
 *
 * <p>Results are undefined if {@code set1} and {@code set2} are sets based
 * on different equivalence relations (as {@code HashSet}, {@code TreeSet},
 * and the keySet of an {@code IdentityHashMap} all are).
 */


public static <E> SetView<E> difference(
  final Set<E> set1, final Set<?> set2) {
  checkNotNull(set1, "set1");
  checkNotNull(set2, "set2");
  final Predicate<Object> notInSet2 = Predicates.not(Predicates.in(set2));
  return new SetView<E>() {
    @Override
    public Iterator<E> iterator() {
      return Iterators.filter(set1.iterator(), notInSet2);
    }

    @Override
    public int size() {
      return Iterators.size(iterator());
    }

    @Override
    public boolean isEmpty() {
      return set2.containsAll(set1);
    }

    @Override
    public boolean contains(Object element) {
      return set1.contains(element) && !set2.contains(element);
    }
  };
}
 
Example 4
Source File: Sets.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Returns an unmodifiable <b>view</b> of the difference of two sets. The
 * returned set contains all elements that are contained by {@code set1} and
 * not contained by {@code set2}. {@code set2} may also contain elements not
 * present in {@code set1}; these are simply ignored. The iteration order of
 * the returned set matches that of {@code set1}.
 *
 * <p>Results are undefined if {@code set1} and {@code set2} are sets based
 * on different equivalence relations (as {@code HashSet}, {@code TreeSet},
 * and the keySet of an {@code IdentityHashMap} all are).
 */


public static <E> SetView<E> difference(
  final Set<E> set1, final Set<?> set2) {
  checkNotNull(set1, "set1");
  checkNotNull(set2, "set2");
  final Predicate<Object> notInSet2 = Predicates.not(Predicates.in(set2));
  return new SetView<E>() {
    @Override
    public Iterator<E> iterator() {
      return Iterators.filter(set1.iterator(), notInSet2);
    }

    @Override
    public int size() {
      return Iterators.size(iterator());
    }

    @Override
    public boolean isEmpty() {
      return set2.containsAll(set1);
    }

    @Override
    public boolean contains(Object element) {
      return set1.contains(element) && !set2.contains(element);
    }
  };
}
 
Example 5
Source File: Sets.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Returns an unmodifiable <b>view</b> of the difference of two sets. The
 * returned set contains all elements that are contained by {@code set1} and
 * not contained by {@code set2}. {@code set2} may also contain elements not
 * present in {@code set1}; these are simply ignored. The iteration order of
 * the returned set matches that of {@code set1}.
 *
 * <p>Results are undefined if {@code set1} and {@code set2} are sets based
 * on different equivalence relations (as {@code HashSet}, {@code TreeSet},
 * and the keySet of an {@code IdentityHashMap} all are).
 */


public static <E> SetView<E> difference(
  final Set<E> set1, final Set<?> set2) {
  checkNotNull(set1, "set1");
  checkNotNull(set2, "set2");
  final Predicate<Object> notInSet2 = Predicates.not(Predicates.in(set2));
  return new SetView<E>() {
    @Override
    public Iterator<E> iterator() {
      return Iterators.filter(set1.iterator(), notInSet2);
    }

    @Override
    public int size() {
      return Iterators.size(iterator());
    }

    @Override
    public boolean isEmpty() {
      return set2.containsAll(set1);
    }

    @Override
    public boolean contains(Object element) {
      return set1.contains(element) && !set2.contains(element);
    }
  };
}
 
Example 6
Source File: Sets.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Returns an unmodifiable <b>view</b> of the difference of two sets. The
 * returned set contains all elements that are contained by {@code set1} and
 * not contained by {@code set2}. {@code set2} may also contain elements not
 * present in {@code set1}; these are simply ignored. The iteration order of
 * the returned set matches that of {@code set1}.
 *
 * <p>Results are undefined if {@code set1} and {@code set2} are sets based
 * on different equivalence relations (as {@code HashSet}, {@code TreeSet},
 * and the keySet of an {@code IdentityHashMap} all are).
 */
public static <E> SetView<E> difference(final Set<E> set1, final Set<?> set2) {
  checkNotNull(set1, "set1");
  checkNotNull(set2, "set2");

  final Predicate<Object> notInSet2 = Predicates.not(Predicates.in(set2));
  return new SetView<E>() {
    @Override
    public Iterator<E> iterator() {
      return Iterators.filter(set1.iterator(), notInSet2);
    }

    @Override
    public int size() {
      return Iterators.size(iterator());
    }

    @Override
    public boolean isEmpty() {
      return set2.containsAll(set1);
    }

    @Override
    public boolean contains(Object element) {
      return set1.contains(element) && !set2.contains(element);
    }
  };
}
 
Example 7
Source File: ElementCostOfDataStructures.java    From memory-measurer with Apache License 2.0 5 votes vote down vote up
static AvgEntryCost averageEntryCost(Populator<?> populator, int initialEntries, int entriesToAdd) {
  Preconditions.checkArgument(initialEntries >= 0, "initialEntries negative");
  Preconditions.checkArgument(entriesToAdd > 0, "entriesToAdd negative or zero");

  Predicate<Object> predicate = Predicates.not(Predicates.instanceOf(
      populator.getEntryType()));

  Object collection1 = populator.construct(initialEntries);
  Footprint footprint1 = ObjectGraphMeasurer.measure(collection1, predicate);
  long bytes1 = MemoryMeasurer.measureBytes(collection1, predicate);

  Object collection2 = populator.construct(initialEntries + entriesToAdd);
  Footprint footprint2 = ObjectGraphMeasurer.measure(collection2, predicate);
  long bytes2 = MemoryMeasurer.measureBytes(collection2, predicate);

  double objects = (footprint2.getObjects() - footprint1.getObjects()) / (double) entriesToAdd;
  double refs = (footprint2.getReferences() - footprint1.getReferences()) / (double) entriesToAdd;
  double bytes = (bytes2 - bytes1) / (double)entriesToAdd;

  Map<Class<?>, Double> primitives = Maps.newHashMap();
  for (Class<?> primitiveType : primitiveTypes) {
    int initial = footprint1.getPrimitives().count(primitiveType);
    int ending = footprint2.getPrimitives().count(primitiveType);
    if (initial != ending) {
      primitives.put(primitiveType, (ending - initial) / (double) entriesToAdd);
    }
  }

  return new AvgEntryCost(objects, refs, primitives, bytes);
}
 
Example 8
Source File: FootprintUtils.java    From oopsla15-artifact with Eclipse Public License 1.0 5 votes vote down vote up
public static String measureAndReport(final Object objectToMeasure,
		final String className, DataType dataType, Archetype archetype,
		boolean supportsStagedMutability, int size, int run,
		MemoryFootprintPreset preset) {
	final Predicate<Object> predicate;

	switch (preset) {
	case DATA_STRUCTURE_OVERHEAD:
		predicate = Predicates.not(Predicates.instanceOf(org.eclipse.imp.pdb.facts.IValue.class));
		break;
	case RETAINED_SIZE:
		predicate = Predicates.alwaysTrue();
		break;
	default:
		throw new IllegalStateException();
	}

	// System.out.println(GraphLayout.parseInstance(objectToMeasure).totalSize());

	long memoryInBytes = objectexplorer.MemoryMeasurer.measureBytes(
			objectToMeasure, predicate);

	Footprint memoryFootprint = objectexplorer.ObjectGraphMeasurer.measure(
			objectToMeasure, predicate);

	final String statString = String.format("%d\t %60s\t[%s]\t %s",
			memoryInBytes, className, dataType, memoryFootprint);
	System.out.println(statString);

	final String statFileString = String.format(
			"%d,%d,%s,%s,%s,%b,%d,%d,%d", size, run, className, dataType,
			archetype, supportsStagedMutability, memoryInBytes,
			memoryFootprint.getObjects(), memoryFootprint.getReferences());

	return statFileString;
}
 
Example 9
Source File: RuleSetUtils.java    From bazel with Apache License 2.0 4 votes vote down vote up
/**
 * Predicate for checking if a rule class is not in excluded.
 */
public static Predicate<String> notContainsAnyOf(final ImmutableSet<String> excluded) {
  return Predicates.not(Predicates.in(excluded));
}
 
Example 10
Source File: ModelPredicateMatcher.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
public ModelPredicateMatcher not() {
   return new ModelPredicateMatcher(Predicates.not(selector), Predicates.not(matcher));
}
 
Example 11
Source File: CollectionFunctionals.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public static Predicate<Iterable<?>> notEmpty() {
    return Predicates.not(emptyOrNull());
}
 
Example 12
Source File: DslComponent.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
protected Maybe<Entity> callImpl(boolean immediate) throws Exception {
    Maybe<Entity> entityMaybe = getEntity(immediate);
    if (immediate && entityMaybe.isAbsent()) {
        return entityMaybe;
    }
    EntityInternal entity = (EntityInternal) entityMaybe.get();
    
    Iterable<Entity> entitiesToSearch = null;
    Predicate<Entity> notSelfPredicate = Predicates.not(Predicates.<Entity>equalTo(entity));

    switch (scope) {
        case THIS:
            return Maybe.<Entity>of(entity);
        case PARENT:
            return Maybe.<Entity>of(entity.getParent());
        case GLOBAL:
            entitiesToSearch = ((EntityManagerInternal)entity.getManagementContext().getEntityManager())
                .getAllEntitiesInApplication( entity().getApplication() );
            break;
        case ROOT:
            return Maybe.<Entity>of(entity.getApplication());
        case SCOPE_ROOT:
            return Maybe.<Entity>of(Entities.catalogItemScopeRoot(entity));
        case DESCENDANT:
            entitiesToSearch = Entities.descendantsWithoutSelf(entity);
            break;
        case ANCESTOR:
            entitiesToSearch = Entities.ancestorsWithoutSelf(entity);
            break;
        case SIBLING:
            entitiesToSearch = entity.getParent().getChildren();
            entitiesToSearch = Iterables.filter(entitiesToSearch, notSelfPredicate);
            break;
        case CHILD:
            entitiesToSearch = entity.getChildren();
            break;
        default:
            throw new IllegalStateException("Unexpected scope "+scope);
    }
    
    String desiredComponentId;
    if (componentId == null) {
        if (componentIdSupplier == null) {
            throw new IllegalArgumentException("No component-id or component-id supplier, when resolving entity in scope '" + scope + "' wrt " + entity);
        }
        
        Maybe<Object> maybeComponentId = Tasks.resolving(componentIdSupplier)
                .as(Object.class)
                .context(getExecutionContext())
                .immediately(immediate)
                .description("Resolving component-id from " + componentIdSupplier)
                .getMaybe();
        
        if (immediate) {
            if (maybeComponentId.isAbsent()) {
                return ImmediateValueNotAvailableException.newAbsentWrapping("Cannot find component ID", maybeComponentId);
            }
        }
        
        // Support being passed an explicit entity via the DSL
        if (maybeComponentId.get() instanceof BrooklynObject) {
            if (Iterables.contains(entitiesToSearch, maybeComponentId.get())) {
                return Maybe.of((Entity)maybeComponentId.get());
            } else {
                throw new IllegalStateException("Resolved component " + maybeComponentId.get() + " is not in scope '" + scope + "' wrt " + entity);
            }
        }
        
        desiredComponentId = TypeCoercions.coerce(maybeComponentId.get(), String.class);

        if (Strings.isBlank(desiredComponentId)) {
            throw new IllegalStateException("component-id blank, from " + componentIdSupplier);
        }
        
    } else {
        desiredComponentId = componentId;
    }
    
    Optional<Entity> result = Iterables.tryFind(entitiesToSearch, EntityPredicates.configEqualTo(BrooklynCampConstants.PLAN_ID, desiredComponentId));
    if (result.isPresent()) {
        return Maybe.of(result.get());
    }
    
    result = Iterables.tryFind(entitiesToSearch, EntityPredicates.idEqualTo(desiredComponentId));
    if (result.isPresent()) {
        return Maybe.of(result.get());
    }
    
    // could be nice if DSL has an extra .block() method to allow it to wait for a matching entity.
    // previously we threw if nothing existed; now we return an absent with a detailed error
    return Maybe.absent(new NoSuchElementException("No entity matching id " + desiredComponentId+
        (scope==Scope.GLOBAL ? "" : ", in scope "+scope+" wrt "+entity+
        (scopeComponent!=null ? " ("+scopeComponent+" from "+entity()+")" : ""))));
}
 
Example 13
Source File: MachinePoolPredicates.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public static Predicate<NodeMetadata> except(final Predicate<NodeMetadata> predicateToExclude) {
    return Predicates.not(predicateToExclude);
}
 
Example 14
Source File: ListTeamsCommand.java    From UHC with MIT License 4 votes vote down vote up
@Override
protected boolean runCommand(CommandSender sender, OptionSet options) {
    final int page = pageSpec.value(options);
    final boolean emptyOnly = options.has(emptyOnlySpec);
    final boolean showAll = options.has(showAllSpec);

    if (showAll && emptyOnly) {
        sender.sendMessage(ChatColor.RED + "You must provide -e OR -a, you cannot supply both");
        return true;
    }

    final Predicate<Team> predicate;
    final String type;

    if (emptyOnly) {
        type = "(empty teams)";
        predicate = Predicates.not(FunctionalUtil.TEAMS_WITH_PLAYERS);
    } else if (showAll) {
        type = "(all teams)";
        predicate = Predicates.alwaysTrue();
    } else {
        type = "(with players)";
        predicate = FunctionalUtil.TEAMS_WITH_PLAYERS;
    }

    final List<Team> teams = Lists.newArrayList(Iterables.filter(teamModule.getTeams().values(), predicate));

    if (teams.size() == 0) {
        sender.sendMessage(ChatColor.RED + "No results found for query " + type);
        return true;
    }

    final List<List<Team>> partitioned = Lists.partition(teams, COUNT_PER_PAGE);

    if (page > partitioned.size()) {
        sender.sendMessage(ChatColor.RED + "Page " + page + " does not exist");
        return true;
    }

    final List<Team> pageItems = partitioned.get(page - 1);

    final Map<String, Object> context = ImmutableMap.<String, Object>builder()
            .put("page", page)
            .put("pages", partitioned.size())
            .put("type", type)
            .put("count", pageItems.size())
            .put("teams", teams.size())
            .put("multiple", partitioned.size() > 1)
            .build();

    sender.sendMessage(messages.evalTemplate("header", context));

    final Joiner joiner = Joiner.on(", ");
    for (final Team team : pageItems) {
        final String memberString;
        final Set<OfflinePlayer> members = team.getPlayers();

        if (members.size() == 0) {
            memberString = NO_MEMBERS;
        } else {
            memberString = joiner.join(Iterables.transform(team.getPlayers(), FunctionalUtil.PLAYER_NAME_FETCHER));
        }

        sender.sendMessage(
                String.format(FORMAT, team.getPrefix() + team.getDisplayName(), team.getName(), memberString)
        );
    }

    return true;
}
 
Example 15
Source File: BaseRackIsolationPlacementRules.java    From libcrunch with Apache License 2.0 4 votes vote down vote up
/**
 * Use the predicate to reject already selected racks.
 */
private Predicate<Node> getRackPredicate(Set<Node> selectedRacks) {
  return Predicates.not(Predicates.in(selectedRacks));
}
 
Example 16
Source File: SwaggerConfig.java    From moon-api-gateway with MIT License 4 votes vote down vote up
private Predicate<String> paths() {
    return Predicates.not(PathSelectors.regex("/basic-error-controller.*"));
}
 
Example 17
Source File: ContentFolderScopes.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
public static Predicate<ContentFolderTypeProvider> all(final boolean withExclude) {
  return withExclude
         ? Predicates.<ContentFolderTypeProvider>alwaysTrue()
         : Predicates.not(Predicates.<ContentFolderTypeProvider>equalTo(ExcludedContentFolderTypeProvider.getInstance()));
}
 
Example 18
Source File: CrushRebalanceStrategy.java    From helix with Apache License 2.0 4 votes vote down vote up
/**
 * Use the predicate to reject already selected zones or nodes.
 */
private Predicate<Node> nodeAlreadySelected(Set<Node> selectedNodes) {
  return Predicates.not(Predicates.in(selectedNodes));
}
 
Example 19
Source File: MultiRoundCrushRebalanceStrategy.java    From helix with Apache License 2.0 4 votes vote down vote up
/**
 * Use the predicate to reject already selected zones or nodes.
 */
private Predicate<Node> nodeAlreadySelected(Set<Node> selectedNodes) {
  return Predicates.not(Predicates.in(selectedNodes));
}
 
Example 20
Source File: ProjectTypePredicate.java    From n4js with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Sugar for negating the predicate with type-safety.
 *
 * @param predicate
 *            the predicate to negate.
 * @return the negated predicate.
 */
public static ProjectTypePredicate not(ProjectTypePredicate predicate) {
	return new ProjectTypePredicate(Predicates.not(predicate));
}