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

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

Introduction

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

Prototype

int size();

Source Link

Document

Returns the number of elements in this list.

Usage

From source file:com.opengamma.strata.pricer.swaption.HullWhiteSwaptionPhysicalProductPricer.java

/**
 * Calculates the present value sensitivity of the swaption product.
 * <p>/*from  w w w  .  j  ava  2 s .  c  o m*/
 * The present value sensitivity of the product is the sensitivity of the present value to
 * the underlying curves.
 * 
 * @param swaption  the product
 * @param ratesProvider  the rates provider
 * @param hwProvider  the Hull-White model parameter provider
 * @return the point sensitivity to the rate curves
 */
public PointSensitivityBuilder presentValueSensitivityRates(ResolvedSwaption swaption,
        RatesProvider ratesProvider, HullWhiteOneFactorPiecewiseConstantParametersProvider hwProvider) {

    validate(swaption, ratesProvider, hwProvider);
    ResolvedSwap swap = swaption.getUnderlying();
    LocalDate expiryDate = swaption.getExpiryDate();
    if (expiryDate.isBefore(ratesProvider.getValuationDate())) { // Option has expired already
        return PointSensitivityBuilder.none();
    }
    ImmutableMap<Payment, PointSensitivityBuilder> cashFlowEquivSensi = CashFlowEquivalentCalculator
            .cashFlowEquivalentAndSensitivitySwap(swap, ratesProvider);
    ImmutableList<Payment> list = cashFlowEquivSensi.keySet().asList();
    ImmutableList<PointSensitivityBuilder> listSensi = cashFlowEquivSensi.values().asList();
    int nPayments = list.size();
    double[] alpha = new double[nPayments];
    double[] discountedCashFlow = new double[nPayments];
    for (int loopcf = 0; loopcf < nPayments; loopcf++) {
        Payment payment = list.get(loopcf);
        alpha[loopcf] = hwProvider.alpha(ratesProvider.getValuationDate(), expiryDate, expiryDate,
                payment.getDate());
        discountedCashFlow[loopcf] = paymentPricer.presentValueAmount(payment, ratesProvider);
    }
    double omega = (swap.getLegs(SwapLegType.FIXED).get(0).getPayReceive().isPay() ? -1d : 1d);
    double kappa = computeKappa(hwProvider, discountedCashFlow, alpha, omega);
    PointSensitivityBuilder point = PointSensitivityBuilder.none();
    for (int loopcf = 0; loopcf < nPayments; loopcf++) {
        Payment payment = list.get(loopcf);
        double cdf = NORMAL.getCDF(omega * (kappa + alpha[loopcf]));
        point = point
                .combinedWith(paymentPricer.presentValueSensitivity(payment, ratesProvider).multipliedBy(cdf));
        if (!listSensi.get(loopcf).equals(PointSensitivityBuilder.none())) {
            point = point.combinedWith(listSensi.get(loopcf).multipliedBy(
                    cdf * ratesProvider.discountFactor(payment.getCurrency(), payment.getDate())));
        }
    }
    return swaption.getLongShort().isLong() ? point : point.multipliedBy(-1d);
}

From source file:com.facebook.presto.operator.scalar.ArrayConstructor.java

@Override
public ScalarFunctionImplementation specialize(Map<String, Type> types, int arity, TypeManager typeManager,
        FunctionRegistry functionRegistry) {
    checkArgument(types.size() == 1, "Can only construct arrays from exactly matching types");
    ImmutableList.Builder<Class<?>> builder = ImmutableList.builder();
    Type type = types.get("E");
    for (int i = 0; i < arity; i++) {
        if (type.getJavaType().isPrimitive()) {
            builder.add(Primitives.wrap(type.getJavaType()));
        } else {/*from w  w  w  .j a v a 2  s.  co m*/
            builder.add(type.getJavaType());
        }
    }
    ImmutableList<Class<?>> stackTypes = builder.build();
    Class<?> clazz = generateArrayConstructor(stackTypes, type);
    MethodHandle methodHandle;
    try {
        Method method = clazz.getMethod("arrayConstructor",
                stackTypes.toArray(new Class<?>[stackTypes.size()]));
        methodHandle = lookup().unreflect(method);
    } catch (ReflectiveOperationException e) {
        throw Throwables.propagate(e);
    }
    List<Boolean> nullableParameters = ImmutableList.copyOf(Collections.nCopies(stackTypes.size(), true));
    return new ScalarFunctionImplementation(false, nullableParameters, methodHandle, isDeterministic());
}

From source file:org.apache.drill.common.expression.ExpressionStringBuilder.java

@Override
public Void visitFunctionCall(FunctionCall call, StringBuilder sb) throws RuntimeException {
    ImmutableList<LogicalExpression> args = call.args;
    sb.append(call.getName());// w ww.j  a  va 2s .c  o m
    sb.append("(");
    for (int i = 0; i < args.size(); i++) {
        if (i != 0) {
            sb.append(", ");
        }
        args.get(i).accept(this, sb);
    }
    sb.append(") ");
    return null;
}

From source file:io.prestosql.operator.scalar.ArrayConstructor.java

@Override
public ScalarFunctionImplementation specialize(BoundVariables boundVariables, int arity,
        TypeManager typeManager, FunctionRegistry functionRegistry) {
    Map<String, Type> types = boundVariables.getTypeVariables();
    checkArgument(types.size() == 1, "Can only construct arrays from exactly matching types");
    ImmutableList.Builder<Class<?>> builder = ImmutableList.builder();
    Type type = types.get("E");
    for (int i = 0; i < arity; i++) {
        if (type.getJavaType().isPrimitive()) {
            builder.add(Primitives.wrap(type.getJavaType()));
        } else {//from w w  w.jav a  2s.c om
            builder.add(type.getJavaType());
        }
    }
    ImmutableList<Class<?>> stackTypes = builder.build();
    Class<?> clazz = generateArrayConstructor(stackTypes, type);
    MethodHandle methodHandle;
    try {
        Method method = clazz.getMethod("arrayConstructor",
                stackTypes.toArray(new Class<?>[stackTypes.size()]));
        methodHandle = lookup().unreflect(method);
    } catch (ReflectiveOperationException e) {
        throw new RuntimeException(e);
    }
    return new ScalarFunctionImplementation(false,
            nCopies(stackTypes.size(), valueTypeArgumentProperty(USE_BOXED_TYPE)), methodHandle,
            isDeterministic());
}

From source file:net.bunselmeyer.mongo.maven.plugin.MigrateMojo.java

public void execute() throws MojoExecutionException {

    if (StringUtils.isBlank(host)) {
        host = "localhost";
    }/*from w  w  w.ja v a  2  s.c o  m*/

    Set<Class<? extends Migration>> allMigrations = scanProjectForMigrations();

    ImmutableListMultimap<MIGRATION_CHECK, MigrationDetails> statusIndex = buildStatusIndex(allMigrations);

    ImmutableList<MigrationDetails> errors = statusIndex.get(MIGRATION_CHECK.ERROR);
    if (!errors.isEmpty()) {
        getLog().error("Fail: Please correct the following issues...");
        for (MigrationDetails error : errors) {
            getLog().error("    " + error.migration.getName() + ": " + error.message);
        }
        return;
    }

    ImmutableList<MigrationDetails> warnings = statusIndex.get(MIGRATION_CHECK.WARNING);
    if (!warnings.isEmpty()) {
        getLog().warn("Warnings...");
        for (MigrationDetails warning : warnings) {
            getLog().warn("    " + warning.migration.getName() + ": " + warning.message);
        }
    }

    ImmutableList<MigrationDetails> goodMigrations = statusIndex.get(MIGRATION_CHECK.GOOD);

    getLog().info("Found " + goodMigrations.size() + " migrations.");

    ImmutableListMultimap<String, MigrationDetails> index = buildIndex(goodMigrations);

    List<String> keys = Lists.newArrayList(index.keySet());
    Collections.sort(keys);

    for (String connectionDef : keys) {
        runMigrations(Lists.newArrayList(index.get(connectionDef)));
    }
}

From source file:blockplus.transport.BlockplusServerEvents.java

@Subscribe
@AllowConcurrentEvents/*from  www  . j a va2 s .c o m*/
public void onGameConnection(final IGameConnection gameConnection) {
    final IGame<Context> game = this.getServer().getGame(gameConnection.getOrdinal());
    if (!game.isFull()) {
        final IClient oldClient = this.getServer().getClientByEndpoint(gameConnection.getEndpoint());
        final IClient newClient = new Client(gameConnection.getEndpoint(), oldClient.getName(),
                game.getOrdinal());
        this.getServer().updateClients(newClient.getEndpoint(), newClient);

        final BlockplusGame newGame = (BlockplusGame) game.connect(newClient);

        final ImmutableList<IClient> clients = newGame.getClients();
        this.getServer().updateGame(newGame.getOrdinal(), newGame);

        final JsonObject gameInfo = new JsonObject();
        gameInfo.addProperty("id", newGame.getOrdinal());
        gameInfo.addProperty("players", clients.size());

        newClient.getEndpoint().emit("game", gameInfo.toString());

        final JsonObject playerInfo = new JsonObject();
        playerInfo.addProperty("name", newClient.getName());

        for (final IClient client : clients) {
            client.getEndpoint().emit("player", playerInfo.toString());
        }
        this.getServer().removeFromPatio(newClient.getEndpoint());
        for (final IEndPoint endPoint : this.getServer().getEndpointsInPatio()) {
            endPoint.emit("tables", this.getServer().games().toString());
        }
        if (newGame.isFull() && !newGame.isPaused())
            newGame.update();
    }
}

From source file:org.apache.drill.common.expression.ExpressionStringBuilder.java

@Override
public Void visitFunctionHolderExpression(FunctionHolderExpression holder, StringBuilder sb)
        throws RuntimeException {
    ImmutableList<LogicalExpression> args = holder.args;
    sb.append(holder.getName());/*from  w ww  . ja  v a  2  s . co  m*/
    sb.append("(");
    for (int i = 0; i < args.size(); i++) {
        if (i != 0) {
            sb.append(", ");
        }
        args.get(i).accept(this, sb);
    }
    sb.append(") ");
    return null;
}

From source file:com.google.devtools.build.lib.analysis.mock.BazelAnalysisMock.java

@Override
public void setupMockClient(MockToolsConfig config) throws IOException {
    String bazelToolWorkspace = config.getPath("/bazel_tools_workspace").getPathString();
    ArrayList<String> workspaceContents = new ArrayList<>(
            ImmutableList.of("local_repository(name = 'bazel_tools', path = '" + bazelToolWorkspace + "')",
                    "local_repository(name = 'local_config_xcode', path = '/local_config_xcode')", "bind(",
                    "  name = 'objc_proto_lib',", "  actual = '//objcproto:ProtocolBuffers_lib',", ")", "bind(",
                    "  name = 'objc_protobuf_lib',", "  actual = '//objcproto:protobuf_lib',", ")",
                    "bind(name = 'android/sdk', actual='@bazel_tools//tools/android:sdk')",
                    "bind(name = 'tools/python', actual='//tools/python')"));

    config.create("/local_config_xcode/BUILD", "xcode_config(name = 'host_xcodes')");
    config.overwrite("WORKSPACE", workspaceContents.toArray(new String[workspaceContents.size()]));
    config.create("/bazel_tools_workspace/WORKSPACE", "workspace(name = 'bazel_tools')");
    config.create("/bazel_tools_workspace/tools/jdk/BUILD",
            "package(default_visibility=['//visibility:public'])", "java_toolchain(", "  name = 'toolchain',",
            "  encoding = 'UTF-8',", "  source_version = '8',", "  target_version = '8',",
            "  bootclasspath = [':bootclasspath'],", "  extclasspath = [':extclasspath'],",
            "  javac = [':langtools'],", "  javabuilder = ['JavaBuilder_deploy.jar'],",
            "  header_compiler = ['turbine_deploy.jar'],", "  singlejar = ['SingleJar_deploy.jar'],",
            "  genclass = ['GenClass_deploy.jar'],", "  ijar = ['ijar'],", ")", "filegroup(name = 'jdk-null')",
            "filegroup(name = 'jdk-default', srcs = [':java'], path = 'jdk/jre')",
            "filegroup(name = 'jdk', srcs = [':jdk-default', ':jdk-null'])",
            "filegroup(name='langtools', srcs=['jdk/lib/tools.jar'])",
            "filegroup(name='bootclasspath', srcs=['jdk/jre/lib/rt.jar'])",
            "filegroup(name='extdir', srcs=glob(['jdk/jre/lib/ext/*']))",
            // "dummy" is needed so that RedirectChaser stops here
            "filegroup(name='java', srcs = ['jdk/jre/bin/java', 'dummy'])",
            "filegroup(name='JacocoCoverage', srcs = [])", "filegroup(name='jacoco-blaze-agent', srcs = [])",
            "exports_files(['JavaBuilder_deploy.jar','SingleJar_deploy.jar','TestRunner_deploy.jar',",
            "               'JavaBuilderCanary_deploy.jar', 'ijar', 'GenClass_deploy.jar',",
            "               'turbine_deploy.jar'])");

    ImmutableList<String> androidBuildContents = createAndroidBuildContents();
    config.create("/bazel_tools_workspace/tools/android/BUILD",
            androidBuildContents.toArray(new String[androidBuildContents.size()]));

    config.create("/bazel_tools_workspace/tools/genrule/BUILD", "exports_files(['genrule-setup.sh'])");
    config.create("/bazel_tools_workspace/third_party/java/jarjar/BUILD",
            "package(default_visibility=['//visibility:public'])", "licenses(['notice'])",
            "java_binary(name = 'jarjar_bin',", "            runtime_deps = [ ':jarjar_import' ],",
            "            main_class = 'com.tonicsystems.jarjar.Main')", "java_import(name = 'jarjar_import',",
            "            jars = [ 'jarjar.jar' ])");

    config.create("/bazel_tools_workspace/tools/test/BUILD",
            "filegroup(name = 'runtime', srcs = ['test-setup.sh'],)",
            "filegroup(name='coverage_support', srcs=['collect_coverage.sh',':LcovMerger_deploy.jar'])",
            "filegroup(name = 'coverage_report_generator', srcs = ['coverage_report_generator.sh'])");

    config.create("/bazel_tools_workspace/tools/python/BUILD",
            "package(default_visibility=['//visibility:public'])", "exports_files(['precompile.py'])",
            "sh_binary(name='2to3', srcs=['2to3.sh'])");

    config.create("/bazel_tools_workspace/tools/zip/BUILD",
            "package(default_visibility=['//visibility:public'])", "exports_files(['precompile.py'])",
            "cc_binary(name='zipper', srcs=['zip_main.cc'])");
    ccSupport().setup(config);//from w ww. ja v a 2  s . c om
}

From source file:com.facebook.buck.versions.AbstractFlavorSearchTargetNodeFinder.java

public Optional<TargetNode<?>> get(BuildTarget target) {

    // If this node is in the graph under the given name, return it.
    TargetNode<?> node = getBuildTargetIndex().get(target);
    if (node != null) {
        return Optional.of(node);
    }//  ww  w . j a v a2 s. c o m

    ImmutableSet<ImmutableSet<Flavor>> flavorList = getBaseTargetFlavorMap()
            .get(target.getUnflavoredBuildTarget());
    if (flavorList == null) {
        return Optional.empty();
    }

    // Otherwise, see if this node exists in the graph with a "less" flavored name.  We initially
    // select all targets which contain a subset of the original flavors, which should be sorted by
    // from largest flavor set to smallest.  We then use the first match, and verify the subsequent
    // matches are subsets.
    ImmutableList<ImmutableSet<Flavor>> matches = RichStream.from(flavorList)
            .filter(target.getFlavors()::containsAll).toImmutableList();
    if (!matches.isEmpty()) {
        ImmutableSet<Flavor> firstMatch = matches.get(0);
        for (ImmutableSet<Flavor> subsequentMatch : matches.subList(1, matches.size())) {
            Preconditions
                    .checkState(firstMatch.size() > subsequentMatch.size(),
                            "Expected to find larger flavor lists earlier in the flavor map "
                                    + "index (sizeof(%s) <= sizeof(%s))",
                            firstMatch.size(), subsequentMatch.size());
            Preconditions.checkState(firstMatch.containsAll(subsequentMatch),
                    "Found multiple disjoint flavor matches for %s: %s and %s (from %s)", target, firstMatch,
                    subsequentMatch, matches);
        }
        return Optional.of(Preconditions.checkNotNull(getBaseTargetIndex().get(target.withFlavors(firstMatch)),
                "%s missing in index", target.withFlavors(firstMatch)));
    }

    // Otherwise, return `null` to indicate this node isn't in the target graph.
    return Optional.empty();
}

From source file:com.palantir.docker.compose.execution.DefaultDockerCompose.java

private String[] constructFullDockerComposeRunArguments(DockerComposeRunOption dockerComposeRunOption,
        String containerName, DockerComposeRunArgument dockerComposeRunArgument) {
    ImmutableList<String> fullArgs = new ImmutableList.Builder<String>().add("run")
            .addAll(dockerComposeRunOption.options()).add(containerName)
            .addAll(dockerComposeRunArgument.arguments()).build();
    return fullArgs.toArray(new String[fullArgs.size()]);
}