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:com.opengamma.financial.analytics.model.hullwhitediscounting.HullWhiteConvexityAdjustmentFunction.java

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

        @Override/*from  ww  w  .  ja  v a  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 HullWhiteOneFactorProviderInterface data = getMergedProviders(inputs, fxMatrix);
            final ValueRequirement desiredValue = Iterables.getOnlyElement(desiredValues);
            final double convexityAdjustment = derivative.accept(CALCULATOR, data);
            final ValueProperties properties = desiredValue.getConstraints().copy().get();
            final ValueSpecification spec = new ValueSpecification(CONVEXITY_ADJUSTMENT,
                    target.toSpecification(), properties);
            return Collections.singleton(new ComputedValue(spec, convexityAdjustment));
        }

        @Override
        public boolean canApplyTo(final FunctionCompilationContext compilationContext,
                final ComputationTarget target) {
            final Security security = target.getTrade().getSecurity();
            return security instanceof DeliverableSwapFutureSecurity
                    || security instanceof InterestRateFutureSecurity;
        }

    };
}

From source file:com.opengamma.financial.analytics.model.fx.FXForwardPointsFCNSFunction.java

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

        @Override/*from  ww  w  .  jav a  2 s . c om*/
        protected Set<ComputedValue> getValues(final FunctionInputs inputs, final ComputationTarget target,
                final Set<ValueRequirement> desiredValues, final Forex forex, final FXMatrix fxMatrix,
                final ZonedDateTime now) {
            final MulticurveProviderInterface data = getMergedProviders(inputs, fxMatrix);
            final ValueRequirement desiredValue = Iterables.getOnlyElement(desiredValues);
            final String fxForwardCurveName = desiredValue.getConstraint(FORWARD_CURVE_NAME);
            final DoublesCurve forwardPoints = getForwardPoints(inputs, fxForwardCurveName, now);
            final CurrencyPairs pairs = (CurrencyPairs) inputs.getValue(CURRENCY_PAIRS);
            final Pair<Currency, Currency> ccyPair;
            final Currency currency1 = forex.getCurrency1();
            final Currency currency2 = forex.getCurrency2();
            if (currency1.equals(pairs.getCurrencyPair(currency1, currency2).getBase())) {
                ccyPair = Pair.of(currency1, currency2);
            } else {
                ccyPair = Pair.of(currency2, currency1);
            }
            final double[] sensitivities = CALCULATOR.presentValueForwardPointsSensitivity(forex, data,
                    forwardPoints, ccyPair);
            final CurveDefinition definition = (CurveDefinition) inputs
                    .getValue(new ValueRequirement(CURVE_DEFINITION, ComputationTargetSpecification.NULL,
                            ValueProperties.with(CURVE, fxForwardCurveName).get()));
            final DoubleLabelledMatrix1D matrix = MultiCurveUtils
                    .getLabelledMatrix(new DoubleMatrix1D(sensitivities), definition);
            final ValueProperties properties = desiredValue.getConstraints().copy().get();
            final ValueSpecification spec = new ValueSpecification(FX_FORWARD_POINTS_NODE_SENSITIVITIES,
                    target.toSpecification(), properties);
            return Collections.singleton(new ComputedValue(spec, matrix));
        }
    };
}

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

@Override
public PlanNode replaceChildren(List<PlanNode> newChildren) {
    return new TopNNode(getId(), Iterables.getOnlyElement(newChildren), count, orderingScheme, step);
}

From source file:edu.buaa.satla.analysis.core.programcounter.ProgramCounterCPA.java

@Override
public AbstractState getInitialState(CFANode pNode) {
    // Try to get all possible program counter values
    SingleLoopHead singleLoopHead = null;
    if (pNode instanceof SingleLoopHead) {
        singleLoopHead = (SingleLoopHead) pNode;
    } else if (cfa.getLoopStructure().isPresent()) {
        LoopStructure loopStructure = cfa.getLoopStructure().get();
        if (loopStructure.getCount() == 1) {
            Loop singleLoop = Iterables.getOnlyElement(loopStructure.getAllLoops());
            if (singleLoop.getLoopHeads().size() == 1) {
                CFANode loopHead = Iterables.getOnlyElement(singleLoop.getLoopHeads());
                if (loopHead instanceof SingleLoopHead) {
                    singleLoopHead = (SingleLoopHead) loopHead;
                }//from w w w  .  ja va  2 s  . c o m
            }
        }
    }

    if (singleLoopHead != null) {
        FluentIterable<BigInteger> potentialValues = FluentIterable
                .from(singleLoopHead.getProgramCounterValues()).transform(new Function<Integer, BigInteger>() {

                    @Override
                    public BigInteger apply(Integer pArg0) {
                        return BigInteger.valueOf(pArg0);
                    }

                });

        if (!potentialValues.isEmpty()) {
            return ProgramCounterState.getStateForValues(potentialValues);
        }
    }

    // If the possible program counter values cannot be determined, return TOP
    return ProgramCounterState.getTopState();
}

From source file:grakn.core.graql.reasoner.query.ReasonerAtomicQuery.java

ReasonerAtomicQuery(Conjunction<Statement> pattern, TransactionOLTP tx) {
    super(pattern, tx);
    this.atom = Iterables.getOnlyElement(selectAtoms()::iterator);
}

From source file:org.jclouds.filesystem.integration.FilesystemContainerIntegrationTestDisabled.java

@Test(groups = { "integration", "live" })
public void testNotWithDetails() throws InterruptedException {

    String key = "hello";

    // NOTE all metadata in jclouds comes out as lowercase, in an effort to normalize the
    // providers.
    Blob object = view.getBlobStore().blobBuilder(key).userMetadata(ImmutableMap.of("Adrian", "powderpuff"))
            .payload(TEST_STRING).contentType(MediaType.TEXT_PLAIN).build();
    String containerName = getContainerName();
    try {/* w ww.  j av  a  2  s.  c  om*/
        addBlobToContainer(containerName, object);
        validateContent(containerName, key);

        PageSet<? extends StorageMetadata> container = view.getBlobStore().list(containerName, maxResults(1));

        BlobMetadata metadata = (BlobMetadata) Iterables.getOnlyElement(container);
        // transient container should be lenient and not return metadata on undetailed listing.

        assertEquals(metadata.getUserMetadata().size(), 0);

    } finally {
        returnContainer(containerName);
    }
}

From source file:com.b2international.index.lucene.QueryBuilderBase.java

private Query build(final Occur occur, Iterable<Query> queries) {
    final int size = Iterables.size(queries);
    checkArgument(size > 0, "At least one clause must be specified to build a query");
    if (size == 1) {
        return Iterables.getOnlyElement(queries);
    } else {/*w  w  w  .j  av a2 s .c  o  m*/
        final BooleanQuery.Builder query = new BooleanQuery.Builder();
        for (Query q : queries) {
            query.add(q, occur);
        }
        return query.build();
    }
}

From source file:org.sosy_lab.cpachecker.cpa.value.refiner.ValueAnalysisStrongestPostOperator.java

@Override
public Optional<ValueAnalysisState> getStrongestPost(final ValueAnalysisState pOrigin,
        final Precision pPrecision, final CFAEdge pOperation) throws CPAException {

    final Collection<ValueAnalysisState> successors = transfer.getAbstractSuccessorsForEdge(pOrigin, pPrecision,
            pOperation);/*from w  w  w.j a  va 2 s  . c  o m*/

    if (successors.isEmpty()) {
        return Optional.absent();

    } else {
        return Optional.of(Iterables.getOnlyElement(successors));
    }
}

From source file:com.facebook.presto.sql.planner.plan.StatisticsWriterNode.java

@Override
public PlanNode replaceChildren(List<PlanNode> newChildren) {
    return new StatisticsWriterNode(getId(), Iterables.getOnlyElement(newChildren), target, rowCountSymbol,
            rowCountEnabled, descriptor);
}

From source file:reconcile.drivers.CorefAnnotator.java

public void annotate(Document doc, String outputAnnotationSetName) throws IOException {
    Clusterer.printClusteringAsAnnotationSet(doc, doc.readClusterFile(), outputAnnotationSetName);

    // remove singletons
    AnnotationSet coref = doc.getAnnotationSet(outputAnnotationSetName);
    Map<String, Set<String>> map = new HashMap<String, Set<String>>();
    Map<String, Annotation> aMap = new HashMap<String, Annotation>();
    for (Annotation a : coref) {
        String key = a.getAttribute(Constants.CLUSTER_ID);
        String val = a.getAttribute(Constants.CE_ID);
        MapUtil.addToMapSet(map, key, val);
        aMap.put(key, a);//from  w ww  .j  a  va2s.  c om
    }
    for (String key : map.keySet()) {
        Set<String> vals = map.get(key);
        if (vals.size() == 1) {
            String val = Iterables.getOnlyElement(vals);
            Annotation a = aMap.get(val);
            boolean success = coref.remove(a);
            if (!success) {
                System.out.println("failed to remove: " + a);
            }
        }
    }
    doc.writeAnnotationSet(coref);
}