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

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

Introduction

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

Prototype

E get(int index);

Source Link

Document

Returns the element at the specified position in this list.

Usage

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  . j  a  v  a 2  s  .  co m*/
        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:com.google.javascript.jscomp.TypeTransformation.java

private JSType evalTemplatizedType(Node ttlAst, NameResolver nameResolver) {
    ImmutableList<Node> params = getCallParams(ttlAst);
    JSType firstParam = evalInternal(params.get(0), nameResolver);
    if (!isTemplatizable(firstParam)) {
        reportWarning(ttlAst, BASETYPE_INVALID, firstParam.toString());
        return getUnknownType();
    }/*from  w w w.  jav a 2  s .c om*/
    ObjectType baseType = firstParam.toObjectType();
    // TODO(lpino): Check that the number of parameters correspond with the
    // number of template types that the base type can take when creating
    // a templatized type. For instance, if the base type is Array then there
    // must be just one parameter.
    JSType[] templatizedTypes = new JSType[params.size() - 1];
    for (int i = 0; i < templatizedTypes.length; i++) {
        templatizedTypes[i] = evalInternal(params.get(i + 1), nameResolver);
    }
    return createTemplatizedType(baseType, templatizedTypes);
}

From source file:com.facebook.buck.rust.RustCompile.java

@VisibleForTesting
Path getCrateRoot() {//  w  ww . j  av  a2s  .c om
    SourcePathResolver resolver = getResolver();
    Optional<Path> crateRoot = this.crateRoot.map(resolver::getRelativePath);
    String crateName = String.format("%s.rs", getCrateName());
    ImmutableList<Path> candidates = srcs.stream().map(resolver::getRelativePath).filter(Objects::nonNull)
            .filter(p -> crateRoot.map(p::equals).orElse(false) || p.endsWith(crateName)
                    || getDefaultSources().contains(p.getFileName().toString()))
            .collect(MoreCollectors.toImmutableList());

    if (candidates.size() != 1) {
        throw new HumanReadableException("srcs of %s must contain either %s or %s.rs!",
                getBuildTarget().getFullyQualifiedName(), getDefaultSources(), crate);
    }
    // We end up creating a symlink tree to ensure that the crate only uses the files that it
    // declares in the BUCK file.
    return scratchDir.resolve(candidates.get(0));
}

From source file:com.google.javascript.jscomp.TypeTransformation.java

private JSType evalMapunion(Node ttlAst, NameResolver nameResolver) {
    ImmutableList<Node> params = getCallParams(ttlAst);
    Node unionParam = params.get(0);
    Node mapFunction = params.get(1);
    String paramName = getFunctionParameter(mapFunction, 0);

    // The mapunion variable must not be defined in the environment
    if (nameResolver.typeVars.containsKey(paramName)) {
        reportWarning(ttlAst, DUPLICATE_VARIABLE, paramName);
        return getUnknownType();
    }/*from w  w  w  . j  a v  a 2 s  .  c om*/

    Node mapFunctionBody = getFunctionBody(mapFunction);
    JSType unionType = evalInternal(unionParam, nameResolver);
    // If the first parameter does not correspond to a union type then
    // consider it as a union with a single type and evaluate
    if (!unionType.isUnionType()) {
        NameResolver newNameResolver = new NameResolver(
                addNewEntry(nameResolver.typeVars, paramName, unionType), nameResolver.nameVars);
        return evalInternal(mapFunctionBody, newNameResolver);
    }

    // Otherwise obtain the elements in the union type. Note that the block
    // above guarantees the casting to be safe
    Collection<JSType> unionElms = ((UnionType) unionType).getAlternates();
    // Evaluate the map function body using each element in the union type
    int unionSize = unionElms.size();
    JSType[] newUnionElms = new JSType[unionSize];
    int i = 0;
    for (JSType elm : unionElms) {
        NameResolver newNameResolver = new NameResolver(addNewEntry(nameResolver.typeVars, paramName, elm),
                nameResolver.nameVars);
        newUnionElms[i] = evalInternal(mapFunctionBody, newNameResolver);
        i++;
    }

    return createUnionType(newUnionElms);
}

From source file:org.geogit.cli.porcelain.Show.java

public void printFormatted(GeogitCLI cli) throws IOException {
    ConsoleReader console = cli.getConsole();
    GeoGIT geogit = cli.getGeogit();//  ww w.  ja v  a2  s  .com
    for (String ref : refs) {
        Optional<RevObject> obj = geogit.command(RevObjectParse.class).setRefSpec(ref).call();
        checkParameter(obj.isPresent(), "refspec did not resolve to any object.");
        RevObject revObject = obj.get();
        if (revObject instanceof RevFeature) {
            RevFeatureType ft = geogit.command(ResolveFeatureType.class).setRefSpec(ref).call().get();
            ImmutableList<PropertyDescriptor> attribs = ft.sortedDescriptors();
            RevFeature feature = (RevFeature) revObject;
            Ansi ansi = super.newAnsi(console.getTerminal());
            ansi.newline().fg(Color.YELLOW).a("ID:  ").reset().a(feature.getId().toString()).newline()
                    .newline();
            ansi.a("ATTRIBUTES  ").newline();
            ansi.a("----------  ").newline();
            ImmutableList<Optional<Object>> values = feature.getValues();
            int i = 0;
            for (Optional<Object> value : values) {
                ansi.fg(Color.YELLOW).a(attribs.get(i).getName() + ": ").reset();
                ansi.a(value.or("[NULL]").toString()).newline();
                i++;
            }
            console.println(ansi.toString());

        } else if (revObject instanceof RevTree) {
            RevTree tree = (RevTree) revObject;
            Optional<RevFeatureType> opt = geogit.command(ResolveFeatureType.class).setRefSpec(ref).call();
            checkParameter(opt.isPresent(), "Refspec must resolve to a commit, tree, feature or feature type");
            RevFeatureType ft = opt.get();
            Ansi ansi = super.newAnsi(console.getTerminal());

            ansi.fg(Color.YELLOW).a("TREE ID:  ").reset().a(tree.getId().toString()).newline();
            ansi.fg(Color.YELLOW).a("SIZE:  ").reset().a(Long.toString(tree.size())).newline();
            ansi.fg(Color.YELLOW).a("NUMBER Of SUBTREES:  ").reset()
                    .a(Integer.toString(tree.numTrees()).toString()).newline();

            printFeatureType(ansi, ft, true);

            console.println(ansi.toString());
        } else if (revObject instanceof RevCommit) {
            RevCommit commit = (RevCommit) revObject;
            Ansi ansi = super.newAnsi(console.getTerminal());
            ansi.a(Strings.padEnd("Commit:", 15, ' ')).fg(Color.YELLOW).a(commit.getId().toString()).reset()
                    .newline();
            ansi.a(Strings.padEnd("Author:", 15, ' ')).fg(Color.GREEN).a(formatPerson(commit.getAuthor()))
                    .reset().newline();
            ansi.a(Strings.padEnd("Committer:", 15, ' ')).fg(Color.GREEN).a(formatPerson(commit.getAuthor()))
                    .reset().newline();
            ansi.a(Strings.padEnd("Author date:", 15, ' ')).a("(").fg(Color.RED)
                    .a(estimateSince(geogit.getPlatform(), commit.getAuthor().getTimestamp())).reset().a(") ")
                    .a(new Date(commit.getAuthor().getTimestamp())).newline();
            ansi.a(Strings.padEnd("Committer date:", 15, ' ')).a("(").fg(Color.RED)
                    .a(estimateSince(geogit.getPlatform(), commit.getCommitter().getTimestamp())).reset()
                    .a(") ").a(new Date(commit.getCommitter().getTimestamp())).newline();
            ansi.a(Strings.padEnd("Subject:", 15, ' ')).a(commit.getMessage()).newline();
            console.println(ansi.toString());
        } else if (revObject instanceof RevFeatureType) {
            Ansi ansi = super.newAnsi(console.getTerminal());
            printFeatureType(ansi, (RevFeatureType) revObject, false);
            console.println(ansi.toString());
        } else {
            throw new InvalidParameterException(
                    "Refspec must resolve to a commit, tree, feature or feature type");
        }
        console.println();
    }

}

From source file:com.android.build.gradle.internal.transforms.InstantRunTransform.java

/**
 * Use asm to generate a concrete subclass of the AppPathLoaderImpl class.
 * It only implements one method :/*from  w  ww. ja v  a  2s  .  c o  m*/
 *      String[] getPatchedClasses();
 *
 * The method is supposed to return the list of classes that were patched in this iteration.
 * This will be used by the InstantRun runtime to load all patched classes and register them
 * as overrides on the original classes.2 class files.
 *
 * @param patchFileContents list of patched class names.
 * @param outputDir output directory where to generate the .class file in.
 */
private static void writePatchFileContents(@NonNull ImmutableList<String> patchFileContents,
        @NonNull File outputDir, long buildId) {

    ClassWriter cw = new ClassWriter(0);
    MethodVisitor mv;

    cw.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER, IncrementalVisitor.APP_PATCHES_LOADER_IMPL,
            null, IncrementalVisitor.ABSTRACT_PATCHES_LOADER_IMPL, null);

    // Add the build ID to force the patch file to be repackaged.
    cw.visitField(Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC + Opcodes.ACC_FINAL, "BUILD_ID", "J", null, buildId);

    {
        mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
        mv.visitCode();
        mv.visitVarInsn(Opcodes.ALOAD, 0);
        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, IncrementalVisitor.ABSTRACT_PATCHES_LOADER_IMPL, "<init>",
                "()V", false);
        mv.visitInsn(Opcodes.RETURN);
        mv.visitMaxs(1, 1);
        mv.visitEnd();
    }
    {
        mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "getPatchedClasses", "()[Ljava/lang/String;", null, null);
        mv.visitCode();
        mv.visitIntInsn(Opcodes.BIPUSH, patchFileContents.size());
        mv.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/String");
        for (int index = 0; index < patchFileContents.size(); index++) {
            mv.visitInsn(Opcodes.DUP);
            mv.visitIntInsn(Opcodes.BIPUSH, index);
            mv.visitLdcInsn(patchFileContents.get(index));
            mv.visitInsn(Opcodes.AASTORE);
        }
        mv.visitInsn(Opcodes.ARETURN);
        mv.visitMaxs(4, 1);
        mv.visitEnd();
    }
    cw.visitEnd();

    byte[] classBytes = cw.toByteArray();
    File outputFile = new File(outputDir, IncrementalVisitor.APP_PATCHES_LOADER_IMPL + ".class");
    try {
        Files.createParentDirs(outputFile);
        Files.write(classBytes, outputFile);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.google.javascript.jscomp.parsing.parser.codegeneration.ParseTreeTransformer.java

@SuppressWarnings("unchecked")
protected <E extends ParseTree> ImmutableList<E> transformList(ImmutableList<E> list) {
    if (list == null || list.size() == 0) {
        return list;
    }//from  w ww.j  a  v  a2s.co m

    ImmutableList.Builder<E> builder = null;

    for (int index = 0; index < list.size(); index++) {
        ParseTree element = list.get(index);
        ParseTree transformed = transformAny(element);

        if (builder != null || element != transformed) {
            if (builder == null) {
                builder = ImmutableList.builder();
                builder.addAll(list.subList(0, index));
            }
            builder.add((E) transformed);
        }
    }

    return builder != null ? builder.build() : list;
}

From source file:com.facebook.buck.cli.BuckConfig.java

public ArtifactCache createArtifactCache(Optional<String> currentWifiSsid, BuckEventBus buckEventBus) {
    ImmutableList<String> modes = getArtifactCacheModes();
    if (modes.isEmpty()) {
        return new NoopArtifactCache();
    }/*from   w  ww. j a v a2 s.c  o  m*/
    ImmutableList.Builder<ArtifactCache> builder = ImmutableList.builder();
    try {
        for (String mode : modes) {
            switch (ArtifactCacheNames.valueOf(mode)) {
            case dir:
                ArtifactCache dirArtifactCache = createDirArtifactCache();
                buckEventBus.register(dirArtifactCache);
                builder.add(dirArtifactCache);
                break;
            case cassandra:
                ArtifactCache cassandraArtifactCache = createCassandraArtifactCache(currentWifiSsid,
                        buckEventBus);
                if (cassandraArtifactCache != null) {
                    builder.add(cassandraArtifactCache);
                }
                break;
            }
        }
    } catch (IllegalArgumentException e) {
        throw new HumanReadableException("Unusable cache.mode: '%s'", modes.toString());
    }
    ImmutableList<ArtifactCache> artifactCaches = builder.build();
    if (artifactCaches.size() == 1) {
        // Don't bother wrapping a single artifact cache in MultiArtifactCache.
        return artifactCaches.get(0);
    } else {
        return new MultiArtifactCache(artifactCaches);
    }
}

From source file:com.google.javascript.jscomp.parsing.parser.codegeneration.ParseTreeTransformer.java

final protected ImmutableList<ParseTree> transformSourceElements(ImmutableList<ParseTree> list) {
    if (list == null || list.size() == 0) {
        return list;
    }//w ww.ja  v  a 2 s  . com

    ImmutableList.Builder<ParseTree> builder = null;

    for (int index = 0; index < list.size(); index++) {
        ParseTree element = list.get(index);
        ParseTree transformed = toSourceElement(transformAny(element));

        if (builder != null || element != transformed) {
            if (builder == null) {
                builder = ImmutableList.builder();
                builder.addAll(list.subList(0, index));
            }
            builder.add(transformed);
        }
    }

    return builder != null ? builder.build() : list;
}

From source file:org.elasticsearch.client.transport.TransportClientNodesService.java

public <Response> void execute(NodeListenerCallback<Response> callback, ActionListener<Response> listener)
        throws ElasticsearchException {
    ImmutableList<DiscoveryNode> nodes = this.nodes;
    if (nodes.isEmpty()) {
        throw new NoNodeAvailableException();
    }//from  w w w .  j a  v  a 2 s . c  om
    int index = randomNodeGenerator.incrementAndGet();
    if (index < 0) {
        index = 0;
        randomNodeGenerator.set(0);
    }
    RetryListener<Response> retryListener = new RetryListener<>(callback, listener, nodes, index);
    try {
        callback.doWithNode(nodes.get((index) % nodes.size()), retryListener);
    } catch (ElasticsearchException e) {
        if (e.unwrapCause() instanceof ConnectTransportException) {
            retryListener.onFailure(e);
        } else {
            throw e;
        }
    }
}