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.trancecode.xproc.PipelineResult.java

public void readNode(final String portName, final File outputFile) {
    Preconditions.checkNotNull(outputFile);
    final XdmNode node = Iterables.getOnlyElement(readNodes(portName));
    try {//ww w  .j  a  v  a 2 s  . c  o  m
        Files.write(node.toString(), outputFile, Charset.defaultCharset());
    } catch (final IOException e) {
        throw new RuntimeIOException(e);
    }
}

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

public static Predicate<Firewall> equalsIpPermission(final IpPermission permission) {
    return new Predicate<Firewall>() {
        @Override/*from  w  w  w  . j a  va  2s  . c  o  m*/
        public boolean apply(Firewall input) {
            return Iterables.elementsEqual(permission.getGroupIds(), input.getSourceTags())
                    && Iterables.elementsEqual(permission.getCidrBlocks(), input.getSourceRanges())
                    && (input.getAllowed().size() == 1 && ruleEqualsIpPermission(permission)
                            .apply(Iterables.getOnlyElement(input.getAllowed())));
        }
    };
}

From source file:com.opengamma.financial.analytics.model.volatility.surface.ForexFlatWithTermStructureVolatilitySurfaceFunction.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 surfaceName = desiredValue.getConstraint(ValuePropertyNames.SURFACE);
    final String interpolatorName = desiredValue.getConstraint(InterpolatedDataProperties.X_INTERPOLATOR_NAME);
    final String leftExtrapolatorName = desiredValue
            .getConstraint(InterpolatedDataProperties.LEFT_X_EXTRAPOLATOR_NAME);
    final String rightExtrapolatorName = desiredValue
            .getConstraint(InterpolatedDataProperties.RIGHT_X_EXTRAPOLATOR_NAME);
    final Set<String> shifts = desiredValue.getConstraints().getValues(VolatilitySurfaceShiftFunction.SHIFT);
    final ValueRequirement surfaceRequirement = getDataRequirement(surfaceName, target);
    final Object volatilitySurfaceObject = inputs.getValue(surfaceRequirement);
    if (volatilitySurfaceObject == null) {
        throw new OpenGammaRuntimeException("Could not get " + surfaceRequirement);
    }//  w  w w .j  av a 2  s. c  o  m
    @SuppressWarnings("unchecked")
    final VolatilitySurfaceData<Tenor, Pair<Number, FXVolQuoteType>> fxVolatilitySurface = (VolatilitySurfaceData<Tenor, Pair<Number, FXVolQuoteType>>) volatilitySurfaceObject;
    if (fxVolatilitySurface.getYs().length != 1) {
        throw new OpenGammaRuntimeException(
                "Have smile data present in a surface that should only have a term structure");
    }
    final Tenor[] tenors = fxVolatilitySurface.getXs();
    Arrays.sort(tenors);
    final double shiftMultiplier;
    if ((shifts != null) && (shifts.size() == 1)) {
        final String shift = shifts.iterator().next();
        shiftMultiplier = 1 + Double.parseDouble(shift);
    } else {
        shiftMultiplier = 1;
    }
    final DoubleArrayList timesList = new DoubleArrayList();
    final DoubleArrayList volsList = new DoubleArrayList();
    for (final Tenor tenor : tenors) {
        final double t = getTime(tenor);
        for (final Pair<Number, FXVolQuoteType> y : fxVolatilitySurface.getYs()) {
            Double volatility = fxVolatilitySurface.getVolatility(tenor, y);
            if (volatility != null) {
                volatility *= shiftMultiplier;
                if (y.getSecond().equals(FXVolQuoteType.ATM)) {
                    volsList.add(volatility);
                    timesList.add(t);
                }
            }
        }
    }
    if (volsList.size() == 0) {
        throw new OpenGammaRuntimeException(
                "No volatility surface data for FX surface " + target.getUniqueId());
    }
    final ValueProperties.Builder resultProperties = createValueProperties()
            .with(ValuePropertyNames.SURFACE, surfaceName)
            .with(InstrumentTypeProperties.PROPERTY_SURFACE_INSTRUMENT_TYPE, InstrumentTypeProperties.FOREX)
            .with(InterpolatedDataProperties.X_INTERPOLATOR_NAME, interpolatorName)
            .with(InterpolatedDataProperties.LEFT_X_EXTRAPOLATOR_NAME, leftExtrapolatorName)
            .with(InterpolatedDataProperties.RIGHT_X_EXTRAPOLATOR_NAME, rightExtrapolatorName);
    if (shifts != null) {
        resultProperties.with(VolatilitySurfaceShiftFunction.SHIFT, shifts);
    }
    final Interpolator1D interpolator = CombinedInterpolatorExtrapolatorFactory
            .getInterpolator(interpolatorName, leftExtrapolatorName, rightExtrapolatorName);
    final DoublesCurve volatility = InterpolatedDoublesCurve.fromSorted(timesList.toDoubleArray(),
            volsList.toDoubleArray(), interpolator);
    final BlackForexTermStructureParameters termStructure = new BlackForexTermStructureParameters(volatility);
    return Collections.singleton(
            new ComputedValue(new ValueSpecification(ValueRequirementNames.STANDARD_VOLATILITY_SURFACE_DATA,
                    target.toSpecification(), resultProperties.get()), termStructure));
}

From source file:com.opengamma.financial.analytics.model.equity.varianceswap.EquityVarianceSwapPureLocalVolPVFunction.java

@Override
public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs,
        final ComputationTarget target, final Set<ValueRequirement> desiredValues)
        throws AsynchronousExecution {
    final Clock snapshotClock = executionContext.getValuationClock();
    final ZonedDateTime now = ZonedDateTime.now(snapshotClock);
    final ValueRequirement desiredValue = Iterables.getOnlyElement(desiredValues);
    final EquityVarianceSwapSecurity security = (EquityVarianceSwapSecurity) target.getSecurity();
    final EquityVarianceSwapDefinition definition = security.accept(getConverter());
    final Object spotObject = inputs.getValue(MarketDataRequirementNames.MARKET_VALUE);
    if (spotObject == null) {
        throw new OpenGammaRuntimeException("Spot value was null");
    }//w  w  w  . j  a v a  2  s .com
    final Object yieldCurveObject = inputs.getValue(ValueRequirementNames.YIELD_CURVE);
    if (yieldCurveObject == null) {
        throw new OpenGammaRuntimeException("Yield curve was null");
    }
    final Object dividendsObject = inputs.getValue(ValueRequirementNames.AFFINE_DIVIDENDS);
    if (dividendsObject == null) {
        throw new OpenGammaRuntimeException("Dividends were null");
    }
    final Object forwardCurveObject = inputs.getValue(ValueRequirementNames.FORWARD_CURVE);
    if (forwardCurveObject == null) {
        throw new OpenGammaRuntimeException("Forward curve was null");
    }
    final Object volatilitiesObject = inputs.getValue(ValueRequirementNames.STANDARD_VOLATILITY_SURFACE_DATA);
    if (volatilitiesObject == null) {
        throw new OpenGammaRuntimeException("Volatility data were null");
    }
    final Object tsObject = inputs.getValue(ValueRequirementNames.HISTORICAL_TIME_SERIES);
    final double spot = (Double) spotObject;
    final YieldAndDiscountCurve yieldCurve = (YieldAndDiscountCurve) yieldCurveObject;
    final AffineDividends dividends = (AffineDividends) dividendsObject;
    final SmileSurfaceDataBundle volatilities = getData(inputs);
    final DoubleTimeSeries<LocalDate> underlyingTS = ((HistoricalTimeSeries) tsObject).getTimeSeries();
    final EquityVarianceSwap swap = definition.toDerivative(now, underlyingTS);
    final EquityVarianceSwapPricer pricer = EquityVarianceSwapPricer.builder().create(); //TODO don't just use defaults
    final double pv = pricer.priceFromImpliedVolsBackwardPDE(swap, spot, yieldCurve, dividends, volatilities);
    final ValueProperties properties = desiredValue.getConstraints().copy()
            .withoutAny(ValuePropertyNames.FUNCTION).with(ValuePropertyNames.FUNCTION, getUniqueId()).get();
    final ValueSpecification spec = new ValueSpecification(getValueRequirementName(), target.toSpecification(),
            properties);
    return Collections.singleton(new ComputedValue(spec, pv));
}

From source file:com.vmware.photon.controller.apife.commands.steps.HostEnterMaintenanceModeStepCmd.java

@Override
protected void execute() throws ApiFeException, InterruptedException, RpcException {

    List<BaseEntity> entityList = step.getTransientResourceEntities();

    HostEntity hostEntity = (HostEntity) Iterables.getOnlyElement(entityList);

    int vmCount = vmBackend.countVmsOnHost(hostEntity);
    if (vmCount > 0) {
        throw new HostHasVmsException(hostEntity.getId(), vmCount);
    }//from www .j a  v  a 2  s .c  o m

    try {
        taskCommand.getDeployerClient().enterMaintenanceMode(hostEntity.getId());
        hostBackend.updateState(hostEntity, HostState.MAINTENANCE);
    } catch (InterruptedException | RpcException e) {
        HostStateChangeException exception = new HostStateChangeException(hostEntity, HostState.SUSPENDED, e);
        logger.error(exception.getMessage());
        throw exception;
    }
}

From source file:com.facebook.swift.service.metadata.ThriftServiceMetadata.java

public static ThriftService getThriftServiceAnnotation(Class<?> serviceClass) {
    Set<ThriftService> serviceAnnotations = getAllClassAnnotations(serviceClass, ThriftService.class);
    Preconditions.checkArgument(!serviceAnnotations.isEmpty(),
            "Service class %s is not annotated with @ThriftService", serviceClass.getName());
    Preconditions.checkArgument(serviceAnnotations.size() == 1,
            "Service class %s has multiple conflicting @ThriftService annotations: %s", serviceClass.getName(),
            serviceAnnotations);/*www. j  a  va 2s .  com*/

    return Iterables.getOnlyElement(serviceAnnotations);
}

From source file:com.opengamma.master.historicaltimeseries.impl.FieldMappingHistoricalTimeSeriesResolver.java

@Override
public HistoricalTimeSeriesResolutionResult resolve(ExternalIdBundle identifierBundle,
        LocalDate identifierValidityDate, String dataSource, String dataProvider, String dataField,
        String resolutionKey) {/* w ww.ja v a 2  s . co m*/
    ArgumentChecker.notNull(dataField, "dataField");
    // Apply any field mappings
    Map<String, HistoricalTimeSeriesFieldAdjustment> fieldMappings = getFieldAdjustments(dataSource, dataField);
    if (fieldMappings.size() == 1) {
        // Optimisation - might as well restrict the search results
        Map.Entry<String, HistoricalTimeSeriesFieldAdjustment> fieldMappingEntry = Iterables
                .getOnlyElement(fieldMappings.entrySet());
        dataSource = fieldMappingEntry.getKey();
        dataProvider = fieldMappingEntry.getValue().getUnderlyingDataProvider();
        dataField = fieldMappingEntry.getValue().getUnderlyingDataField();
    } else if (fieldMappings.size() > 1) {
        // Could have been mapped to multiple underlying providers/fields
        dataField = null;
        dataProvider = null;
    }
    if (identifierBundle != null) {
        Collection<ManageableHistoricalTimeSeriesInfo> timeSeriesCandidates = search(identifierBundle,
                identifierValidityDate, dataSource, dataProvider, dataField);
        if (!fieldMappings.isEmpty()) {
            Iterator<ManageableHistoricalTimeSeriesInfo> it = timeSeriesCandidates.iterator();
            while (it.hasNext()) {
                ManageableHistoricalTimeSeriesInfo candidate = it.next();
                HistoricalTimeSeriesFieldAdjustment fieldAdjustment = fieldMappings
                        .get(candidate.getDataSource());
                if (fieldAdjustment == null || ((fieldAdjustment.getUnderlyingDataProvider() != null
                        && !fieldAdjustment.getUnderlyingDataProvider().equals(candidate.getDataProvider()))
                        || !fieldAdjustment.getUnderlyingDataField().equals(candidate.getDataField()))) {
                    // Incompatible
                    it.remove();
                }
            }
        }
        ManageableHistoricalTimeSeriesInfo selectedResult = select(timeSeriesCandidates, resolutionKey);
        if (selectedResult == null) {
            s_logger.debug("Resolver failed to find any time-series for {} using {}/{}",
                    new Object[] { identifierBundle, dataField, resolutionKey });
            return null;
        }
        HistoricalTimeSeriesFieldAdjustment fieldAdjustment = fieldMappings.get(selectedResult.getDataSource());
        HistoricalTimeSeriesAdjuster adjuster = fieldAdjustment != null ? fieldAdjustment.getAdjuster() : null;
        return new HistoricalTimeSeriesResolutionResult(selectedResult, adjuster);
    } else {
        return search(dataSource, dataProvider, dataField);
    }
}

From source file:com.opengamma.financial.analytics.model.forex.option.black.FXOptionBlackForwardThetaTheoreticalFunction.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;/*from   w  w w. j a  v a  2  s  . c om*/
        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(ForwardBlackThetaTheoreticalForexCalculator.getInstance(), data)
                / scale;
        return Collections.singleton(new ComputedValue(new ValueSpecification(ValueRequirementNames.THETA,
                target.toSpecification(), resultProperties.get()), result));
    }
    throw new OpenGammaRuntimeException("Can only calculate theoretical theta for surfaces with smiles");
}

From source file:org.jclouds.location.suppliers.all.ZoneToProvider.java

@Override
public Set<? extends Location> get() {
    Location provider = Iterables.getOnlyElement(justProvider.get());
    Set<String> zoneIds = zoneIdsSupplier.get();
    checkState(zoneIds.size() > 0, "no zones found for provider %s, using supplier %s", provider,
            zoneIdsSupplier);/*from   ww w.j av a  2 s  . c om*/
    Map<String, Supplier<Set<String>>> isoCodesById = isoCodesByIdSupplier.get();

    Builder<Location> locations = ImmutableSet.builder();
    for (String zoneId : zoneIds) {
        LocationBuilder builder = new LocationBuilder().scope(LocationScope.ZONE).id(zoneId).description(zoneId)
                .parent(provider);
        if (isoCodesById.containsKey(zoneId))
            builder.iso3166Codes(isoCodesById.get(zoneId).get());
        locations.add(builder.build());
    }
    return locations.build();
}

From source file:com.opengamma.financial.analytics.model.forex.option.black.FXOptionBlackRhoFunction.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");
    }// ww w.  j av a 2 s. c o m
    final String callCurrency = security.accept(ForexVisitors.getCallCurrencyVisitor()).getCode();
    final String callCurrencyCurve = desiredValue.getConstraint(FXOptionBlackFunction.CALL_CURVE);
    final String resultCurrency = FXOptionBlackSingleValuedFunction.getResultCurrency(target);
    final String fullCurveName = callCurrencyCurve + "_" + callCurrency;
    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).get());
    final double rho = sensitivitiesForCurrency.get(fullCurveName).get(0).second;
    return Collections.singleton(new ComputedValue(spec, rho));
}