Example usage for com.google.common.base Predicates alwaysTrue

List of usage examples for com.google.common.base Predicates alwaysTrue

Introduction

In this page you can find the example usage for com.google.common.base Predicates alwaysTrue.

Prototype

@GwtCompatible(serializable = true)
public static <T> Predicate<T> alwaysTrue() 

Source Link

Document

Returns a predicate that always evaluates to true .

Usage

From source file:brooklyn.enricher.basic.Propagator.java

@Override
public void setEntity(EntityLocal entity) {
    super.setEntity(entity);

    this.producer = getConfig(PRODUCER) == null ? entity : getConfig(PRODUCER);
    if (getConfig(PROPAGATING) != null) {
        if (Boolean.TRUE.equals(getConfig(PROPAGATING_ALL)) || getConfig(PROPAGATING_ALL_BUT) != null) {
            throw new IllegalStateException("Propagator enricher " + this
                    + " must not have 'propagating' set at same time as either 'propagatingAll' or 'propagatingAllBut'");
        }// w w w .j  a va  2s .  c  o  m

        Map<Sensor<?>, Sensor<?>> sensorMappingTemp = Maps.newLinkedHashMap();
        if (getConfig(SENSOR_MAPPING) != null) {
            sensorMappingTemp.putAll(getConfig(SENSOR_MAPPING));
        }
        for (Sensor<?> sensor : getConfig(PROPAGATING)) {
            if (!sensorMappingTemp.containsKey(sensor)) {
                sensorMappingTemp.put(sensor, sensor);
            }
        }
        this.sensorMapping = ImmutableMap.copyOf(sensorMappingTemp);
        this.propagatingAll = false;
        this.sensorFilter = new Predicate<Sensor<?>>() {
            @Override
            public boolean apply(Sensor<?> input) {
                return input != null && sensorMapping.keySet().contains(input);
            }
        };
    } else if (getConfig(PROPAGATING_ALL_BUT) == null) {
        this.sensorMapping = getConfig(SENSOR_MAPPING) == null ? ImmutableMap.<Sensor<?>, Sensor<?>>of()
                : getConfig(SENSOR_MAPPING);
        this.propagatingAll = Boolean.TRUE.equals(getConfig(PROPAGATING_ALL));
        this.sensorFilter = Predicates.alwaysTrue();
    } else {
        this.sensorMapping = getConfig(SENSOR_MAPPING) == null ? ImmutableMap.<Sensor<?>, Sensor<?>>of()
                : getConfig(SENSOR_MAPPING);
        this.propagatingAll = true;
        this.sensorFilter = new Predicate<Sensor<?>>() {
            @Override
            public boolean apply(Sensor<?> input) {
                Collection<Sensor<?>> exclusions = getConfig(PROPAGATING_ALL_BUT);
                return input != null && !exclusions.contains(input);
            }
        };
    }

    Preconditions.checkState(propagatingAll ^ sensorMapping.size() > 0,
            "Exactly one must be set of propagatingAll (%s, excluding %s), sensorMapping (%s)", propagatingAll,
            getConfig(PROPAGATING_ALL_BUT), sensorMapping);

    if (propagatingAll) {
        subscribe(producer, null, this);
    } else {
        for (Sensor<?> sensor : sensorMapping.keySet()) {
            subscribe(producer, sensor, this);
        }
    }

    emitAllAttributes();
}

From source file:clocker.docker.location.strategy.affinity.AffinityRules.java

private Predicate<Entity> predicate(String rule) {
    Preconditions.checkNotNull(rule, "rule");
    Queue<String> tokens = Queues
            .newArrayDeque(Splitter.on(CharMatcher.WHITESPACE).omitEmptyStrings().splitToList(rule));

    boolean same = true;
    Predicate<Entity> predicate = Predicates.alwaysTrue();

    // Check first token for special values
    String first = tokens.peek();
    if (first.equalsIgnoreCase(NOT)) {
        same = false;//from   w ww. ja  va 2  s.  c om
        tokens.remove();
    }

    // Check verb
    String verb = tokens.peek();
    if (verb == null) {
        throw new IllegalStateException("Affinity rule verb not specified: " + rule);
    } else {
        if (Iterables.contains(VERBS, verb.toUpperCase(Locale.ENGLISH))) {
            tokens.remove();
        } else {
            throw new IllegalStateException("Affinity rule parser found unexpected verb token: " + verb);
        }
    }

    // Check paramater and instantiate if required
    final String parameter = tokens.peek();
    if (parameter == null) {
        if (verb.equalsIgnoreCase(EMPTY)) {
            allowEmpty = same;
            tokens.remove();
            if (tokens.isEmpty()) {
                return predicate;
            } else {
                throw new IllegalStateException("Affinity rule has extra tokens: " + rule);
            }
        } else if (verb.equalsIgnoreCase(TYPE)) {
            predicate = new Predicate<Entity>() {
                @Override
                public boolean apply(@Nullable Entity input) {
                    return input.getEntityType().getName().equalsIgnoreCase(entity.getEntityType().getName())
                            || input.getEntityType().getSimpleName()
                                    .equalsIgnoreCase(entity.getEntityType().getSimpleName());
                }
            };
        } else if (verb.equalsIgnoreCase(ID)) {
            predicate = EntityPredicates.idEqualTo(entity.getId());
        } else if (verb.equalsIgnoreCase(APPLICATION)) {
            predicate = EntityPredicates.applicationIdEqualTo(entity.getApplicationId());
        } else {
            throw new IllegalStateException("Affinity rule parameter not specified: " + rule);
        }
    } else {
        tokens.remove();
        if (verb.equalsIgnoreCase(TYPE)) {
            predicate = new Predicate<Entity>() {
                @Override
                public boolean apply(@Nullable Entity input) {
                    return input.getEntityType().getName().equalsIgnoreCase(parameter)
                            || input.getEntityType().getSimpleName().equalsIgnoreCase(parameter);
                }
            };
        } else if (verb.equalsIgnoreCase(NAME)) {
            predicate = new Predicate<Entity>() {
                @Override
                public boolean apply(@Nullable Entity input) {
                    return input.getDisplayName().toLowerCase(Locale.ENGLISH)
                            .contains(parameter.toLowerCase(Locale.ENGLISH));
                }
            };
        } else if (verb.equalsIgnoreCase(ID)) {
            predicate = EntityPredicates.idEqualTo(parameter);
        } else if (verb.equalsIgnoreCase(APPLICATION)) {
            predicate = EntityPredicates.applicationIdEqualTo(parameter);
        } else if (verb.equalsIgnoreCase(PREDICATE)) {
            try {
                Class<?> clazz = Class.forName(parameter);
                if (Reflections.hasNoArgConstructor(clazz)) {
                    predicate = (Predicate<Entity>) Reflections.invokeConstructorWithArgs(clazz);
                } else {
                    throw new IllegalStateException("Could not instantiate predicate: " + parameter);
                }
            } catch (ClassNotFoundException e) {
                throw new IllegalStateException("Could not find predicate: " + parameter);
            }
        }
    }

    // Check for left-over tokens
    if (tokens.peek() != null) {
        throw new IllegalStateException("Affinity rule has extra tokens: " + rule);
    }

    // Create predicate and return
    if (same) {
        return predicate;
    } else {
        return Predicates.not(predicate);
    }
}

From source file:org.jclouds.vcloud.config.DefaultVCloudReferencesModule.java

@Provides
@Singleton
@org.jclouds.vcloud.endpoints.VDC
protected Predicate<ReferenceType> provideDefaultVDCSelector(Injector i) {
    return Predicates.alwaysTrue();
}

From source file:com.eucalyptus.util.Exceptions.java

private static Predicate<String> makeSteFilter(final List<String> patterns) {
    Predicate<String> filter = Predicates.alwaysTrue();
    for (String f : patterns) {
        filter = Predicates.or(filter, Predicates.containsPattern(f));
    }//w  w  w .ja  v a2s .  c  om
    return filter;
}

From source file:io.crate.analyze.CopyAnalyzer.java

private static Predicate<DiscoveryNode> discoveryNodePredicate(Row parameters,
        @Nullable Expression nodeFiltersExpression) {
    if (nodeFiltersExpression == null) {
        return Predicates.alwaysTrue();
    }// w ww.  j  a  v a2s .c o m
    Object nodeFiltersObj = ExpressionToObjectVisitor.convert(nodeFiltersExpression, parameters);
    try {
        return NodeFilters.fromMap((Map) nodeFiltersObj);
    } catch (ClassCastException e) {
        throw new IllegalArgumentException(String.format(Locale.ENGLISH,
                "Invalid parameter passed to %s. Expected an object with name or id keys and string values. Got '%s'",
                NodeFilters.NAME, nodeFiltersObj));
    }
}

From source file:com.google.devtools.build.android.dexer.DexFileSplitter.java

@VisibleForTesting
static void splitIntoShards(Options options) throws IOException {
    checkArgument(!options.minimalMainDex || options.mainDexListFile != null,
            "--minimal-main-dex not allowed without --main-dex-list");

    if (!Files.exists(options.outputDirectory)) {
        Files.createDirectories(options.outputDirectory);
    }/*from  ww w  .j a va  2 s  . c o  m*/

    ImmutableSet<String> classesInMainDex = options.mainDexListFile != null
            ? ImmutableSet.copyOf(Files.readAllLines(options.mainDexListFile, UTF_8))
            : null;
    try (Closer closer = Closer.create();
            DexFileSplitter out = new DexFileSplitter(options.outputDirectory, options.maxNumberOfIdxPerDex)) {
        // 1. Scan inputs in order and keep first occurrence of each class, keeping all zips open.
        // We don't process anything yet so we can shard in sorted order, which is what dx would do
        // if presented with a single jar containing all the given inputs.
        // TODO(kmb): Abandon alphabetic sorting to process each input fully before moving on (still
        // requires scanning inputs twice for main dex list).
        LinkedHashMap<String, ZipFile> deduped = new LinkedHashMap<>();
        for (Path inputArchive : options.inputArchives) {
            ZipFile zip = closer.register(new ZipFile(inputArchive.toFile()));
            zip.stream().filter(ZipEntryPredicates.suffixes(".dex", ".class"))
                    .forEach(e -> deduped.putIfAbsent(e.getName(), zip));
        }
        ImmutableList<Map.Entry<String, ZipFile>> files = deduped.entrySet().stream()
                .sorted(Comparator.comparing(e -> e.getKey(), ZipEntryComparator::compareClassNames))
                .collect(ImmutableList.toImmutableList());

        // 2. Process each class in desired order, rolling from shard to shard as needed.
        if (classesInMainDex == null || classesInMainDex.isEmpty()) {
            out.processDexFiles(files, Predicates.alwaysTrue());
        } else {
            // To honor --main_dex_list make two passes:
            // 1. process only the classes listed in the given file
            // 2. process the remaining files
            Predicate<String> mainDexFilter = ZipEntryPredicates.classFileNameFilter(classesInMainDex);
            out.processDexFiles(files, mainDexFilter);
            // Fail if main_dex_list is too big, following dx's example
            checkState(out.shardsWritten() == 0,
                    "Too many classes listed in main dex list file " + "%s, main dex capacity exceeded",
                    options.mainDexListFile);
            if (options.minimalMainDex) {
                out.nextShard(); // Start new .dex file if requested
            }
            out.processDexFiles(files, Predicates.not(mainDexFilter));
        }
    }
}

From source file:brooklyn.rest.resources.EntityConfigResource.java

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override/*from  w w w  . j a v  a  2s.c  o m*/
public void setFromMap(String application, String entityToken, Boolean recurse, Map newValues) {
    final EntityLocal entity = brooklyn().getEntity(application, entityToken);
    if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.MODIFY_ENTITY, entity)) {
        throw WebResourceUtils.unauthorized("User '%s' is not authorized to modify entity '%s'",
                Entitlements.getEntitlementContext().user(), entity);
    }

    if (LOG.isDebugEnabled())
        LOG.debug("REST user " + Entitlements.getEntitlementContext() + " setting configs " + newValues);
    for (Object entry : newValues.entrySet()) {
        String configName = Strings.toString(((Map.Entry) entry).getKey());
        Object newValue = ((Map.Entry) entry).getValue();

        ConfigKey ck = findConfig(entity, configName);
        ((EntityInternal) entity).setConfig(ck, TypeCoercions.coerce(newValue, ck.getTypeToken()));
        if (Boolean.TRUE.equals(recurse)) {
            for (Entity e2 : Entities.descendants(entity, Predicates.alwaysTrue(), false)) {
                ((EntityInternal) e2).setConfig(ck, newValue);
            }
        }
    }
}

From source file:brooklyn.enricher.basic.AbstractAggregator.java

@SuppressWarnings({ "unchecked" })
protected void setEntityLoadingConfig() {
    this.producer = getConfig(PRODUCER);
    this.fromHardcodedProducers = getConfig(FROM_HARDCODED_PRODUCERS);
    this.defaultMemberValue = (T) getConfig(DEFAULT_MEMBER_VALUE);
    this.fromMembers = Maybe.fromNullable(getConfig(FROM_MEMBERS)).or(fromMembers);
    this.fromChildren = Maybe.fromNullable(getConfig(FROM_CHILDREN)).or(fromChildren);
    this.entityFilter = (Predicate<? super Entity>) (getConfig(ENTITY_FILTER) == null ? Predicates.alwaysTrue()
            : getConfig(ENTITY_FILTER));
    this.valueFilter = (Predicate<? super T>) (getConfig(VALUE_FILTER) == null ? Predicates.alwaysTrue()
            : getConfig(VALUE_FILTER));/*from ww w  .j av a 2  s .c  o  m*/

    setEntityLoadingTargetConfig();
}

From source file:org.apache.brooklyn.core.network.OnPublicNetworkEnricher.java

@Override
public void setEntity(final EntityLocal entity) {
    super.setEntity(entity);

    /*//from w  w  w.ja  v a  2 s.  co  m
     * To find the transformed sensor value we need several things to be set. Therefore 
     * subscribe to all of them, and re-compute whenever any of the change. These are:
     *  - A port-mapping to exist for the relevant machine + private port.
     *  - The entity to have a machine location (so we can lookup the mapped port association).
     *  - The relevant sensors to have a value, which includes the private port.
     */
    pfmListener = new PortForwardManager.AssociationListener() {
        @Override
        public void onAssociationCreated(PortForwardManager.AssociationMetadata metadata) {
            Maybe<MachineLocation> machine = getMachine();
            if (!(machine.isPresent() && machine.get().equals(metadata.getLocation()))) {
                // not related to this entity's machine; ignoring
                return;
            }

            LOG.debug(
                    "{} attempting transformations, triggered by port-association {}, with machine {} of entity {}",
                    new Object[] { OnPublicNetworkEnricher.this, metadata, machine.get(), entity });
            tryTransformAll();
        }

        @Override
        public void onAssociationDeleted(PortForwardManager.AssociationMetadata metadata) {
            // no-op
        }
    };
    getPortForwardManager().addAssociationListener(pfmListener, Predicates.alwaysTrue());
}

From source file:com.eucalyptus.autoscaling.common.internal.groups.PersistenceAutoScalingGroups.java

@Override
public void markScalingRequiredForZones(final Set<String> availabilityZones)
        throws AutoScalingMetadataException {
    if (!availabilityZones.isEmpty()) {
        persistenceSupport.transactionWithRetry(AutoScalingGroup.class,
                new AbstractOwnedPersistents.WorkCallback<Void>() {
                    @Override/*w  ww . jav  a 2 s.com*/
                    public Void doWork() throws AutoScalingMetadataException {
                        final List<AutoScalingGroup> groups = persistenceSupport.listByExample(
                                AutoScalingGroup.withOwner(null), Predicates.alwaysTrue(),
                                Functions.<AutoScalingGroup>identity());
                        for (final AutoScalingGroup group : groups) {
                            if (!Sets.union(Sets.newHashSet(group.getAvailabilityZones()), availabilityZones)
                                    .isEmpty()) {
                                group.setScalingRequired(true);
                            }
                        }
                        return null;
                    }
                });
    }
}