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.gogrid.compute.strategy.GoGridLifeCycleStrategy.java

@Override
public NodeMetadata rebootNode(String id) {
    executeCommandOnServer(PowerCommand.RESTART, id);
    Server server = Iterables.getOnlyElement(client.getServerServices().getServersById(new Long(id)));
    client.getServerServices().power(server.getName(), PowerCommand.START);
    serverLatestJobCompletedShort.apply(server);
    return getNode.getNode(id);
}

From source file:org.apache.cassandra.service.BatchlogEndpointSelector.java

/**
 * @param endpoints nodes in the local datacenter, grouped by rack name
 * @return list of candidates for batchlog hosting.  if possible these will be two nodes from different racks.
 *///from w  w w. j  a v  a  2 s  . co m
public Collection<InetAddress> chooseEndpoints(Multimap<String, InetAddress> endpoints) {
    // strip out dead endpoints and localhost
    ListMultimap<String, InetAddress> validated = ArrayListMultimap.create();
    for (Map.Entry<String, InetAddress> entry : endpoints.entries()) {
        if (isValid(entry.getValue()))
            validated.put(entry.getKey(), entry.getValue());
    }
    if (validated.size() <= 2)
        return validated.values();

    if ((validated.size() - validated.get(localRack).size()) >= 2) {
        // we have enough endpoints in other racks
        validated.removeAll(localRack);
    }

    if (validated.keySet().size() == 1) {
        // we have only 1 `other` rack
        Collection<InetAddress> otherRack = Iterables.getOnlyElement(validated.asMap().values());
        return Lists.newArrayList(Iterables.limit(otherRack, 2));
    }

    // randomize which racks we pick from if more than 2 remaining
    Collection<String> racks;
    if (validated.keySet().size() == 2) {
        racks = validated.keySet();
    } else {
        racks = Lists.newArrayList(validated.keySet());
        Collections.shuffle((List) racks);
    }

    // grab a random member of up to two racks
    List<InetAddress> result = new ArrayList<>(2);
    for (String rack : Iterables.limit(racks, 2)) {
        List<InetAddress> rackMembers = validated.get(rack);
        result.add(rackMembers.get(getRandomInt(rackMembers.size())));
    }

    return result;
}

From source file:com.opengamma.financial.analytics.model.fx.FXForwardPointsCurrencyExposureFunction.java

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

        @Override// w  w w .  j  av a2 s.  com
        protected Set<ComputedValue> getValues(final FunctionInputs inputs, final ComputationTarget target,
                final Set<ValueRequirement> desiredValues, final Forex forex, final FXMatrix fxMatrix,
                final ZonedDateTime now) {
            final MulticurveProviderInterface data = getMergedProviders(inputs, fxMatrix);
            final ValueRequirement desiredValue = Iterables.getOnlyElement(desiredValues);
            final ValueProperties properties = desiredValue.getConstraints().copy().get();
            final String fxForwardCurveName = desiredValue.getConstraint(FORWARD_CURVE_NAME);
            final DoublesCurve forwardPoints = getForwardPoints(inputs, fxForwardCurveName, now);
            final CurrencyPairs pairs = (CurrencyPairs) inputs.getValue(CURRENCY_PAIRS);
            final Pair<Currency, Currency> ccyPair;
            final Currency currency1 = forex.getCurrency1();
            final Currency currency2 = forex.getCurrency2();
            if (currency1.equals(pairs.getCurrencyPair(currency1, currency2).getBase())) {
                ccyPair = Pair.of(currency1, currency2);
            } else {
                ccyPair = Pair.of(currency2, currency1);
            }
            final MultipleCurrencyAmount mca = CALCULATOR.currencyExposure(forex, data, forwardPoints, ccyPair);
            final ValueSpecification spec = new ValueSpecification(FX_CURRENCY_EXPOSURE,
                    target.toSpecification(), properties);
            return Collections.singleton(new ComputedValue(spec, mca));
        }
    };
}

From source file:com.cloudera.nav.sdk.model.relations.ParentChildRelation.java

public String getParentId() {
    return Iterables.getOnlyElement(getEp1Ids());
}

From source file:io.druid.indexing.common.task.DeleteTask.java

@Override
public TaskStatus run(TaskToolbox toolbox) throws Exception {
    // Strategy: Create an empty segment covering the interval to be deleted
    final TaskLock myLock = Iterables.getOnlyElement(getTaskLocks(toolbox));
    final IncrementalIndex empty = new IncrementalIndex(0, QueryGranularity.NONE, new AggregatorFactory[0]);
    final IndexableAdapter emptyAdapter = new IncrementalIndexAdapter(getInterval(), empty);

    // Create DataSegment
    final DataSegment segment = DataSegment.builder().dataSource(this.getDataSource()).interval(getInterval())
            .version(myLock.getVersion()).shardSpec(new NoneShardSpec()).build();

    final File outDir = new File(toolbox.getTaskWorkDir(), segment.getIdentifier());
    final File fileToUpload = IndexMerger.merge(Lists.newArrayList(emptyAdapter), new AggregatorFactory[0],
            outDir);//  w  ww.ja  v  a2 s  .  c o  m

    // Upload the segment
    final DataSegment uploadedSegment = toolbox.getSegmentPusher().push(fileToUpload, segment);

    log.info("Uploaded tombstone segment for[%s] interval[%s] with version[%s]", segment.getDataSource(),
            segment.getInterval(), segment.getVersion());

    toolbox.pushSegments(ImmutableList.of(uploadedSegment));

    return TaskStatus.success(getId());
}

From source file:org.jclouds.googlecomputeengine.compute.predicates.NetworkFirewallPredicates.java

public static Predicate<Firewall> equalsIpPermission(final IpPermission permission) {
    return new Predicate<Firewall>() {
        @Override//  w w  w  . j  av a2  s  .  co m
        public boolean apply(Firewall input) {
            return Iterables.elementsEqual(permission.getGroupIds(), input.sourceTags())
                    && Iterables.elementsEqual(permission.getCidrBlocks(), input.sourceRanges())
                    && (input.allowed().size() == 1 && ruleEqualsIpPermission(permission)
                            .apply(Iterables.getOnlyElement(input.allowed())));
        }
    };
}

From source file:com.cloudera.exhibit.hive.WithinUDF.java

@Override
public Object evaluate(DeferredObject[] args) throws HiveException {
    for (int i = 1; i < args.length; i++) {
        ((HiveFrame) exhibit.frames().get("T" + i)).updateValues(args[i].get());
    }//w w w  . j  a v  a 2 s . co m
    return getResult(Iterables.getOnlyElement(calculator.apply(exhibit)));
}

From source file:com.opengamma.financial.analytics.model.forex.option.black.FXOptionBlackForwardDriftlessThetaFunction.java

@Override
protected Set<ComputedValue> getResult(final InstrumentDerivative forex, final ForexOptionDataBundle<?> data,
        final ComputationTarget target, final Set<ValueRequirement> desiredValues, final FunctionInputs inputs,
        final ValueSpecification spec, final FunctionExecutionContext executionContext) {
    final ValueRequirement desiredValue = Iterables.getOnlyElement(desiredValues);
    final ValueProperties constraints = desiredValue.getConstraints();
    final ValueProperties.Builder resultProperties = constraints.copy();
    final double scale;
    final Set<String> scaleFactors = constraints.getValues(PROPERTY_DAYS_PER_YEAR);
    if (scaleFactors.isEmpty()) {
        scale = DEFAULT_DAYS_PER_YEAR;/*  w  w w  .  j a v  a 2 s.  c o m*/
        resultProperties.withoutAny(PROPERTY_DAYS_PER_YEAR).with(PROPERTY_DAYS_PER_YEAR,
                Double.toString(DEFAULT_DAYS_PER_YEAR));
    } else {
        scale = Double.parseDouble(scaleFactors.iterator().next());
    }
    if (data instanceof SmileDeltaTermStructureDataBundle) {
        final double result = forex.accept(ForwardBlackDriftlessThetaForexCalculator.getInstance(), data);
        return Collections.singleton(new ComputedValue(spec, result / scale));
    }
    throw new OpenGammaRuntimeException("Can only calculate forward driftless theta for surfaces with smiles");
}

From source file:com.google.errorprone.bugpatterns.formatstring.FormatStringValidation.java

@Nullable
public static ValidationResult validate(Collection<? extends ExpressionTree> arguments,
        final VisitorState state) {

    Deque<ExpressionTree> args = new ArrayDeque<ExpressionTree>(arguments);

    String formatString = ASTHelpers.constValue(args.removeFirst(), String.class);
    if (formatString == null) {
        return null;
    }/* w  w  w .  j  a v a2  s .  c o m*/

    // If the only argument is an Object[], it's an explicit varargs call.
    // Bail out, since we don't know what the actual argument types are.
    if (args.size() == 1) {
        Type type = ASTHelpers.getType(Iterables.getOnlyElement(args));
        if (type instanceof Type.ArrayType && ASTHelpers.isSameType(((Type.ArrayType) type).elemtype,
                state.getSymtab().objectType, state)) {
            return null;
        }
    }

    Iterable<Object> instances = Iterables.transform(args, new Function<ExpressionTree, Object>() {
        @Override
        public Object apply(ExpressionTree input) {
            try {
                return getInstance(input, state);
            } catch (Throwable t) {
                // ignore symbol completion failures
                return null;
            }
        }
    });

    return validate(formatString, instances);
}

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

@Override
public void processElement(Object element) throws Exception {
    WindowedValue<Iterable<Object>> elemsToWrite = (WindowedValue<Iterable<Object>>) element;
    BoundedWindow window = Iterables.getOnlyElement(elemsToWrite.getWindows());

    stepContext.writePCollectionViewData(viewTag, elemsToWrite.getValue(), IterableCoder.of(elemCoder), window,
            windowCoder);/* w w w  .ja va 2 s  .  c o m*/
}