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.github.rinde.rinsim.central.SolverValidator.java

/**
 * Validates the routes that are produced by a {@link Solver}. If one of the
 * routes is infeasible an {@link IllegalArgumentException} is thrown.
 * @param routes The routes that are validated.
 * @param state Parameter as specified by
 *          {@link Solver#solve(GlobalStateObject)}.
 * @return The routes./*  w w w .j a va  2s .  c o  m*/
 */
public static ImmutableList<ImmutableList<Parcel>> validateOutputs(ImmutableList<ImmutableList<Parcel>> routes,
        GlobalStateObject state) {

    checkArgument(routes.size() == state.getVehicles().size(),
            "There must be exactly one route for every vehicle, found %s routes " + "with %s vehicles.",
            routes.size(), state.getVehicles().size());

    final Set<Parcel> inputParcels = newHashSet(state.getAvailableParcels());
    final Set<Parcel> outputParcels = newHashSet();
    for (int i = 0; i < routes.size(); i++) {
        final List<Parcel> route = routes.get(i);
        final Set<Parcel> routeSet = ImmutableSet.copyOf(route);
        checkArgument(routeSet.containsAll(state.getVehicles().get(i).getContents()),
                "The route of vehicle %s doesn't visit all parcels in its cargo.", i);
        inputParcels.addAll(state.getVehicles().get(i).getContents());

        if (state.getVehicles().get(i).getDestination().isPresent()) {
            checkArgument(state.getVehicles().get(i).getDestination().asSet().contains(route.get(0)),
                    "The route of vehicle %s should start with its current destination:" + " %s.", i,
                    state.getVehicles().get(i).getDestination());
        }

        for (final Parcel p : route) {
            checkArgument(!outputParcels.contains(p), "Found a parcel which is already in another route: %s.",
                    p);
            final int frequency = Collections.frequency(route, p);
            if (state.getAvailableParcels().contains(p)) {
                // if the parcel is available, it needs to occur twice in
                // the route (once for pickup, once for delivery).
                checkArgument(frequency == 2,
                        "Route %s: a parcel that is picked up needs to be delivered as "
                                + "well, so it should occur twice in the route, found %s "
                                + "occurence(s) of parcel %s.",
                        i, frequency, p);
            } else {
                checkArgument(state.getVehicles().get(i).getContents().contains(p),
                        "The parcel in this route is not available, which means it should"
                                + " be in the contents of this vehicle. Parcel: %s.",
                        p);
                checkArgument(frequency == 1, "A parcel that is already in cargo should occur once in the "
                        + "route, found %s occurences of parcel %s.", frequency, p);
            }
        }
        outputParcels.addAll(route);
    }
    checkArgument(inputParcels.equals(outputParcels),
            "The number of distinct parcels in the routes should equal the number "
                    + "of parcels in the input, parcels that should be added in routes:"
                    + " %s, parcels that should be removed from routes: %s.",
            Sets.difference(inputParcels, outputParcels), Sets.difference(outputParcels, inputParcels));
    return routes;
}

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

/**
 * Construct a store by asking the system keychain for all stored code sign identities.
 *
 * The loading process is deferred till first access.
 *///from ww w. j  a  v  a 2s .com
public static CodeSignIdentityStore fromSystem(final ProcessExecutor processExecutor,
        ImmutableList<String> command) {
    return new CodeSignIdentityStore(Suppliers.memoize(() -> {
        ProcessExecutorParams processExecutorParams = ProcessExecutorParams.builder().addAllCommand(command)
                .build();
        // Specify that stdout is expected, or else output may be wrapped in Ansi escape chars.
        Set<ProcessExecutor.Option> options = EnumSet.of(ProcessExecutor.Option.EXPECTING_STD_OUT);
        ProcessExecutor.Result result;
        try {
            result = processExecutor.launchAndExecute(processExecutorParams, options,
                    /* stdin */ Optional.empty(), /* timeOutMs */ Optional.empty(),
                    /* timeOutHandler */ Optional.empty());
        } catch (InterruptedException | IOException e) {
            LOG.warn("Could not execute security, continuing without codesign identity.");
            return ImmutableList.of();
        }

        if (result.getExitCode() != 0) {
            throw new RuntimeException(result.getMessageForUnexpectedResult("security -v -p codesigning"));
        }

        Matcher matcher = CODE_SIGN_IDENTITY_PATTERN.matcher(result.getStdout().get());
        ImmutableList.Builder<CodeSignIdentity> builder = ImmutableList.builder();
        while (matcher.find()) {
            Optional<HashCode> fingerprint = CodeSignIdentity.toFingerprint(matcher.group(1));
            if (!fingerprint.isPresent()) {
                // security should always output a valid fingerprint string.
                LOG.warn("Code sign identity fingerprint is invalid, ignored: " + matcher.group(1));
                break;
            }
            String subjectCommonName = matcher.group(2);
            CodeSignIdentity identity = CodeSignIdentity.builder().setFingerprint(fingerprint)
                    .setSubjectCommonName(subjectCommonName).build();
            builder.add(identity);
            LOG.debug("Found code signing identity: " + identity.toString());
        }
        ImmutableList<CodeSignIdentity> allValidIdentities = builder.build();
        if (allValidIdentities.isEmpty()) {
            LOG.warn("No valid code signing identities found.  Device build/install won't work.");
        } else if (allValidIdentities.size() > 1) {
            LOG.info("Multiple valid identity found.  This could potentially cause the wrong one to"
                    + " be used unless explicitly specified via CODE_SIGN_IDENTITY.");
        }
        return allValidIdentities;
    }));
}

From source file:com.sourceclear.headlines.util.HeaderBuilder.java

/**
 * @param values - list of String attribute values
 * @return formatted values//w w  w  .j a  va2s .  c  om
 */
public static String formatListAttributeValues(ImmutableList<String> values) {

    // In the case of an empty map return the empty string:
    if (values.isEmpty()) {
        return "";
    }

    StringBuilder sb = new StringBuilder();

    // Outer loop - loop through each directive
    for (int i = 0; i < values.size(); i++) {

        // Don't add a directive if it has zero elements
        if (values.size() == 0) {
            continue;
        }

        //adding value of header attributes
        sb.append("'").append(values.get(i)).append("'");

        // adding comma if list value isn't last
        if (values.size() > 1 && i < values.size() - 1) {
            sb.append(",");
        }
    }

    return sb.toString().trim();
}

From source file:com.google.api.codegen.discovery.DefaultString.java

/** Returns a default string from `pattern`, or null if the pattern is not supported. */
@VisibleForTesting/*from  w  ww .j av  a  2s  .c  o  m*/
static String forPattern(String pattern, String placeholderFormat, boolean placeholderUpperCase) {
    // We only care about patterns that have alternating literal and wildcard like
    //  ^foo/[^/]*/bar/[^/]*$
    // Ignore if what we get looks nothing like this.
    if (pattern == null || !pattern.startsWith("^") || !pattern.endsWith("$")) {
        return null;
    }
    pattern = pattern.substring(1, pattern.length() - 1);
    ImmutableList<Elem> elems = parse(pattern);
    if (!validElems(elems)) {
        return null;
    }

    StringBuilder ret = new StringBuilder();
    for (int i = 0; i < elems.size(); i += 2) {
        String literal = elems.get(i).getLiteral();
        String placeholder = Inflector.singularize(literal);
        if (placeholderUpperCase) {
            placeholder = placeholder.toUpperCase();
        }
        ret.append('/').append(literal).append("/").append(String.format(placeholderFormat, placeholder));
    }
    return ret.substring(1);
}

From source file:com.facebook.buck.apple.xcode.ProjectGeneratorTestUtils.java

public static void assertHasSingletonFrameworksPhaseWithFrameworkEntries(PBXTarget target,
        ImmutableList<String> frameworks) {
    PBXFrameworksBuildPhase buildPhase = getSingletonPhaseByType(target, PBXFrameworksBuildPhase.class);
    assertEquals("Framework phase should have right number of elements", frameworks.size(),
            buildPhase.getFiles().size());

    for (PBXBuildFile file : buildPhase.getFiles()) {
        PBXReference.SourceTree sourceTree = file.getFileRef().getSourceTree();
        switch (sourceTree) {
        case GROUP:
            fail("Should not emit frameworks with sourceTree <group>");
            break;
        case ABSOLUTE:
            fail("Should not emit frameworks with sourceTree <absolute>");
            break;
        // $CASES-OMITTED$
        default:/*from ww w.ja va 2  s . co m*/
            String serialized = "$" + sourceTree + "/" + file.getFileRef().getPath();
            assertTrue("Framework should be listed in list of expected frameworks: " + serialized,
                    frameworks.contains(serialized));
            break;
        }
    }
}

From source file:com.facebook.buck.android.resources.ResTablePackage.java

public static ResTablePackage slice(ResTablePackage resPackage, Map<Integer, Integer> countsToSlice) {
    resPackage.assertValidIds(countsToSlice.keySet());

    int packageId = resPackage.packageId;
    byte[] nameData = Arrays.copyOf(resPackage.nameData, NAME_DATA_LENGTH);

    List<ResTableTypeSpec> newSpecs = resPackage.getTypeSpecs().stream()
            .map(spec -> ResTableTypeSpec.slice(spec, countsToSlice.getOrDefault(spec.getResourceType(), 0)))
            .collect(ImmutableList.toImmutableList());

    StringPool keys = resPackage.keys;//from   w w w .  ja va  2 s .com

    // Figure out what keys are used by the retained references.
    ImmutableSortedSet.Builder<Integer> keyRefs = ImmutableSortedSet
            .orderedBy(Comparator.comparing(keys::getString));
    newSpecs.forEach(spec -> spec.visitKeyReferences(keyRefs::add));
    ImmutableList<Integer> keysToExtract = keyRefs.build().asList();
    Map<Integer, Integer> keyMapping = Maps.uniqueIndex(IntStream.range(0, keysToExtract.size())::iterator,
            keysToExtract::get);

    // Extract a StringPool that contains just the keys used by the new specs.
    StringPool newKeys = StringPool.create(keysToExtract.stream().map(keys::getString)::iterator);

    // Adjust the key references.
    for (ResTableTypeSpec spec : newSpecs) {
        spec.transformKeyReferences(keyMapping::get);
    }

    StringPool types = resPackage.types.copy();

    int chunkSize = HEADER_SIZE + types.getChunkSize() + newKeys.getChunkSize();
    for (ResTableTypeSpec spec : newSpecs) {
        chunkSize += spec.getTotalSize();
    }

    return new ResTablePackage(chunkSize, packageId, nameData, types, newKeys, newSpecs);
}

From source file:com.google.errorprone.refaster.UClassDecl.java

private static Function<UnifierWithRemainingMembers, Choice<UnifierWithRemainingMembers>> match(
        final Tree tree) {
    return new Function<UnifierWithRemainingMembers, Choice<UnifierWithRemainingMembers>>() {
        @Override//from w ww.  j ava2 s . c  o  m
        public Choice<UnifierWithRemainingMembers> apply(final UnifierWithRemainingMembers state) {
            final ImmutableList<UMethodDecl> currentMembers = state.remainingMembers();
            Choice<Integer> methodChoice = Choice.from(ContiguousSet
                    .create(Range.closedOpen(0, currentMembers.size()), DiscreteDomain.integers()));
            return methodChoice.thenChoose(new Function<Integer, Choice<UnifierWithRemainingMembers>>() {
                @Override
                public Choice<UnifierWithRemainingMembers> apply(Integer i) {
                    ImmutableList<UMethodDecl> remainingMembers = new ImmutableList.Builder<UMethodDecl>()
                            .addAll(currentMembers.subList(0, i))
                            .addAll(currentMembers.subList(i + 1, currentMembers.size())).build();
                    UMethodDecl chosenMethod = currentMembers.get(i);
                    Unifier unifier = state.unifier().fork();
                    /* 
                     * If multiple methods use the same parameter name, preserve the last parameter
                     * name from the target code.  For example, given a @BeforeTemplate with
                     * 
                     *    int get(int index) {...}
                     *    int set(int index, int value) {...}
                     *    
                     * and target code with the lines
                     * 
                     *    int get(int i) {...}
                     *    int set(int j) {...}
                     *    
                     * then use "j" in place of index in the @AfterTemplates.
                     */
                    for (UVariableDecl param : chosenMethod.getParameters()) {
                        unifier.clearBinding(param.key());
                    }
                    return chosenMethod.unify(tree, unifier)
                            .transform(UnifierWithRemainingMembers.withRemaining(remainingMembers));
                }
            });
        }
    };
}

From source file:me.Wundero.Ray.utils.TextSplitter.java

private static Text transformTranslationText(TranslatableText text, Locale locale) {
    // This is bad, don't look
    Translation translation = text.getTranslation();
    ImmutableList<Object> arguments = text.getArguments();
    Object[] markers = new Object[arguments.size()];
    for (int i = 0; i < markers.length; i++) {
        markers[i] = "$MARKER" + i + "$";
    }/*  www  .  ja v  a2s.  c  om*/
    String patched = translation.get(locale, markers);

    List<Object> sections = Lists.newArrayList();
    Matcher m = MARKER_PATTERN.matcher(patched);
    int prevPos = 0;
    while (m.find()) {
        if (m.start() != prevPos) {
            sections.add(patched.substring(prevPos, m.start()));
        }
        int index = Integer.parseInt(m.group(1));
        sections.add(arguments.get(index));
        prevPos = m.end();
    }
    if (prevPos != patched.length() - 1) {
        sections.add(patched.substring(prevPos));
    }
    Text.Builder builder = new Format(text).applyToBuilder(Text.builder());
    for (Object val : sections) {
        builder.append(Text.of(val));
    }
    builder.append(text.getChildren());
    return builder.build();
}

From source file:com.google.devtools.build.lib.rules.android.DexArchiveAspect.java

private static boolean checkBasenameClash(ImmutableList<Artifact> artifacts) {
    if (artifacts.size() <= 1) {
        return false;
    }/* ww w  .  java2 s  . c  om*/
    HashSet<String> seen = new HashSet<>();
    for (Artifact artifact : artifacts) {
        if (!seen.add(artifact.getFilename())) {
            return true;
        }
    }
    return false;
}

From source file:com.spectralogic.ds3autogen.utils.ResponsePayloadUtil.java

/**
 * Gets the Response Type associated with a Ds3ResponseCode. This assumes that all component
 * response types have already been converted into encapsulating types, which is done within
 * the parser module./* w w  w.j ava2 s  .  co m*/
 */
public static String getResponseType(final ImmutableList<Ds3ResponseType> responseTypes) {
    if (isEmpty(responseTypes)) {
        throw new IllegalArgumentException("Response code does not contain any associated types");
    }
    switch (responseTypes.size()) {
    case 1:
        return responseTypes.get(0).getType();
    default:
        throw new IllegalArgumentException("Response code has multiple associated types");
    }
}