List of usage examples for com.google.common.collect Iterables getOnlyElement
public static <T> T getOnlyElement(Iterable<T> iterable)
From source file:org.jclouds.vcloud.terremark.suppliers.TerremarkVCloudExpressInternetServiceAndPublicIpAddressSupplier.java
@Override public Entry<InternetService, PublicIpAddress> getNewInternetServiceAndIp(VCloudExpressVApp vApp, int port, Protocol protocol) {/* w w w . j a v a 2 s . com*/ logger.debug(">> creating InternetService in vDC %s:%s:%d", vApp.getVDC().getName(), protocol, port); InternetService is = client.addInternetServiceToVDC(vApp.getVDC().getHref(), vApp.getName() + "-" + port, protocol, port, withDescription(String.format("port %d access to serverId: %s name: %s", port, vApp.getName(), vApp.getName()))); PublicIpAddress ip = is.getPublicIpAddress(); Map<InternetService, PublicIpAddress> result = ImmutableMap.<InternetService, PublicIpAddress>of(is, ip); Entry<InternetService, PublicIpAddress> entry = Iterables.getOnlyElement(result.entrySet()); return entry; }
From source file:com.opengamma.financial.analytics.model.futureoption.EquityFutureOptionFunction.java
@Override public Set<ValueRequirement> getRequirements(final FunctionCompilationContext context, final ComputationTarget target, final ValueRequirement desiredValue) { final ValueProperties constraints = desiredValue.getConstraints(); final Set<String> calculationMethod = constraints.getValues(ValuePropertyNames.CALCULATION_METHOD); if (calculationMethod == null || calculationMethod.isEmpty()) { return null; }//from www . ja va2 s.c o m if (calculationMethod != null && calculationMethod.size() == 1) { if (!getCalculationMethod().equals(Iterables.getOnlyElement(calculationMethod))) { return null; } } final EquityIndexFutureOptionSecurity security = (EquityIndexFutureOptionSecurity) target.getSecurity(); final Set<String> discountingCurveNames = constraints .getValues(EquityOptionFunction.PROPERTY_DISCOUNTING_CURVE_NAME); if (discountingCurveNames == null || discountingCurveNames.size() != 1) { return null; } final Set<String> discountingCurveConfigs = constraints .getValues(EquityOptionFunction.PROPERTY_DISCOUNTING_CURVE_CONFIG); if (discountingCurveConfigs == null || discountingCurveConfigs.size() != 1) { return null; } final String discountingCurveName = Iterables.getOnlyElement(discountingCurveNames); final String discountingCurveConfig = Iterables.getOnlyElement(discountingCurveConfigs); final ValueRequirement discountingReq = getDiscountCurveRequirement(discountingCurveName, discountingCurveConfig, security); final Set<String> surfaceNames = constraints.getValues(ValuePropertyNames.SURFACE); if (surfaceNames == null || surfaceNames.size() != 1) { return null; } final String volSurfaceName = Iterables.getOnlyElement(surfaceNames); final Set<String> surfaceCalculationMethods = constraints .getValues(ValuePropertyNames.SURFACE_CALCULATION_METHOD); if (surfaceCalculationMethods == null || surfaceCalculationMethods.size() != 1) { return null; } final String surfaceCalculationMethod = Iterables.getOnlyElement(surfaceCalculationMethods); final Set<String> forwardCurveNames = constraints .getValues(ForwardCurveValuePropertyNames.PROPERTY_FORWARD_CURVE_NAME); if (forwardCurveNames == null || forwardCurveNames.size() != 1) { return null; } final Set<String> forwardCurveCalculationMethods = constraints .getValues(ForwardCurveValuePropertyNames.PROPERTY_FORWARD_CURVE_CALCULATION_METHOD); if (forwardCurveCalculationMethods == null || forwardCurveCalculationMethods.size() != 1) { return null; } final ExternalIdBundle underlyingFutureId = ExternalIdBundle.of(security.getUnderlyingId()); final SecuritySource securitySource = OpenGammaCompilationContext.getSecuritySource(context); final ExternalId underlyingIndexId; Security underlyingFuture = securitySource.getSingle(underlyingFutureId); if (underlyingFuture == null) { throw new OpenGammaRuntimeException( "The underlying (" + underlyingFutureId.toString() + ") of EquityIndexFutureOption (" + security.getName() + ") was not found in security source. Please try to reload."); } else if (underlyingFuture instanceof EquityFutureSecurity) { underlyingIndexId = ((EquityFutureSecurity) underlyingFuture).getUnderlyingId(); } else if (underlyingFuture instanceof IndexFutureSecurity) { underlyingIndexId = ((IndexFutureSecurity) underlyingFuture).getUnderlyingId(); } else { throw new OpenGammaRuntimeException( "The Security type of the future underlying the Index Future Option must be added to this function: " + underlyingFuture.getClass()); } final String forwardCurveCalculationMethod = Iterables.getOnlyElement(forwardCurveCalculationMethods); final String forwardCurveName = Iterables.getOnlyElement(forwardCurveNames); final ValueRequirement volReq = getVolatilitySurfaceRequirement(desiredValue, volSurfaceName, forwardCurveName, surfaceCalculationMethod, underlyingIndexId); final ValueRequirement forwardCurveReq = getForwardCurveRequirement(forwardCurveName, forwardCurveCalculationMethod, underlyingIndexId); return Sets.newHashSet(discountingReq, forwardCurveReq, volReq); }
From source file:com.palantir.atlasdb.stream.AbstractPersistentStreamStore.java
private Long lookupStreamIdByHash(Transaction t, Sha256Hash hash) { Map<Sha256Hash, Long> hashToId = lookupStreamIdsByHash(t, Sets.newHashSet(hash)); if (hashToId.isEmpty()) { return null; }// w w w. jav a 2 s .c om return Iterables.getOnlyElement(hashToId.entrySet()).getValue(); }
From source file:com.opengamma.financial.analytics.timeseries.HistoricalTimeSeriesLatestSecurityValueFunction.java
@Override public Set<ValueRequirement> getRequirements(final FunctionCompilationContext context, final ComputationTarget target, final ValueRequirement desiredValue) { final HistoricalTimeSeriesResolver htsResolver = OpenGammaCompilationContext .getHistoricalTimeSeriesResolver(context); final Set<String> dataFieldConstraints = desiredValue.getConstraints() .getValues(HistoricalTimeSeriesFunctionUtils.DATA_FIELD_PROPERTY); if (dataFieldConstraints.size() > 1) { return null; }//from w ww.j a v a2 s . com final String dataField = dataFieldConstraints.isEmpty() ? null : Iterables.getOnlyElement(dataFieldConstraints); HistoricalTimeSeriesResolutionResult resolutionResult = htsResolver .resolve(target.getSecurity().getExternalIdBundle(), null, null, null, dataField, null); if (resolutionResult == null) { return null; } UniqueId htsId = resolutionResult.getHistoricalTimeSeriesInfo().getUniqueId(); ValueRequirement valueRequirement = new ValueRequirement( ValueRequirementNames.HISTORICAL_TIME_SERIES_LATEST, htsId, desiredValue.getConstraints()); return Collections.singleton(valueRequirement); }
From source file:com.opengamma.financial.analytics.model.g2ppdiscounting.G2ppDiscountingParRateFunction.java
@Override public CompiledFunctionDefinition compile(final FunctionCompilationContext context, final Instant atInstant) { return new G2ppCompiledFunction(getTargetToDefinitionConverter(context), getDefinitionToDerivativeConverter(context), false) { @Override//from ww w.j av a 2 s .c om protected Set<ComputedValue> getValues(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target, final Set<ValueRequirement> desiredValues, final InstrumentDerivative derivative, final FXMatrix fxMatrix) { final MulticurveProviderInterface data = (MulticurveProviderInterface) inputs .getValue(CURVE_BUNDLE); final ValueRequirement desiredValue = Iterables.getOnlyElement(desiredValues); final ValueProperties properties = desiredValue.getConstraints().copy().get(); final double parRate = derivative.accept(CALCULATOR, data); final ValueSpecification spec = new ValueSpecification(PAR_RATE, target.toSpecification(), properties); return Collections.singleton(new ComputedValue(spec, parRate)); } }; }
From source file:io.druid.sql.calcite.aggregation.builtin.AvgSqlAggregator.java
@Nullable @Override//from ww w . j av a2 s. com 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 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 = StringUtils.format("%s:sum", name); final String countName = StringUtils.format("%s:count", name); 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.github.strawberry.guice.config.ConfigLoader.java
private static Option getFromProperties(Map properties, final Field field, final Config annotation) { Object value = null;// ww w . j a v a2 s . c o m Class<?> fieldType = field.getType(); String pattern = annotation.value(); boolean allowNull = annotation.allowNull(); Set<String> matchingKeys = getKeys(properties, pattern); if (matchingKeys.size() == 1) { String matchingKey = Iterables.getOnlyElement(matchingKeys); if (fieldType.equals(char[].class)) { value = properties.get(matchingKey).toString().toCharArray(); } else if (fieldType.equals(Character[].class)) { value = ArrayUtils.toObject(properties.get(matchingKey).toString().toCharArray()); } else if (fieldType.equals(char.class) || fieldType.equals(Character.class)) { String toConvert = properties.get(matchingKey).toString(); if (toConvert.length() == 1) { value = properties.get(matchingKey).toString().charAt(0); } else { throw ConversionException.of(toConvert, matchingKey, fieldType); } } else if (fieldType.equals(String.class)) { value = properties.get(matchingKey); } else if (fieldType.equals(byte[].class)) { if (properties.containsKey(matchingKey)) { value = properties.get(matchingKey).toString().getBytes(); } else { value = null; } } else if (fieldType.equals(Byte[].class)) { value = ArrayUtils.toObject(properties.get(matchingKey).toString().getBytes()); } else if (fieldType.equals(boolean.class) || fieldType.equals(Boolean.class)) { String toConvert = properties.get(matchingKey).toString(); if (BOOLEAN.matcher(toConvert).matches()) { value = TRUE.matcher(toConvert).matches(); } else { throw ConversionException.of(toConvert, matchingKey, fieldType); } } else if (Map.class.isAssignableFrom(fieldType)) { value = mapOf(field, properties, matchingKey); } else if (Collection.class.isAssignableFrom(fieldType)) { value = collectionOf(field, properties, matchingKey); } else { String toConvert = properties.get(matchingKey).toString(); try { if (fieldType.equals(byte.class) || fieldType.equals(Byte.class)) { value = Byte.parseByte(properties.get(matchingKey).toString()); } else if (fieldType.equals(short.class) || fieldType.equals(Short.class)) { value = Short.parseShort(toConvert); } else if (fieldType.equals(int.class) || fieldType.equals(Integer.class)) { value = Integer.parseInt(toConvert); } else if (fieldType.equals(long.class) || fieldType.equals(Long.class)) { value = Long.parseLong(toConvert); } else if (fieldType.equals(BigInteger.class)) { value = new BigInteger(toConvert); } else if (fieldType.equals(float.class) || fieldType.equals(Float.class)) { value = Float.parseFloat(toConvert); } else if (fieldType.equals(double.class) || fieldType.equals(Double.class)) { value = Double.parseDouble(toConvert); } else if (fieldType.equals(BigDecimal.class)) { value = new BigDecimal(toConvert); } } catch (NumberFormatException exception) { throw ConversionException.of(exception, toConvert, matchingKey, fieldType); } } } else if (matchingKeys.size() > 1) { if (Map.class.isAssignableFrom(fieldType)) { value = nestedMapOf(field, properties, matchingKeys); } else if (Collection.class.isAssignableFrom(fieldType)) { value = nestedCollectionOf(field, properties, matchingKeys); } } else { if (!allowNull) { value = nonNullValueOf(fieldType); } } return Option.fromNull(value); }
From source file:fr.xebia.workshop.continuousdelivery.CreateNexusInstance.java
@Override public void execute(AmazonEC2 ec2, WorkshopInfrastructure workshopInfrastructure) throws Exception { logger.info("STARTING CREATE NEXUS SERVER"); // TERMINATE EXISTING NEXUS SERVERS IF EXIST AmazonAwsUtils.terminateInstancesByRole(TeamInfrastructure.ROLE_NEXUS, ec2); // CREATE NEXUS INSTANCE String cloudConfigFilePath = "fr/xebia/workshop/continuousdelivery/cloud-config-amzn-linux-nexus.txt"; String userData = CloudInitUserDataBuilder.start().addCloudConfigFromFilePath(cloudConfigFilePath) .buildBase64UserData();// w w w . j a v a 2s .c o m RunInstancesRequest runInstancesRequest = new RunInstancesRequest() // .withInstanceType(InstanceType.T1Micro.toString()) // .withImageId(AmazonAwsUtils.AMI_AMZN_LINUX_EU_WEST) // .withMinCount(1) // .withMaxCount(1) // .withSecurityGroupIds("accept-all") // .withKeyName(KEY_PAIR_NAME) // .withUserData(userData); // START NEXUS INSTANCE List<Instance> nexusInstances = AmazonAwsUtils.reliableEc2RunInstances(runInstancesRequest, ec2); Instance nexusInstance = Iterables.getOnlyElement(nexusInstances); // TAG NEXUS INSTANCES CreateTagsRequest createTagsRequest = new CreateTagsRequest(); createTagsRequest.withResources(nexusInstance.getInstanceId()) // .withTags(// new Tag("Name", "nexus"), // new Tag("Workshop", "continuous-delivery-workshop"), // new Tag("Role", TeamInfrastructure.ROLE_NEXUS)); ec2.createTags(createTagsRequest); // first waits for Nexus availability, otherwise the following elastic IP assignment will break its installation waitForNexusAvailability(nexusInstance); final String publicIp = workshopInfrastructure.getNexusPublicIp(); // ASSOCIATE NEXUS INSTANCE WITH PUBLIC IP Address address = Iterables.getOnlyElement( ec2.describeAddresses(new DescribeAddressesRequest().withPublicIps(publicIp)).getAddresses()); String currentlyAssociatedId = address.getInstanceId(); if (currentlyAssociatedId == null) { logger.debug("Public IP {} is not currently associated with an instance", publicIp); } else { logger.info("Public IP {} is currently associated instance '{}'. Disassociate it first.", publicIp, currentlyAssociatedId); ec2.disassociateAddress(new DisassociateAddressRequest(publicIp)); } ec2.associateAddress(new AssociateAddressRequest(nexusInstance.getInstanceId(), publicIp)); try { AmazonAwsUtils.awaitForHttpAvailability(workshopInfrastructure.getNexusUrlWithIp()); AmazonAwsUtils.awaitForHttpAvailability(workshopInfrastructure.getNexusUrlWithDomainName()); } catch (Exception e) { logger.warn("Silently skipped " + e, e); } logger.info("1 NEXUS SERVER {} SUCCESSFULLY CREATED AND ASSOCIATED WITH {}: {}", new Object[] { nexusInstance.getInstanceId(), publicIp, nexusInstance }); }
From source file:org.jclouds.trmk.vcloud_0_8.compute.suppliers.OrgAndVDCToLocationSupplier.java
protected Builder<Location> buildJustProviderOrVDCs() { Builder<Location> locations = ImmutableSet.builder(); Location provider = Iterables.getOnlyElement(super.get()); if (orgNameToResource.get().size() == 0) return locations.add(provider); else//ww w . ja v a 2 s . co m for (ReferenceType org : orgNameToResource.get().values()) { LocationBuilder builder = new LocationBuilder().scope(LocationScope.REGION) .id(org.getHref().toASCIIString()).description((org.getName())).parent(provider); if (isoCodesById.containsKey(org.getHref().toASCIIString())) builder.iso3166Codes(isoCodesById.get(org.getHref().toASCIIString())); Location orgL = builder.build(); for (ReferenceType vdc : orgNameToVDCResource.get().get(org.getName()).getVDCs().values()) { builder = new LocationBuilder().scope(LocationScope.ZONE).id(vdc.getHref().toASCIIString()) .description((vdc.getName())).parent(orgL); if (isoCodesById.containsKey(vdc.getHref().toASCIIString())) builder.iso3166Codes(isoCodesById.get(vdc.getHref().toASCIIString())); locations.add(builder.build()); } } return locations; }
From source file:io.druid.sql.calcite.aggregation.ApproxCountDistinctSqlAggregator.java
@Override public Aggregation toDruidAggregation(final String name, final RowSignature rowSignature, final List<Aggregation> existingAggregations, final Project project, final AggregateCall aggregateCall, final DimFilter filter) { final RexNode rexNode = Expressions.fromFieldAccess(rowSignature, project, Iterables.getOnlyElement(aggregateCall.getArgList())); final RowExtraction rex = Expressions.toRowExtraction(rowSignature.getRowOrder(), rexNode); if (rex == null) { return null; }/*w w w. j a va 2 s. co m*/ final AggregatorFactory aggregatorFactory; if (rowSignature.getColumnType(rex.getColumn()) == ValueType.COMPLEX) { aggregatorFactory = new HyperUniquesAggregatorFactory(name, rex.getColumn()); } else { final SqlTypeName sqlTypeName = rexNode.getType().getSqlTypeName(); final ValueType outputType = Calcites.getValueTypeForSqlTypeName(sqlTypeName); if (outputType == null) { throw new ISE("Cannot translate sqlTypeName[%s] to Druid type for field[%s]", sqlTypeName, name); } final DimensionSpec dimensionSpec = rex.toDimensionSpec(rowSignature, null, ValueType.STRING); if (dimensionSpec == null) { return null; } aggregatorFactory = new CardinalityAggregatorFactory(name, ImmutableList.of(dimensionSpec), false); } return Aggregation.createFinalizable(ImmutableList.<AggregatorFactory>of(aggregatorFactory), null, new PostAggregatorFactory() { @Override public PostAggregator factorize(String outputName) { return new HyperUniqueFinalizingPostAggregator(outputName, name); } }).filter(filter); }