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:com.google.testing.compile.MoreTrees.java

/** Parses the source given into a {@link CompilationUnitTree}. */
static CompilationUnitTree parseLinesToTree(Iterable<String> source) {
    Iterable<? extends CompilationUnitTree> parseResults = Compilation
            .parse(ImmutableList.of(JavaFileObjects.forSourceLines("", source))).compilationUnits();
    return Iterables.getOnlyElement(parseResults);
}

From source file:com.b2international.snowowl.snomed.reasoner.model.SnomedOntologyUtils.java

/**
 * Creates an {@link OWLObjectIntersectionOf} expression for the passed in class expression set, or returns a single expression if the set has
 * only one element.//from  w w  w.  ja v a  2 s  .  co  m
 * @param df the {@link OWLDataFactory} to use for creating OWL objects
 * @param terms the set of terms to convert
 * @return the converted class expression
 */
public static OWLClassExpression simplifyIntersectionOf(final OWLDataFactory df,
        final Set<OWLClassExpression> terms) {
    if (terms.size() > 1) {
        return df.getOWLObjectIntersectionOf(terms);
    } else {
        return Iterables.getOnlyElement(terms); // Also handles case when terms is empty
    }
}

From source file:linn.core.lang.production.RewriteProduction.java

@Override
public List<Production> execute(final LinnTurtle state, final ProductionParameter... parameters) {
    final List<Integer> ruleIds = this.linn.getRuleIds(this.ruleName);
    if (ruleIds.size() == 1) {
        final Integer ruleId = Iterables.getOnlyElement(ruleIds);
        // TODO check condition if any
        final List<Production> rewriteProductions = this.linn.getRuleProductions(ruleId);
        return rewriteProductions;
    } else if (ruleIds.size() > 1) {
        // TODO impl conditional case
        double totalRuleWeight = 0;
        // range for probability based on weight for all potential rules
        final TreeMap<Double, Integer> weightRangeOfRule = Maps.newTreeMap();
        for (final Integer ruleId : ruleIds) {
            final double ruleWeight = this.linn.getRuleWeight(ruleId);
            totalRuleWeight += ruleWeight;
            weightRangeOfRule.put(totalRuleWeight, ruleId);
        }/*from  w w w  .j a v  a 2  s.c  o  m*/
        // pick a random rule considering weights
        final double chosenRangeValue = LOCAL_RAND.nextDouble() * totalRuleWeight;
        final Entry<Double, Integer> chosenRuleEntry = weightRangeOfRule.ceilingEntry(chosenRangeValue);
        checkNotNull(chosenRuleEntry);
        final List<Production> rewriteProductions = this.linn.getRuleProductions(chosenRuleEntry.getValue());
        return rewriteProductions;
    }
    return null;
}

From source file:org.wso2.carbon.identity.application.authenticator.fido.u2f.data.messages.RegisterRequestData.java

public RegisterRequest getRegisterRequest(RegisterResponse response) {
    return Iterables.getOnlyElement(registerRequests);
}

From source file:com.opengamma.financial.analytics.model.black.ConstantBlackDiscountingImpliedVolatilitySwaptionFunction.java

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

        @Override/*from  w ww .  ja  v  a2s  .  com*/
        protected Set<ComputedValue> getValues(final FunctionExecutionContext executionContext,
                final FunctionInputs inputs, final ComputationTarget target,
                final Set<ValueRequirement> desiredValues, final InstrumentDerivative derivative,
                final FXMatrix fxMatrix) {
            final BlackSwaptionFlatProvider blackData = getSwaptionBlackSurface(executionContext, inputs,
                    target, fxMatrix);
            final ValueRequirement desiredValue = Iterables.getOnlyElement(desiredValues);
            final ValueProperties properties = desiredValue.getConstraints().copy().get();
            final ValueSpecification spec = new ValueSpecification(IMPLIED_VOLATILITY, target.toSpecification(),
                    properties);
            final Double impliedVolatility = blackData.getBlackParameters().getVolatility(0, 0);
            return Collections.singleton(new ComputedValue(spec, impliedVolatility));
        }

    };
}

From source file:org.jclouds.aws.ec2.predicates.SpotInstanceRequestActive.java

private SpotInstanceRequest refresh(SpotInstanceRequest spot) {
    return Iterables.getOnlyElement(client.getSpotInstanceApi().get()
            .describeSpotInstanceRequestsInRegion(spot.getRegion(), spot.getId()));
}

From source file:org.eclipse.sirius.diagram.sequence.business.internal.refresh.SequenceRefreshExtension.java

/**
 * {@inheritDoc}//from  ww w  . j  a  v a 2 s  .c  om
 */
public void beforeRefresh(DDiagram dDiagram) {
    if (dDiagram instanceof SequenceDDiagram) {
        currentDiagram = (SequenceDDiagram) dDiagram;

        Collection<DDiagramElement> nodeEvents = getEventsToSync(currentDiagram);

        if (nodeEvents.size() != 0) {
            flags = Maps.newHashMapWithExpectedSize(nodeEvents.size());
            for (DDiagramElement elt : nodeEvents) {
                Iterable<AbsoluteBoundsFilter> flag = Iterables.filter(elt.getGraphicalFilters(),
                        AbsoluteBoundsFilter.class);
                EObject semanticTarget = elt.getTarget();
                if (semanticTarget != null && Iterables.size(flag) == 1) {
                    flags.put(semanticTarget, Iterables.getOnlyElement(flag));
                }
            }
        }
    }
}

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

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

        @Override/*from www . ja v a2 s  .  c  o  m*/
        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.presentValue(forex, data, forwardPoints, ccyPair);
            if (mca.size() != 1) {
                throw new OpenGammaRuntimeException("Expecting a single value for present value");
            }
            final CurrencyAmount ca = mca.getCurrencyAmounts()[0];
            final ValueSpecification spec = new ValueSpecification(PRESENT_VALUE, target.toSpecification(),
                    properties);
            return Collections.singleton(new ComputedValue(spec, ca.getAmount()));
        }
    };
}

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

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

From source file:com.google.devtools.build.lib.actions.MiddlemanFactory.java

/**
 * Creates a {@link MiddlemanType#AGGREGATING_MIDDLEMAN aggregating} middleman.
 *
 * @param owner the owner of the action that will be created; must not be null
 * @param purpose the purpose for which this middleman is created. This should be a string which
 *        is suitable for use as a filename. A single rule may have many middlemen with distinct
 *        purposes.// w w  w .ja va2  s  . c  om
 * @param inputs the set of artifacts for which the created artifact is to be the middleman.
 * @param middlemanDir the directory in which to place the middleman.
 * @return null iff {@code inputs} is empty; the single element of {@code inputs} if there's only
 *         one; a new aggregating middleman for the {@code inputs} otherwise
 */
public Artifact createAggregatingMiddleman(ActionOwner owner, String purpose, Iterable<Artifact> inputs,
        Root middlemanDir) {
    if (hasExactlyOneInput(inputs)) { // Optimization: No middleman for just one input.
        return Iterables.getOnlyElement(inputs);
    }
    Pair<Artifact, Action> result = createMiddleman(owner, Label.print(owner.getLabel()), purpose, inputs,
            middlemanDir, MiddlemanType.AGGREGATING_MIDDLEMAN);
    return result == null ? null : result.getFirst();
}