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:io.druid.sql.calcite.rule.CaseFilteredAggregatorRule.java

@Override
public boolean matches(final RelOptRuleCall call) {
    final Aggregate aggregate = call.rel(0);
    final Project project = call.rel(1);

    if (aggregate.indicator || aggregate.getGroupSets().size() != 1) {
        return false;
    }/*from  w ww .  j a  v  a2s  .  c o  m*/

    for (AggregateCall aggregateCall : aggregate.getAggCallList()) {
        if (isNonDistinctOneArgAggregateCall(aggregateCall) && isThreeArgCase(
                project.getChildExps().get(Iterables.getOnlyElement(aggregateCall.getArgList())))) {
            return true;
        }
    }

    return false;
}

From source file:com.opengamma.financial.analytics.model.credit.isda.cdx.ISDACDXAsSingleNameParallelCS01Function.java

@Override
protected Set<ComputedValue> getComputedValue(final CreditDefaultSwapDefinition definition,
        final ISDACompliantYieldCurve yieldCurve, final ZonedDateTime[] times, final double[] marketSpreads,
        final ZonedDateTime valuationDate, final ComputationTarget target, final ValueProperties properties,
        final FunctionInputs inputs, ISDACompliantCreditCurve hazardCurve, CDSAnalytic analytic) {

    //TODO: bump type
    Double bump = Double.valueOf(Iterables.getOnlyElement(
            properties.getValues(CreditInstrumentPropertyNamesAndValues.PROPERTY_SPREAD_CURVE_BUMP)));
    double cs01 = StandardVanillaParallelCS01CDSFunction.parallelCS01(definition, yieldCurve, times,
            marketSpreads, analytic, bump * 1e-4);
    //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 PriceType priceType = PriceType.valueOf(Iterables.getOnlyElement(properties.getValues(CreditInstrumentPropertyNamesAndValues.PROPERTY_CDS_PRICE_TYPE)));
    //final double cs01 = CALCULATOR.getCS01ParallelShiftCreditDefaultSwap(valuationDate, definition, yieldCurve, times, marketSpreads, spreadCurveBump,
    //    spreadBumpType, priceType);
    final ValueSpecification spec = new ValueSpecification(ValueRequirementNames.CS01, target.toSpecification(),
            properties);//from   w w  w  . j av  a  2  s  . c  o m
    return Collections.singleton(new ComputedValue(spec, cs01));
}

From source file:com.google.devtools.build.lib.rules.objc.LipoSupport.java

/**
 * Registers an action to invoke "lipo" on all artifacts in {@code inputBinaries} to create the
 * {@code outputBinary} multi-architecture artifact, built for platform {@code platform}.
 *
 * <p>If there is only one input binary given, since "lipo" is an expensive action, this will only
 * symlink the output location to the input binary.
 *
 * @return this object/*from   ww  w .  j a  v  a 2s.c  o  m*/
 */
public LipoSupport registerCombineArchitecturesAction(NestedSet<Artifact> inputBinaries, Artifact outputBinary,
        Platform platform) {
    if (inputBinaries.toList().size() > 1) {
        ruleContext.registerAction(ObjcRuleClasses
                .spawnAppleEnvActionBuilder(ruleContext.getFragment(AppleConfiguration.class), platform)
                .setMnemonic("ObjcCombiningArchitectures").addTransitiveInputs(inputBinaries)
                .addOutput(outputBinary).setExecutable(CompilationSupport.xcrunwrapper(ruleContext))
                .setCommandLine(CustomCommandLine.builder().add(ObjcRuleClasses.LIPO)
                        .addExecPaths("-create", inputBinaries).addExecPath("-o", outputBinary).build())
                .build(ruleContext));
    } else {
        ruleContext.registerAction(
                new SymlinkAction(ruleContext.getActionOwner(), Iterables.getOnlyElement(inputBinaries),
                        outputBinary, "Symlinking single-architecture binary"));
    }
    return this;
}

From source file:org.jclouds.rimuhosting.miro.compute.suppliers.RimuHostingLocationSupplier.java

@Override
public Set<? extends Location> get() {
    Builder<Location> locations = ImmutableSet.builder();
    Iterable<DataCenter> list = Iterables
            .filter(Iterables.transform(sync.getPricingPlanList(), new Function<PricingPlan, DataCenter>() {

                @Override//from  w w w. ja v a 2s . co m
                public DataCenter apply(PricingPlan arg0) {
                    return arg0.getDataCenter();
                }

            }), Predicates.<DataCenter>notNull());
    Location provider = Iterables.getOnlyElement(super.get());
    if (Iterables.size(list) == 0)
        locations.add(provider);
    else
        for (DataCenter from : list) {
            LocationBuilder builder = new LocationBuilder().scope(LocationScope.ZONE).id(from.getId())
                    .description(from.getName()).parent(provider);
            if (isoCodesById.containsKey(from.getId()))
                builder.iso3166Codes(isoCodesById.get(from.getId()));
            locations.add(builder.build());
        }
    return locations.build();
}

From source file:com.spotify.helios.cli.command.WildcardJobCommand.java

@Override
int run(final Namespace options, final HeliosClient client, final PrintStream out, final boolean json,
        final BufferedReader stdin) throws ExecutionException, InterruptedException, IOException {

    final String jobIdString = options.getString(jobArg.getDest());
    final Map<JobId, Job> jobs = client.jobs(jobIdString).get();

    if (jobs.size() == 0) {
        if (!json) {
            out.printf("Unknown job: %s%n", jobIdString);
        } else {//from   w ww. ja v  a  2s .c o m
            final JobDeployResponse jobDeployResponse = new JobDeployResponse(
                    JobDeployResponse.Status.JOB_NOT_FOUND, null, null);
            out.print(jobDeployResponse.toJsonString());
        }
        return 1;
    } else if (jobs.size() > 1) {
        if (!json) {
            out.printf("Ambiguous job reference: %s%n", jobIdString);
        } else {
            final JobDeployResponse jobDeployResponse = new JobDeployResponse(
                    JobDeployResponse.Status.AMBIGUOUS_JOB_REFERENCE, null, null);
            out.print(jobDeployResponse.toJsonString());
        }
        return 1;
    }

    final JobId jobId = Iterables.getOnlyElement(jobs.keySet());

    return runWithJobId(options, client, out, json, jobId, stdin);
}

From source file:org.apache.druid.sql.calcite.rule.CaseFilteredAggregatorRule.java

@Override
public boolean matches(final RelOptRuleCall call) {
    final Aggregate aggregate = call.rel(0);
    final Project project = call.rel(1);

    if (aggregate.indicator || aggregate.getGroupSets().size() != 1) {
        return false;
    }/*ww  w.jav a2 s . c  o m*/

    for (AggregateCall aggregateCall : aggregate.getAggCallList()) {
        if (isOneArgAggregateCall(aggregateCall) && isThreeArgCase(
                project.getChildExps().get(Iterables.getOnlyElement(aggregateCall.getArgList())))) {
            return true;
        }
    }

    return false;
}

From source file:org.apache.shindig.social.opensocial.service.ActivityHandler.java

/**
 * Allowed end-points /activities/{userId}/@self/{actvityId}+
 *
 * examples: /activities/john.doe/@self/1
 *///from  w  w w. j  a  v  a2 s . c o m
@Operation(httpMethods = "DELETE")
public Future<?> delete(SocialRequestItem request) throws ProtocolException {

    Set<UserId> userIds = request.getUsers();
    Set<String> activityIds = ImmutableSet.copyOf(request.getListParameter("activityId"));

    HandlerPreconditions.requireNotEmpty(userIds, "No userId specified");
    HandlerPreconditions.requireSingular(userIds, "Multiple userIds not supported");
    // Throws exceptions if userIds contains more than one element or zero elements
    return service.deleteActivities(Iterables.getOnlyElement(userIds), request.getGroup(), request.getAppId(),
            activityIds, request.getToken());
}

From source file:org.apache.aries.blueprint.plugin.OsgiServiceProviderWriter.java

public void write(Bean bean) throws XMLStreamException {
    OsgiServiceProvider serviceProvider = bean.clazz.getAnnotation(OsgiServiceProvider.class);
    if (serviceProvider == null) {
        return;//from   w ww . ja  v a2s . c  o m
    }

    Properties properties = bean.clazz.getAnnotation(Properties.class);
    List<String> interfaceNames = Lists.newArrayList();
    for (Class<?> serviceIf : serviceProvider.classes()) {
        interfaceNames.add(serviceIf.getName());
    }

    // If there are no properties to write and only one service attribute (either
    // interface="MyServiceInterface" or auto-export="interfaces") then create an
    // empty element
    boolean writeEmptyElement = properties == null && interfaceNames.size() < 2;
    if (writeEmptyElement) {
        writer.writeEmptyElement("service");
    } else {
        writer.writeStartElement("service");
    }
    writer.writeAttribute("ref", bean.id);

    if (interfaceNames.size() == 0) {
        writer.writeAttribute("auto-export", "interfaces");
    } else if (interfaceNames.size() == 1) {
        writer.writeAttribute("interface", Iterables.getOnlyElement(interfaceNames));
    } else {
        writeInterfacesElement(interfaceNames);
    }

    writer.writeCharacters("\n");
    if (properties != null) {
        writeProperties(properties);
    }

    if (!writeEmptyElement) {
        writer.writeEndElement();
        writer.writeCharacters("\n");
    }
}

From source file:org.trancecode.xproc.PipelineResult.java

public void readNode(final String portName, final Result result) {
    Preconditions.checkNotNull(result);/*from   w  ww.  ja  va2s  .c  o  m*/
    final XdmNode node = Iterables.getOnlyElement(readNodes(portName));
    try {
        TransformerFactoryImpl.newInstance().newTransformer().transform(node.asSource(), result);
    } catch (final TransformerException e) {
        throw new XmlException(e, "cannot push node from port '%' to result", portName);
    }
}

From source file:org.apache.beam.runners.direct.ViewEvaluatorFactory.java

private <InT, OuT> TransformEvaluator<Iterable<InT>> createEvaluator(
        final AppliedPTransform<PCollection<Iterable<InT>>, PCollectionView<OuT>, WriteView<InT, OuT>> application) {
    PCollection<Iterable<InT>> input = (PCollection<Iterable<InT>>) Iterables
            .getOnlyElement(application.getInputs().values());
    final PCollectionViewWriter<InT, OuT> writer = context.createPCollectionViewWriter(input,
            (PCollectionView<OuT>) Iterables.getOnlyElement(application.getOutputs().values()));
    return new TransformEvaluator<Iterable<InT>>() {
        private final List<WindowedValue<InT>> elements = new ArrayList<>();

        @Override// w  ww .  j av a2s  .  c o m
        public void processElement(WindowedValue<Iterable<InT>> element) {
            for (InT input : element.getValue()) {
                elements.add(element.withValue(input));
            }
        }

        @Override
        public TransformResult<Iterable<InT>> finishBundle() {
            writer.add(elements);
            Builder resultBuilder = StepTransformResult.withoutHold(application);
            if (!elements.isEmpty()) {
                resultBuilder = resultBuilder.withAdditionalOutput(OutputType.PCOLLECTION_VIEW);
            }
            return resultBuilder.build();
        }
    };
}