Example usage for com.google.common.collect Iterables getOnlyElement

List of usage examples for com.google.common.collect Iterables getOnlyElement

Introduction

In this page you can find the example usage for com.google.common.collect Iterables getOnlyElement.

Prototype

public static <T> T getOnlyElement(Iterable<T> iterable) 

Source Link

Document

Returns the single element contained in iterable .

Usage

From source file:org.jclouds.fujitsu.fgcp.location.SystemAndNetworkSegmentToLocationSupplier.java

@Override
public Set<Location> get() {
    Builder<Location> locations = ImmutableSet.builder();

    for (VSystem system : api.getVirtualDCApi().listVirtualSystems()) {

        VSystemWithDetails systemWithDetails = api.getVirtualSystemApi().getDetails(system.getId());

        Location systemLocation = new LocationBuilder().scope(LocationScope.SYSTEM)
                .parent(Iterables.getOnlyElement(regionProvider.get())).description(system.getName())
                .id(system.getId()).build();

        for (VNet net : systemWithDetails.getNetworks()) {

            locations.add(new LocationBuilder().scope(LocationScope.NETWORK).parent(systemLocation)
                    .description(net.getNetworkId().replaceFirst(".+-N-", "")).id(net.getNetworkId()).build());
        }/*from ww w  .  j a  va  2s  .c  om*/
    }

    return locations.build();
}

From source file:see.util.Either.java

/**
 * Get left value, throwing exception if value is not present.
 * @return left value/*from  w w w . j  av a  2  s .  c  o  m*/
 * @throws NoSuchElementException if container doesn't hold left value
 */
public L leftValue() {
    return Iterables.getOnlyElement(left);
}

From source file:com.google.devtools.build.lib.bazel.rules.genrule.GenRule.java

private Artifact getExecutable(RuleContext ruleContext, NestedSet<Artifact> filesToBuild) {
    if (Iterables.size(filesToBuild) == 1) {
        Artifact out = Iterables.getOnlyElement(filesToBuild);
        if (ruleContext.attributes().get("executable", Type.BOOLEAN)) {
            return out;
        }/*from w  w  w.  j  av a  2s .c  om*/
    }
    return null;
}

From source file:com.google.caliper.worker.MicrobenchmarkWorker.java

private Trial createTrial(Benchmark benchmark, String methodName, Options options, WorkerEventLog log) {
    final String timeMethodName = "time" + methodName;
    // where's the right place for 'time' to be prepended again?
    Iterable<Method> timeMethods = Iterables.filter(Arrays.asList(benchmark.getClass().getDeclaredMethods()),
            new Predicate<Method>() {
                @Override//from w  w w .  jav a2  s  .co m
                public boolean apply(@Nullable Method input) {
                    return timeMethodName.equals(input.getName());
                }
            });

    Method timeMethod = Iterables.getOnlyElement(timeMethods);
    timeMethod.setAccessible(true);

    Class<?> repsType = Iterables.getOnlyElement(Arrays.asList(timeMethod.getParameterTypes()));
    if (int.class.equals(repsType)) {
        return new IntTrial(benchmark, timeMethod, options, log);
    } else if (long.class.equals(repsType)) {
        return new LongTrial(benchmark, timeMethod, options, log);
    } else {
        throw new IllegalStateException(
                String.format("Got a benchmark method (%s) with an invalid reps parameter.", timeMethod));
    }
}

From source file:com.opengamma.financial.analytics.model.discounting.DiscountingInflationParSpreadFunction.java

@Override
public CompiledFunctionDefinition compile(final FunctionCompilationContext context, final Instant atInstant) {
    return new DiscountingInflationCompiledFunction(getTargetToDefinitionConverter(context),
            getDefinitionToDerivativeConverter(context), false) {

        @Override//from   w w  w.j  a  v a2 s  .co m
        protected Set<ComputedValue> getValues(final FunctionExecutionContext executionContext,
                final FunctionInputs inputs, final ComputationTarget target,
                final Set<ValueRequirement> desiredValues, final InstrumentDerivative derivative,
                final FXMatrix fxMatrix) {
            final InflationProviderInterface data = (InflationProviderInterface) inputs.getValue(CURVE_BUNDLE);
            final ValueRequirement desiredValue = Iterables.getOnlyElement(desiredValues);
            final ValueProperties properties = desiredValue.getConstraints().copy().get();
            final double parSpread = derivative.accept(CALCULATOR, data);
            final ValueSpecification spec = new ValueSpecification(PAR_SPREAD, target.toSpecification(),
                    properties);
            return Collections.singleton(new ComputedValue(spec, parSpread));
        }
    };
}

From source file:com.google.errorprone.bugpatterns.time.JavaDurationWithNanos.java

@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
    if (!MATCHER.matches(tree, state)) {
        return Description.NO_MATCH;
    }//from w  w  w .j  ava 2 s  . com

    SuggestedFix.Builder builder = SuggestedFix.builder();
    ExpressionTree nanosArg = Iterables.getOnlyElement(tree.getArguments());
    ExpressionTree receiver = ASTHelpers.getReceiver(tree);
    String replacement = SuggestedFixes.qualifyType(state, builder, "java.time.Duration") + ".ofSeconds("
            + state.getSourceForNode(receiver) + ".getSeconds(), ";

    builder.replace(((JCTree) tree).getStartPosition(), ((JCTree) nanosArg).getStartPosition(), replacement);
    return describeMatch(tree, builder.build());
}

From source file:org.apache.beam.runners.dataflow.worker.DataflowProcessFnRunner.java

private static <T> void checkTrivialOuterWindows(WindowedValue<KeyedWorkItem<byte[], T>> windowedKWI) {
    // In practice it will be in 0 or 1 windows (ValueInEmptyWindows or ValueInGlobalWindow)
    Collection<? extends BoundedWindow> outerWindows = windowedKWI.getWindows();
    if (!outerWindows.isEmpty()) {
        checkArgument(outerWindows.size() == 1,
                "The KeyedWorkItem itself must not be in multiple windows, but was in: %s", outerWindows);
        BoundedWindow onlyWindow = Iterables.getOnlyElement(outerWindows);
        checkArgument(onlyWindow instanceof GlobalWindow,
                "KeyedWorkItem must be in the Global window, but was in: %s", onlyWindow);
    }// w  ww . ja v a2s.  c  om
}

From source file:com.opengamma.financial.analytics.model.g2ppdiscounting.G2ppDiscountingPVFunction.java

@Override
public CompiledFunctionDefinition compile(final FunctionCompilationContext context, final Instant atInstant) {
    return new G2ppCompiledFunction(getTargetToDefinitionConverter(context),
            getDefinitionToDerivativeConverter(context), true) {

        @Override//from  w  w w . j  a va2  s .  c o m
        protected Set<ComputedValue> getValues(final FunctionExecutionContext executionContext,
                final FunctionInputs inputs, final ComputationTarget target,
                final Set<ValueRequirement> desiredValues, final InstrumentDerivative derivative,
                final FXMatrix fxMatrix) {
            final G2ppProviderInterface data = getMergedProviders(inputs, fxMatrix);
            final ValueRequirement desiredValue = Iterables.getOnlyElement(desiredValues);
            final ValueProperties properties = desiredValue.getConstraints().copy().get();
            final Currency currency = FinancialSecurityUtils.getCurrency(target.getTrade().getSecurity());
            final MultipleCurrencyAmount mca = derivative.accept(CALCULATOR, data);
            final ValueSpecification spec = new ValueSpecification(PRESENT_VALUE, target.toSpecification(),
                    properties);
            return Collections.singleton(new ComputedValue(spec, mca.getAmount(currency)));
        }
    };
}

From source file:brooklyn.entity.database.mysql.MySqlClusterTestHelper.java

public static void test(TestApplication app, Location location) throws Exception {
    MySqlCluster mysql = app.createAndManageChild(
            EntitySpec.create(MySqlCluster.class).configure(MySqlCluster.INITIAL_SIZE, 2).configure(
                    MySqlNode.MYSQL_SERVER_CONF, MutableMap.<String, Object>of("skip-name-resolve", "")));

    app.start(ImmutableList.of(location));
    log.info("MySQL started");
    MySqlNode masterEntity = (MySqlNode) mysql.getAttribute(MySqlCluster.FIRST);
    masterEntity.invoke(MySqlNode.EXECUTE_SCRIPT, ImmutableMap.of("commands", CREATION_SCRIPT)).asTask()
            .getUnchecked();//  w  ww .j a va2 s .c o  m

    VogellaExampleAccess masterDb = new VogellaExampleAccess("com.mysql.jdbc.Driver",
            mysql.getAttribute(MySqlNode.DATASTORE_URL));
    VogellaExampleAccess slaveDb = new VogellaExampleAccess("com.mysql.jdbc.Driver",
            Iterables.getOnlyElement(mysql.getAttribute(MySqlCluster.SLAVE_DATASTORE_URL_LIST)));
    masterDb.connect();
    slaveDb.connect();

    assertSlave(masterDb, slaveDb, 1);
    masterDb.modifyDataBase();
    assertSlave(masterDb, slaveDb, 2);
    masterDb.revertDatabase();
    assertSlave(masterDb, slaveDb, 1);

    masterDb.close();
    slaveDb.close();

    log.info("Ran vogella MySQL example -- SUCCESS");
}

From source file:at.ac.univie.isc.asio.database.MysqlSchemaService.java

private org.jooq.Schema findActiveSchema(final DSLContext jooq, final Id target) throws SQLException {
    final String activeSchemaName = target.asString();
    if (INTERNAL_SCHEMA.contains(activeSchemaName.toLowerCase(Locale.ENGLISH))) {
        throw new Id.NotFound(target);
    }//from www.j  ava  2  s .  c  om
    final org.jooq.Schema schema = Iterables.getOnlyElement(jooq.meta().getCatalogs())
            .getSchema(activeSchemaName);
    if (schema == null) {
        throw new Id.NotFound(target);
    }
    return schema;
}