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

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

Introduction

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

Prototype

public static <T> Predicate<T> equalTo(@Nullable T target) 

Source Link

Document

Returns a predicate that evaluates to true if the object being tested equals() the given target or both are null.

Usage

From source file:clocker.mesos.entity.framework.MesosFrameworkImpl.java

public List<String> scanTasks(JsonArray frameworks) {
    String frameworkId = sensors().get(FRAMEWORK_ID);
    Entity mesosCluster = sensors().get(MESOS_CLUSTER);
    LOG.debug("Periodic scanning of framework tasks: frameworkId={}, mesosCluster={}", frameworkId,
            mesosCluster);//  www  . j  a  v  a 2 s.c o  m

    for (int i = 0; i < frameworks.size(); i++) {
        JsonObject framework = frameworks.get(i).getAsJsonObject();
        if (frameworkId.equals(framework.get("id").getAsString())) {
            JsonArray completed = framework.getAsJsonArray("completed_tasks");
            JsonArray tasks = framework.getAsJsonArray("tasks");
            sensors().set(MESOS_COMPLETED_TASKS, completed.size());
            sensors().set(MESOS_RUNNING_TASKS, tasks.size());

            List<String> taskNames = MutableList.<String>of();
            for (int j = 0; j < tasks.size(); j++) {
                JsonObject json = tasks.get(j).getAsJsonObject();
                String id = json.get("id").getAsString();
                String name = json.get("name").getAsString();
                String state = json.get("state").getAsString();

                Optional<Entity> taskEntity = Iterables.tryFind(sensors().get(FRAMEWORK_TASKS).getMembers(),
                        Predicates.compose(Predicates.equalTo(id),
                                EntityFunctions.attribute(MesosTask.TASK_ID)));
                MesosTask task = null;
                if (taskEntity.isPresent()) {
                    // Only interested in tasks for our own use of Marathon.
                    // Tasks that other people create we'll ignore.
                    task = (MesosTask) taskEntity.get();
                }
                if (task != null) {
                    taskNames.add(name);
                    task.sensors().set(MesosTask.TASK_ID, id);
                    task.sensors().set(MesosTask.TASK_STATE, state);
                }
            }

            Set<String> taskNamesSet = Sets.newHashSet(taskNames);
            for (Entity member : ImmutableList.copyOf(getTaskCluster().getMembers())) {
                final String name = member.sensors().get(MesosTask.TASK_NAME);
                if (name != null) {
                    boolean found = taskNamesSet.contains(name);
                    if (found)
                        continue;
                }

                // Stop and then remove the task as it is no longer running, unless ON_FIRE
                //
                // TODO Aled worries about this: if task has gone, then MarathonTask polling
                // the task's URL will fail, setting the serviceUp to false, setting it 
                // on-fire. What will ever remove the task on a graceful shutdown of a container?
                // Or is that handled elsewhere?
                Lifecycle state = member.sensors().get(Attributes.SERVICE_STATE_ACTUAL);
                if (Lifecycle.ON_FIRE.equals(state) || Lifecycle.STARTING.equals(state)) {
                    continue;
                } else if (Lifecycle.STOPPING.equals(state) || Lifecycle.STOPPED.equals(state)) {
                    getTaskCluster().removeMember(member);
                    getTaskCluster().removeChild(member);
                    Entities.unmanage(member);
                } else {
                    ServiceStateLogic.setExpectedState(member, Lifecycle.STOPPING);
                }
            }
            return taskNames;
        }
    }
    // not found
    return null;
}

From source file:com.google.devtools.build.lib.rules.cpp.CppCompileActionBuilder.java

private Iterable<IncludeScannable> getLipoScannables(NestedSet<Artifact> realMandatoryInputs) {
    return lipoScannableMap == null ? ImmutableList.<IncludeScannable>of()
            : Iterables.filter(Iterables.transform(
                    Iterables.filter(/* w  w w . j  a v  a2  s.  c om*/
                            FileType.filter(realMandatoryInputs, CppFileTypes.C_SOURCE, CppFileTypes.CPP_SOURCE,
                                    CppFileTypes.ASSEMBLER_WITH_C_PREPROCESSOR),
                            Predicates.not(Predicates.equalTo(getSourceFile()))),
                    Functions.forMap(lipoScannableMap, null)), Predicates.notNull());
}

From source file:org.obeonetwork.m2doc.generator.TableClientProcessor.java

/**
 * Fill a newly created word table with the data from an MTable.
 * /*from   w ww .ja v  a2s . c  o  m*/
 * @param table
 *            The newly created word table
 * @param mtable
 *            The MTable that describes the data and styles to insert
 */
private void fillTable(XWPFTable table, MTable mtable) {
    XWPFTableRow headerRow = table.getRow(0);
    initializeEmptyTableCell(headerRow.getCell(0), null, null);
    Iterable<? extends MColumn> mcolumns = mtable.getColumns();
    for (MColumn mcol : mcolumns) {
        XWPFTableCell cell;
        cell = headerRow.addNewTableCell();
        initializeEmptyTableCell(cell, null, null);
        setCellContent(cell, mcol.getLabel(), null);
    }
    for (MRow mrow : mtable.getRows()) {
        XWPFTableRow row = table.createRow();
        List<XWPFTableCell> cells = row.getTableCells();
        for (int i = 0; i < cells.size(); i++) {
            XWPFTableCell cell = cells.get(i);
            // Make sure empty cells are empty and have the right style
            if (i > 0) {
                initializeEmptyTableCell(cell, mrow, Iterables.get(mtable.getColumns(), i - 1));
            } else {
                initializeEmptyTableCell(cell, null, null);
            }
        }
        XWPFTableCell cell0 = row.getCell(0);
        setCellContent(cell0, mrow.getLabel(), null);
        for (MCell mcell : mrow.getCells()) {
            MColumn mcol = mcell.getColumn();
            if (mcol != null) {
                XWPFTableCell cell = row.getCell(Iterables.indexOf(mcolumns, Predicates.equalTo(mcol)) + 1);
                setCellContent(cell, mcell.getLabel(), mcell.getStyle());
            }
        }
    }
}

From source file:brooklyn.entity.brooklynnode.effector.BrooklynNodeUpgradeEffectorBody.java

private String dryRunUpdate(ConfigBag parameters) {
    // TODO require entity() node state master or hot standby AND require persistence enabled, or a new 'force_attempt_upgrade' parameter to be applied
    // TODO could have a 'skip_dry_run_upgrade' parameter
    // TODO could support 'dry_run_only' parameter, with optional resumption tasks (eg new dynamic effector)

    // 1 add new brooklyn version entity as child (so uses same machine), with same config apart from things in parameters
    final Entity dryRunChild = entity().addChild(createDryRunSpec().displayName("Upgraded Version Dry-Run Node")
            // install dir and label are recomputed because they are not inherited, and download_url will normally be different
            .configure(parameters.getAllConfig()));

    //force this to start as hot-standby
    // TODO alternatively could use REST API as in BrooklynClusterUpgradeEffectorBody
    String launchParameters = dryRunChild.getConfig(BrooklynNode.EXTRA_LAUNCH_PARAMETERS);
    if (Strings.isBlank(launchParameters))
        launchParameters = "";
    else//from   w w  w  .  ja v  a  2s .c o  m
        launchParameters += " ";
    launchParameters += "--highAvailability " + HighAvailabilityMode.HOT_STANDBY;
    ((EntityInternal) dryRunChild).setConfig(BrooklynNode.EXTRA_LAUNCH_PARAMETERS, launchParameters);

    Entities.manage(dryRunChild);
    final String dryRunNodeUid = dryRunChild.getId();
    ((EntityInternal) dryRunChild).setDisplayName("Dry-Run Upgraded Brooklyn Node (" + dryRunNodeUid + ")");

    DynamicTasks.queue(Effectors.invocation(dryRunChild, BrooklynNode.START, ConfigBag.EMPTY));

    // 2 confirm hot standby status
    DynamicTasks.queue(EntityTasks.requiringAttributeEventually(dryRunChild, BrooklynNode.MANAGEMENT_NODE_STATE,
            Predicates.equalTo(ManagementNodeState.HOT_STANDBY), Duration.FIVE_MINUTES));

    // 3 stop new version
    DynamicTasks.queue(Tasks.builder().name("shutdown transient node")
            .add(Effectors.invocation(dryRunChild, BrooklynNode.STOP_NODE_BUT_LEAVE_APPS,
                    ImmutableMap.of(StopSoftwareParameters.STOP_MACHINE, Boolean.FALSE)))
            .build());

    DynamicTasks.queue(Tasks.<Void>builder().name("remove transient node").body(new Runnable() {
        @Override
        public void run() {
            Entities.unmanage(dryRunChild);
        }
    }).build());

    return dryRunChild.getId();
}

From source file:org.apache.druid.cli.CliCoordinator.java

@Override
protected List<? extends Module> getModules() {
    List<Module> modules = new ArrayList<>();

    modules.add(JettyHttpClientModule.global());

    modules.add(new Module() {
        @Override//  ww  w  . j  a va2 s . c  om
        public void configure(Binder binder) {
            binder.bindConstant().annotatedWith(Names.named("serviceName"))
                    .to(TieredBrokerConfig.DEFAULT_COORDINATOR_SERVICE_NAME);
            binder.bindConstant().annotatedWith(Names.named("servicePort")).to(8081);
            binder.bindConstant().annotatedWith(Names.named("tlsServicePort")).to(8281);

            ConfigProvider.bind(binder, DruidCoordinatorConfig.class);

            binder.bind(MetadataStorage.class).toProvider(MetadataStorageProvider.class);

            JsonConfigProvider.bind(binder, "druid.manager.segments", MetadataSegmentManagerConfig.class);
            JsonConfigProvider.bind(binder, "druid.manager.rules", MetadataRuleManagerConfig.class);
            JsonConfigProvider.bind(binder, "druid.manager.lookups", LookupCoordinatorManagerConfig.class);
            JsonConfigProvider.bind(binder, "druid.coordinator.balancer", BalancerStrategyFactory.class);

            binder.bind(RedirectFilter.class).in(LazySingleton.class);
            if (beOverlord) {
                binder.bind(RedirectInfo.class).to(CoordinatorOverlordRedirectInfo.class)
                        .in(LazySingleton.class);
            } else {
                binder.bind(RedirectInfo.class).to(CoordinatorRedirectInfo.class).in(LazySingleton.class);
            }

            binder.bind(MetadataSegmentManager.class).toProvider(MetadataSegmentManagerProvider.class)
                    .in(ManageLifecycle.class);

            binder.bind(MetadataRuleManager.class).toProvider(MetadataRuleManagerProvider.class)
                    .in(ManageLifecycle.class);

            binder.bind(AuditManager.class).toProvider(AuditManagerProvider.class).in(ManageLifecycle.class);

            binder.bind(IndexingServiceClient.class).to(HttpIndexingServiceClient.class)
                    .in(LazySingleton.class);
            binder.bind(CoordinatorServerView.class).in(LazySingleton.class);

            binder.bind(LookupCoordinatorManager.class).in(LazySingleton.class);
            binder.bind(DruidCoordinator.class);

            LifecycleModule.register(binder, MetadataStorage.class);
            LifecycleModule.register(binder, DruidCoordinator.class);

            binder.bind(JettyServerInitializer.class).to(CoordinatorJettyServerInitializer.class);

            Jerseys.addResource(binder, CoordinatorResource.class);
            Jerseys.addResource(binder, CoordinatorDynamicConfigsResource.class);
            Jerseys.addResource(binder, CoordinatorCompactionConfigsResource.class);
            Jerseys.addResource(binder, TiersResource.class);
            Jerseys.addResource(binder, RulesResource.class);
            Jerseys.addResource(binder, ServersResource.class);
            Jerseys.addResource(binder, DatasourcesResource.class);
            Jerseys.addResource(binder, MetadataResource.class);
            Jerseys.addResource(binder, IntervalsResource.class);
            Jerseys.addResource(binder, LookupCoordinatorResource.class);
            Jerseys.addResource(binder, ClusterResource.class);
            Jerseys.addResource(binder, HttpServerInventoryViewResource.class);

            LifecycleModule.register(binder, Server.class);
            LifecycleModule.register(binder, DatasourcesResource.class);

            ConditionalMultibind
                    .create(properties, binder, DruidCoordinatorHelper.class,
                            CoordinatorIndexingServiceHelper.class)
                    .addConditionBinding("druid.coordinator.merge.on", Predicates.equalTo("true"),
                            DruidCoordinatorSegmentMerger.class)
                    .addConditionBinding("druid.coordinator.kill.on", Predicates.equalTo("true"),
                            DruidCoordinatorSegmentKiller.class)
                    .addConditionBinding("druid.coordinator.kill.pendingSegments.on",
                            Predicates.equalTo("true"), DruidCoordinatorCleanupPendingSegments.class);

            binder.bind(DiscoverySideEffectsProvider.Child.class).annotatedWith(Coordinator.class)
                    .toProvider(new DiscoverySideEffectsProvider(
                            DruidNodeDiscoveryProvider.NODE_TYPE_COORDINATOR, ImmutableList.of()))
                    .in(LazySingleton.class);
            LifecycleModule.registerKey(binder,
                    Key.get(DiscoverySideEffectsProvider.Child.class, Coordinator.class));
        }

        @Provides
        @LazySingleton
        public LoadQueueTaskMaster getLoadQueueTaskMaster(CuratorFramework curator, ObjectMapper jsonMapper,
                ScheduledExecutorFactory factory, DruidCoordinatorConfig config,
                @EscalatedGlobal HttpClient httpClient, ZkPathsConfig zkPaths) {
            return new LoadQueueTaskMaster(curator, jsonMapper, factory.create(1, "Master-PeonExec--%d"),
                    Executors.newSingleThreadExecutor(), config, httpClient, zkPaths);
        }
    });

    if (beOverlord) {
        modules.addAll(new CliOverlord().getModules(false));
    }

    return modules;
}

From source file:org.apache.brooklyn.entity.brooklynnode.effector.BrooklynClusterUpgradeEffectorBody.java

protected Collection<Entity> createNodes(int nodeCnt) {
    DynamicCluster cluster = (DynamicCluster) entity();

    //1. Create the nodes
    Collection<Entity> newNodes = cluster.resizeByDelta(nodeCnt);

    //2. Wait for them to be RUNNING (or at least STARTING to have completed)
    // (should already be the case, because above is synchronous and, we think, it will fail if start does not succeed)
    DynamicTasks.queue(EntityTasks.requiringAttributeEventually(newNodes, Attributes.SERVICE_STATE_ACTUAL,
            Predicates.not(Predicates.equalTo(Lifecycle.STARTING)), Duration.minutes(30)));

    //3. Set HOT_STANDBY in case it is not enabled on the command line ...
    // TODO support via EntitySpec
    DynamicTasks.queue(Effectors.invocation(BrooklynNode.SET_HIGH_AVAILABILITY_MODE,
            MutableMap.of(SetHighAvailabilityModeEffector.MODE, HighAvailabilityMode.HOT_STANDBY), newNodes))
            .asTask().getUnchecked();//from  w  ww.  j a  v a 2  s.c o m
    //... and wait until all of the nodes change state
    // TODO fail quicker if state changes to FAILED
    DynamicTasks.queue(EntityTasks.requiringAttributeEventually(newNodes, BrooklynNode.MANAGEMENT_NODE_STATE,
            Predicates.equalTo(ManagementNodeState.HOT_STANDBY), Duration.FIVE_MINUTES));

    // TODO also check that the nodes created all report the original master, in case persistence changes it

    //5. Just in case check if all of the nodes are SERVICE_UP (which would rule out ON_FIRE as well)
    Collection<Entity> failedNodes = Collections2.filter(newNodes,
            EntityPredicates.attributeEqualTo(BrooklynNode.SERVICE_UP, Boolean.FALSE));
    if (!failedNodes.isEmpty()) {
        throw new IllegalStateException("Nodes " + failedNodes + " are not " + BrooklynNode.SERVICE_UP
                + " though successfully in " + ManagementNodeState.HOT_STANDBY);
    }
    return newNodes;
}

From source file:com.eucalyptus.reporting.ReportingDataVerifier.java

private static Predicate<ResourceWithRelation<?>> withKeyMatching(final ResourceKey key) {
    return Predicates.compose(Predicates.equalTo(key), key());
}

From source file:org.apache.brooklyn.entity.nosql.riak.RiakClusterImpl.java

protected void onServerPoolMemberChanged(final Entity member) {
    synchronized (mutex) {
        log.trace("For {}, considering membership of {} which is in locations {}",
                new Object[] { this, member, member.getLocations() });

        Map<Entity, String> nodes = getAttribute(RIAK_CLUSTER_NODES);
        if (belongsInServerPool(member)) {
            // TODO can we discover the nodes by asking the riak cluster, rather than assuming what we add will be in there?
            // TODO and can we do join as part of node starting?

            if (nodes == null) {
                nodes = Maps.newLinkedHashMap();
            }/* w  w  w. ja  v a 2s. c o  m*/
            String riakName = getRiakName(member);
            Preconditions.checkNotNull(riakName);

            // flag a first node to be the first node in the riak cluster.
            Boolean firstNode = getAttribute(IS_FIRST_NODE_SET);
            if (!Boolean.TRUE.equals(firstNode)) {
                sensors().set(IS_FIRST_NODE_SET, Boolean.TRUE);

                nodes.put(member, riakName);
                sensors().set(RIAK_CLUSTER_NODES, nodes);

                ((EntityInternal) member).sensors().set(RiakNode.RIAK_NODE_HAS_JOINED_CLUSTER, Boolean.TRUE);

                log.info("Added initial Riak node {}: {}; {} to new cluster",
                        new Object[] { this, member, getRiakName(member) });
            } else {
                // TODO: be wary of erroneous nodes but are still flagged 'in cluster'
                // add the new node to be part of the riak cluster.
                Optional<Entity> anyNodeInCluster = Iterables.tryFind(nodes.keySet(), Predicates.and(
                        Predicates.instanceOf(RiakNode.class),
                        EntityPredicates.attributeEqualTo(RiakNode.RIAK_NODE_HAS_JOINED_CLUSTER, true)));
                if (anyNodeInCluster.isPresent()) {
                    if (!nodes.containsKey(member)
                            && member.getAttribute(RiakNode.RIAK_NODE_HAS_JOINED_CLUSTER) == null) {
                        String anyNodeName = anyNodeInCluster.get().getAttribute(RiakNode.RIAK_NODE_NAME);
                        Entities.invokeEffectorWithArgs(this, member, RiakNode.JOIN_RIAK_CLUSTER, anyNodeName)
                                .blockUntilEnded();
                        nodes.put(member, riakName);
                        sensors().set(RIAK_CLUSTER_NODES, nodes);
                        log.info("Added Riak node {}: {}; {} to cluster",
                                new Object[] { this, member, getRiakName(member) });
                    }
                } else {
                    log.error("isFirstNodeSet, but no cluster members found to add {}", member.getId());
                }
            }
        } else {
            if (nodes != null && nodes.containsKey(member)) {
                DependentConfiguration.attributeWhenReady(member, RiakNode.RIAK_NODE_HAS_JOINED_CLUSTER,
                        Predicates.equalTo(false)).blockUntilEnded(Duration.TWO_MINUTES);
                @SuppressWarnings("unchecked")
                Optional<Entity> anyNodeInCluster = Iterables.tryFind(nodes.keySet(),
                        Predicates.and(Predicates.instanceOf(RiakNode.class),
                                EntityPredicates.attributeEqualTo(RiakNode.RIAK_NODE_HAS_JOINED_CLUSTER, true),
                                Predicates.not(Predicates.equalTo(member))));
                if (anyNodeInCluster.isPresent()) {
                    Entities.invokeEffectorWithArgs(this, anyNodeInCluster.get(), RiakNode.REMOVE_FROM_CLUSTER,
                            getRiakName(member)).blockUntilEnded();
                }
                nodes.remove(member);
                sensors().set(RIAK_CLUSTER_NODES, nodes);
                log.info("Removed Riak node {}: {}; {} from cluster",
                        new Object[] { this, member, getRiakName(member) });
            }
        }

        ServiceNotUpLogic.updateNotUpIndicatorRequiringNonEmptyMap(this, RIAK_CLUSTER_NODES);

        calculateClusterAddresses();
    }
}

From source file:org.apache.brooklyn.core.catalog.internal.BasicBrooklynCatalog.java

/** returns best version, as defined by {@link BrooklynCatalog#getCatalogItem(String, String)} */
private String getBestVersion(String symbolicName) {
    Iterable<CatalogItem<Object, Object>> versions = getCatalogItems(
            Predicates.and(CatalogPredicates.disabled(false),
                    CatalogPredicates.symbolicName(Predicates.equalTo(symbolicName))));
    Collection<CatalogItem<Object, Object>> orderedVersions = sortVersionsDesc(versions);
    if (!orderedVersions.isEmpty()) {
        return orderedVersions.iterator().next().getVersion();
    } else {/*from  w  w  w  .ja v a 2  s .c om*/
        return null;
    }
}

From source file:com.facebook.buck.android.AndroidResource.java

@Override
public Sha1HashCode getAbiKeyForDeps() {
    // We hash the transitive dependencies and not just the first order deps because we pass these
    // to aapt to generate R.java/R.txt.
    // Transitive dependencies includes this rule itself; filter it out.
    return HasAndroidResourceDeps.ABI_HASHER.apply(Iterables.filter(transitiveAndroidResourceDeps.get(),
            Predicates.not(Predicates.equalTo((HasAndroidResourceDeps) AndroidResource.this))));
}