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.google.errorprone.refaster.CodeTransformerTestHelper.java

public JavaFileObject transform(JavaFileObject original) {
    JavaCompiler compiler = JavacTool.create();
    DiagnosticCollector<JavaFileObject> diagnosticsCollector = new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnosticsCollector, Locale.ENGLISH,
            UTF_8);//from   w  w w.j  ava  2  s. c o m
    JavacTaskImpl task = (JavacTaskImpl) compiler.getTask(CharStreams.nullWriter(), fileManager,
            diagnosticsCollector, ImmutableList.<String>of(), null, ImmutableList.of(original));

    try {
        SourceFile sourceFile = SourceFile.create(original);
        Iterable<? extends CompilationUnitTree> trees = task.parse();
        task.analyze();
        JCCompilationUnit tree = Iterables.getOnlyElement(Iterables.filter(trees, JCCompilationUnit.class));
        DescriptionBasedDiff diff = DescriptionBasedDiff.create(tree);
        transformer().apply(new TreePath(tree), task.getContext(), diff);
        diff.applyDifferences(sourceFile);

        return JavaFileObjects.forSourceString(
                Iterables.getOnlyElement(Iterables.filter(tree.getTypeDecls(), JCClassDecl.class)).sym
                        .getQualifiedName().toString(),
                sourceFile.getSourceText());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.jclouds.vcloud.terremark.TerremarkECloudClientLiveTestDisabled.java

@Override
protected Entry<InternetService, PublicIpAddress> getNewInternetServiceAndIpForSSH(URI vdc) {
    PublicIpAddress ip = TerremarkECloudClient.class.cast(tmClient)
            .activatePublicIpInVDC(tmClient.findVDCInOrgNamed(null, null).getHref());
    InternetService is = tmClient.addInternetServiceToExistingIp(ip.getId(), "SSH", Protocol.TCP, 22);
    Map<InternetService, PublicIpAddress> result = ImmutableMap.<InternetService, PublicIpAddress>of(is, ip);
    Entry<InternetService, PublicIpAddress> entry = Iterables.getOnlyElement(result.entrySet());
    return entry;
}

From source file:org.obm.icalendar.ical4jwrapper.ICalendarRecur.java

public Integer byMonthDay() {
    Collection<Integer> monthDayList = recur.getMonthDayList();
    if (monthDayList != null && !monthDayList.isEmpty()) {
        return Iterables.getOnlyElement(monthDayList);
    }/*www.ja  va 2s  .c o  m*/
    return null;
}

From source file:org.sosy_lab.cpachecker.cpa.smg.join.SMGJoinMapTargetAddress.java

public SMGJoinMapTargetAddress(SMG pSMG1, SMG pSMG2, SMG destSMG, SMGNodeMapping pMapping1,
        SMGNodeMapping pMapping2, Integer pAddress1, Integer pAddress2) {
    smg = destSMG;//  w  w  w.  ja  va  2s. co m
    mapping1 = pMapping1;
    mapping2 = pMapping2;
    SMGObject target = destSMG.getNullObject();

    // TODO: Ugly, refactor
    SMGEdgePointsTo pt = pSMG1.getPointer(pAddress1);
    SMGEdgePointsTo pt2 = pSMG2.getPointer(pAddress2);
    if (pt.getObject().notNull()) {
        target = pMapping1.get(pt.getObject());
    }

    SMGTargetSpecifier tg;

    /*When mapping optional object to other abstract object, use tg of other object.*/
    if ((pt.getObject().isAbstract() && pt.getObject().getKind() != SMGObjectKind.OPTIONAL) || pt2 == null
            || pt2.getObject().getKind() == SMGObjectKind.OPTIONAL) {
        tg = pt.getTargetSpecifier();
    } else {
        tg = pt2.getTargetSpecifier();
    }

    Set<SMGEdgePointsTo> edges = smg.getPtEdges(SMGEdgePointsToFilter.targetObjectFilter(target)
            .filterAtTargetOffset(pt.getOffset()).filterByTargetSpecifier(tg));

    if (!edges.isEmpty()) {
        value = Iterables.getOnlyElement(edges).getValue();
        return;
    }

    if (pAddress1.equals(pAddress2)) {
        value = pAddress1;
    } else {
        value = SMGValueFactory.getNewValue();
    }

    smg.addValue(value);

    SMGEdgePointsTo nPtEdge = new SMGEdgePointsTo(value, target, pt.getOffset(), tg);

    smg.addPointsToEdge(nPtEdge);
    mapping1.map(pAddress1, value);
    mapping2.map(pAddress2, value);
}

From source file:com.opengamma.financial.analytics.model.future.BondFutureFunction.java

@Override
public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs,
        final ComputationTarget target, final Set<ValueRequirement> desiredValues) {
    final ZonedDateTime date = ZonedDateTime.now(executionContext.getValuationClock());
    final ValueRequirement desiredValue = Iterables.getOnlyElement(desiredValues);
    final BondFutureSecurity security = (BondFutureSecurity) target.getSecurity();
    final BondFutureDefinition definition = (BondFutureDefinition) security.accept(_visitor);
    final Double referencePrice = 0.0; // TODO Futures Refactor
    final String[] curveNames = getCurveNames(desiredValue);
    final BondFuture bondFuture = definition.toDerivative(date, referencePrice, curveNames);
    return calculate(security, bondFuture, getData(desiredValue, inputs, target), target);
}

From source file:sklearn.svm.BaseLibSVMRegressor.java

@Override
public SupportVectorMachineModel encodeModel(Schema schema) {
    int[] shape = getSupportVectorsShape();

    int numberOfVectors = shape[0];
    int numberOfFeatures = shape[1];

    List<Integer> support = getSupport();
    List<? extends Number> supportVectors = getSupportVectors();
    List<? extends Number> dualCoef = getDualCoef();
    List<? extends Number> intercept = getIntercept();

    VectorDictionary vectorDictionary = SupportVectorMachineUtil.encodeVectorDictionary(support, supportVectors,
            numberOfVectors, numberOfFeatures, schema);

    List<VectorInstance> vectorInstances = vectorDictionary.getVectorInstances();

    Kernel kernel = SupportVectorMachineUtil.encodeKernel(getKernel(), getDegree(), getGamma(), getCoef0());

    SupportVectorMachine supportVectorMachine = SupportVectorMachineUtil
            .encodeSupportVectorMachine(vectorInstances, dualCoef, Iterables.getOnlyElement(intercept));

    SupportVectorMachineModel supportVectorMachineModel = new SupportVectorMachineModel(
            MiningFunction.REGRESSION, ModelUtil.createMiningSchema(schema), vectorDictionary, null)
                    .setKernel(kernel).addSupportVectorMachines(supportVectorMachine);

    return supportVectorMachineModel;
}

From source file:org.trancecode.xproc.step.TemplateStepProcessor.java

@Override
protected void execute(final StepInput input, final StepOutput output) {
    LOG.trace("start of step");
    assert input != null;
    assert output != null;

    final XdmNode templateNode = input.readNode(XProcPorts.TEMPLATE);
    final Iterable<XdmNode> sourceNodeList = input.readNodes(XProcPorts.SOURCE);
    final int sourcesCount = Iterables.size(sourceNodeList);
    final XdmNode sourceNode;

    assert templateNode != null;
    assert sourceNodeList != null;

    if (sourcesCount == 1) {
        sourceNode = Iterables.getOnlyElement(sourceNodeList);
    } else if (sourcesCount > 1) {
        throw XProcExceptions.xc0068(input.getLocation());
    } else {//from  ww w .j a  v  a  2s  . co m
        sourceNode = null;
    }

    final Map<QName, String> parameters = input.getParameters(XProcPorts.PARAMETERS);
    final Processor processor = input.getPipelineContext().getProcessor();
    final SaxonBuilder builder = new SaxonBuilder(processor.getUnderlyingConfiguration());

    builder.startDocument();
    processNode(templateNode, sourceNode, input, builder, processor, parameters);
    builder.endDocument();

    final XdmNode resultNode = builder.getNode();
    output.writeNodes(XProcPorts.RESULT, resultNode);
    LOG.trace("built result:\n{}", resultNode);
    LOG.trace("end of step");
}

From source file:org.springframework.xd.ec2.cloud.AWSInstanceProvisioner.java

/**
 * Retrieve the instance information for the instance id based on the EC2Client
 * @param client AWS Client that executes the commands necessary to create the instance.
 * @param instanceId The id of the instance.
 * @return Instance with that instance id.
 *//*from   w  w  w . ja v a  2s  .  co  m*/
public static RunningInstance findInstanceById(AWSEC2Api client, String instanceId) {
    Assert.notNull(client, "client can not be null");
    // search my account for the instance I just created
    Set<? extends Reservation<? extends RunningInstance>> reservations = client.getInstanceApi().get()
            .describeInstancesInRegion(null, instanceId); // last parameter (ids) narrows the
    // since we refined by instanceId there should only be one instance
    return Iterables.getOnlyElement(Iterables.getOnlyElement(reservations));
}

From source file:com.opengamma.financial.analytics.model.equity.EquityOptionMonetizedVegaFunction.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.size() != 1) {
        s_logger.error("Need to have a single calculation method");
        return null;
    }//from w  ww .  j a  va2 s  .c o  m
    final ValueProperties properties = ValueProperties.builder()
            .with(ValuePropertyNames.CALCULATION_METHOD, Iterables.getOnlyElement(calculationMethod)).get();
    return Collections
            .singleton(new ValueRequirement(ValueRequirementNames.VEGA, target.toSpecification(), properties));
}

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

@Nullable
@Override//from  ww w  . j  av a  2s  .  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) {
    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));
}