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:net.techcable.sonarpet.utils.ProfileUtils.java

public static ImmutableList<PlayerProfile> lookupAll(Iterable<String> iterable) {
    ImmutableList<String> names = ImmutableList.copyOf(Preconditions.checkNotNull(iterable, "Null collection"));
    PlayerProfile[] profiles = new PlayerProfile[names.size()];
    int profilesSize = 0;
    int requests = MathMagic.divideRoundUp(names.size(), PROFILES_PER_REQUEST);
    int nameIndex = 0;
    List<String> toRequest = new ArrayList<>(PROFILES_PER_REQUEST);
    for (int requestId = 0; requestId < requests; requestId++) {
        toRequest.clear();//from ww w .  j a  v a2  s.  co  m
        for (int start = nameIndex; nameIndex < names.size() && nameIndex < start + 100; nameIndex++) {
            String name = names.get(nameIndex);
            PlayerProfile profile;
            if ((profile = nameCache.get(name)) != null) {
                profiles[profilesSize++] = profile;
            } else {
                toRequest.add(name);
            }
        }
        for (PlayerProfile profile : postNames(toRequest)) {
            profiles[profilesSize++] = profile;
        }
    }
    profiles = Arrays.copyOf(profiles, profilesSize); // Trim
    return ImmutableList.copyOf(profiles);
}

From source file:com.android.tools.idea.editors.theme.ThemeEditorUtils.java

/**
 * Creates a new style by displaying the dialog of the {@link NewStyleDialog}.
 * @param defaultParentStyle is used in NewStyleDialog, will be preselected in the parent text field and name will be suggested based on it
 * @param themeEditorContext  current theme editor context
 * @param isTheme whether theme or style will be created
 * @param message is used in NewStyleDialog to display message to user
 * @return the new style name or null if the style wasn't created
 *//*from ww w .ja  v  a2s . c om*/
@Nullable
public static String showCreateNewStyleDialog(@Nullable ConfiguredThemeEditorStyle defaultParentStyle,
        @NotNull final ThemeEditorContext themeEditorContext, boolean isTheme, boolean enableParentChoice,
        @Nullable final String message,
        @Nullable ThemeSelectionPanel.ThemeChangedListener themeChangedListener) {
    // if isTheme is true, defaultParentStyle shouldn't be null
    String defaultParentStyleName = null;
    if (isTheme && defaultParentStyle == null) {
        ImmutableList<String> defaultThemes = getDefaultThemeNames(themeEditorContext.getThemeResolver());
        defaultParentStyleName = !defaultThemes.isEmpty() ? defaultThemes.get(0) : null;
    } else if (defaultParentStyle != null) {
        defaultParentStyleName = defaultParentStyle.getQualifiedName();
    }

    final NewStyleDialog dialog = new NewStyleDialog(isTheme, themeEditorContext, defaultParentStyleName,
            (defaultParentStyle == null) ? null : defaultParentStyle.getName(), message);
    dialog.enableParentChoice(enableParentChoice);
    if (themeChangedListener != null) {
        dialog.setThemeChangedListener(themeChangedListener);
    }

    boolean createStyle = dialog.showAndGet();
    if (!createStyle) {
        return null;
    }

    int minModuleApi = getMinApiLevel(themeEditorContext.getCurrentContextModule());
    int minAcceptableApi = ResolutionUtils.getOriginalApiLevel(
            ResolutionUtils.getStyleResourceUrl(dialog.getStyleParentName()), themeEditorContext.getProject());

    final String fileName = AndroidResourceUtil.getDefaultResourceFileName(ResourceType.STYLE);
    FolderConfiguration config = new FolderConfiguration();
    if (minModuleApi < minAcceptableApi) {
        VersionQualifier qualifier = new VersionQualifier(minAcceptableApi);
        config.setVersionQualifier(qualifier);
    }

    if (fileName == null) {
        LOG.error("Couldn't find a default filename for ResourceType.STYLE");
        return null;
    }

    final List<String> dirNames = Collections.singletonList(config.getFolderName(ResourceFolderType.VALUES));
    String parentStyleName = dialog.getStyleParentName();

    Module module = themeEditorContext.getCurrentContextModule();
    AndroidFacet facet = AndroidFacet.getInstance(module);
    if (facet == null) {
        LOG.error("Create new style for non-Android module " + module.getName());
        return null;
    }
    Project project = module.getProject();
    VirtualFile resourceDir = facet.getPrimaryResourceDir();
    if (resourceDir == null) {
        AndroidUtils.reportError(project, AndroidBundle.message("check.resource.dir.error", module.getName()));
        return null;
    }
    boolean isCreated = createNewStyle(project, resourceDir, dialog.getStyleName(), parentStyleName, fileName,
            dirNames);

    return isCreated ? dialog.getStyleName() : null;
}

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/* w w  w .  j  a  va  2 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:com.github.rinde.logistics.pdptw.solver.CheapestInsertionHeuristic.java

static ImmutableList<ImmutableList<Parcel>> decomposed(GlobalStateObject state, ObjectiveFunction objFunc)
        throws InterruptedException {
    ImmutableList<ImmutableList<Parcel>> schedule = createSchedule(state);
    ImmutableList<Double> costs = decomposedCost(state, schedule, objFunc);
    final ImmutableSet<Parcel> newParcels = GlobalStateObjects.unassignedParcels(state);
    // all new parcels need to be inserted in the plan
    for (final Parcel p : newParcels) {
        double cheapestInsertion = Double.POSITIVE_INFINITY;
        ImmutableList<Parcel> cheapestRoute = null;
        double cheapestRouteCost = 0;
        int cheapestRouteIndex = -1;

        for (int i = 0; i < state.getVehicles().size(); i++) {
            final int startIndex = state.getVehicles().get(i).getDestination().isPresent() ? 1 : 0;

            final Iterator<ImmutableList<Parcel>> insertions = Insertions.insertionsIterator(schedule.get(i), p,
                    startIndex, 2);//from w w  w.  j  a  v  a 2 s  . c  om

            while (insertions.hasNext()) {
                if (Thread.interrupted()) {
                    throw new InterruptedException();
                }

                final ImmutableList<Parcel> r = insertions.next();
                final double absCost = objFunc
                        .computeCost(Solvers.computeStats(state.withSingleVehicle(i), ImmutableList.of(r)));

                final double insertionCost = absCost - costs.get(i);
                if (insertionCost < cheapestInsertion) {
                    cheapestInsertion = insertionCost;
                    cheapestRoute = r;
                    cheapestRouteIndex = i;
                    cheapestRouteCost = absCost;
                }
            }
        }
        schedule = modifySchedule(schedule, verifyNotNull(cheapestRoute), cheapestRouteIndex);
        costs = modifyCosts(costs, cheapestRouteCost, cheapestRouteIndex);
    }
    return schedule;
}

From source file:com.google.devtools.kythe.analyzers.jvm.ClassFileIndexer.java

private static VName getEnclosingJar(ImmutableList<VName> enclosingJars, CompilationUnit.FileInput file) {
    JarEntryDetails jarEntryDetails = null;
    for (Any details : file.getDetailsList()) {
        if (details.getTypeUrl().equals(JAR_ENTRY_DETAILS_URL)) {
            try {
                jarEntryDetails = JarEntryDetails.parseFrom(details.getValue());
            } catch (InvalidProtocolBufferException ipbe) {
                logger.atWarning().withCause(ipbe).log("Error unpacking JarEntryDetails");
            }//from   w w w  .  ja  v a  2  s  .  c  o m
        }
    }
    if (jarEntryDetails == null) {
        return null;
    }
    int idx = jarEntryDetails.getJarContainer();
    if (idx < 0 || idx >= enclosingJars.size()) {
        logger.atWarning().log("JarEntryDetails index out of range: %s (jars: %s)", jarEntryDetails,
                enclosingJars);
        return null;
    }
    return enclosingJars.get(idx);
}

From source file:com.facebook.buck.rules.macros.FunctionMacroReplacer.java

@Override
public String replace(ImmutableList<String> input) throws MacroException {
    return function.apply(input.get(0));
}

From source file:org.xlrnet.tibaija.commands.DummyCommand.java

/**
 * Main method for invoking a command. Must be overwritten by the specific implementation. When this method gets
 * called by the framework, both hasValidArgumentValues() and hasValidNumberOfArguments() have already been called.
 *
 * @param arguments/*  ww  w.  j  a  v  a 2  s .com*/
 *         The arguments for the command.
 * @return An optional return value.
 */
@NotNull
@Override
protected Optional<Value> execute(@NotNull ImmutableList<Parameter> arguments) {
    return Optional.of(arguments.get(0).value());
}

From source file:com.facebook.buck.query.FilterFunction.java

@Override
protected QueryExpression getExpressionToEval(ImmutableList<Argument> args) {
    return args.get(1).getExpression();
}

From source file:com.facebook.buck.query.FilterFunction.java

@Override
protected String getPattern(ImmutableList<Argument> args) {
    return args.get(0).getWord();
}

From source file:com.facebook.buck.rules.coercer.LocationMacroTypeCoercer.java

@Override
public LocationMacro coerce(CellPathResolver cellRoots, ProjectFilesystem filesystem,
        Path pathRelativeToProjectRoot, TargetConfiguration targetConfiguration, ImmutableList<String> args)
        throws CoerceFailedException {
    if (args.size() != 1 || args.get(0).isEmpty()) {
        throw new CoerceFailedException(String.format("expected exactly one argument (found %d)", args.size()));
    }//from   ww  w .  ja v a 2 s .  c  o  m
    LocationMacro.SplitResult parts = LocationMacro.splitSupplementaryOutputPart(args.get(0));
    BuildTarget target = buildTargetTypeCoercer.coerce(cellRoots, filesystem, pathRelativeToProjectRoot,
            targetConfiguration, parts.target);
    return LocationMacro.of(target, parts.supplementaryOutput);
}