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:org.gradle.model.internal.manage.schema.extract.StructStrategy.java

public <R> ModelSchemaExtractionResult<R> extract(final ModelSchemaExtractionContext<R> extractionContext,
        final ModelSchemaCache cache) {
    ModelType<R> type = extractionContext.getType();
    Class<? super R> clazz = type.getRawClass();
    if (clazz.isAnnotationPresent(Managed.class)) {
        validateType(type, extractionContext);

        Iterable<Method> methods = Arrays.asList(clazz.getMethods());
        if (!clazz.isInterface()) {
            methods = filterIgnoredMethods(methods);
        }/*w  w  w  . j  a  va  2  s  . c o  m*/
        ImmutableListMultimap<String, Method> methodsByName = Multimaps.index(methods,
                new Function<Method, String>() {
                    public String apply(Method method) {
                        return method.getName();
                    }
                });

        ensureNoOverloadedMethods(extractionContext, methodsByName);

        List<ModelProperty<?>> properties = Lists.newLinkedList();
        List<Method> handled = Lists.newArrayListWithCapacity(clazz.getMethods().length);
        ReturnTypeSpecializationOrdering returnTypeSpecializationOrdering = new ReturnTypeSpecializationOrdering();

        for (String methodName : methodsByName.keySet()) {
            if (methodName.startsWith("get") && !methodName.equals("get")) {
                ImmutableList<Method> getterMethods = methodsByName.get(methodName);

                // The overload check earlier verified that all methods for are equivalent for our purposes
                // So, taking the first one with the most specialized return type is fine.
                Method sampleMethod = returnTypeSpecializationOrdering.max(getterMethods);

                boolean abstractGetter = Modifier.isAbstract(sampleMethod.getModifiers());

                if (sampleMethod.getParameterTypes().length != 0) {
                    throw invalidMethod(extractionContext, "getter methods cannot take parameters",
                            sampleMethod);
                }

                Character getterPropertyNameFirstChar = methodName.charAt(3);
                if (!Character.isUpperCase(getterPropertyNameFirstChar)) {
                    throw invalidMethod(extractionContext,
                            "the 4th character of the getter method name must be an uppercase character",
                            sampleMethod);
                }

                ModelType<?> returnType = ModelType.returnType(sampleMethod);

                String propertyNameCapitalized = methodName.substring(3);
                String propertyName = StringUtils.uncapitalize(propertyNameCapitalized);
                String setterName = "set" + propertyNameCapitalized;
                ImmutableList<Method> setterMethods = methodsByName.get(setterName);

                boolean isWritable = !setterMethods.isEmpty();
                if (isWritable) {
                    Method setter = setterMethods.get(0);

                    if (!abstractGetter) {
                        throw invalidMethod(extractionContext,
                                "setters are not allowed for non-abstract getters", setter);
                    }
                    validateSetter(extractionContext, returnType, setter);
                    handled.addAll(setterMethods);
                }

                if (abstractGetter) {
                    ImmutableSet<ModelType<?>> declaringClasses = ImmutableSet
                            .copyOf(Iterables.transform(getterMethods, new Function<Method, ModelType<?>>() {
                                public ModelType<?> apply(Method input) {
                                    return ModelType.of(input.getDeclaringClass());
                                }
                            }));

                    boolean unmanaged = Iterables.any(getterMethods, new Predicate<Method>() {
                        public boolean apply(Method input) {
                            return input.getAnnotation(Unmanaged.class) != null;
                        }
                    });

                    properties.add(ModelProperty.of(returnType, propertyName, isWritable, declaringClasses,
                            unmanaged));
                }
                handled.addAll(getterMethods);
            }
        }

        Iterable<Method> notHandled = Iterables.filter(methodsByName.values(),
                Predicates.not(Predicates.in(handled)));

        // TODO - should call out valid getters without setters
        if (!Iterables.isEmpty(notHandled)) {
            throw invalidMethods(extractionContext, "only paired getter/setter methods are supported",
                    notHandled);
        }

        Class<R> concreteClass = type.getConcreteClass();
        Class<? extends R> implClass = classGenerator.generate(concreteClass);
        final ModelStructSchema<R> schema = ModelSchema.struct(type, properties, implClass);
        extractionContext.addValidator(new Action<ModelSchemaExtractionContext<R>>() {
            @Override
            public void execute(ModelSchemaExtractionContext<R> validatorModelSchemaExtractionContext) {
                ensureCanBeInstantiated(extractionContext, schema);
            }
        });
        Iterable<ModelSchemaExtractionContext<?>> propertyDependencies = Iterables.transform(properties,
                new Function<ModelProperty<?>, ModelSchemaExtractionContext<?>>() {
                    public ModelSchemaExtractionContext<?> apply(final ModelProperty<?> property) {
                        return toPropertyExtractionContext(extractionContext, property, cache);
                    }
                });

        return new ModelSchemaExtractionResult<R>(schema, propertyDependencies);
    } else {
        return null;
    }
}

From source file:com.google.googlejavaformat.OpsBuilder.java

public final void token(String token, Doc.Token.RealOrImaginary realOrImaginary,
        Indent plusIndentCommentsBefore, Optional<Indent> breakAndIndentTrailingComment) {
    ImmutableList<? extends Input.Token> tokens = input.getTokens();
    if (token.equals(peekToken().orElse(null))) { // Found the input token. Output it.
        add(Doc.Token.make(tokens.get(tokenI++), Doc.Token.RealOrImaginary.REAL, plusIndentCommentsBefore,
                breakAndIndentTrailingComment));
    } else {//ww w.  j  av  a  2 s.  c  om
        /*
         * Generated a "bad" token, which doesn't exist on the input. Drop it, and complain unless
         * (for example) we're guessing at an optional token.
         */
        if (realOrImaginary.isReal()) {
            throw new FormattingError(diagnostic(String.format("expected token: '%s'; generated %s instead",
                    peekToken().orElse(null), token)));
        }
    }
}

From source file:com.facebook.presto.cli.AlignedTablePrinter.java

@Override
public void printRows(List<List<?>> rows, boolean complete) throws IOException {
    rowCount += rows.size();// w  w w. j a v a 2s  .  com
    int columns = fieldNames.size();

    int[] maxWidth = new int[columns];
    for (int i = 0; i < columns; i++) {
        maxWidth[i] = max(1, consoleWidth(fieldNames.get(i)));
    }
    for (List<?> row : rows) {
        for (int i = 0; i < row.size(); i++) {
            String s = formatValue(row.get(i));
            maxWidth[i] = max(maxWidth[i], maxLineLength(s));
        }
    }

    if (!headerOutput) {
        headerOutput = true;

        for (int i = 0; i < columns; i++) {
            if (i > 0) {
                writer.append('|');
            }
            String name = fieldNames.get(i);
            writer.append(center(name, maxWidth[i], 1));
        }
        writer.append('\n');

        for (int i = 0; i < columns; i++) {
            if (i > 0) {
                writer.append('+');
            }
            writer.append(repeat("-", maxWidth[i] + 2));
        }
        writer.append('\n');
    }

    for (List<?> row : rows) {
        List<List<String>> columnLines = new ArrayList<>(columns);
        int maxLines = 1;
        for (int i = 0; i < columns; i++) {
            String s = formatValue(row.get(i));
            ImmutableList<String> lines = ImmutableList.copyOf(LINE_SPLITTER.split(s));
            columnLines.add(lines);
            maxLines = max(maxLines, lines.size());
        }

        for (int line = 0; line < maxLines; line++) {
            for (int column = 0; column < columns; column++) {
                if (column > 0) {
                    writer.append('|');
                }
                List<String> lines = columnLines.get(column);
                String s = (line < lines.size()) ? lines.get(line) : "";
                boolean numeric = row.get(column) instanceof Number;
                String out = align(s, maxWidth[column], 1, numeric);
                if ((!complete || (rowCount > 1)) && ((line + 1) < lines.size())) {
                    out = out.substring(0, out.length() - 1) + "+";
                }
                writer.append(out);
            }
            writer.append('\n');
        }
    }

    writer.flush();
}

From source file:com.google.defcoin.crypto.DeterministicHierarchy.java

/**
 * Returns a key for the given path, optionally creating it.
 *
 * @param path the path to the key/* ww w.  j a  v a  2  s .  c  o  m*/
 * @param relativePath whether the path is relative to the root path
 * @param create whether the key corresponding to path should be created (with any necessary ancestors) if it doesn't exist already
 * @return next newly created key using the child derivation function
 * @throws IllegalArgumentException if create is false and the path was not found.
 */
public DeterministicKey get(List<ChildNumber> path, boolean relativePath, boolean create) {
    ImmutableList<ChildNumber> absolutePath = relativePath
            ? ImmutableList.<ChildNumber>builder().addAll(rootPath).addAll(path).build()
            : ImmutableList.copyOf(path);
    if (!keys.containsKey(absolutePath)) {
        checkArgument(create, "No key found for {} path {}.", relativePath ? "relative" : "absolute", path);
        checkArgument(absolutePath.size() > 0, "Can't derive the master key: nothing to derive from.");
        DeterministicKey parent = get(absolutePath.subList(0, absolutePath.size() - 1), relativePath, true);
        putKey(HDKeyDerivation.deriveChildKey(parent, absolutePath.get(absolutePath.size() - 1)));
    }
    return keys.get(absolutePath);
}

From source file:com.facebook.buck.core.resources.AbstractResourcesConfig.java

@Value.Lazy
public ImmutableMap<String, ResourceAmounts> getResourceAmountsPerRuleType() {
    ImmutableMap.Builder<String, ResourceAmounts> result = ImmutableMap.builder();
    ImmutableMap<String, String> entries = getDelegate()
            .getEntriesForSection(RESOURCES_PER_RULE_SECTION_HEADER);
    for (String ruleName : entries.keySet()) {
        ImmutableList<String> configAmounts = getDelegate()
                .getListWithoutComments(RESOURCES_PER_RULE_SECTION_HEADER, ruleName);
        Preconditions.checkArgument(configAmounts.size() == ResourceAmounts.RESOURCE_TYPE_COUNT,
                "Buck config entry [%s].%s contains %s values, but expected to contain %s values "
                        + "in the following order: cpu, memory, disk_io, network_io",
                RESOURCES_PER_RULE_SECTION_HEADER, ruleName, configAmounts.size(),
                ResourceAmounts.RESOURCE_TYPE_COUNT);
        ResourceAmounts amounts = ResourceAmounts.of(Integer.parseInt(configAmounts.get(0)),
                Integer.parseInt(configAmounts.get(1)), Integer.parseInt(configAmounts.get(2)),
                Integer.parseInt(configAmounts.get(3)));
        result.put(ruleName, amounts);//from   w  w  w  . j a va 2  s. c o  m
    }
    return result.build();
}

From source file:solar.blaz.rondel.compiler.manager.AbstractInjectorManager.java

protected TypeElement[] parseModuleElements(ImmutableList<TypeMirror> modules) {
    if (modules == null || modules.size() == 0) {
        return null;
    } else {//from  w w w.j a v a2  s .c  o m
        boolean validModules = true;

        TypeElement[] moduleElements = new TypeElement[modules.size()];
        for (int i = 0; i < modules.size(); i++) {
            TypeMirror moduleClass = modules.get(i);

            TypeElement module = elementUtils.getTypeElement(moduleClass.toString());

            if (module.getAnnotation(Module.class) == null) {
                messager.error("App module is missing @Module annotation.");
                validModules = false;
            } else {
                moduleElements[i] = module;
            }
        }

        if (validModules) {
            return moduleElements;
        } else {
            return null;
        }
    }

}

From source file:org.sosy_lab.cpachecker.util.refinement.InterpolationTree.java

/**
 * This method builds a (linear) tree from a single path.
 *
 * Note that, while this is just a special case of {@link buildTreeFromMultiplePaths},
 * this is the preferred way, because the given path could come from any analysis,
 * e.g., a predicate analysis, and the exact given path should be used for interpolation.
 * This is not guaranteed by the more general approach given in {@link buildTreeFromMultiplePaths},
 * because there the interpolation tree is build from a (non-unambiguous) set of states.
 *///from ww w. j a va2  s .  co m
private ARGState buildTreeFromSinglePath(final ARGPath targetPath) {
    ImmutableList<ARGState> states = targetPath.asStatesList();

    for (int i = 0; i < states.size() - 1; i++) {
        ARGState predecessorState = states.get(i);

        ARGState successorState = states.get(i + 1);
        predecessorRelation.put(successorState, predecessorState);
        successorRelation.put(predecessorState, successorState);
    }

    return states.get(0);
}

From source file:io.codis.jodis.RoundRobinJedisPool.java

@Override
public Jedis getResource() {
    ImmutableList<PooledObject> pools = this.pools;
    if (pools.isEmpty()) {
        throw new JedisException("Proxy list empty");
    }//from w ww  . j  a v  a  2  s.  c om
    for (;;) {
        int current = nextIdx.get();
        int next = current >= pools.size() - 1 ? 0 : current + 1;
        if (nextIdx.compareAndSet(current, next)) {
            return pools.get(next).getResource();
        }
    }
}

From source file:com.google.googlejavaformat.OpsBuilder.java

/**
 * Sync to position in the input. If we've skipped outputting any tokens that were present in the
 * input tokens, output them here and optionally complain.
 *
 * @param inputPosition the {@code 0}-based input position
 *///from w w  w. j  a v  a  2  s . c  om
public final void sync(int inputPosition) {
    if (inputPosition > this.inputPosition) {
        ImmutableList<? extends Input.Token> tokens = input.getTokens();
        int tokensN = tokens.size();
        this.inputPosition = inputPosition;
        if (tokenI < tokensN && inputPosition > tokens.get(tokenI).getTok().getPosition()) {
            // Found a missing input token. Insert it and mark it missing (usually not good).
            Input.Token token = tokens.get(tokenI++);
            throw new FormattingError(
                    diagnostic(String.format("did not generate token \"%s\"", token.getTok().getText())));
        }
    }
}

From source file:com.mogujie.instantrun.IncrementalTool.java

public static byte[] getPatchFileContents(ImmutableList<String> patchFileContents,
        ImmutableList<Integer> patchIndexContents) {
    if (patchFileContents.size() != patchIndexContents.size()) {
        throw new GradleException("patchFileContents's size is " + patchFileContents.size()
                + ", but patchIndexContents's size is " + patchIndexContents.size()
                + ", please check the changed classes.");
    }/*from www .j ava  2 s  . co m*/
    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);

    {
        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.SIPUSH, patchFileContents.size());
        mv.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/String");
        for (int index = 0; index < patchFileContents.size(); index++) {
            mv.visitInsn(Opcodes.DUP);
            mv.visitIntInsn(Opcodes.SIPUSH, index);
            mv.visitLdcInsn(patchFileContents.get(index));
            mv.visitInsn(Opcodes.AASTORE);
        }
        mv.visitInsn(Opcodes.ARETURN);
        mv.visitMaxs(4, 1);
        mv.visitEnd();
    }
    {
        mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "getPatchedClassIndexes", "()[I", null, null);
        mv.visitCode();

        mv.visitIntInsn(Opcodes.SIPUSH, patchIndexContents.size());
        mv.visitIntInsn(Opcodes.NEWARRAY, Opcodes.T_INT);
        for (int index = 0; index < patchIndexContents.size(); index++) {
            mv.visitInsn(Opcodes.DUP);
            mv.visitIntInsn(Opcodes.SIPUSH, index);
            mv.visitLdcInsn(patchIndexContents.get(index));
            mv.visitInsn(Opcodes.IASTORE);
        }
        mv.visitInsn(Opcodes.ARETURN);
        mv.visitMaxs(4, 1);
        mv.visitEnd();
    }
    cw.visitEnd();

    return cw.toByteArray();

}