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:io.druid.sql.calcite.aggregation.builtin.MinSqlAggregator.java

@Nullable
@Override//w w  w  .  j  ava2 s  .  c  om
public Aggregation toDruidAggregation(final PlannerContext plannerContext, final RowSignature rowSignature,
        final RexBuilder rexBuilder, final String name, final AggregateCall aggregateCall,
        final Project project, final List<Aggregation> existingAggregations) {
    if (aggregateCall.isDistinct()) {
        return null;
    }

    final List<DruidExpression> arguments = Aggregations.getArgumentsForSimpleAggregator(plannerContext,
            rowSignature, aggregateCall, project);

    if (arguments == null) {
        return null;
    }

    final DruidExpression arg = Iterables.getOnlyElement(arguments);
    final ValueType valueType = Calcites.getValueTypeForSqlTypeName(aggregateCall.getType().getSqlTypeName());
    final ExprMacroTable macroTable = plannerContext.getExprMacroTable();

    final String fieldName;
    final String expression;

    if (arg.isDirectColumnAccess()) {
        fieldName = arg.getDirectColumn();
        expression = null;
    } else {
        fieldName = null;
        expression = arg.getExpression();
    }

    return Aggregation.create(createMinAggregatorFactory(valueType, name, fieldName, expression, macroTable));
}

From source file:io.druid.sql.calcite.aggregation.builtin.SumSqlAggregator.java

@Nullable
@Override//from   w w w.j a va2s  .  c om
public Aggregation toDruidAggregation(final PlannerContext plannerContext, final RowSignature rowSignature,
        final RexBuilder rexBuilder, final String name, final AggregateCall aggregateCall,
        final Project project, final List<Aggregation> existingAggregations) {
    if (aggregateCall.isDistinct()) {
        return null;
    }

    final List<DruidExpression> arguments = Aggregations.getArgumentsForSimpleAggregator(plannerContext,
            rowSignature, aggregateCall, project);

    if (arguments == null) {
        return null;
    }

    final DruidExpression arg = Iterables.getOnlyElement(arguments);
    final ValueType valueType = Calcites.getValueTypeForSqlTypeName(aggregateCall.getType().getSqlTypeName());
    final ExprMacroTable macroTable = plannerContext.getExprMacroTable();

    final String fieldName;
    final String expression;

    if (arg.isDirectColumnAccess()) {
        fieldName = arg.getDirectColumn();
        expression = null;
    } else {
        fieldName = null;
        expression = arg.getExpression();
    }

    return Aggregation.create(createSumAggregatorFactory(valueType, name, fieldName, expression, macroTable));
}

From source file:com.opengamma.financial.analytics.model.horizon.FXForwardConstantSpreadSingleThetaFunction.java

@Override
public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs,
        final ComputationTarget target, final Set<ValueRequirement> desiredValues) {
    final Set<ComputedValue> computedValues = super.execute(executionContext, inputs, target, desiredValues);
    if (computedValues.size() != 1) {
        throw new OpenGammaRuntimeException("Expecting only one computed value");
    }//  w  ww.  j  a v a 2s .co m
    final ComputedValue computedValue = Iterables.getOnlyElement(computedValues);
    final ValueSpecification spec = computedValue.getSpecification();
    final Object thetaObject = computedValue.getValue();
    if (!(thetaObject instanceof MultipleCurrencyAmount)) {
        throw new OpenGammaRuntimeException(
                "Value theta did not have expected type MultipleCurrencyAmount: have "
                        + thetaObject.getClass());
    }
    final MultipleCurrencyAmount theta = (MultipleCurrencyAmount) thetaObject;
    if (theta.size() != 2) {
        throw new OpenGammaRuntimeException("Expected value theta to have two values; have " + theta.size());
    }
    final FinancialSecurity security = (FinancialSecurity) target.getSecurity();
    final Currency payCurrency = security.accept(ForexVisitors.getPayCurrencyVisitor());
    final Currency receiveCurrency = security.accept(ForexVisitors.getReceiveCurrencyVisitor());

    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    final CurrencyPairs currencyPairs = (CurrencyPairs) inputs.getValue(CURRENCY_PAIRS);
    final CurrencyPair currencyPair = currencyPairs.getCurrencyPair(payCurrency, receiveCurrency);
    final double scale;
    if (payCurrency.equals(currencyPair.getBase())) {
        scale = 1;
    } else {
        scale = -1;
    }
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    int payIndex = -1;
    int receiveIndex = -1;
    final CurrencyAmount[] currencyAmounts = theta.getCurrencyAmounts();
    for (int i = 0; i < 2; i++) {
        final Currency currency = currencyAmounts[i].getCurrency();
        if (payCurrency.equals(currency)) {
            payIndex = i;
        } else if (receiveCurrency.equals(currency)) {
            receiveIndex = i;
        } else {
            throw new OpenGammaRuntimeException("Value theta contains unexpected currency " + currency
                    + ". Expected " + payCurrency + " or " + receiveCurrency + ".");
        }
    }
    final double payValue = currencyAmounts[payIndex].getAmount();
    final double receiveValue = currencyAmounts[receiveIndex].getAmount();
    final double spot = (Double) inputs.getValue(ValueRequirementNames.SPOT_RATE);

    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    final double singleTheta = scale * (payValue + spot * receiveValue);
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    final ValueProperties properties = spec.getProperties().copy().withoutAny(FUNCTION)
            .with(FUNCTION, getUniqueId()).withoutAny(PROPERTY_THETA_CALCULATION_METHOD)
            .with(PROPERTY_THETA_CALCULATION_METHOD, CONSTANT_SPREAD_COLLAPSED)
            .with(CURRENCY, ((FinancialSecurity) target.getSecurity())
                    .accept(ForexVisitors.getPayCurrencyVisitor()).getCode())
            .get();
    final ValueSpecification convertedSpec = new ValueSpecification(spec.getValueName(),
            spec.getTargetSpecification(), properties);
    return Collections.singleton(new ComputedValue(convertedSpec, singleTheta));
}

From source file:io.prestosql.sql.planner.plan.ProjectNode.java

@Override
public PlanNode replaceChildren(List<PlanNode> newChildren) {
    return new ProjectNode(getId(), Iterables.getOnlyElement(newChildren), assignments);
}

From source file:com.opengamma.financial.analytics.model.credit.isda.cds.StandardVanillaBucketedIR01CDSFunction.java

public static double[] getBucketedIR01(CreditDefaultSwapDefinition definition,
        ISDACompliantYieldCurve yieldCurve, ZonedDateTime valuationDate, ValueProperties properties,
        ISDACompliantCreditCurve hazardCurve, CDSAnalytic analytic, LocalDate[] dates) {
    final Double interestRateCurveBump = Double.valueOf(Iterables.getOnlyElement(
            properties.getValues(CreditInstrumentPropertyNamesAndValues.PROPERTY_INTEREST_RATE_CURVE_BUMP)));
    //final InterestRateBumpType interestRateBumpType = InterestRateBumpType.valueOf(Iterables.getOnlyElement(properties.getValues(CreditInstrumentPropertyNamesAndValues.PROPERTY_INTEREST_RATE_BUMP_TYPE)));
    //final PriceType priceType = PriceType.valueOf(Iterables.getOnlyElement(properties.getValues(CreditInstrumentPropertyNamesAndValues.PROPERTY_CDS_PRICE_TYPE)));

    final double[] ir01 = CALCULATOR.bucketedIR01(analytic, getCoupon(definition), hazardCurve, yieldCurve);
    for (int i = 0; i < ir01.length; i++) {
        ir01[i] *= interestRateCurveBump * definition.getNotional();
        dates[i] = valuationDate.plusDays((long) yieldCurve.getTimeAtIndex(i) * 365).toLocalDate();
    }/*from  w  w  w  .  j a v a  2  s .  c  om*/
    return ir01;
}

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

@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
    if (!MATCHER.matches(tree, state)) {
        return Description.NO_MATCH;
    }//from w  w w. jav  a 2s. c  o  m

    SuggestedFix.Builder builder = SuggestedFix.builder();
    String replacement = "new " + SuggestedFixes.qualifyType(state, builder, "org.joda.time.Instant") + "(";
    ExpressionTree millisArg = Iterables.getOnlyElement(tree.getArguments());

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

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

public String getRequestId() {
    return Iterables.getOnlyElement(registerRequests).getChallenge();
}

From source file:edu.umd.cs.psl.model.kernel.datacertainty.DataCertaintyKernel.java

@Override
public void notifyAtomEvent(AtomEvent event, Atom atom, GroundingMode mode, ModelApplication app) {
    Preconditions.checkArgument(event == AtomEvent.ReleasedCertainty);
    GroundDataCertainty dc = (GroundDataCertainty) Iterables
            .getOnlyElement(atom.getRegisteredGroundKernels(this));
    app.removeGroundKernel(dc);/*  w w w. j av  a2 s .c om*/
}

From source file:com.opengamma.financial.analytics.model.credit.isda.cds.StandardVanillaRR01CDSFunction.java

public static double getRR01(CreditDefaultSwapDefinition definition, ISDACompliantYieldCurve yieldCurve,
        ValueProperties properties, ISDACompliantCreditCurve hazardCurve, CDSAnalytic analytic) {
    final RecoveryRateBumpType recoveryRateBumpType = RecoveryRateBumpType.valueOf(Iterables.getOnlyElement(
            properties.getValues(CreditInstrumentPropertyNamesAndValues.PROPERTY_RECOVERY_RATE_BUMP_TYPE)));
    if (recoveryRateBumpType != RecoveryRateBumpType.ADDITIVE) {
        throw new UnsupportedOperationException(
                "Only Additive rr01 sensitivity supported currently. Got " + recoveryRateBumpType);
    }//from w ww. j  a  v  a2  s.  c o m
    final Double bump = Double.valueOf(Iterables.getOnlyElement(
            properties.getValues(CreditInstrumentPropertyNamesAndValues.PROPERTY_RECOVERY_RATE_CURVE_BUMP)));
    return bump * 1e-4 * definition.getNotional()
            * CALCULATOR.recoveryRateSensitivity(analytic, yieldCurve, hazardCurve);
}

From source file:com.metamx.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(toolbox.getTaskActionClient().submit(new LockListAction()));
    final Interval interval = this.getImplicitLockInterval().get();
    final IncrementalIndex empty = new IncrementalIndex(0, QueryGranularity.NONE, new AggregatorFactory[0]);
    final IndexableAdapter emptyAdapter = new IncrementalIndexAdapter(interval, empty);

    // Create DataSegment
    final DataSegment segment = DataSegment.builder().dataSource(this.getDataSource()).interval(interval)
            .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  w w  . j  a v a 2 s  .  c om*/

    // 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.getTaskActionClient().submit(new SegmentInsertAction(ImmutableSet.of(uploadedSegment)));

    return TaskStatus.success(getId());
}