Example usage for com.google.common.collect Iterables contains

List of usage examples for com.google.common.collect Iterables contains

Introduction

In this page you can find the example usage for com.google.common.collect Iterables contains.

Prototype

public static boolean contains(Iterable<?> iterable, @Nullable Object element) 

Source Link

Document

Returns true if iterable contains any object for which equals(element) is true.

Usage

From source file:brooklyn.util.task.BasicExecutionContext.java

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override//www.j a va 2s.co  m
protected <T> Task<T> submitInternal(Map<?, ?> propertiesQ, final Object task) {
    if (task instanceof TaskAdaptable<?> && !(task instanceof Task<?>))
        return submitInternal(propertiesQ, ((TaskAdaptable<?>) task).asTask());

    Map properties = propertiesQ;
    if (properties.get("tags") == null)
        properties.put("tags", new ArrayList());
    Collection taskTags = (Collection) properties.get("tags");

    // FIXME some of this is brooklyn-specific logic, should be moved to a BrooklynExecContext subclass;
    // the issue is that we want to ensure that cross-entity calls switch execution contexts;
    // previously it was all very messy how that was handled (and it didn't really handle it in many cases)
    if (task instanceof Task<?>)
        taskTags.addAll(((Task<?>) task).getTags());
    Entity target = BrooklynTaskTags.getWrappedEntityOfType(taskTags, BrooklynTaskTags.TARGET_ENTITY);

    if (target != null && !tags.contains(BrooklynTaskTags.tagForContextEntity(target))) {
        // task is switching execution context boundaries
        /* 
         * longer notes:
         * you fall in to this block if the caller requests a target entity different to the current context 
         * (e.g. where entity X is invoking an effector on Y, it will start in X's context, 
         * but the effector should run in Y's context).
         * 
         * if X is invoking an effector on himself in his own context, or a sensor or other task, it will not come in to this block.
         */
        final ExecutionContext tc = ((EntityInternal) target).getExecutionContext();
        if (log.isDebugEnabled())
            log.debug("Switching task context on execution of " + task + ": from " + this + " to " + target
                    + " (in " + Tasks.current() + ")");

        if (task instanceof Task<?>) {
            final Task<T> t = (Task<T>) task;
            if (!Tasks.isQueuedOrSubmitted(t) && (!(Tasks.current() instanceof HasTaskChildren)
                    || !Iterables.contains(((HasTaskChildren) Tasks.current()).getChildren(), t))) {
                // this task is switching execution context boundaries _and_ it is not a child and not yet queued,
                // so wrap it in a task running in this context to keep a reference to the child
                // (this matters when we are navigating in the GUI; without it we lose the reference to the child 
                // when browsing in the context of the parent)
                return submit(Tasks.<T>builder().name("Cross-context execution: " + t.getDescription())
                        .dynamic(true).body(new Callable<T>() {
                            public T call() {
                                return DynamicTasks.get(t);
                            }
                        }).build());
            } else {
                // if we are already tracked by parent, just submit it 
                return tc.submit(t);
            }
        } else {
            // as above, but here we are definitely not a child (what we are submitting isn't even a task)
            // (will only come here if properties defines tags including a target entity, which probably never happens) 
            submit(Tasks.<T>builder().name("Cross-context execution").dynamic(true).body(new Callable<T>() {
                public T call() {
                    if (task instanceof Callable) {
                        return DynamicTasks
                                .queue(Tasks.<T>builder().dynamic(false).body((Callable<T>) task).build())
                                .getUnchecked();
                    } else if (task instanceof Runnable) {
                        return DynamicTasks
                                .queue(Tasks.<T>builder().dynamic(false).body((Runnable) task).build())
                                .getUnchecked();
                    } else {
                        throw new IllegalArgumentException("Unhandled task type: " + task + "; type="
                                + (task != null ? task.getClass() : "null"));
                    }
                }
            }).build());
        }
    }

    EntitlementContext entitlementContext = BrooklynTaskTags.getEntitlement(taskTags);
    if (entitlementContext == null)
        entitlementContext = Entitlements.getEntitlementContext();
    if (entitlementContext != null) {
        taskTags.add(BrooklynTaskTags.tagForEntitlement(entitlementContext));
    }

    taskTags.addAll(tags);

    final Object startCallback = properties.get("newTaskStartCallback");
    properties.put("newTaskStartCallback", new Function<Object, Void>() {
        public Void apply(Object it) {
            registerPerThreadExecutionContext();
            if (startCallback != null)
                ExecutionUtils.invoke(startCallback, it);
            return null;
        }
    });

    final Object endCallback = properties.get("newTaskEndCallback");
    properties.put("newTaskEndCallback", new Function<Object, Void>() {
        public Void apply(Object it) {
            try {
                if (endCallback != null)
                    ExecutionUtils.invoke(endCallback, it);
            } finally {
                clearPerThreadExecutionContext();
            }
            return null;
        }
    });

    if (task instanceof Task) {
        return executionManager.submit(properties, (Task) task);
    } else if (task instanceof Callable) {
        return executionManager.submit(properties, (Callable) task);
    } else if (task instanceof Runnable) {
        return (Task<T>) executionManager.submit(properties, (Runnable) task);
    } else {
        throw new IllegalArgumentException(
                "Unhandled task type: task=" + task + "; type=" + (task != null ? task.getClass() : "null"));
    }
}

From source file:com.synflow.cx.internal.instantiation.properties.InstancePropertiesChecker.java

/**
 * Validates the given clocks object./*from w w  w  .  ja  v a 2  s  . c o  m*/
 * 
 * @param clocks
 *            a clocks object
 * @param parentClocks
 *            a list of parent clocks
 * @param entityClocks
 *            a list of entity clocks
 */
private void validateClocks(JsonObject clocks, JsonArray parentClocks, JsonArray entityClocks) {
    int size = entityClocks.size();
    int got = 0;

    Iterator<JsonElement> it = entityClocks.iterator();
    for (Entry<String, JsonElement> pair : clocks.entrySet()) {
        String clockName = pair.getKey();
        if (NO_CLOCK.equals(clockName)) {
            // no more clocks after this one => mismatch in number of clocks
            got = clocks.entrySet().size();
            break;
        }

        if (!it.hasNext()) {
            // no more entity clocks => mismatch in number of clocks
            break;
        }

        // check we use a valid entity clock name
        String expected = it.next().getAsString();
        if (!clockName.equals(expected)) {
            handler.addError(clocks,
                    "given clock name '" + clockName + "' does not match entity's clock '" + expected + "'");
        }

        // check value
        JsonElement value = pair.getValue();
        if (value.isJsonPrimitive() && value.getAsJsonPrimitive().isString()) {
            got++;
            if (!Iterables.contains(parentClocks, value)) {
                handler.addError(value, "given clock name '" + value.getAsString()
                        + "' does not appear in parent's clocks " + parentClocks);
            }
        } else {
            handler.addError(value, "invalid clock value: " + value.toString());
        }
    }

    if (got < size) {
        String msg = "not enough clocks given, expected " + size + " clocks, got " + got;
        handler.addError(clocks, msg);
    } else if (got > size) {
        String msg = "too many clocks given, expected " + size + " clocks, got " + got;
        handler.addError(clocks, msg);
    }
}

From source file:org.apache.brooklyn.core.mgmt.persist.BrooklynMementoPersisterTestFixture.java

@Test
public void testCheckPointAndLoadMemento() throws Exception {
    BrooklynMemento reloadedMemento = loadMemento();

    assertNotNull(reloadedMemento);/*from w  w  w . j  a v  a  2 s .  c om*/
    assertTrue(Iterables.contains(reloadedMemento.getEntityIds(), entity.getId()));
    assertEquals(Iterables.getOnlyElement(reloadedMemento.getLocationIds()), location.getId());
    assertEquals(Iterables.getOnlyElement(reloadedMemento.getPolicyIds()), policy.getId());
    assertTrue(reloadedMemento.getEnricherIds().contains(enricher.getId()));
}

From source file:org.immutables.sequence.Sequence.java

/**
 * Returns {@code true} if this fluent iterable contains any object for which
 * {@code equals(element)} is true./* w w  w  .  j  ava  2  s.  com*/
 * @param element the element
 * @return true, if successful
 */
public final boolean contains(@Nullable Object element) {
    return Iterables.contains(iterable, element);
}

From source file:org.apache.brooklyn.util.core.task.BasicExecutionContext.java

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override/*from   www.  j  a v a  2s  .co m*/
protected <T> Task<T> submitInternal(Map<?, ?> propertiesQ, final Object task) {
    if (task instanceof TaskAdaptable<?> && !(task instanceof Task<?>))
        return submitInternal(propertiesQ, ((TaskAdaptable<?>) task).asTask());

    Map properties = propertiesQ;
    if (properties.get("tags") == null)
        properties.put("tags", new ArrayList());
    Collection taskTags = (Collection) properties.get("tags");

    // FIXME some of this is brooklyn-specific logic, should be moved to a BrooklynExecContext subclass;
    // the issue is that we want to ensure that cross-entity calls switch execution contexts;
    // previously it was all very messy how that was handled (and it didn't really handle it in many cases)
    if (task instanceof Task<?>)
        taskTags.addAll(((Task<?>) task).getTags());
    Entity target = BrooklynTaskTags.getWrappedEntityOfType(taskTags, BrooklynTaskTags.TARGET_ENTITY);

    if (target != null && !tags.contains(BrooklynTaskTags.tagForContextEntity(target))) {
        // task is switching execution context boundaries
        /* 
         * longer notes:
         * you fall in to this block if the caller requests a target entity different to the current context 
         * (e.g. where entity X is invoking an effector on Y, it will start in X's context, 
         * but the effector should run in Y's context).
         * 
         * if X is invoking an effector on himself in his own context, or a sensor or other task, it will not come in to this block.
         */
        final ExecutionContext tc = ((EntityInternal) target).getExecutionContext();
        if (log.isDebugEnabled())
            log.debug("Switching task context on execution of " + task + ": from " + this + " to " + target
                    + " (in " + Tasks.current() + ")");

        if (task instanceof Task<?>) {
            final Task<T> t = (Task<T>) task;
            if (!Tasks.isQueuedOrSubmitted(t) && (!(Tasks.current() instanceof HasTaskChildren)
                    || !Iterables.contains(((HasTaskChildren) Tasks.current()).getChildren(), t))) {
                // this task is switching execution context boundaries _and_ it is not a child and not yet queued,
                // so wrap it in a task running in this context to keep a reference to the child
                // (this matters when we are navigating in the GUI; without it we lose the reference to the child 
                // when browsing in the context of the parent)
                return submit(Tasks.<T>builder().displayName("Cross-context execution: " + t.getDescription())
                        .dynamic(true).body(new Callable<T>() {
                            public T call() {
                                return DynamicTasks.get(t);
                            }
                        }).build());
            } else {
                // if we are already tracked by parent, just submit it 
                return tc.submit(t);
            }
        } else {
            // as above, but here we are definitely not a child (what we are submitting isn't even a task)
            // (will only come here if properties defines tags including a target entity, which probably never happens) 
            submit(Tasks.<T>builder().displayName("Cross-context execution").dynamic(true)
                    .body(new Callable<T>() {
                        public T call() {
                            if (task instanceof Callable) {
                                return DynamicTasks.queue(
                                        Tasks.<T>builder().dynamic(false).body((Callable<T>) task).build())
                                        .getUnchecked();
                            } else if (task instanceof Runnable) {
                                return DynamicTasks
                                        .queue(Tasks.<T>builder().dynamic(false).body((Runnable) task).build())
                                        .getUnchecked();
                            } else {
                                throw new IllegalArgumentException("Unhandled task type: " + task + "; type="
                                        + (task != null ? task.getClass() : "null"));
                            }
                        }
                    }).build());
        }
    }

    EntitlementContext entitlementContext = BrooklynTaskTags.getEntitlement(taskTags);
    if (entitlementContext == null)
        entitlementContext = Entitlements.getEntitlementContext();
    if (entitlementContext != null) {
        taskTags.add(BrooklynTaskTags.tagForEntitlement(entitlementContext));
    }

    taskTags.addAll(tags);

    if (Tasks.current() != null && BrooklynTaskTags.isTransient(Tasks.current())
            && !taskTags.contains(BrooklynTaskTags.NON_TRANSIENT_TASK_TAG)
            && !taskTags.contains(BrooklynTaskTags.TRANSIENT_TASK_TAG)) {
        // tag as transient if submitter is transient, unless explicitly tagged as non-transient
        taskTags.add(BrooklynTaskTags.TRANSIENT_TASK_TAG);
    }

    final Object startCallback = properties.get("newTaskStartCallback");
    properties.put("newTaskStartCallback", new Function<Task<?>, Void>() {
        public Void apply(Task<?> it) {
            registerPerThreadExecutionContext();
            if (startCallback != null)
                BasicExecutionManager.invokeCallback(startCallback, it);
            return null;
        }
    });

    final Object endCallback = properties.get("newTaskEndCallback");
    properties.put("newTaskEndCallback", new Function<Task<?>, Void>() {
        public Void apply(Task<?> it) {
            try {
                if (endCallback != null)
                    BasicExecutionManager.invokeCallback(endCallback, it);
            } finally {
                clearPerThreadExecutionContext();
            }
            return null;
        }
    });

    if (task instanceof Task) {
        return executionManager.submit(properties, (Task) task);
    } else if (task instanceof Callable) {
        return executionManager.submit(properties, (Callable) task);
    } else if (task instanceof Runnable) {
        return (Task<T>) executionManager.submit(properties, (Runnable) task);
    } else {
        throw new IllegalArgumentException(
                "Unhandled task type: task=" + task + "; type=" + (task != null ? task.getClass() : "null"));
    }
}

From source file:com.twitter.common.zookeeper.CandidateImpl.java

@Override
public Supplier<Boolean> offerLeadership(final Leader leader)
        throws JoinException, WatchException, InterruptedException {

    final Membership membership = group.join(dataSupplier, new Command() {
        @Override/* w ww.j av  a  2  s .  c o m*/
        public void execute() {
            leader.onDefeated();
        }
    });

    final AtomicBoolean elected = new AtomicBoolean(false);
    final AtomicBoolean abdicated = new AtomicBoolean(false);
    group.watch(new GroupChangeListener() {
        @Override
        public void onGroupChange(Iterable<String> memberIds) {
            boolean noCandidates = Iterables.isEmpty(memberIds);
            String memberId = membership.getMemberId();

            if (noCandidates) {
                LOG.warning("All candidates have temporarily left the group: " + group);
            } else if (!Iterables.contains(memberIds, memberId)) {
                LOG.severe(
                        String.format("Current member ID %s is not a candidate for leader, current voting: %s",
                                memberId, memberIds));
            } else {
                boolean electedLeader = memberId.equals(getLeader(memberIds));
                boolean previouslyElected = elected.getAndSet(electedLeader);

                if (!previouslyElected && electedLeader) {
                    LOG.info(String.format("Candidate %s is now leader of group: %s",
                            membership.getMemberPath(), memberIds));

                    leader.onElected(new ExceptionalCommand<JoinException>() {
                        @Override
                        public void execute() throws JoinException {
                            membership.cancel();
                            abdicated.set(true);
                        }
                    });
                } else if (!electedLeader) {
                    if (previouslyElected) {
                        leader.onDefeated();
                    }
                    LOG.info(String.format(
                            "Candidate %s waiting for the next leader election, current voting: %s",
                            membership.getMemberPath(), memberIds));
                }
            }
        }
    });

    return new Supplier<Boolean>() {
        @Override
        public Boolean get() {
            return !abdicated.get() && elected.get();
        }
    };
}

From source file:edu.umn.msi.tropix.storage.core.impl.StorageManagerImpl.java

private void finalizeUpload(final String id, final String gridId, final long fileLength) {
    if (Iterables.contains(committingCallerIds, gridId)) {
        fileService.commit(id);//from   ww  w . ja  va  2s . co m
    }
    fileService.recordLength(id, fileLength);
}

From source file:com.google.javascript.rhino.jstype.ObjectType.java

/**
 * Detects cycles in either the implicit prototype chain, or the implemented/extended
 * interfaces.<p>//from  www  . j  a v  a2  s .c  o  m
 *
 * @return True iff a cycle was detected.
 */
final boolean detectInheritanceCycle() {
    // TODO(dimvar): This should get moved to preventing cycles in FunctionTypeBuilder
    // rather than removing them here after they have been created.
    // Also, this doesn't do the right thing for extended interfaces, though that is
    // masked by another bug.
    return detectImplicitPrototypeCycle() || Iterables.contains(this.getCtorImplementedInterfaces(), this)
            || Iterables.contains(this.getCtorExtendedInterfaces(), this);
}

From source file:com.google.devtools.build.lib.skyframe.SkyframeLabelVisitor.java

private static boolean isDirectErrorFromTopLevelLabel(Label label, Set<Label> topLevelLabels,
        ErrorInfo errorInfo) {/*from  w w w .ja  va  2  s.c o m*/
    return errorInfo.getException() != null && topLevelLabels.contains(label)
            && Iterables.contains(errorInfo.getRootCauses(), TransitiveTargetValue.key(label));
}

From source file:npanday.plugin.libraryimporter.model.NugetPackage.java

public boolean isDependentOn(NugetPackage other) {
    return Iterables.contains(getDependencies(), other);
}