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:brooklyn.util.yaml.Yamls.java

/** returns the given yaml object (map or list or primitive) as the given yaml-supperted type 
 * (map or list or primitive e.g. string, number, boolean).
 * <p>/*  w ww .  j  a va2 s .  c  om*/
 * if the object is an iterable containing a single element, and the type is not an iterable,
 * this will attempt to unwrap it.
 * 
 * @throws IllegalArgumentException if the input is an iterable not containing a single element,
 *   and the cast is requested to a non-iterable type 
 * @throws ClassCastException if cannot be casted */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> T getAs(Object x, Class<T> type) {
    if (x == null)
        return null;
    if (x instanceof Iterable || x instanceof Iterator) {
        List result = new ArrayList();
        Iterator xi;
        if (Iterator.class.isAssignableFrom(x.getClass())) {
            xi = (Iterator) x;
        } else {
            xi = ((Iterable) x).iterator();
        }
        while (xi.hasNext()) {
            result.add(xi.next());
        }
        if (type.isAssignableFrom(Iterable.class))
            return (T) result;
        if (type.isAssignableFrom(Iterator.class))
            return (T) result.iterator();
        if (type.isAssignableFrom(List.class))
            return (T) result;
        x = Iterables.getOnlyElement(result);
    }
    return (T) x;
}

From source file:com.facebook.buck.rules.InputRule.java

public static InputRule inputPathAsInputRule(String relativePath, Function<String, String> pathRelativizer) {
    return Iterables.getOnlyElement(inputPathsAsInputRules(ImmutableList.of(relativePath), pathRelativizer));
}

From source file:org.apache.beam.runners.core.construction.SingleInputOutputOverrideFactory.java

@Override
public final InputT getInput(List<TaggedPValue> inputs, Pipeline p) {
    return (InputT) Iterables.getOnlyElement(inputs).getValue();
}

From source file:com.opengamma.financial.analytics.CurrencyPairsFunction.java

@Override
public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs,
        final ComputationTarget target, final Set<ValueRequirement> desiredValues)
        throws AsynchronousExecution {
    final ValueRequirement desiredValue = Iterables.getOnlyElement(desiredValues);
    final String name = desiredValue.getConstraint(CURRENCY_PAIRS_NAME);
    @SuppressWarnings("deprecation")
    final CurrencyPairsSource ccyPairsSource = OpenGammaExecutionContext
            .getCurrencyPairsSource(executionContext);
    final CurrencyPairs currencyPairs = ccyPairsSource.getCurrencyPairs(name);
    if (currencyPairs == null) {
        throw new OpenGammaRuntimeException(
                "Could not get CurrencyPairs called " + CurrencyPairs.DEFAULT_CURRENCY_PAIRS);
    }//  w ww  .  ja v a2  s  . c o m
    return Collections.singleton(new ComputedValue(new ValueSpecification(ValueRequirementNames.CURRENCY_PAIRS,
            ComputationTargetSpecification.NULL, createValueProperties().with(CURRENCY_PAIRS_NAME, name).get()),
            currencyPairs));
}

From source file:com.palantir.atlasdb.table.generation.ColumnValues.java

public static <T extends Persistable> Entry<Cell, byte[]> toCellValue(T key, ColumnValue<?> value) {
    Multimap<T, ? extends ColumnValue<?>> singletonMultimap = Multimaps
            .forMap(Collections.singletonMap(key, value));
    Map<Cell, byte[]> cellValues = toCellValues(singletonMultimap);
    return Iterables.getOnlyElement(cellValues.entrySet());
}

From source file:com.opengamma.financial.analytics.model.forex.option.callspreadblack.FXDigitalCallSpreadBlackCurrencyExposureFunction.java

@Override
protected Set<ComputedValue> getResult(final InstrumentDerivative fxDigital,
        final ForexOptionDataBundle<?> data, final ComputationTarget target,
        final Set<ValueRequirement> desiredValues, final FunctionInputs inputs, final ValueSpecification spec,
        final FunctionExecutionContext executionContext) {
    final String spreadName = Iterables.getOnlyElement(desiredValues)
            .getConstraint(CalculationPropertyNamesAndValues.PROPERTY_CALL_SPREAD_VALUE);
    final double spread = Double.parseDouble(spreadName);
    final CurrencyExposureCallSpreadBlackForexCalculator calculator = new CurrencyExposureCallSpreadBlackForexCalculator(
            spread);//from w w  w. ja  va2s . c o m
    final MultipleCurrencyAmount result = fxDigital.accept(calculator, data);
    return Collections.singleton(new ComputedValue(spec, result));
}

From source file:com.facebook.buck.cli.SuggestCommand.java

/**
 * Normalizes the sole build target argument and partitions it using a
 * {@link FineGrainedJavaDependencySuggester}.
 *//*from ww w. j a  v a  2s .com*/
@Override
public int runWithoutHelp(final CommandRunnerParams params) throws IOException, InterruptedException {
    final Console console = params.getConsole();
    if (arguments.size() != 1) {
        console.printErrorText("Must specify exactly one argument to 'buck suggest'.");
        return 1;
    }

    String targetToBreakDown = Iterables.getOnlyElement(arguments);
    final String fullyQualifiedTarget = Iterables.getOnlyElement(
            getCommandLineBuildTargetNormalizer(params.getBuckConfig()).normalize(targetToBreakDown));

    JavaBuildGraphProcessor.Processor processor = (graph, javaDepsFinder, executorService) -> {
        BuildTarget buildTarget = params.getBuckConfig()
                .getBuildTargetForFullyQualifiedTarget(fullyQualifiedTarget);
        FineGrainedJavaDependencySuggester suggester = new FineGrainedJavaDependencySuggester(buildTarget,
                graph, javaDepsFinder, console);
        suggester.suggestRefactoring();
    };
    try {
        JavaBuildGraphProcessor.run(params, this, processor);
    } catch (JavaBuildGraphProcessor.ExitCodeException e) {
        return e.exitCode;
    }

    return 0;
}

From source file:com.opengamma.financial.analytics.AttributesFunction.java

@Override
public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs,
        final ComputationTarget target, final Set<ValueRequirement> desiredValues)
        throws AsynchronousExecution {
    final ValueRequirement desiredValue = Iterables.getOnlyElement(desiredValues);
    final String attributeName = desiredValue.getConstraint(PROPERTY_ATTRIBUTE_NAME);
    final Security security = target.getSecurity();
    final Map<String, String> attributes = security.getAttributes();
    final String result = attributes.get(attributeName);
    if (result == null) {
        throw new OpenGammaRuntimeException("Could not get value for attribute " + attributeName);
    }/*from  w  ww.j a v  a  2  s.  c o m*/
    final ValueProperties properties = createValueProperties().with(PROPERTY_ATTRIBUTE_NAME, attributeName)
            .get();
    final ValueSpecification spec = new ValueSpecification(ValueRequirementNames.ATTRIBUTES,
            target.toSpecification(), properties);
    return Collections.singleton(new ComputedValue(spec, result));
}

From source file:org.jage.communication.message.Messages.java

/**
 * Returns the address of the only receiver selected by the selector in the provided message.
 * //from w w  w.j  a  v  a 2s  .co  m
 * @param message
 *            a message to extract receiver from.
 * @param <A>
 *            a type of addresses.
 * @return An extracted receiver.
 * 
 * @throws NoSuchElementException
 *             if there is no selected receiver.
 * @throws IllegalArgumentException
 *             if the selector selects multiple addresses.
 */
@Nonnull
public static <A extends Address> A getOnlyReceiverAddress(final IMessage<A, ?> message) {
    checkNotNull(message);
    return Iterables.getOnlyElement(message.getHeader().getReceiverSelector().addresses());
}

From source file:org.jclouds.ec2.predicates.SnapshotCompleted.java

public boolean apply(Snapshot snapshot) {
    logger.trace("looking for status on snapshot %s", snapshot.getId());

    snapshot = Iterables.getOnlyElement(
            client.describeSnapshotsInRegion(snapshot.getRegion(), snapshotIds(snapshot.getId())));
    logger.trace("%s: looking for status %s: currently: %s; progress %d/100", snapshot,
            Snapshot.Status.COMPLETED, snapshot.getStatus(), snapshot.getProgress());
    return snapshot.getStatus() == Snapshot.Status.COMPLETED;
}