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

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

Introduction

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

Prototype

@Override
    public ImmutableList<E> subList(int fromIndex, int toIndex) 

Source Link

Usage

From source file:com.google.devtools.build.lib.syntax.FuncallExpression.java

/**
 * Call a method depending on the type of an object it is called on.
 *
 * <p>Public for reflection by the compiler and access from generated byte code.
 *
 * @param positionals The first object is expected to be the object the method is called on.
 * @param call the original expression that caused this call, needed for rules especially
 *//* ww  w . ja  v a2 s . c  om*/
public Object invokeObjectMethod(String method, ImmutableList<Object> positionals,
        ImmutableMap<String, Object> keyWordArgs, FuncallExpression call, Environment env)
        throws EvalException, InterruptedException {
    Location location = call.getLocation();
    Object value = positionals.get(0);
    ImmutableList<Object> positionalArgs = positionals.subList(1, positionals.size());
    BaseFunction function = Runtime.getFunction(EvalUtils.getSkylarkType(value.getClass()), method);
    if (function != null) {
        if (!isNamespace(value.getClass())) {
            // Use self as an implicit parameter in front.
            positionalArgs = positionals;
        }
        return function.call(positionalArgs, ImmutableMap.<String, Object>copyOf(keyWordArgs), call, env);
    } else if (value instanceof ClassObject) {
        Object fieldValue = ((ClassObject) value).getValue(method);
        if (fieldValue == null) {
            throw new EvalException(location, String.format("struct has no method '%s'", method));
        }
        if (!(fieldValue instanceof BaseFunction)) {
            throw new EvalException(location, String.format("struct field '%s' is not a function", method));
        }
        function = (BaseFunction) fieldValue;
        return function.call(positionalArgs, ImmutableMap.<String, Object>copyOf(keyWordArgs), call, env);
    } else {
        // When calling a Java method, the name is not in the Environment,
        // so evaluating 'func' would fail.
        Class<?> objClass;
        Object obj;
        if (value instanceof Class<?>) {
            // Static call
            obj = null;
            objClass = (Class<?>) value;
        } else {
            obj = value;
            objClass = value.getClass();
        }
        Pair<MethodDescriptor, List<Object>> javaMethod = call.findJavaMethod(objClass, method, positionalArgs,
                keyWordArgs);
        if (javaMethod.first.getAnnotation().structField()) {
            // Not a method but a callable attribute
            try {
                return callFunction(javaMethod.first.getMethod().invoke(obj), env);
            } catch (IllegalAccessException e) {
                throw new EvalException(getLocation(), "method invocation failed: " + e);
            } catch (InvocationTargetException e) {
                if (e.getCause() instanceof FuncallException) {
                    throw new EvalException(getLocation(), e.getCause().getMessage());
                } else if (e.getCause() != null) {
                    throw new EvalExceptionWithJavaCause(getLocation(), e.getCause());
                } else {
                    // This is unlikely to happen
                    throw new EvalException(getLocation(), "method invocation failed: " + e);
                }
            }
        }
        return callMethod(javaMethod.first, method, obj, javaMethod.second.toArray(), location, env);
    }
}

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

@Override
public Fix replace(BlockTemplateMatch match) {
    checkNotNull(match);//  w  w w.j  av  a 2  s. c om
    SuggestedFix.Builder fix = SuggestedFix.builder();
    Inliner inliner = match.createInliner();
    Context context = inliner.getContext();
    if (annotations().containsKey(UseImportPolicy.class)) {
        ImportPolicy.bind(context, annotations().getInstance(UseImportPolicy.class).value());
    } else {
        ImportPolicy.bind(context, ImportPolicy.IMPORT_TOP_LEVEL);
    }
    ImmutableList<JCStatement> targetStatements = match.getStatements();
    try {
        ImmutableList.Builder<JCStatement> inlinedStatementsBuilder = ImmutableList.builder();
        for (UStatement statement : templateStatements()) {
            inlinedStatementsBuilder.addAll(statement.inlineStatements(inliner));
        }
        ImmutableList<JCStatement> inlinedStatements = inlinedStatementsBuilder.build();
        int nInlined = inlinedStatements.size();
        int nTargets = targetStatements.size();
        if (nInlined <= nTargets) {
            for (int i = 0; i < nInlined; i++) {
                fix.replace(targetStatements.get(i), printStatement(context, inlinedStatements.get(i)));
            }
            for (int i = nInlined; i < nTargets; i++) {
                fix.delete(targetStatements.get(i));
            }
        } else {
            for (int i = 0; i < nTargets - 1; i++) {
                fix.replace(targetStatements.get(i), printStatement(context, inlinedStatements.get(i)));
            }
            int last = nTargets - 1;
            ImmutableList<JCStatement> remainingInlined = inlinedStatements.subList(last, nInlined);
            fix.replace(targetStatements.get(last),
                    CharMatcher.whitespace().trimTrailingFrom(printStatements(context, remainingInlined)));
        }
    } catch (CouldNotResolveImportException e) {
        logger.log(SEVERE, "Failure to resolve import in replacement", e);
    }
    return addImports(inliner, fix);
}

From source file:dagger2.internal.codegen.BindingGraphValidator.java

private void reportMissingBinding(Deque<ResolvedRequest> path,
        ValidationReport.Builder<BindingGraph> reportBuilder) {
    Key key = path.peek().request().key();
    TypeMirror type = key.type();
    String typeName = TypeNames.forTypeMirror(type).toString();
    boolean requiresContributionMethod = !key.isValidImplicitProvisionKey(types);
    boolean requiresProvision = doesPathRequireProvisionOnly(path);
    StringBuilder errorMessage = new StringBuilder();
    String requiresErrorMessageFormat = requiresContributionMethod
            ? requiresProvision ? REQUIRES_PROVIDER_FORMAT : REQUIRES_PROVIDER_OR_PRODUCER_FORMAT
            : requiresProvision ? REQUIRES_AT_INJECT_CONSTRUCTOR_OR_PROVIDER_FORMAT
                    : REQUIRES_AT_INJECT_CONSTRUCTOR_OR_PROVIDER_OR_PRODUCER_FORMAT;
    errorMessage.append(String.format(requiresErrorMessageFormat, typeName));
    if (key.isValidMembersInjectionKey()
            && !injectBindingRegistry.getOrFindMembersInjectionBinding(key).injectionSites().isEmpty()) {
        errorMessage.append(" ").append(ErrorMessages.MEMBERS_INJECTION_DOES_NOT_IMPLY_PROVISION);
    }//from  w  w  w .  j a  v  a2s .co m
    ImmutableList<String> printableDependencyPath = FluentIterable.from(path)
            .transform(REQUEST_FROM_RESOLVED_REQUEST).transform(dependencyRequestFormatter)
            .filter(Predicates.not(Predicates.equalTo(""))).toList().reverse();
    for (String dependency : printableDependencyPath.subList(1, printableDependencyPath.size())) {
        errorMessage.append("\n").append(dependency);
    }
    reportBuilder.addItem(errorMessage.toString(), path.getLast().request().requestElement());
}

From source file:org.elasticsearch.snapshots.SnapshotUtils.java

/**
 * Filters out list of available indices based on the list of selected indices.
 *
 * @param availableIndices list of available indices
 * @param selectedIndices  list of selected indices
 * @param indicesOptions    ignore indices flag
 * @return filtered out indices/*from   w  w w  .  j  a  va  2 s . c o  m*/
 */
public static ImmutableList<String> filterIndices(ImmutableList<String> availableIndices,
        String[] selectedIndices, IndicesOptions indicesOptions) {
    if (selectedIndices == null || selectedIndices.length == 0) {
        return availableIndices;
    }
    Set<String> result = null;
    for (int i = 0; i < selectedIndices.length; i++) {
        String indexOrPattern = selectedIndices[i];
        boolean add = true;
        if (!indexOrPattern.isEmpty()) {
            if (availableIndices.contains(indexOrPattern)) {
                if (result != null) {
                    result.add(indexOrPattern);
                }
                continue;
            }
            if (indexOrPattern.charAt(0) == '+') {
                add = true;
                indexOrPattern = indexOrPattern.substring(1);
                // if its the first, add empty set
                if (i == 0) {
                    result = new HashSet<>();
                }
            } else if (indexOrPattern.charAt(0) == '-') {
                // if its the first, fill it with all the indices...
                if (i == 0) {
                    result = new HashSet<>(availableIndices);
                }
                add = false;
                indexOrPattern = indexOrPattern.substring(1);
            }
        }
        if (indexOrPattern.isEmpty() || !Regex.isSimpleMatchPattern(indexOrPattern)) {
            if (!availableIndices.contains(indexOrPattern)) {
                if (!indicesOptions.ignoreUnavailable()) {
                    throw new IndexMissingException(new Index(indexOrPattern));
                } else {
                    if (result == null) {
                        // add all the previous ones...
                        result = new HashSet<>();
                        result.addAll(availableIndices.subList(0, i));
                    }
                }
            } else {
                if (result != null) {
                    if (add) {
                        result.add(indexOrPattern);
                    } else {
                        result.remove(indexOrPattern);
                    }
                }
            }
            continue;
        }
        if (result == null) {
            // add all the previous ones...
            result = new HashSet<>();
            result.addAll(availableIndices.subList(0, i));
        }
        boolean found = false;
        for (String index : availableIndices) {
            if (Regex.simpleMatch(indexOrPattern, index)) {
                found = true;
                if (add) {
                    result.add(index);
                } else {
                    result.remove(index);
                }
            }
        }
        if (!found && !indicesOptions.allowNoIndices()) {
            throw new IndexMissingException(new Index(indexOrPattern));
        }
    }
    if (result == null) {
        return ImmutableList.copyOf(selectedIndices);
    }
    return ImmutableList.copyOf(result);
}

From source file:org.killbill.billing.payment.provider.DefaultNoOpPaymentProviderPlugin.java

@Override
public Pagination<PaymentMethodPlugin> searchPaymentMethods(final String searchKey, final Long offset,
        final Long limit, final Iterable<PluginProperty> properties, final TenantContext tenantContext)
        throws PaymentPluginApiException {
    final ImmutableList<PaymentMethodPlugin> allResults = ImmutableList.<PaymentMethodPlugin>copyOf(Iterables
            .<PaymentMethodPlugin>filter(Iterables.<PaymentMethodPlugin>concat(paymentMethods.values()),
                    new Predicate<PaymentMethodPlugin>() {
                        @Override
                        public boolean apply(final PaymentMethodPlugin input) {
                            return input.getKbPaymentMethodId().toString().equals(searchKey);
                        }//from   w  w w .ja  v a2  s.com
                    }));

    final List<PaymentMethodPlugin> results;
    if (offset >= allResults.size()) {
        results = ImmutableList.<PaymentMethodPlugin>of();
    } else if (offset + limit > allResults.size()) {
        results = allResults.subList(offset.intValue(), allResults.size());
    } else {
        results = allResults.subList(offset.intValue(), offset.intValue() + limit.intValue());
    }

    return new DefaultPagination<PaymentMethodPlugin>(offset, limit, (long) results.size(),
            (long) paymentMethods.values().size(), results.iterator());
}

From source file:com.opengamma.basics.schedule.Schedule.java

/**
 * Merges this schedule to form a new schedule by combining the regular schedule periods.
 * <p>//from   w  w w.j a  va 2 s  .c o  m
 * This produces a schedule where some periods are merged together.
 * For example, this could be used to convert a 3 monthly schedule into a 6 monthly schedule.
 * <p>
 * The merging is controlled by the group size, which defines the number of periods
 * to merge together in the result. For example, to convert a 3 monthly schedule into
 * a 6 monthly schedule the group size would be 2 (6 divided by 3).
 * <p>
 * A group size of zero or less will throw an exception.
 * A group size of 1 will return this schedule.
 * A larger group size will return a schedule where each group of regular periods are merged.
 * The roll flag is used to determine the direction in which grouping occurs.
 * <p>
 * Any existing stub periods are considered to be special, and are not merged.
 * Even if the grouping results in an excess period, such as 10 periods with a group size
 * of 3, the excess period will not be merged with a stub.
 * <p>
 * If this period is a 'Term' period, this schedule is returned.
 * 
 * @param groupSize  the group size
 * @param rollForwards  whether to roll forwards (true) or backwards (false)
 * @return the merged schedule
 * @throws IllegalArgumentException if the group size is zero or less
 */
public Schedule mergeRegular(int groupSize, boolean rollForwards) {
    ArgChecker.notNegativeOrZero(groupSize, "groupSize");
    if (isTerm() || groupSize == 1) {
        return this;
    }
    List<SchedulePeriod> newSchedule = new ArrayList<>();
    // retain initial stub
    Optional<SchedulePeriod> initialStub = getInitialStub();
    if (initialStub.isPresent()) {
        newSchedule.add(initialStub.get());
    }
    // merge regular, handling stubs via min/max
    ImmutableList<SchedulePeriod> regularPeriods = getRegularPeriods();
    int regularSize = regularPeriods.size();
    int remainder = regularSize % groupSize;
    int startIndex = (rollForwards || remainder == 0 ? 0 : -(groupSize - remainder));
    for (int i = startIndex; i < regularSize; i += groupSize) {
        int from = Math.max(i, 0);
        int to = Math.min(i + groupSize, regularSize);
        newSchedule.add(createSchedulePeriod(regularPeriods.subList(from, to)));
    }
    // retain final stub
    Optional<SchedulePeriod> finalStub = getFinalStub();
    if (finalStub.isPresent()) {
        newSchedule.add(finalStub.get());
    }
    // build schedule
    return Schedule.builder().periods(newSchedule)
            .frequency(Frequency.of(frequency.getPeriod().multipliedBy(groupSize)))
            .rollConvention(rollConvention).build();
}

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  va2 s.c o  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.google.javascript.jscomp.parsing.parser.codegeneration.ParseTreeTransformer.java

final protected ImmutableList<ParseTree> transformSourceElements(ImmutableList<ParseTree> list) {
    if (list == null || list.size() == 0) {
        return list;
    }/*from   www  .j ava  2s.  c  om*/

    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:com.opengamma.strata.measure.fxopt.BlackFxOptionSmileVolatilitiesSpecification.java

@ImmutableConstructor
private BlackFxOptionSmileVolatilitiesSpecification(FxOptionVolatilitiesName name, CurrencyPair currencyPair,
        DayCount dayCount, List<FxOptionVolatilitiesNode> nodes, CurveInterpolator timeInterpolator,
        CurveExtrapolator timeExtrapolatorLeft, CurveExtrapolator timeExtrapolatorRight,
        CurveInterpolator strikeInterpolator, CurveExtrapolator strikeExtrapolatorLeft,
        CurveExtrapolator strikeExtrapolatorRight) {
    JodaBeanUtils.notNull(name, "name");
    JodaBeanUtils.notNull(currencyPair, "currencyPair");
    JodaBeanUtils.notNull(dayCount, "dayCount");
    JodaBeanUtils.notNull(nodes, "nodes");
    JodaBeanUtils.notNull(timeInterpolator, "timeInterpolator");
    JodaBeanUtils.notNull(timeExtrapolatorLeft, "timeExtrapolatorLeft");
    JodaBeanUtils.notNull(timeExtrapolatorRight, "timeExtrapolatorRight");
    JodaBeanUtils.notNull(strikeInterpolator, "strikeInterpolator");
    JodaBeanUtils.notNull(strikeExtrapolatorLeft, "strikeExtrapolatorLeft");
    JodaBeanUtils.notNull(strikeExtrapolatorRight, "strikeExtrapolatorRight");
    this.name = name;
    this.currencyPair = currencyPair;
    this.dayCount = dayCount;
    this.nodes = ImmutableList.copyOf(nodes);
    this.timeInterpolator = timeInterpolator;
    this.timeExtrapolatorLeft = timeExtrapolatorLeft;
    this.timeExtrapolatorRight = timeExtrapolatorRight;
    this.strikeInterpolator = strikeInterpolator;
    this.strikeExtrapolatorLeft = strikeExtrapolatorLeft;
    this.strikeExtrapolatorRight = strikeExtrapolatorRight;
    this.nodesByTenor = nodes.stream()
            .collect(Guavate.toImmutableListMultimap(FxOptionVolatilitiesNode::getTenor));
    ImmutableList<Double> fullDeltas = nodes.stream().map(FxOptionVolatilitiesNode::getStrike).distinct()
            .map(Strike::getValue).sorted().collect(toImmutableList());

    int nDeltas = fullDeltas.size() - 1;
    ArgChecker.isTrue(fullDeltas.get(nDeltas) == 0.5, "0 < delta <= 0.5");
    this.deltas = fullDeltas.subList(0, nDeltas); // ATM removed
    int nParams = nodes.size();
    for (int i = 0; i < nParams; ++i) {
        ArgChecker.isTrue(nodes.get(i).getCurrencyPair().equals(currencyPair),
                "currency pair must be the same");
        ArgChecker.isTrue(nodes.get(i).getStrike() instanceof DeltaStrike, "Strike must be DeltaStrike");
    }/*from   w  ww  .  j a v a2s . c o m*/
    for (Tenor tenor : nodesByTenor.keys()) {
        ImmutableList<FxOptionVolatilitiesNode> nodesForTenor = nodesByTenor.get(tenor);
        // value type, delta, size
        List<Double> atmDelta = nodesForTenor.stream()
                .filter(node -> node.getQuoteValueType().equals(ValueType.BLACK_VOLATILITY))
                .map(node -> node.getStrike().getValue()).sorted().collect(toList());
        ArgChecker.isTrue(atmDelta.equals(fullDeltas.subList(nDeltas, nDeltas + 1)),
                "The ATM delta set must be " + fullDeltas.subList(nDeltas, nDeltas + 1) + ", but found "
                        + atmDelta + ", for " + tenor);
        List<Double> rrDelta = nodesForTenor.stream()
                .filter(node -> node.getQuoteValueType().equals(ValueType.RISK_REVERSAL))
                .map(node -> node.getStrike().getValue()).sorted().collect(toList());
        ArgChecker.isTrue(rrDelta.equals(deltas), "The delta set for risk reversal must be " + deltas
                + ", but found " + rrDelta + ", for " + tenor);
        List<Double> strDelta = nodesForTenor.stream()
                .filter(node -> node.getQuoteValueType().equals(ValueType.STRANGLE))
                .map(node -> node.getStrike().getValue()).sorted().collect(toList());
        ArgChecker.isTrue(strDelta.equals(deltas),
                "The delta set for strangle must be " + deltas + ", but found " + strDelta + ", for " + tenor);
        // convention
        Set<BusinessDayAdjustment> busAdj = nodesForTenor.stream()
                .map(FxOptionVolatilitiesNode::getBusinessDayAdjustment).collect(toSet());
        ArgChecker.isTrue(busAdj.size() == 1, "BusinessDayAdjustment must be common to all the nodes");
        Set<DaysAdjustment> offset = nodesForTenor.stream().map(FxOptionVolatilitiesNode::getSpotDateOffset)
                .collect(toSet());
        ArgChecker.isTrue(offset.size() == 1, "DaysAdjustment must be common to all the nodes");
    }
}

From source file:net.hydromatic.optiq.materialize.Lattice.java

private Lattice(ImmutableList<Node> nodes, boolean auto, ImmutableList<Column> columns,
        ImmutableList<Measure> defaultMeasures, ImmutableList<Tile> tiles) {
    this.nodes = Preconditions.checkNotNull(nodes);
    this.columns = Preconditions.checkNotNull(columns);
    this.auto = auto;
    this.defaultMeasures = Preconditions.checkNotNull(defaultMeasures);
    this.tiles = Preconditions.checkNotNull(tiles);

    // Validate that nodes form a tree; each node except the first references
    // a predecessor.
    for (int i = 0; i < nodes.size(); i++) {
        Node node = nodes.get(i);
        if (i == 0) {
            assert node.parent == null;
        } else {/* w w w .ja v a  2  s .  co  m*/
            assert nodes.subList(0, i).contains(node.parent);
        }
    }

    List<String> nameList = Lists.newArrayList();
    for (Column column : columns) {
        nameList.add(column.alias);
    }
    uniqueColumnNames = ImmutableList.copyOf(SqlValidatorUtil.uniquify(Lists.transform(columns, GET_ALIAS)));
}