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.apache.druid.sql.calcite.aggregation.builtin.AvgSqlAggregator.java

@Nullable
@Override/*w  w w.jav  a2 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,
        final boolean finalizeAggregations) {
    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 sumType;

    // Use 64-bit sum regardless of the type of the AVG aggregator.
    if (SqlTypeName.INT_TYPES.contains(aggregateCall.getType().getSqlTypeName())) {
        sumType = ValueType.LONG;
    } else {
        sumType = ValueType.DOUBLE;
    }

    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();
    }

    final String sumName = Calcites.makePrefixedName(name, "sum");
    final String countName = Calcites.makePrefixedName(name, "count");
    final AggregatorFactory sum = SumSqlAggregator.createSumAggregatorFactory(sumType, sumName, fieldName,
            expression, macroTable);

    final AggregatorFactory count = new CountAggregatorFactory(countName);

    return Aggregation.create(ImmutableList.of(sum, count),
            new ArithmeticPostAggregator(name, "quotient",
                    ImmutableList.of(new FieldAccessPostAggregator(null, sumName),
                            new FieldAccessPostAggregator(null, countName))));
}

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

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

        @Override//from   w ww . ja va  2  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 BlackSTIRFuturesSmileProviderInterface blackData = getBlackSurface(executionContext, inputs,
                    target, fxMatrix);
            final double positionVega = derivative.accept(CALCULATOR, blackData);
            final ValueRequirement desiredValue = Iterables.getOnlyElement(desiredValues);
            final ValueProperties properties = desiredValue.getConstraints().copy().get();
            final ValueSpecification spec = new ValueSpecification(POSITION_VEGA, target.toSpecification(),
                    properties);
            return Collections.singleton(new ComputedValue(spec, positionVega));
        }

    };
}

From source file:org.sosy_lab.solver.basicimpl.AbstractBooleanFormulaManager.java

@Override
public BooleanFormula and(Collection<BooleanFormula> pBits) {
    if (pBits.isEmpty()) {
        return makeBoolean(true);
    }/*from  ww  w .j a  v a  2  s . co  m*/
    if (pBits.size() == 1) {
        return Iterables.getOnlyElement(pBits);
    }
    TFormulaInfo result = andImpl(Collections2.transform(pBits, extractor));
    return wrap(result);
}

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

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

        @Override/*from   w  w  w  .j  av 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 BlackForexSmileProvider blackData = getBlackSurface(executionContext, inputs, target,
                    fxMatrix);
            final double forwardVega = derivative.accept(CALCULATOR, blackData);
            final ValueRequirement desiredValue = Iterables.getOnlyElement(desiredValues);
            final ValueProperties properties = desiredValue.getConstraints().copy().get();
            final ValueSpecification spec = new ValueSpecification(FORWARD_VEGA, target.toSpecification(),
                    properties);
            return Collections.singleton(new ComputedValue(spec, forwardVega));
        }

    };
}

From source file:com.aipo.social.opensocial.service.AipoActivityHandler.java

/**
 * Allowed end-points /activities/{userId}/@self/{actvityId}+
 *
 * examples: /activities/john.doe/@self/1
 *//*  w  ww. j a va 2  s  . c  om*/
@Operation(httpMethods = "DELETE")
public Future<?> delete(SocialRequestItem request) throws ProtocolException {
    try {
        Set<UserId> userIds = request.getUsers();
        Set<String> activityIds = ImmutableSet.copyOf(request.getListParameter("activityId"));

        // Preconditions
        AipoPreconditions.validateScope(request.getToken(), AipoScope.W_ALL);
        AipoPreconditions.required("userId", userIds);
        AipoPreconditions.notMultiple("userId", userIds);

        return service.deleteActivities(Iterables.getOnlyElement(userIds), request.getGroup(),
                request.getAppId(), activityIds, request.getToken());
    } catch (ProtocolException e) {
        throw e;
    } catch (Throwable t) {
        throw new AipoProtocolException(AipoErrorCode.INTERNAL_ERROR);
    }
}

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

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

        @Override/*www.java 2s .  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 BlackSTIRFuturesSmileProviderInterface blackData = getBlackSurface(executionContext, inputs,
                    target, fxMatrix);
            final double positionDelta = derivative.accept(CALCULATOR, blackData);
            final ValueRequirement desiredValue = Iterables.getOnlyElement(desiredValues);
            final ValueProperties properties = desiredValue.getConstraints().copy().get();
            final ValueSpecification spec = new ValueSpecification(POSITION_DELTA, target.toSpecification(),
                    properties);
            return Collections.singleton(new ComputedValue(spec, positionDelta));
        }

    };
}

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

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

        @Override//from   ww  w  . j a  v a 2s .  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 BlackSTIRFuturesSmileProviderInterface blackData = getBlackSurface(executionContext, inputs,
                    target, fxMatrix);
            final double positionGamma = derivative.accept(CALCULATOR, blackData);
            final ValueRequirement desiredValue = Iterables.getOnlyElement(desiredValues);
            final ValueProperties properties = desiredValue.getConstraints().copy().get();
            final ValueSpecification spec = new ValueSpecification(POSITION_GAMMA, target.toSpecification(),
                    properties);
            return Collections.singleton(new ComputedValue(spec, positionGamma));
        }

    };
}

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

@Override
public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs,
        final ComputationTarget target, final Set<ValueRequirement> desiredValues)
        throws AsynchronousExecution {
    final FinancialSecurity security = (FinancialSecurity) target.getSecurity();
    final ValueRequirement desiredValue = Iterables.getOnlyElement(desiredValues);
    final Object curveSensitivitiesObject = inputs.getValue(ValueRequirementNames.FX_CURVE_SENSITIVITIES);
    if (curveSensitivitiesObject == null) {
        throw new OpenGammaRuntimeException("Could not get curve sensitivities");
    }/*w  w w  . j a  v  a2 s.  c o m*/
    final Currency putCurrency = security.accept(ForexVisitors.getPutCurrencyVisitor());
    final Currency callCurrency = security.accept(ForexVisitors.getCallCurrencyVisitor());
    final Object baseQuotePairsObject = inputs.getValue(ValueRequirementNames.CURRENCY_PAIRS);
    if (baseQuotePairsObject == null) {
        throw new OpenGammaRuntimeException("Could not get base/quote pair data");
    }
    final CurrencyPairs baseQuotePairs = (CurrencyPairs) baseQuotePairsObject;
    final CurrencyPair baseQuotePair = baseQuotePairs.getCurrencyPair(putCurrency, callCurrency);
    if (baseQuotePair == null) {
        throw new OpenGammaRuntimeException(
                "Could not get base/quote pair for currency pair (" + putCurrency + ", " + callCurrency + ")");
    }
    final String callCurrencyCurve = desiredValue.getConstraint(FXOptionBlackFunction.CALL_CURVE);
    final String resultCurrency = getResultCurrency(target, baseQuotePair);
    final String fullCurveName = callCurrencyCurve + "_" + callCurrency.getCode();
    final MultipleCurrencyInterestRateCurveSensitivity curveSensitivities = (MultipleCurrencyInterestRateCurveSensitivity) curveSensitivitiesObject;
    final Map<String, List<DoublesPair>> sensitivitiesForCurrency = curveSensitivities
            .getSensitivity(Currency.of(resultCurrency)).getSensitivities();
    final ValueSpecification spec = new ValueSpecification(ValueRequirementNames.VALUE_RHO,
            target.toSpecification(), getResultProperties(target, desiredValue, baseQuotePair).get());
    final double rho = sensitivitiesForCurrency.get(fullCurveName).get(0).second;
    return Collections.singleton(new ComputedValue(spec, rho));
}

From source file:org.apache.beam.runners.gearpump.translators.TranslationContext.java

public PValue getInput() {
    return Iterables.getOnlyElement(TransformInputs.nonAdditionalInputs(getCurrentTransform()));
}

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

@Override
public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs,
        final ComputationTarget target, final Set<ValueRequirement> desiredValues)
        throws AsynchronousExecution {
    final FinancialSecurity security = (FinancialSecurity) target.getSecurity();
    final ValueRequirement desiredValue = Iterables.getOnlyElement(desiredValues);
    final Object curveSensitivitiesObject = inputs.getValue(ValueRequirementNames.FX_CURVE_SENSITIVITIES);
    if (curveSensitivitiesObject == null) {
        throw new OpenGammaRuntimeException("Could not get curve sensitivities");
    }//from www .j  a  v a2s .c  om
    final Currency putCurrency = security.accept(ForexVisitors.getPutCurrencyVisitor());
    final Currency callCurrency = security.accept(ForexVisitors.getCallCurrencyVisitor());
    final String putCurrencyCurve = desiredValue.getConstraint(FXOptionBlackFunction.PUT_CURVE);
    final Object baseQuotePairsObject = inputs.getValue(ValueRequirementNames.CURRENCY_PAIRS);
    if (baseQuotePairsObject == null) {
        throw new OpenGammaRuntimeException("Could not get base/quote pair data");
    }
    final CurrencyPairs baseQuotePairs = (CurrencyPairs) baseQuotePairsObject;
    final CurrencyPair baseQuotePair = baseQuotePairs.getCurrencyPair(putCurrency, callCurrency);
    if (baseQuotePair == null) {
        throw new OpenGammaRuntimeException(
                "Could not get base/quote pair for currency pair (" + putCurrency + ", " + callCurrency + ")");
    }
    final String resultCurrency = getResultCurrency(target, baseQuotePair);
    final String fullCurveName = putCurrencyCurve + "_" + putCurrency.getCode();
    final MultipleCurrencyInterestRateCurveSensitivity curveSensitivities = (MultipleCurrencyInterestRateCurveSensitivity) curveSensitivitiesObject;
    final Map<String, List<DoublesPair>> sensitivitiesForCurrency = curveSensitivities
            .getSensitivity(Currency.of(resultCurrency)).getSensitivities();
    final ValueSpecification spec = new ValueSpecification(ValueRequirementNames.VALUE_PHI,
            target.toSpecification(), getResultProperties(target, desiredValue, baseQuotePair).get());
    final double phi = sensitivitiesForCurrency.get(fullCurveName).get(0).second;
    return Collections.singleton(new ComputedValue(spec, phi));
}