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.github.emabrey.rtmp4j.amf.io.AMFOutputStream.java

/**
 * Write an AMF version 0 ECMAArray to the underlying {@code OutputStream}.
 *
 * @param array The AMF version 0 ECMAArray to write.
 *
 * @throws IOException If an IO error occurs in the underlying stream or
 * within the reference pool.// w w  w.  j a v a  2 s  .c om
 */
public final void writeECMAArray0(final AMF0ECMAArray array) throws IOException {

    LOG.trace("Write AMF0ECMAArray");

    if (writeComplexTypeAsEvaluatedReference0(array)) {
        //The object was encoded via reference, so no additional encoding is needed
        return;
    }

    final ImmutableSet<Entry<String, Object>> arrayEntries = array.getImmutableViewOfFields();

    writeUByte(AMFMarker.Version0.ECMAArray);

    //Write the array size data            
    final UInteger arraySize = uint(arrayEntries.size());
    writeUInteger(arraySize);

    writeObjectEntries0(arrayEntries);
    writeObjectTerminator0();
}

From source file:cc.kune.kunecli.cmds.CustomDeltaMigrator.java

public void run() {
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override/*  w w w.j a  va 2s  .c  om*/
        public void run() {
            printStats();
        }
    });

    LOG.info("Starting Wave migration from " + sourceStore.getClass().getSimpleName() + " to "
            + targetStore.getClass().getSimpleName());

    final long startTime = System.currentTimeMillis();

    try {
        // We need the total number of waves to make a progress bar
        int waveCount = 0;
        final ExceptionalIterator<WaveId, PersistenceException> countIterator = sourceStore.getWaveIdIterator();
        while (countIterator.hasNext()) {
            waveCount++;
            countIterator.next();
        }

        final ExceptionalIterator<WaveId, PersistenceException> srcItr = sourceStore.getWaveIdIterator();
        final File stopFile = new File(System.getProperty("java.io.tmpdir") + "/wave-mongo-migration-stop");

        bar = new Progressbar(waveCount, "Migrating " + waveCount + " Waves");

        int currentWave = 0;
        // Waves
        while (srcItr.hasNext()) {
            currentWave++;

            if (stopFile.exists()) {
                LOG.info("Stopping Wave migration as requested. Partial migration.");
                break;
            }

            bar.setVal(currentWave);

            final WaveId waveId = srcItr.next();
            final ImmutableSet<WaveletId> sourceLookup = sourceStore.lookup(waveId);
            final ImmutableSet<WaveletId> targetLookup = targetStore.lookup(waveId);
            final ImmutableSet<WaveletId> waveletIds = sourceLookup;

            boolean wavesAreNotTheSame = false;

            if (!targetLookup.isEmpty()) {
                if (targetLookup.size() != sourceLookup.size()) {
                    wavesAreNotTheSame = true;
                } else {
                    // Comparing source and target deltas
                    for (final WaveletId waveletId : waveletIds) {
                        setStatus("comparing");
                        bar.setVal(currentWave);

                        final DeltasAccess sourceDeltas = sourceStore.open(WaveletName.of(waveId, waveletId));
                        final DeltasAccess targetDeltas = targetStore.open(WaveletName.of(waveId, waveletId));
                        final HashedVersion deltaResultingVersion = sourceDeltas.getEndVersion();
                        final HashedVersion deltaResultingTargetVersion = targetDeltas.getEndVersion();

                        if (!deltaResultingVersion.equals(deltaResultingTargetVersion)) {
                            wavesAreNotTheSame = true;
                            break;
                        }
                    }

                    if (wavesAreNotTheSame) {
                        for (final WaveletId targetWaveletId : targetLookup) {
                            // LOG.info(
                            // "Deleting and appending Wave in target because it's found and
                            // has not the same size: "
                            // + waveId.toString());
                            targetStore.delete(WaveletName.of(waveId, targetWaveletId));
                        }
                        // Continue migrating that wave
                    } else {
                        setStatus("skipping already migrated");
                        bar.setVal(currentWave);
                        countSkipped++;
                        continue;
                    }
                }
            }

            if (wavesAreNotTheSame) {
                setStatus("migrating partial wave");
                countMigratedBecausePartial++;
            } else {
                setStatus("migrating");
                countMigrated++;
            }
            setStatus(wavesAreNotTheSame ? "migrating partial wave" : "migrating");

            // LOG.info("--- Migrating Wave " + waveId.toString() + " with " +
            // waveletIds.size() + " wavelets");
            // final long waveStartTime = System.currentTimeMillis();
            //
            // Wavelets

            try {
                for (final WaveletId waveletId : waveletIds) {
                    bar.setVal(currentWave);

                    // LOG.info(
                    // "Migrating wavelet " + waveletsCount + "/" + waveletsTotal + " :
                    // "
                    // + waveletId.toString());

                    final DeltasAccess sourceDeltas = sourceStore.open(WaveletName.of(waveId, waveletId));
                    final DeltasAccess targetDeltas = targetStore.open(WaveletName.of(waveId, waveletId));

                    // Get all deltas from last version to initial version (0): reverse
                    // order
                    // int deltasCount = 0;

                    final ArrayList<WaveletDeltaRecord> deltas = new ArrayList<WaveletDeltaRecord>();
                    HashedVersion deltaResultingVersion = sourceDeltas.getEndVersion();

                    // Deltas
                    while (deltaResultingVersion != null && deltaResultingVersion.getVersion() != 0) {
                        // deltasCount++;
                        final WaveletDeltaRecord deltaRecord = sourceDeltas
                                .getDeltaByEndVersion(deltaResultingVersion.getVersion());
                        deltas.add(deltaRecord);
                        // get the previous delta, this is the appliedAt
                        deltaResultingVersion = deltaRecord.getAppliedAtVersion();
                    }
                    // LOG.info("Appending " + deltasCount + " deltas to target");
                    targetDeltas.append(deltas);
                }

            } catch (final EOFException e) {
                processCorruptedWave(waveId, e);
            } catch (final PersistenceException e) {
                processCorruptedWave(waveId, e);
            } catch (final IOException e) {
                processCorruptedWave(waveId, e);
            }

        } // While Waves

        bar.finish();
        final long endTime = System.currentTimeMillis();
        LOG.info("Migration completed. Total time = " + (endTime - startTime) + "ms");
        printStats();
    } catch (final PersistenceException e) {
        LOG.warning("Error iterating over waves");
        throw new RuntimeException(e);
    }
}

From source file:com.google.devtools.build.lib.pkgcache.LegacyLoadingPhaseRunner.java

private void reportAboutPartiallySuccesfulLoading(ImmutableSet<Target> requestedTargets,
        ImmutableSet<Target> loadedTargets, EventHandler eventHandler) {
    // Tell the user about the subset of successful targets.
    int requested = requestedTargets.size();
    int loaded = loadedTargets.size();
    if (0 < loaded) {
        String message = String.format("Loading succeeded for only %d of %d targets", loaded, requested);
        eventHandler.handle(Event.info(message));
        LOG.info(message);//from w  w  w.j a v  a2 s  .  com
    }
}

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

@Override
public PrepareAnalysisPhaseValue compute(SkyKey key, Environment env)
        throws InterruptedException, PrepareAnalysisPhaseFunctionException {
    PrepareAnalysisPhaseKey options = (PrepareAnalysisPhaseKey) key.argument();

    BuildOptions targetOptions = defaultBuildOptions.applyDiff(options.getOptionsDiff());
    BuildOptions hostOptions = targetOptions.get(BuildConfiguration.Options.class).useDistinctHostConfiguration
            ? HostTransition.INSTANCE.patch(targetOptions)
            : targetOptions;//from   w  w  w.  j av  a2s . c  o m

    ImmutableSortedSet<Class<? extends BuildConfiguration.Fragment>> allFragments = options.getFragments()
            .fragmentClasses();
    BuildConfigurationValue.Key hostConfigurationKey = BuildConfigurationValue.key(allFragments,
            BuildOptions.diffForReconstruction(defaultBuildOptions, hostOptions));
    ImmutableList<BuildConfigurationValue.Key> targetConfigurationKeys = getTopLevelBuildOptions(targetOptions,
            options.getMultiCpu())
                    .stream()
                    .map(elem -> BuildConfigurationValue.key(allFragments,
                            BuildOptions.diffForReconstruction(defaultBuildOptions, elem)))
                    .collect(ImmutableList.toImmutableList());

    // We don't need the host configuration below, but we call this to get the error, if any.
    try {
        env.getValueOrThrow(hostConfigurationKey, InvalidConfigurationException.class);
    } catch (InvalidConfigurationException e) {
        throw new PrepareAnalysisPhaseFunctionException(e);
    }

    Map<SkyKey, SkyValue> configs = env.getValues(targetConfigurationKeys);

    // We only report invalid options for the target configurations, and abort if there's an error.
    ErrorSensingEventHandler nosyEventHandler = new ErrorSensingEventHandler(env.getListener());
    targetConfigurationKeys.stream().map(k -> configs.get(k)).filter(Predicates.notNull())
            .map(v -> ((BuildConfigurationValue) v).getConfiguration())
            .forEach(config -> config.reportInvalidOptions(nosyEventHandler));
    if (nosyEventHandler.hasErrors()) {
        throw new PrepareAnalysisPhaseFunctionException(
                new InvalidConfigurationException("Build options are invalid"));
    }

    // We get the list of labels from the TargetPatternPhaseValue, so we are reasonably certain that
    // there will not be an error loading these again.
    ResolvedTargets<Target> resolvedTargets = TestSuiteExpansionFunction.labelsToTargets(env,
            options.getLabels(), false);
    if (resolvedTargets == null) {
        return null;
    }
    ImmutableSet<Target> targets = resolvedTargets.getTargets();

    // We use a hash set here to remove duplicate nodes; this can happen for input files and package
    // groups.
    LinkedHashSet<TargetAndConfiguration> nodes = new LinkedHashSet<>(targets.size());
    for (Target target : targets) {
        if (target.isConfigurable()) {
            for (BuildConfigurationValue.Key configKey : targetConfigurationKeys) {
                BuildConfiguration config = ((BuildConfigurationValue) configs.get(configKey))
                        .getConfiguration();
                nodes.add(new TargetAndConfiguration(target, config));
            }
        } else {
            nodes.add(new TargetAndConfiguration(target, null));
        }
    }

    // We'll get the configs from #resolveConfigurations below, which started out as a copy of the
    // same code in SkyframeExecutor, which gets configurations for deps including transitions. So,
    // for now, to satisfy its API we resolve transitions and repackage each target as a Dependency
    // (with a NONE transition if necessary).
    // Keep this in sync with AnalysisUtils#getTargetsWithConfigs.
    Multimap<BuildConfiguration, Dependency> asDeps = AnalysisUtils.targetsToDeps(nodes, ruleClassProvider);
    LinkedHashSet<TargetAndConfiguration> topLevelTargetsWithConfigs = resolveConfigurations(env, nodes,
            asDeps);
    if (env.valuesMissing()) {
        return null;
    }
    ImmutableList<ConfiguredTargetKey> topLevelCtKeys = topLevelTargetsWithConfigs.stream()
            .map(node -> ConfiguredTargetKey.of(node.getLabel(), node.getConfiguration()))
            .collect(ImmutableList.toImmutableList());
    return new PrepareAnalysisPhaseValue(hostConfigurationKey, targetConfigurationKeys, topLevelCtKeys);
}

From source file:dagger2.internal.codegen.InjectBindingRegistry.java

Optional<ProvisionBinding> getOrFindProvisionBinding(Key key) {
    checkNotNull(key);//from  www . j  av  a  2 s.  co m
    if (!key.isValidImplicitProvisionKey(types)) {
        return Optional.absent();
    }
    ProvisionBinding binding = provisionBindings.getBinding(key);
    if (binding != null) {
        return Optional.of(binding);
    }

    // ok, let's see if we can find an @Inject constructor
    TypeElement element = MoreElements.asType(types.asElement(key.type()));
    List<ExecutableElement> constructors = ElementFilter.constructorsIn(element.getEnclosedElements());
    ImmutableSet<ExecutableElement> injectConstructors = FluentIterable.from(constructors)
            .filter(new Predicate<ExecutableElement>() {
                @Override
                public boolean apply(ExecutableElement input) {
                    return isAnnotationPresent(input, Inject.class);
                }
            }).toSet();
    switch (injectConstructors.size()) {
    case 0:
        // No constructor found.
        return Optional.absent();
    case 1:
        ProvisionBinding constructorBinding = provisionBindingFactory
                .forInjectConstructor(Iterables.getOnlyElement(injectConstructors), Optional.of(key.type()));
        return Optional.of(registerBinding(constructorBinding, false));
    default:
        throw new IllegalStateException("Found multiple @Inject constructors: " + injectConstructors);
    }
}

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

/**
 * Adds an error if an {@link IntoMap @IntoMap} or {@code MAP} method doesn't have exactly one
 * {@link MapKey @MapKey} annotation, or if a method that is neither {@link IntoMap @IntoMap} nor
 * {@code MAP} has any.//from ww w  .ja  v a2 s .  c  o  m
 */
protected void checkMapKeys(ValidationReport.Builder<ExecutableElement> builder) {
    if (!allowsMultibindings.allowsMultibindings()) {
        return;
    }
    ImmutableSet<? extends AnnotationMirror> mapKeys = getMapKeys(builder.getSubject());
    if (ContributionType.fromBindingMethod(builder.getSubject()).equals(ContributionType.MAP)) {
        switch (mapKeys.size()) {
        case 0:
            builder.addError(formatErrorMessage(BINDING_METHOD_WITH_NO_MAP_KEY));
            break;
        case 1:
            break;
        default:
            builder.addError(formatErrorMessage(BINDING_METHOD_WITH_MULTIPLE_MAP_KEYS));
            break;
        }
    } else if (!mapKeys.isEmpty()) {
        builder.addError(formatErrorMessage(BINDING_METHOD_NOT_MAP_HAS_MAP_KEY));
    }
}

From source file:com.github.rinde.rinsim.core.pdptw.RandomVehicle.java

Optional<Parcel> findTarget() {
    final Collection<Parcel> available = pm.get().getParcels(ParcelState.AVAILABLE);
    final ImmutableSet<Parcel> contents = pm.get().getContents(this);
    if (available.isEmpty() && contents.isEmpty()) {
        return Optional.absent();
    }/*  w w  w .j  a v  a 2s.com*/
    boolean pickup;
    if (!available.isEmpty() && !contents.isEmpty()) {
        pickup = rng.nextBoolean();
    } else {
        pickup = !available.isEmpty();
    }
    if (pickup) {
        return Optional.of(newArrayList(available).get(rng.nextInt(available.size())));
    } else {
        return Optional.of(contents.asList().get(rng.nextInt(contents.size())));
    }
}

From source file:com.github.rinde.rinsim.core.model.pdp.RandomVehicle.java

Optional<Parcel> findTarget() {
    final Collection<Parcel> available = pm.get().getParcels(ParcelState.AVAILABLE);
    final ImmutableSet<Parcel> contents = pm.get().getContents(this);
    if (available.isEmpty() && contents.isEmpty()) {
        return Optional.absent();
    }/*from  w w w.j ava 2s.c om*/
    boolean pickup;
    if (!available.isEmpty() && !contents.isEmpty()) {
        pickup = rng.get().nextBoolean();
    } else {
        pickup = !available.isEmpty();
    }
    if (pickup) {
        return Optional.of(newArrayList(available).get(rng.get().nextInt(available.size())));
    }
    return Optional.of(contents.asList().get(rng.get().nextInt(contents.size())));
}

From source file:com.facebook.buck.features.project.intellij.IjProjectTemplateDataPreparer.java

private void addAndroidAssetPaths(Map<String, Object> androidProperties, IjModule module,
        IjModuleAndroidFacet androidFacet) {
    if (androidFacet.isAndroidLibrary()) {
        return;//from  w  ww. ja va2s  .  co m
    }
    ImmutableSet<Path> assetPaths = androidFacet.getAssetPaths();
    if (assetPaths.isEmpty()) {
        return;
    }
    Set<Path> relativeAssetPaths = new HashSet<>(assetPaths.size());
    for (Path assetPath : assetPaths) {
        relativeAssetPaths.add(projectPaths.getModuleRelativePath(assetPath, module));
    }
    androidProperties.put(ASSETS_FOLDER_TEMPLATE_PARAMETER, "/" + Joiner.on(";/").join(relativeAssetPaths));
}

From source file:com.github.rinde.jaamas17.ResultWriter.java

@Override
public void startComputing(int numberOfSimulations, ImmutableSet<MASConfiguration> configurations,
        ImmutableSet<Scenario> scenarios, int repetitions, int seedRepetitions) {

    final StringBuilder sb = new StringBuilder("Experiment summary");
    sb.append(System.lineSeparator()).append("Number of simulations: ").append(numberOfSimulations)
            .append(System.lineSeparator()).append("Number of configurations: ").append(configurations.size())
            .append(System.lineSeparator()).append("Number of scenarios: ").append(scenarios.size())
            .append(System.lineSeparator()).append("Number of repetitions: ").append(repetitions)
            .append(System.lineSeparator()).append("Number of seed repetitions: ").append(seedRepetitions)
            .append(System.lineSeparator()).append("Configurations:").append(System.lineSeparator());

    for (final MASConfiguration config : configurations) {
        sb.append(config.getName()).append(System.lineSeparator());
    }//from  w  w  w  .j  a v a  2 s  .  co m

    final File setup = new File(experimentDirectory, "experiment-setup.txt");
    try {
        setup.createNewFile();
        Files.write(sb.toString(), setup, Charsets.UTF_8);
    } catch (final IOException e) {
        throw new IllegalStateException(e);
    }
}