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

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

Introduction

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

Prototype

int size();

Source Link

Document

Returns the number of elements in this list.

Usage

From source file:com.facebook.buck.apple.FatBinaryInfos.java

/**
 * Inspect the given build target and return information about it if its a fat binary.
 *
 * @return non-empty when the target represents a fat binary.
 * @throws com.facebook.buck.util.HumanReadableException
 *    when the target is a fat binary but has incompatible flavors.
 *//*from   www  .  j av a  2 s  .c o m*/
public static Optional<FatBinaryInfo> create(
        final Map<Flavor, AppleCxxPlatform> platformFlavorsToAppleCxxPlatforms, BuildTarget target) {
    ImmutableList<ImmutableSortedSet<Flavor>> thinFlavorSets = generateThinFlavors(
            platformFlavorsToAppleCxxPlatforms.keySet(), target.getFlavors());
    if (thinFlavorSets.size() <= 1) { // Actually a thin binary
        return Optional.absent();
    }

    if (!Sets.intersection(target.getFlavors(), FORBIDDEN_BUILD_ACTIONS).isEmpty()) {
        throw new HumanReadableException("%s: Fat binaries is only supported when building an actual binary.",
                target);
    }

    Predicate<Flavor> isPlatformFlavor = Predicates.in(platformFlavorsToAppleCxxPlatforms.keySet());

    AppleCxxPlatform representativePlatform = null;
    AppleSdk sdk = null;
    for (SortedSet<Flavor> flavorSet : thinFlavorSets) {
        AppleCxxPlatform platform = Preconditions.checkNotNull(
                platformFlavorsToAppleCxxPlatforms.get(Iterables.find(flavorSet, isPlatformFlavor)));
        if (sdk == null) {
            sdk = platform.getAppleSdk();
            representativePlatform = platform;
        } else if (sdk != platform.getAppleSdk()) {
            throw new HumanReadableException(
                    "%s: Fat binaries can only be generated from binaries compiled for the same SDK.", target);
        }
    }

    FatBinaryInfo.Builder builder = FatBinaryInfo.builder().setFatTarget(target)
            .setRepresentativePlatform(Preconditions.checkNotNull(representativePlatform));

    BuildTarget platformFreeTarget = target.withoutFlavors(platformFlavorsToAppleCxxPlatforms.keySet());
    for (SortedSet<Flavor> flavorSet : thinFlavorSets) {
        builder.addThinTargets(platformFreeTarget.withFlavors(flavorSet));
    }

    return Optional.of(builder.build());
}

From source file:com.facebook.buck.parser.implicit.AbstractImplicitInclude.java

/**
 * Constructs a {@link AbstractImplicitInclude} from a configuration string in the form of
 *
 * <p>//path/to:bzl_file.bzl::symbol_to_import::second_symbol_to_import
 *
 * @param configurationString The string used in configuration
 * @return A parsed {@link AbstractImplicitInclude} object
 * @throws {@link HumanReadableException} if the configuration string is invalid
 *///from   w w  w . j  av  a 2s.com
public static ImplicitInclude fromConfigurationString(String configurationString) {
    // Double colons are used so that if someone uses an absolute windows path, their error
    // messages will not be confusing. e.g. C:\foo.bzl:bar would lead to a file named
    // 'C', and symbols '\foo.bzl' and 'bar'. This just makes things explicit.
    ImmutableList<String> parts = Arrays.stream(configurationString.split("::")).map(String::trim)
            .collect(ImmutableList.toImmutableList());
    if (parts.size() < 2) {
        throw new HumanReadableException(
                "Configuration setting '%s' did not list any symbols to load. Setting should be of "
                        + "the format //<load label>::<symbol1>::<symbol2>...",
                configurationString);
    }

    String rawLabel = validateLabelFromConfiguration(parts.get(0), configurationString);
    ImmutableMap<String, String> symbols = parseAllSymbolsFromConfiguration(parts.subList(1, parts.size()),
            configurationString);

    return ImplicitInclude.of(rawLabel, symbols);
}

From source file:com.google.devtools.build.lib.analysis.extra.ExtraActionSpec.java

/**
 * Creates a unique id for the action shadowed by this extra_action.
 *
 * We need to have a unique id for the extra_action to use. We build this
 * from the owner's  label and the shadowed action id (which is only
 * guaranteed to be unique per target). Together with the subfolder
 * matching the original target's package name, we believe this is enough
 * of a uniqueness guarantee./*w  w w  .j a v a 2  s  . c om*/
 */
@VisibleForTesting
public static String getActionId(ActionOwner owner, Action action) {
    Fingerprint f = new Fingerprint();
    f.addString(owner.getLabel().toString());
    ImmutableList<AspectDescriptor> aspectDescriptors = owner.getAspectDescriptors();
    f.addInt(aspectDescriptors.size());
    for (AspectDescriptor aspectDescriptor : aspectDescriptors) {
        f.addString(aspectDescriptor.getDescription());
    }
    f.addString(action.getKey());
    return f.hexDigestAndReset();
}

From source file:com.facebook.buck.model.BuildFileTree.java

/**
 * Finds the parent Node of the specified child Node.
 * @param child whose parent is sought in {@code basePathToNodeIndex}.
 * @param basePathToNodeIndex Map that must contain a Node with a basePath that is a prefix of
 *     {@code child}'s basePath./*w w  w  .jav  a2s  . co m*/
 * @return the Node in {@code basePathToNodeIndex} with the longest basePath that is a prefix of
 *     {@code child}'s basePath.
 */
private static Node findParent(Node child, Map<String, Node> basePathToNodeIndex) {
    ImmutableList<String> parts = ImmutableList.copyOf(child.basePath.split("/"));
    for (int numParts = parts.size() - 1; numParts > 0; numParts--) {
        List<String> partsCandidate = parts.subList(0, numParts);
        String candidateBasePath = PATH_JOINER.join(partsCandidate);
        Node candidate = basePathToNodeIndex.get(candidateBasePath);
        if (candidate != null) {
            return candidate;
        }
    }

    return basePathToNodeIndex.get("");
}

From source file:com.google.api.tools.framework.aspects.http.RestAnalyzer.java

static RestMethod createCustomMethod(Method method, HttpAttribute httpConfig, String customNamePrefix) {
    ImmutableList<PathSegment> path = httpConfig.getFlatPath();
    PathSegment lastSegment = path.get(path.size() - 1);

    // Determine base name.
    String customName = "";
    if (lastSegment instanceof LiteralSegment) {
        customName = ((LiteralSegment) lastSegment).getLiteral();
        path = path.subList(0, path.size() - 1);
    } else {//from   w ww.jav  a  2 s  . c  o m
        if (method.getModel().getConfigVersion() > 1) {
            // From version 2 on, we generate a meaningful name here.
            customName = method.getSimpleName();
        } else if (customNamePrefix.isEmpty()) {
            // Older versions use the prefix or derive from the http method.
            customName = httpConfig.getMethodKind().toString().toLowerCase();
        }
    }

    // Prepend prefix.
    if (!customNamePrefix.isEmpty() && !customName.toLowerCase().startsWith(customNamePrefix.toLowerCase())) {
        customName = customNamePrefix + ensureUpperCase(customName);
    }

    // Ensure effective start is lower case.
    customName = ensureLowerCase(customName);

    return RestMethod.create(method, RestKind.CUSTOM, buildCollectionName(path), customName);
}

From source file:com.github.rinde.opt.localsearch.Insertions.java

/**
 * Creates an {@link Iterator} for a list of lists, each list contains a
 * specified number of insertions of <code>item</code> at a different position
 * in the list. Only creates insertions starting at <code>startIndex</code>.
 * @param list The original list./*from ww w .ja  v  a  2s.com*/
 * @param item The item to be inserted.
 * @param startIndex Must be &ge; 0 &amp;&amp; &le; list size.
 * @param numOfInsertions The number of times <code>item</code> is inserted.
 * @param <T> The list item type.
 * @return Iterator producing a list of lists of size
 *         <code>(n+1)-startIndex</code>.
 */
public static <T> Iterator<ImmutableList<T>> insertionsIterator(ImmutableList<T> list, T item, int startIndex,
        int numOfInsertions) {
    checkArgument(startIndex >= 0 && startIndex <= list.size(),
            "startIndex must be >= 0 and <= %s (list size), it is %s.", list.size(), startIndex);
    checkArgument(numOfInsertions > 0, "numOfInsertions must be positive.");
    return Iterators.transform(new InsertionIndexGenerator(numOfInsertions, list.size(), startIndex),
            new IndexToInsertionTransform<T>(list, item));
}

From source file:org.gradle.internal.component.external.model.LazyToRealisedModuleComponentResolveMetadataHelper.java

/**
 * Method to transform lazy variants into realised ones
 *
 * @param mutableMetadata the source metadata
 * @param variantMetadataRules the lazy rules
 * @param variants the variants to transform
 * @return a list of realised variants//from  www .jav  a2 s.c  om
 */
public static ImmutableList<AbstractRealisedModuleComponentResolveMetadata.ImmutableRealisedVariantImpl> realiseVariants(
        ModuleComponentResolveMetadata mutableMetadata, VariantMetadataRules variantMetadataRules,
        ImmutableList<? extends ComponentVariant> variants) {
    List<AbstractRealisedModuleComponentResolveMetadata.ImmutableRealisedVariantImpl> realisedVariants = Lists
            .newArrayListWithExpectedSize(variants.size());
    for (ComponentVariant variant : variants) {
        ImmutableAttributes attributes = variantMetadataRules.applyVariantAttributeRules(variant,
                variant.getAttributes());
        CapabilitiesMetadata capabilitiesMetadata = variantMetadataRules.applyCapabilitiesRules(variant,
                variant.getCapabilities());
        List<GradleDependencyMetadata> dependencies = variantMetadataRules.applyDependencyMetadataRules(variant,
                convertDependencies(variant.getDependencies(), variant.getDependencyConstraints()));
        realisedVariants.add(new AbstractRealisedModuleComponentResolveMetadata.ImmutableRealisedVariantImpl(
                mutableMetadata.getId(), variant.getName(), attributes, variant.getDependencies(),
                variant.getDependencyConstraints(), variant.getFiles(),
                ImmutableCapabilities.of(capabilitiesMetadata.getCapabilities()), dependencies));
    }
    return ImmutableList.copyOf(realisedVariants);
}

From source file:com.github.rinde.rinsim.central.rt.ScheduleUtil.java

static List<List<Parcel>> fixSchedule(ImmutableList<ImmutableList<Parcel>> schedule, GlobalStateObject state) {

    checkArgument(schedule.size() == state.getVehicles().size(),
            "The number of routes (%s) and the number of vehicles (%s) must " + "be equal.", schedule.size(),
            state.getVehicles().size());
    checkArgument(!state.getVehicles().get(0).getRoute().isPresent(),
            "A state object without routes is expected.");

    // only parcels in this set may occur in the schedule
    final Set<Parcel> undeliveredParcels = new HashSet<>();
    undeliveredParcels.addAll(state.getAvailableParcels());

    // for each vehicle, we create a multiset that is a representation of the
    // number of times the occurrence of a parcel is REQUIRED to be in the
    // route of the vehicle
    final List<Multiset<Parcel>> expectedRoutes = new ArrayList<>();
    for (int i = 0; i < state.getVehicles().size(); i++) {
        expectedRoutes.add(HashMultiset.<Parcel>create());
        final VehicleStateObject vehicle = state.getVehicles().get(i);
        expectedRoutes.get(i).addAll(vehicle.getContents());
        if (vehicle.getDestination().isPresent()
                && !vehicle.getContents().contains(vehicle.getDestination().get())) {
            expectedRoutes.get(i).add(vehicle.getDestination().get(), 2);
        }/*from   w  ww. ja v a 2  s  . com*/
        undeliveredParcels.addAll(vehicle.getContents());
    }

    // create map of parcel -> vehicle index
    final Multimap<Parcel, Integer> parcelOwner = LinkedHashMultimap.create();
    for (int i = 0; i < schedule.size(); i++) {
        final List<Parcel> route = schedule.get(i);
        final Set<Parcel> routeSet = ImmutableSet.copyOf(route);
        for (final Parcel p : routeSet) {
            parcelOwner.put(p, i);
        }
    }

    // copy schedule into a modifiable structure
    final List<List<Parcel>> newSchedule = new ArrayList<>();
    for (final ImmutableList<Parcel> route : schedule) {
        newSchedule.add(new ArrayList<>(route));
    }
    // compare with current vehicle cargo
    for (int i = 0; i < state.getVehicles().size(); i++) {
        final VehicleStateObject vehicle = state.getVehicles().get(i);
        final Multiset<Parcel> routeSet = ImmutableMultiset.copyOf(schedule.get(i));

        final Set<Parcel> test = Sets.union(routeSet.elementSet(), expectedRoutes.get(i).elementSet());

        for (final Parcel p : test) {
            final int actualOccurences = routeSet.count(p);
            checkState(actualOccurences <= 2);
            final int expectedOccurrences = expectedRoutes.get(i).count(p);

            if (!undeliveredParcels.contains(p)) {
                // it is already delivered, remove all occurrences
                newSchedule.get(i).removeAll(Collections.singleton(p));
            } else if (actualOccurences != expectedOccurrences && expectedOccurrences > 0) {
                if (expectedOccurrences == 1 && actualOccurences == 2) {
                    newSchedule.get(i).remove(p);
                } else {
                    // expected occurr = 1 or 2
                    final boolean destinationIsCurrent = vehicle.getDestination().asSet().contains(p);

                    int toAdd = expectedOccurrences - actualOccurences;

                    // add it once at the front of the route
                    if (destinationIsCurrent) {
                        newSchedule.get(i).add(0, p);
                        toAdd--;
                    }

                    // add it once to the end of the route
                    if (toAdd > 0) {
                        newSchedule.get(i).add(p);
                    }
                }
            }

            // if the parcel is expected in the current vehicle, but it also appears
            // in (an) other vehicle(s), we have to remove it there
            if (expectedOccurrences > 0 && parcelOwner.containsKey(p)) {
                for (final Integer v : parcelOwner.get(p)) {
                    if (!v.equals(i)) {
                        newSchedule.get(v).removeAll(Collections.singleton(p));
                    }
                }
            }
        }

        if (vehicle.getDestination().isPresent()
                && !newSchedule.get(i).get(0).equals(vehicle.getDestination().get())) {
            newSchedule.get(i).remove(vehicle.getDestination().get());
            newSchedule.get(i).add(0, vehicle.getDestination().get());
        }
    }
    return newSchedule;
}

From source file:org.eigenbase.rel.rules.AggregateStarTableRule.java

private static int find(ImmutableList<Lattice.Measure> measures, Pair<Aggregation, List<Integer>> seek) {
    for (int i = 0; i < measures.size(); i++) {
        Lattice.Measure measure = measures.get(i);
        if (measure.agg.equals(seek.left) && measure.argOrdinals().equals(seek.right)) {
            return i;
        }//  www  .j  ava 2  s . c om
    }
    return -1;
}

From source file:org.apache.calcite.rel.rules.AggregateStarTableRule.java

private static int find(ImmutableList<Lattice.Measure> measures, Pair<SqlAggFunction, List<Integer>> seek) {
    for (int i = 0; i < measures.size(); i++) {
        Lattice.Measure measure = measures.get(i);
        if (measure.agg.equals(seek.left) && measure.argOrdinals().equals(seek.right)) {
            return i;
        }/*from   ww w  . j av  a2  s .  c o m*/
    }
    return -1;
}