Example usage for com.google.common.collect ImmutableSet size

List of usage examples for com.google.common.collect ImmutableSet size

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableSet size.

Prototype

int size();

Source Link

Document

Returns the number of elements in this set (its cardinality).

Usage

From source file:com.twitter.aurora.scheduler.state.SchedulerCoreImpl.java

@Override
public void addInstances(final IJobKey jobKey, final ImmutableSet<Integer> instanceIds,
        final ITaskConfig config) throws ScheduleException {

    runJobFilters(jobKey, config, instanceIds.size(), true);
    storage.write(new MutateWork.NoResult<ScheduleException>() {
        @Override//from  w w w  . j  a v a2  s .c  om
        protected void execute(MutableStoreProvider storeProvider) throws ScheduleException {

            ImmutableSet<IScheduledTask> tasks = storeProvider.getTaskStore()
                    .fetchTasks(Query.jobScoped(jobKey).active());

            Set<Integer> existingInstanceIds = FluentIterable.from(tasks)
                    .transform(Tasks.SCHEDULED_TO_INSTANCE_ID).toSet();
            if (!Sets.intersection(existingInstanceIds, instanceIds).isEmpty()) {
                throw new ScheduleException("Instance ID collision detected.");
            }

            stateManager.insertPendingTasks(Maps.asMap(instanceIds, Functions.constant(config)));
        }
    });
}

From source file:dagger.internal.codegen.InjectValidator.java

ValidationReport<TypeElement> validateConstructor(ExecutableElement constructorElement) {
    ValidationReport.Builder<TypeElement> builder = ValidationReport
            .about(MoreElements.asType(constructorElement.getEnclosingElement()));
    if (constructorElement.getModifiers().contains(PRIVATE)) {
        builder.addError(INJECT_ON_PRIVATE_CONSTRUCTOR, constructorElement);
    }/*from  www .  ja v  a2s.c  om*/

    for (AnnotationMirror qualifier : getQualifiers(constructorElement)) {
        builder.addError(QUALIFIER_ON_INJECT_CONSTRUCTOR, constructorElement, qualifier);
    }

    for (AnnotationMirror scope : getScopes(constructorElement)) {
        builder.addError(SCOPE_ON_INJECT_CONSTRUCTOR, constructorElement, scope);
    }

    for (VariableElement parameter : constructorElement.getParameters()) {
        ImmutableSet<? extends AnnotationMirror> qualifiers = getQualifiers(parameter);
        if (qualifiers.size() > 1) {
            for (AnnotationMirror qualifier : qualifiers) {
                builder.addError(MULTIPLE_QUALIFIERS, constructorElement, qualifier);
            }
        }
        if (FrameworkTypes.isProducerType(parameter.asType())) {
            builder.addError(provisionMayNotDependOnProducerType(parameter.asType()), parameter);
        }
    }

    if (throwsCheckedExceptions(constructorElement)) {
        builder.addItem(CHECKED_EXCEPTIONS_ON_CONSTRUCTORS,
                privateAndStaticInjectionDiagnosticKind.orElse(compilerOptions.privateMemberValidationKind()),
                constructorElement);
    }

    TypeElement enclosingElement = MoreElements.asType(constructorElement.getEnclosingElement());
    Set<Modifier> typeModifiers = enclosingElement.getModifiers();

    if (!Accessibility.isElementAccessibleFromOwnPackage(enclosingElement)) {
        builder.addItem(INJECT_INTO_PRIVATE_CLASS,
                privateAndStaticInjectionDiagnosticKind.orElse(compilerOptions.privateMemberValidationKind()),
                constructorElement);
    }

    if (typeModifiers.contains(ABSTRACT)) {
        builder.addError(INJECT_CONSTRUCTOR_ON_ABSTRACT_CLASS, constructorElement);
    }

    if (enclosingElement.getNestingKind().isNested() && !typeModifiers.contains(STATIC)) {
        builder.addError(INJECT_CONSTRUCTOR_ON_INNER_CLASS, constructorElement);
    }

    // This is computationally expensive, but probably preferable to a giant index
    ImmutableSet<ExecutableElement> injectConstructors = injectedConstructors(enclosingElement);

    if (injectConstructors.size() > 1) {
        builder.addError(MULTIPLE_INJECT_CONSTRUCTORS, constructorElement);
    }

    ImmutableSet<? extends AnnotationMirror> scopes = getScopes(enclosingElement);
    if (scopes.size() > 1) {
        for (AnnotationMirror scope : scopes) {
            builder.addError(MULTIPLE_SCOPES, enclosingElement, scope);
        }
    }

    return builder.build();
}

From source file:com.github.rinde.rinsim.experiment.CommandLineProgress.java

@Override
public void startComputing(int numberOfSimulations, ImmutableSet<MASConfiguration> configurations,
        ImmutableSet<Scenario> scenarios, int repetitions, int seedRepetitions) {
    startTime = System.currentTimeMillis();
    printStream.print("Start computing: ");
    printStream.print(numberOfSimulations);
    printStream.print(" simulations (=");
    printStream.print(configurations.size());
    printStream.print(" configurations x ");
    printStream.print(scenarios.size());
    printStream.print(" scenarios x ");
    printStream.print(repetitions);/*from  w w w .j av a2 s.  c o  m*/
    printStream.print(" repetitions x ");
    printStream.print(seedRepetitions);
    printStream.println(" seed repetitions)");
    printMemorySummary(printStream);

    total = numberOfSimulations;
    received = 0;
    failures = 0;
}

From source file:com.google.devtools.build.skyframe.ReverseDepsUtilImpl.java

@Override
public ImmutableSet<SkyKey> getReverseDeps(T container) {
    consolidateData(container);//from  w w  w  . j av  a  2  s. c  o  m

    // TODO(bazel-team): Unfortunately, we need to make a copy here right now to be on the safe side
    // wrt. thread-safety. The parents of a node get modified when any of the parents is deleted,
    // and we can't handle that right now.
    if (isSingleReverseDep(container)) {
        return ImmutableSet.of((SkyKey) getReverseDepsObject(container));
    } else {
        @SuppressWarnings("unchecked")
        List<SkyKey> reverseDeps = (List<SkyKey>) getReverseDepsObject(container);
        ImmutableSet<SkyKey> set = ImmutableSet.copyOf(reverseDeps);
        Preconditions.checkState(set.size() == reverseDeps.size(),
                "Duplicate reverse deps present in %s: %s. %s", this, reverseDeps, container);
        return set;
    }
}

From source file:org.elasticsearch.river.RiversService.java

@Override
protected void doStop() throws ElasticsearchException {
    ImmutableSet<RiverName> indices = ImmutableSet.copyOf(this.rivers.keySet());
    final CountDownLatch latch = new CountDownLatch(indices.size());
    for (final RiverName riverName : indices) {
        threadPool.generic().execute(new Runnable() {
            @Override/*from w  w w .  j a  v a 2s .  c  o m*/
            public void run() {
                try {
                    closeRiver(riverName);
                } catch (Exception e) {
                    logger.warn("failed to delete river on stop [{}]/[{}]", e, riverName.type(),
                            riverName.name());
                } finally {
                    latch.countDown();
                }
            }
        });
    }
    try {
        latch.await();
    } catch (InterruptedException e) {
        // ignore
    }
}

From source file:google.registry.flows.domain.DomainApplicationCreateFlow.java

/**
 * Prohibit creating a landrush application in LANDRUSH (but not in SUNRUSH) if there is exactly
 * one sunrise application for the same name.
 *//*from   w w w. jav  a2s  .c o m*/
private void prohibitLandrushIfExactlyOneSunrise(Registry registry, DateTime now)
        throws UncontestedSunriseApplicationBlockedInLandrushException {
    if (registry.getTldState(now) == TldState.LANDRUSH) {
        ImmutableSet<DomainApplication> applications = loadActiveApplicationsByDomainName(targetId, now);
        if (applications.size() == 1 && getOnlyElement(applications).getPhase().equals(LaunchPhase.SUNRISE)) {
            throw new UncontestedSunriseApplicationBlockedInLandrushException();
        }
    }
}

From source file:com.kolich.curacao.components.ComponentTable.java

private final ImmutableMap<Class<?>, Object> buildComponentTable(final String bootPackage) {
    final Map<Class<?>, Object> componentMap = Maps.newLinkedHashMap(); // Linked hash map to preserve order.
    // Immediately add the Servlet context object to the component map
    // such that components and controllers who need access to the context
    // via their Injectable constructor can get it w/o any trickery.
    componentMap.put(ServletContext.class, context_);
    // Use the reflections package scanner to scan the boot package looking
    // for all classes therein that contain "annotated" component classes.
    final ImmutableSet<Class<?>> components = getTypesInPackageAnnotatedWith(bootPackage, Component.class);
    logger__.debug("Found {} components annotated with @{}", components.size(), COMPONENT_ANNOTATION_SN);
    // For each discovered component...
    for (final Class<?> component : components) {
        logger__.debug("Found @{}: {}", COMPONENT_ANNOTATION_SN, component.getCanonicalName());
        try {//from   w  ww . j a  v a  2  s  .c o  m
            // If the component mapping table does not already contain an
            // instance for component class type, then instantiate one.
            if (!componentMap.containsKey(component)) {
                // The "dep stack" is used to keep track of where we are as
                // far as circular dependencies go.
                final Set<Class<?>> depStack = Sets.newLinkedHashSet();
                componentMap.put(component,
                        // Recursively instantiate components up-the-tree
                        // as needed, as defined based on their @Injectable
                        // annotated constructors.  Note that this method does
                        // NOT initialize the component, that is done later
                        // after all components are instantiated.
                        instantiate(components, componentMap, component, depStack));
            }
        } catch (Exception e) {
            // The component could not be instantiated.  There's no point
            // in continuing, so give up in error.
            throw new ComponentInstantiationException(
                    "Failed to " + "instantiate component instance: " + component.getCanonicalName(), e);
        }
    }
    return ImmutableMap.copyOf(componentMap);
}

From source file:de.metas.ui.web.window.datatypes.DocumentIdsSelection.java

public DocumentIdsSelection toDocumentIdsSelectionWithOnlyIntegerDocumentIds() {
    if (all) {//w  w  w . j  a v  a  2 s  .  com
        return this;
    } else if (documentIds.isEmpty()) {
        return this;
    } else {
        final ImmutableSet<DocumentId> intDocumentIds = documentIds.stream()
                .filter(documentId -> documentId != null && documentId.isInt())
                .collect(ImmutableSet.toImmutableSet());

        if (documentIds.size() == intDocumentIds.size()) {
            return this;
        } else {
            return new DocumentIdsSelection(false, intDocumentIds);
        }
    }
}

From source file:com.facebook.buck.io.filesystem.impl.DefaultProjectFilesystemView.java

@Override
public DefaultProjectFilesystemView withView(Path newRelativeRoot,
        ImmutableSet<PathMatcher> additionalIgnores) {
    Path newRoot = projectRoot.resolve(newRelativeRoot);
    Path resolvedNewRoot = filesystemParent.resolve(newRoot);
    ImmutableMap.Builder<PathMatcher, Predicate<Path>> mapBuilder = ImmutableMap
            .builderWithExpectedSize(ignoredPaths.size() + additionalIgnores.size());
    mapBuilder.putAll(ignoredPaths);//from   ww w . j a v  a2  s  . co  m
    for (PathMatcher p : additionalIgnores) {
        mapBuilder.put(p, path -> p.matches(resolvedNewRoot.relativize(path)));
    }
    return new DefaultProjectFilesystemView(filesystemParent, newRoot, resolvedNewRoot, mapBuilder.build());
}

From source file:com.facebook.buck.parser.TargetSpecResolver.java

private <T extends HasBuildTarget> void handleTargetNodeSpec(FlavorEnhancer<T> flavorEnhancer,
        TargetNodeProviderForSpecResolver<T> targetNodeProvider,
        TargetNodeFilterForSpecResolver<T> targetNodeFilter,
        List<ListenableFuture<Map.Entry<Integer, ImmutableSet<BuildTarget>>>> targetFutures, Cell cell,
        Path buildFile, TargetConfiguration targetConfiguration, int index, TargetNodeSpec spec) {
    if (spec instanceof BuildTargetSpec) {
        BuildTargetSpec buildTargetSpec = (BuildTargetSpec) spec;
        targetFutures.add(Futures.transform(targetNodeProvider.getTargetNodeJob(
                buildTargetSpec.getUnconfiguredBuildTarget().configure(EmptyTargetConfiguration.INSTANCE)),
                node -> {//ww  w .  j  av a 2s .  co m
                    ImmutableSet<BuildTarget> buildTargets = applySpecFilter(spec, ImmutableList.of(node),
                            flavorEnhancer, targetNodeFilter);
                    Preconditions.checkState(buildTargets.size() == 1,
                            "BuildTargetSpec %s filter discarded target %s, but was not supposed to.", spec,
                            node.getBuildTarget());
                    return new AbstractMap.SimpleEntry<>(index, buildTargets);
                }, MoreExecutors.directExecutor()));
    } else {
        // Build up a list of all target nodes from the build file.
        targetFutures.add(
                Futures.transform(targetNodeProvider.getAllTargetNodesJob(cell, buildFile, targetConfiguration),
                        nodes -> new AbstractMap.SimpleEntry<>(index,
                                applySpecFilter(spec, nodes, flavorEnhancer, targetNodeFilter)),
                        MoreExecutors.directExecutor()));
    }
}