List of usage examples for com.google.common.collect Iterables getOnlyElement
public static <T> T getOnlyElement(Iterable<T> iterable)
From source file:com.eucalyptus.compute.vpc.persist.PersistenceSubnets.java
@Override public <T> T lookupDefault(final OwnerFullName ownerFullName, final String availabilityZone, final Function<? super Subnet, T> transform) throws VpcMetadataException { try {//from ww w .j av a2s. c o m return Iterables.getOnlyElement(listByExample(Subnet.exampleDefault(ownerFullName, availabilityZone), Predicates.alwaysTrue(), transform)); } catch (NoSuchElementException e) { throw new VpcMetadataNotFoundException( qualifyOwner("Default subnet not found for zone: " + availabilityZone, ownerFullName)); } }
From source file:io.druid.indexing.common.task.RestoreTask.java
@Override public TaskStatus run(TaskToolbox toolbox) throws Exception { // Confirm we have a lock (will throw if there isn't exactly one element) final TaskLock myLock = Iterables.getOnlyElement(getTaskLocks(toolbox)); if (!myLock.getDataSource().equals(getDataSource())) { throw new ISE("WTF?! Lock dataSource[%s] != task dataSource[%s]", myLock.getDataSource(), getDataSource());//from w w w . j a v a 2 s . c o m } if (!myLock.getInterval().equals(getInterval())) { throw new ISE("WTF?! Lock interval[%s] != task interval[%s]", myLock.getInterval(), getInterval()); } // List unused segments final List<DataSegment> unusedSegments = toolbox.getTaskActionClient() .submit(new SegmentListUnusedAction(myLock.getDataSource(), myLock.getInterval())); // Verify none of these segments have versions > lock version for (final DataSegment unusedSegment : unusedSegments) { if (unusedSegment.getVersion().compareTo(myLock.getVersion()) > 0) { throw new ISE("WTF?! Unused segment[%s] has version[%s] > task version[%s]", unusedSegment.getIdentifier(), unusedSegment.getVersion(), myLock.getVersion()); } log.info("OK to restore segment: %s", unusedSegment.getIdentifier()); } List<DataSegment> restoredSegments = Lists.newLinkedList(); // Move segments for (DataSegment segment : unusedSegments) { restoredSegments.add(toolbox.getDataSegmentArchiver().restore(segment)); } // Update metadata for moved segments toolbox.getTaskActionClient() .submit(new SegmentMetadataUpdateAction(ImmutableSet.copyOf(restoredSegments))); return TaskStatus.success(getId()); }
From source file:com.opengamma.financial.analytics.model.credit.isda.cdsoption.ISDACreditDefaultSwapOptionBucketedGammaCS01Function.java
@Override protected Set<ComputedValue> getComputedValue(final CreditDefaultSwapOptionDefinition definition, final ISDADateCurve yieldCurve, final double vol, final ZonedDateTime[] calibrationTenors, final double[] marketSpreads, final HazardRateCurve hazardRateCurve, final ZonedDateTime valuationTime, final ComputationTarget target, final ValueProperties properties) { final Double spreadCurveBump = Double.valueOf(Iterables.getOnlyElement( properties.getValues(CreditInstrumentPropertyNamesAndValues.PROPERTY_SPREAD_CURVE_BUMP))); final SpreadBumpType spreadBumpType = SpreadBumpType.valueOf(Iterables.getOnlyElement( properties.getValues(CreditInstrumentPropertyNamesAndValues.PROPERTY_SPREAD_BUMP_TYPE))); final double[] gammaCS01 = CALCULATOR.getGammaBucketedCreditDefaultSwapOption(valuationTime, definition, vol, yieldCurve, hazardRateCurve, calibrationTenors, marketSpreads, spreadCurveBump, spreadBumpType);/*from w w w.j a va 2s .co m*/ final int n = calibrationTenors.length; final LocalDate[] dates = new LocalDate[n]; for (int i = 0; i < n; i++) { dates[i] = calibrationTenors[i].toLocalDate(); } final LocalDateLabelledMatrix1D cs01Matrix = new LocalDateLabelledMatrix1D(dates, gammaCS01); final ValueSpecification spec = new ValueSpecification(ValueRequirementNames.BUCKETED_GAMMA_CS01, target.toSpecification(), properties); return Collections.singleton(new ComputedValue(spec, cs01Matrix)); }
From source file:io.druid.indexing.common.task.KillTask.java
@Override public TaskStatus run(TaskToolbox toolbox) throws Exception { // Confirm we have a lock (will throw if there isn't exactly one element) final TaskLock myLock = Iterables.getOnlyElement(getTaskLocks(toolbox)); if (!myLock.getDataSource().equals(getDataSource())) { throw new ISE("WTF?! Lock dataSource[%s] != task dataSource[%s]", myLock.getDataSource(), getDataSource());/* ww w.j a va 2s . co m*/ } if (!myLock.getInterval().equals(getInterval())) { throw new ISE("WTF?! Lock interval[%s] != task interval[%s]", myLock.getInterval(), getInterval()); } // List unused segments final List<DataSegment> unusedSegments = toolbox.getTaskActionClient() .submit(new SegmentListUnusedAction(myLock.getDataSource(), myLock.getInterval())); // Verify none of these segments have versions > lock version for (final DataSegment unusedSegment : unusedSegments) { if (unusedSegment.getVersion().compareTo(myLock.getVersion()) > 0) { throw new ISE("WTF?! Unused segment[%s] has version[%s] > task version[%s]", unusedSegment.getIdentifier(), unusedSegment.getVersion(), myLock.getVersion()); } log.info("OK to kill segment: %s", unusedSegment.getIdentifier()); } // Kill segments for (DataSegment segment : unusedSegments) { toolbox.getDataSegmentKiller().kill(segment); toolbox.getTaskActionClient().submit(new SegmentNukeAction(ImmutableSet.of(segment))); } return TaskStatus.success(getId()); }
From source file:org.apache.beam.runners.direct.ParDoSingleViaMultiOverrideFactory.java
@Override public PCollection<? extends InputT> getInput(List<TaggedPValue> inputs, Pipeline p) { return (PCollection<? extends InputT>) Iterables.getOnlyElement(inputs).getValue(); }
From source file:com.opengamma.financial.analytics.model.forex.option.FXOptionSpotRateFunction.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 dataType = desiredValue.getConstraint(PROPERTY_DATA_TYPE); final FinancialSecurity security = (FinancialSecurity) target.getSecurity(); final Currency putCurrency = security.accept(ForexVisitors.getPutCurrencyVisitor()); final Currency callCurrency = security.accept(ForexVisitors.getCallCurrencyVisitor()); final UnorderedCurrencyPair currencyPair = UnorderedCurrencyPair.of(putCurrency, callCurrency); if (dataType.equals(LIVE)) { final Object spotObject = inputs.getValue(ValueRequirementNames.SPOT_RATE); if (spotObject == null) { throw new OpenGammaRuntimeException("Could not get live market data for " + currencyPair); }//from w w w.j a va2 s. c om final double spot = (Double) spotObject; return Collections.singleton(new ComputedValue( new ValueSpecification(ValueRequirementNames.SPOT_RATE_FOR_SECURITY, target.toSpecification(), createValueProperties().with(PROPERTY_DATA_TYPE, LIVE).get()), spot)); } else if (dataType.equals(LAST_CLOSE)) { final Object spotObject = inputs.getValue(ValueRequirementNames.HISTORICAL_TIME_SERIES_LATEST); if (spotObject == null) { throw new OpenGammaRuntimeException("Could not get last close market data for " + currencyPair); } final double spot = (Double) spotObject; return Collections.singleton(new ComputedValue( new ValueSpecification(ValueRequirementNames.SPOT_RATE_FOR_SECURITY, target.toSpecification(), createValueProperties().with(PROPERTY_DATA_TYPE, LAST_CLOSE).get()), spot)); } throw new OpenGammaRuntimeException("Did not recognise property type " + dataType); }
From source file:com.opengamma.engine.function.MarketDataAliasingFunction.java
@Override public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target, final Set<ValueRequirement> desiredValues) { final Collection<ComputedValue> values = inputs.getAllValues(); final Object value = values.isEmpty() ? MissingInput.MISSING_MARKET_DATA : Iterables.getOnlyElement(values).getValue(); final Set<ComputedValue> result = Sets.newHashSetWithExpectedSize(desiredValues.size()); for (ValueRequirement desiredValueReq : desiredValues) { final ValueSpecification desiredValue = new ValueSpecification(desiredValueReq.getValueName(), target.toSpecification(), desiredValueReq.getConstraints()); result.add(new ComputedValue(desiredValue, value)); }//from www.j a v a2s .c o m return result; }
From source file:org.apache.beam.runners.flink.translation.functions.FlinkAssignContext.java
@Override public BoundedWindow window() { return Iterables.getOnlyElement(value.getWindows()); }
From source file:com.google.errorprone.bugpatterns.AssertThrowsUtils.java
/** * Transforms a try-catch block in the try-fail pattern into a call to JUnit's {@code * assertThrows}, inserting the behavior of the {@code try} block into a lambda parameter, and * assigning the expected exception to a variable, if it is used within the {@code catch} block. * For example:/* w w w .jav a 2 s . c o m*/ * * <pre> * try { * foo(); * fail(); * } catch (MyException expected) { * assertThat(expected).isEqualTo(other); * } * </pre> * * becomes * * <pre> * {@code MyException expected = assertThrows(MyException.class, () -> foo());} * assertThat(expected).isEqualTo(other); * </pre> * * @param tryTree the tree representing the try-catch block to be refactored. * @param throwingStatements the list of statements in the {@code throw} clause, <b>excluding</b> * the fail statement. * @param state current visitor state (for source positions). * @return an {@link Optional} containing a {@link Fix} that replaces {@code tryTree} with an * equivalent {@code assertThrows}, if possible. Returns an {@code Optional.empty()} if a fix * could not be constructed for the given code (e.g. multi-catch). */ public static Optional<Fix> tryFailToAssertThrows(TryTree tryTree, List<? extends StatementTree> throwingStatements, VisitorState state) { List<? extends CatchTree> catchTrees = tryTree.getCatches(); if (catchTrees.size() != 1) { return Optional.empty(); } CatchTree catchTree = Iterables.getOnlyElement(catchTrees); SuggestedFix.Builder fix = SuggestedFix.builder(); StringBuilder fixPrefix = new StringBuilder(); if (throwingStatements.isEmpty()) { return Optional.empty(); } List<? extends StatementTree> catchStatements = catchTree.getBlock().getStatements(); fix.addStaticImport("org.junit.Assert.assertThrows"); if (!catchStatements.isEmpty()) { // TODO(cushon): pick a fresh name for the variable, if necessary fixPrefix.append(String.format("%s = ", state.getSourceForNode(catchTree.getParameter()))); } fixPrefix.append(String.format("assertThrows(%s.class, () -> ", state.getSourceForNode(catchTree.getParameter().getType()))); boolean useExpressionLambda = throwingStatements.size() == 1 && getOnlyElement(throwingStatements).getKind() == Kind.EXPRESSION_STATEMENT; if (!useExpressionLambda) { fixPrefix.append("{"); } fix.replace(((JCTree) tryTree).getStartPosition(), ((JCTree) throwingStatements.iterator().next()).getStartPosition(), fixPrefix.toString()); if (useExpressionLambda) { fix.postfixWith(((ExpressionStatementTree) throwingStatements.iterator().next()).getExpression(), ")"); } else { fix.postfixWith(getLast(throwingStatements), "});"); } if (catchStatements.isEmpty()) { fix.replace(state.getEndPosition(getLast(throwingStatements)), state.getEndPosition(tryTree), ""); } else { fix.replace(/* startPos= */ state.getEndPosition(getLast(throwingStatements)), /* endPos= */ ((JCTree) catchStatements.get(0)).getStartPosition(), "\n"); fix.replace(state.getEndPosition(getLast(catchStatements)), state.getEndPosition(tryTree), ""); } return Optional.of(fix.build()); }
From source file:com.eucalyptus.objectstorage.policy.SignatureVersionKey.java
@Nullable static AccessKeyCredential getAccessKeyCredential() throws AuthException { try {//w ww. jav a 2 s .co m final Context context = Contexts.lookup(); final Subject subject = context.getSubject(); if (subject != null) { final Set<AccessKeyCredential> credentialSet = subject .getPublicCredentials(AccessKeyCredential.class); if (credentialSet.size() == 1) { return Iterables.getOnlyElement(credentialSet); } } return null; } catch (final Exception e) { Exceptions.findAndRethrow(e, AuthException.class); throw new AuthException("Error getting s3 signature value", e); } }