List of usage examples for com.google.common.collect ImmutableList get
E get(int index);
From source file:com.google.errorprone.bugpatterns.TypeParameterNaming.java
private static String suggestedNameFollowedWithT(String identifier) { Preconditions.checkArgument(!identifier.isEmpty()); // Some early checks: // TFoo => FooT if (identifier.length() > 2 && identifier.charAt(0) == 'T' && Ascii.isUpperCase(identifier.charAt(1)) && Ascii.isLowerCase(identifier.charAt(2))) { // splitToLowercaseTerms thinks "TFooBar" is ["tfoo", "bar"], so we remove "t", have it parse // as ["foo", "bar"], then staple "t" back on the end. ImmutableList<String> tokens = NamingConventions.splitToLowercaseTerms(identifier.substring(1)); return Streams.concat(tokens.stream(), Stream.of("T")).map(TypeParameterNaming::upperCamelToken) .collect(Collectors.joining()); }// ww w .ja v a2 s.com ImmutableList<String> tokens = NamingConventions.splitToLowercaseTerms(identifier); // UPPERCASE => UppercaseT if (tokens.size() == 1) { String token = tokens.get(0); if (Ascii.toUpperCase(token).equals(identifier)) { return upperCamelToken(token) + "T"; } } // FooType => FooT if (Iterables.getLast(tokens).equals("type")) { return Streams.concat(tokens.subList(0, tokens.size() - 1).stream(), Stream.of("T")) .map(TypeParameterNaming::upperCamelToken).collect(Collectors.joining()); } return identifier + "T"; }
From source file:com.google.devtools.build.lib.skyframe.AspectFunction.java
private static SkyValue createAliasAspect(Environment env, Target originalTarget, Aspect aspect, AspectKey originalKey, ConfiguredTarget configuredTarget) throws InterruptedException { ImmutableList<Label> aliasChain = configuredTarget.getProvider(AliasProvider.class).getAliasChain(); // Find the next alias in the chain: either the next alias (if there are two) or the name of // the real configured target. Label aliasLabel = aliasChain.size() > 1 ? aliasChain.get(1) : configuredTarget.getLabel(); SkyKey depKey = ActionLookupValue.key(originalKey.withLabel(aliasLabel)); // Compute the AspectValue of the target the alias refers to (which can itself be either an // alias or a real target) AspectValue real = (AspectValue) env.getValue(depKey); if (env.valuesMissing()) { return null; }// w w w . ja v a 2s . c o m NestedSet<Package> transitivePackages = NestedSetBuilder.<Package>stableOrder() .addTransitive(real.getTransitivePackages()).add(originalTarget.getPackage()).build(); return new AspectValue(originalKey, aspect, originalTarget.getLabel(), originalTarget.getLocation(), ConfiguredAspect.forAlias(real.getConfiguredAspect()), ImmutableList.<ActionAnalysisMetadata>of(), transitivePackages); }
From source file:org.locationtech.geogig.plumbing.merge.DiffMergeFeaturesOp.java
static RevFeature merge(FeatureDiff mergeIntoDiff, FeatureDiff toMergeDiff) { if (!mergeIntoDiff.getNewFeatureType().equals(toMergeDiff.getNewFeatureType())) { throw new IllegalArgumentException( String.format("Non-matching feature types. Cannot merge. Left: %s, right: %s", mergeIntoDiff.getNewFeatureType().getId(), toMergeDiff.getNewFeatureType().getId())); }//from www. jav a 2s . c o m RevFeatureType featureType = mergeIntoDiff.getNewFeatureType(); Map<PropertyDescriptor, AttributeDiff> leftDiffs = mergeIntoDiff.getDiffs(); Map<PropertyDescriptor, AttributeDiff> rightDiffs = toMergeDiff.getDiffs(); ImmutableList<PropertyDescriptor> descriptors; descriptors = ImmutableList.copyOf(featureType.type().getDescriptors()); final List<Object> ancestorValues; ancestorValues = getAncestorValues(mergeIntoDiff, toMergeDiff, descriptors); RevFeatureBuilder mergedValues = RevFeatureBuilder.builder(); for (int i = 0; i < descriptors.size(); i++) { final PropertyDescriptor descriptor = descriptors.get(i); final boolean isGeom = descriptor instanceof GeometryDescriptor; @Nullable Object ancestorValue = ancestorValues.get(i); @Nullable AttributeDiff leftAttDiff = leftDiffs.get(descriptor); @Nullable AttributeDiff rightAttDiff = rightDiffs.get(descriptor); Object valueA = leftAttDiff == null ? null : leftAttDiff.getNewValue(); Object valueB = rightAttDiff == null ? null : rightAttDiff.getNewValue(); Object merged; if (leftAttDiff == null) { merged = rightAttDiff == null ? ancestorValue : valueB; } else if (rightAttDiff == null) { merged = valueA; } else if (valueEquals(isGeom, valueA, valueB)) { merged = valueA; } else { // both modified the attribute and didn't set the same value merged = valueA; } mergedValues.addValue(merged); } return mergedValues.build(); }
From source file:co.jirm.orm.builder.ConditionVisitors.java
public static ConditionVisitor conditionVisitor(final Appendable appendable) { final SafeAppendable sb = new SafeAppendable(appendable); ConditionVisitor v = new ConditionVisitor() { private int depth = 0; @Override/*from w w w. j a va 2 s . c o m*/ public void visitAnd(ImmutableList<ImmutableCondition> conditions, Parameters parameters) { depth++; doCondition(" AND ", conditions, parameters); } @Override public void visitOr(ImmutableList<ImmutableCondition> conditions, Parameters parameters) { depth++; doCondition(" OR ", conditions, parameters); } private void doCondition(String op, ImmutableList<ImmutableCondition> conditions, Parameters parameters) { if (conditions.size() == 1) { sb.append(op); conditions.get(0).accept(this); } else { boolean top = depth == 1; if (!top) sb.append("( "); boolean first = true; for (ImmutableCondition c : conditions) { if (first) { first = false; c.accept(this); } else { sb.append(op); c.accept(this); } } if (!top) sb.append(" )"); } } @Override public void visitSql(String sql, Parameters parameters) { sb.append(sql); } }; return v; }
From source file:org.spongepowered.api.item.inventory.ItemStackBuilderPopulators.java
/** * Creates a new {@link BiConsumer} that provides a random * {@link ItemType} from the provided collection of item types. * * @param itemTypes The item types to use * @return The new biconsumer to apply to an itemstack builder */// w w w .j av a 2s .c o m public static BiConsumer<ItemStack.Builder, Random> items(final Collection<ItemType> itemTypes) { final ImmutableList<ItemType> copiedItemTypes = ImmutableList.copyOf(itemTypes); return (builder, random) -> builder.itemType(copiedItemTypes.get(random.nextInt(copiedItemTypes.size()))); }
From source file:com.analog.lyric.collect.Supers.java
/** * Returns nearest common super class between {@code c1} and {@code c2}. * <ul>/*from w w w .ja va2s . com*/ * <li>If {@code c1} and {@code c2} are equal, then {@code c1} will be returned, * even if it is an interface or primitive. * <li>Likewise if {@code c1} is assignable from {@code c2} ({@link Class#isAssignableFrom}) * then {@code c1} will be returned even if it is an interface, and vice versa if the * {@code c2} is assignable from {@code c1}. * <li>If the above is not true, and either argument is a primitive, then null will be returned. * <li>If the above is not true, and either argument is an interface, then {@link Object} will * be returned. * <li>Otherwise, the nearest superclass of both {@code c1} and {@code c2} will be returned. * </ul> */ public static @Nullable Class<?> nearestCommonSuperClass(Class<?> c1, Class<?> c2) { if (c1.isAssignableFrom(c2)) { return c1; } else if (c2.isAssignableFrom(c1)) { return c2; } // At this point we know that the common superclass cannot be c1 or c2. if (c1.isPrimitive() || c2.isPrimitive()) { return null; } if (c1.isInterface() || c2.isInterface()) { return Object.class; } ImmutableList<Class<?>> supers1 = superClasses(c1); ImmutableList<Class<?>> supers2 = superClasses(c2); Class<?> common = Object.class; for (int i = 0, end = Math.min(supers1.size(), supers2.size()); i < end; ++i) { Class<?> super1 = supers1.get(i); if (super1.equals(supers2.get(i))) { common = super1; } else { break; } } return common; }
From source file:com.google.javascript.jscomp.parsing.TypeDeclarationsIRFactory.java
/** * The root of a JSTypeExpression is very different from an AST node, even * though we use the same Java class to represent them. * This function converts root nodes of JSTypeExpressions into TypeDeclaration ASTs, * to make them more similar to ordinary AST nodes. * * @return the root node of a TypeDeclaration AST, or null if no type is * available for the node.//from w w w. ja v a 2 s . c om */ // TODO(dimvar): Eventually, we want to just parse types to the new // representation directly, and delete this function. @Nullable public static TypeDeclarationNode convertTypeNodeAST(Node n) { int token = n.getType(); switch (token) { case Token.STAR: case Token.EMPTY: // for function types that don't declare a return type return anyType(); case Token.VOID: return undefinedType(); case Token.BANG: // TODO(alexeagle): non-nullable is assumed to be the default return convertTypeNodeAST(n.getFirstChild()); case Token.STRING: String typeName = n.getString(); switch (typeName) { case "boolean": return booleanType(); case "number": return numberType(); case "string": return stringType(); case "null": case "undefined": case "void": return null; default: TypeDeclarationNode root = namedType(typeName); if (n.getChildCount() > 0 && n.getFirstChild().isBlock()) { Node block = n.getFirstChild(); if ("Array".equals(typeName)) { return arrayType(convertTypeNodeAST(block.getFirstChild())); } return parameterizedType(root, Iterables.transform(block.children(), CONVERT_TYPE_NODE)); } return root; } case Token.QMARK: Node child = n.getFirstChild(); return child == null ? anyType() // For now, our ES6_TYPED language doesn't support nullable // so we drop it before building the tree. // : nullable(convertTypeNodeAST(child)); : convertTypeNodeAST(child); case Token.LC: LinkedHashMap<String, TypeDeclarationNode> properties = new LinkedHashMap<>(); for (Node field : n.getFirstChild().children()) { boolean isFieldTypeDeclared = field.getType() == Token.COLON; Node fieldNameNode = isFieldTypeDeclared ? field.getFirstChild() : field; String fieldName = fieldNameNode.getString(); if (fieldName.startsWith("'") || fieldName.startsWith("\"")) { fieldName = fieldName.substring(1, fieldName.length() - 1); } TypeDeclarationNode fieldType = isFieldTypeDeclared ? convertTypeNodeAST(field.getLastChild()) : null; properties.put(fieldName, fieldType); } return recordType(properties); case Token.ELLIPSIS: return arrayType(convertTypeNodeAST(n.getFirstChild())); case Token.PIPE: ImmutableList<TypeDeclarationNode> types = FluentIterable.from(n.children()) .transform(CONVERT_TYPE_NODE).filter(Predicates.notNull()).toList(); switch (types.size()) { case 0: return null; case 1: return types.get(0); default: return unionType(types); } case Token.FUNCTION: Node returnType = anyType(); LinkedHashMap<String, TypeDeclarationNode> parameters = new LinkedHashMap<>(); String restName = null; TypeDeclarationNode restType = null; for (Node child2 : n.children()) { if (child2.isParamList()) { int paramIdx = 1; for (Node param : child2.children()) { String paramName = "p" + paramIdx++; if (param.getType() == Token.ELLIPSIS) { restName = paramName; if (param.getFirstChild() != null) { restType = convertTypeNodeAST(param.getFirstChild()); } } else { parameters.put(paramName, convertTypeNodeAST(param)); } } } else if (child2.isNew()) { // TODO(alexeagle): keep the constructor signatures on the tree, and emit them following // the syntax in TypeScript 1.4 spec, section 3.7.8 Constructor Type Literals } else if (child2.isThis()) { // Not expressible in TypeScript syntax, so we omit them from the tree. // They could be added as properties on the result node. } else { returnType = convertTypeNodeAST(child2); } } return functionType(returnType, parameters, restName, restType); case Token.EQUALS: return optionalParameter(convertTypeNodeAST(n.getFirstChild())); default: throw new IllegalArgumentException( "Unsupported node type: " + Token.name(n.getType()) + " " + n.toStringTree()); } }
From source file:com.palantir.common.base.BatchingVisitables.java
public static <T, TOKEN> TokenBackedBasicResultsPage<T, TOKEN> getFirstPage(BatchingVisitable<T> v, int numToVisitArg, Function<T, TOKEN> tokenExtractor) { Preconditions.checkArgument(numToVisitArg >= 0, "numToVisit cannot be negative. Value was: " + numToVisitArg); if (numToVisitArg == Integer.MAX_VALUE) { // prevent issue with overflow numToVisitArg--;// w w w . ja va 2 s . c om } final int numToVisit = numToVisitArg + 1; ImmutableList<T> list = BatchingVisitableView.of(v).limit(numToVisit).immutableCopy(); Preconditions.checkState(list.size() <= numToVisit); if (list.size() >= numToVisit) { TOKEN token = tokenExtractor.apply(list.get(list.size() - 1)); list = list.subList(0, numToVisit - 1); return new SimpleTokenBackedResultsPage<T, TOKEN>(token, list, true); } return new SimpleTokenBackedResultsPage<T, TOKEN>(null, list, false); }
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 2 s . c om*/ */ 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.google.template.soy.jbcsrc.restricted.Expression.java
/** Checks that the given expressions are compatible with the given types. */ static void checkTypes(ImmutableList<Type> types, Iterable<? extends Expression> exprs) { if (Flags.DEBUG) { int size = Iterables.size(exprs); checkArgument(size == types.size(), "Supplied the wrong number of parameters. Expected %s, got %s", types.size(), size);//w ww .j av a2s.c o m int i = 0; for (Expression expr : exprs) { expr.checkAssignableTo(types.get(i), "Parameter %s", i); i++; } } }