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.b2international.snowowl.datastore.server.reindex.ReindexRequest.java

@Override
public ReindexResult execute(RepositoryContext context) {
    final InternalRepository repository = (InternalRepository) context.service(Repository.class);
    final FeatureToggles features = context.service(FeatureToggles.class);
    final String reindexToggle = Features.getReindexFeatureToggle(context.id());

    // XXX: We are deliberately side-stepping health checks here
    final Index index = repository.getIndex();
    final Hits<Integer> maxCdoBranchIdHits = index.read(searcher -> {
        return searcher.search(Query.select(Integer.class).from(BranchDocument.class).fields(CDO_BRANCH_ID)
                .where(Expressions.matchAll()).sortBy(SortBy.field(CDO_BRANCH_ID, Order.DESC)).limit(1)
                .build());/*from w w w. jav  a  2 s.c  om*/
    });

    final int maxCdoBranchId = maxCdoBranchIdHits.isEmpty() ? -1 : Iterables.getOnlyElement(maxCdoBranchIdHits);
    final org.eclipse.emf.cdo.internal.server.Repository cdoRepository = (org.eclipse.emf.cdo.internal.server.Repository) repository
            .getCdoRepository().getRepository();
    final InternalSession session = cdoRepository.getSessionManager().openSession(null);

    try {
        repository.setHealth(Health.YELLOW, "Reindex is in progress...");
        features.enable(reindexToggle);
        //set the session on the StoreThreadlocal for later access
        StoreThreadLocal.setSession(session);
        //for partial replication get the last branch id and commit time from the index
        //right now index is fully recreated
        final IndexMigrationReplicationContext replicationContext = new IndexMigrationReplicationContext(
                context, maxCdoBranchId, failedCommitTimestamp - 1, session);
        cdoRepository.replicate(replicationContext);
        // update repository state after the re-indexing
        return new ReindexResult(replicationContext.getFailedCommitTimestamp(),
                replicationContext.getProcessedCommits(), replicationContext.getSkippedCommits(),
                replicationContext.getException());
    } finally {
        features.disable(reindexToggle);
        StoreThreadLocal.release();
        session.close();
        repository.checkHealth();
    }
}

From source file:org.apache.beam.runners.core.ProcessFnRunner.java

private static <T> void checkTrivialOuterWindows(WindowedValue<KeyedWorkItem<String, T>> windowedKWI) {
    // In practice it will be in 0 or 1 windows (ValueInEmptyWindows or ValueInGlobalWindow)
    Collection<? extends BoundedWindow> outerWindows = windowedKWI.getWindows();
    if (!outerWindows.isEmpty()) {
        checkArgument(outerWindows.size() == 1,
                "The KeyedWorkItem itself must not be in multiple windows, but was in: %s", outerWindows);
        BoundedWindow onlyWindow = Iterables.getOnlyElement(outerWindows);
        checkArgument(onlyWindow instanceof GlobalWindow,
                "KeyedWorkItem must be in the Global window, but was in: %s", onlyWindow);
    }//from w  w w . j  a  v  a  2  s  .  c  o  m
}

From source file:com.kurtraschke.septa.gtfsrealtime.services.TransitViewService.java

public Collection<Bus> getBuses() throws URISyntaxException, ClientProtocolException, IOException {
    URIBuilder b = new URIBuilder("http://www3.septa.org/hackathon/TransitViewAll/");

    CloseableHttpClient client = HttpClients.custom().setConnectionManager(_connectionManager).build();

    HttpGet httpget = new HttpGet(b.build());
    try (CloseableHttpResponse response = client.execute(httpget);
            InputStream responseInputStream = response.getEntity().getContent();
            Reader responseEntityReader = new InputStreamReader(responseInputStream)) {
        JsonParser parser = new JsonParser();

        JsonObject root = (JsonObject) parser.parse(responseEntityReader);

        JsonArray routes = (JsonArray) Iterables.getOnlyElement(root.entrySet()).getValue();

        List<Bus> allBuses = new ArrayList<>();

        for (JsonElement routeElement : routes) {
            JsonArray buses = ((JsonArray) (Iterables.getOnlyElement(((JsonObject) routeElement).entrySet())
                    .getValue()));/* w  w  w. jav a 2  s  .  co  m*/

            for (JsonElement busElement : buses) {
                JsonObject busObject = (JsonObject) busElement;

                try {
                    allBuses.add(new Bus(busObject.get("lat").getAsDouble(), busObject.get("lng").getAsDouble(),
                            busObject.get("label").getAsString(), busObject.get("VehicleID").getAsString(),
                            busObject.get("BlockID").getAsString(), busObject.get("Direction").getAsString(),
                            (!(busObject.get("destination") instanceof JsonNull))
                                    ? busObject.get("destination").getAsString()
                                    : null,
                            busObject.get("Offset").getAsInt()));
                } catch (Exception e) {
                    _log.warn("Exception processing bus JSON", e);
                    _log.warn(busObject.toString());
                }
            }
        }
        return allBuses;
    }
}

From source file:org.apache.druid.sql.calcite.aggregation.builtin.SumSqlAggregator.java

@Nullable
@Override/*from  w w  w  .j  a va  2s.c  o m*/
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 valueType = Calcites.getValueTypeForSqlTypeName(aggregateCall.getType().getSqlTypeName());
    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();
    }

    return Aggregation.create(createSumAggregatorFactory(valueType, name, fieldName, expression, macroTable));
}

From source file:org.apache.druid.sql.calcite.aggregation.builtin.MaxSqlAggregator.java

@Nullable
@Override/*  ww  w  .  j  a  v  a  2  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 valueType = Calcites.getValueTypeForSqlTypeName(aggregateCall.getType().getSqlTypeName());
    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();
    }

    return Aggregation.create(createMaxAggregatorFactory(valueType, name, fieldName, expression, macroTable));
}

From source file:org.apache.druid.sql.calcite.aggregation.builtin.MinSqlAggregator.java

@Nullable
@Override/*from   w w w  . j ava  2  s  .co m*/
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 valueType = Calcites.getValueTypeForSqlTypeName(aggregateCall.getType().getSqlTypeName());
    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();
    }

    return Aggregation.create(createMinAggregatorFactory(valueType, name, fieldName, expression, macroTable));
}

From source file:org.apache.beam.runners.spark.translation.SparkAbstractCombineFn.java

protected static <T> Iterable<WindowedValue<T>> sortByWindows(Iterable<WindowedValue<T>> iter) {
    List<WindowedValue<T>> sorted = Lists.newArrayList(iter);
    Collections.sort(sorted, new Comparator<WindowedValue<T>>() {
        @Override/*from w w  w .ja  v  a  2  s .co  m*/
        public int compare(WindowedValue<T> o1, WindowedValue<T> o2) {
            return Iterables.getOnlyElement(o1.getWindows()).maxTimestamp()
                    .compareTo(Iterables.getOnlyElement(o2.getWindows()).maxTimestamp());
        }
    });
    return sorted;
}

From source file:com.opengamma.financial.analytics.model.discounting.DiscountingMarketQuoteFunction.java

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

        @Override//www. jav  a2s  . 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 MulticurveProviderInterface data = getMergedProviders(inputs, fxMatrix);
            final ValueRequirement desiredValue = Iterables.getOnlyElement(desiredValues);
            final double marketQuote = derivative.accept(CALCULATOR, data);
            final ValueProperties properties = desiredValue.getConstraints().copy().get();
            final ValueSpecification spec = new ValueSpecification(MARKET_QUOTE, target.toSpecification(),
                    properties);
            return Collections.singleton(new ComputedValue(spec, marketQuote));
        }

        @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.black.BlackDiscountingGammaIRFutureOptionFunction.java

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

        @Override/*from  www  .  j  a  v a  2  s.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 gamma = derivative.accept(CALCULATOR, blackData);
            final ValueRequirement desiredValue = Iterables.getOnlyElement(desiredValues);
            final ValueProperties properties = desiredValue.getConstraints().copy().get();
            final ValueSpecification spec = new ValueSpecification(GAMMA, target.toSpecification(), properties);
            return Collections.singleton(new ComputedValue(spec, gamma));
        }

    };
}

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

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

        @Override/*from w  ww  . j  a va2  s  .  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 delta = derivative.accept(CALCULATOR, blackData);
            final ValueRequirement desiredValue = Iterables.getOnlyElement(desiredValues);
            final ValueProperties properties = desiredValue.getConstraints().copy().get();
            final ValueSpecification spec = new ValueSpecification(DELTA, target.toSpecification(), properties);
            return Collections.singleton(new ComputedValue(spec, delta));
        }

    };
}