Example usage for com.google.common.collect Iterables getFirst

List of usage examples for com.google.common.collect Iterables getFirst

Introduction

In this page you can find the example usage for com.google.common.collect Iterables getFirst.

Prototype

@Nullable
public static <T> T getFirst(Iterable<? extends T> iterable, @Nullable T defaultValue) 

Source Link

Document

Returns the first element in iterable or defaultValue if the iterable is empty.

Usage

From source file:io.brooklyn.ambari.hostgroup.AmbariHostGroupImpl.java

private AmbariCluster getAmbariCluster() {
    return Iterables.getFirst(Iterables.filter(Entities.ancestors(this), AmbariCluster.class), null);
}

From source file:org.immutables.value.processor.meta.TypeIntrospectionBase.java

public String getDirectSupertype() {
    ensureTypeIntrospected();
    return Iterables.getFirst(extendedClassesNames, null);
}

From source file:com.b2international.snowowl.snomed.datastore.converter.InactivationExpander.java

void expand(List<T> results, Set<String> componentIds) {

    if (componentIds.isEmpty()) {
        return;//  www .  j av a2  s .  c  o  m
    }

    final List<String> refSetIds = newArrayList();
    for (final AssociationType associationType : AssociationType.values()) {
        refSetIds.add(associationType.getConceptId());
    }

    refSetIds.add(inactivationIndicatorId);

    final SnomedReferenceSetMembers members = SnomedRequests.prepareSearchMember().all()
            .filterByRefSet(refSetIds).filterByReferencedComponent(componentIds).filterByActive(true).build()
            .execute(context);

    if (members.getItems().isEmpty()) {
        return;
    }

    final Multimap<String, SnomedReferenceSetMember> membersByReferencedComponentId = Multimaps.index(members,
            new Function<SnomedReferenceSetMember, String>() {
                @Override
                public String apply(SnomedReferenceSetMember input) {
                    return input.getReferencedComponent().getId();
                }
            });

    for (T result : results) {
        final Collection<SnomedReferenceSetMember> referringMembers = membersByReferencedComponentId
                .get(result.getId());
        final List<SnomedReferenceSetMember> associationMembers = newArrayList();
        final List<SnomedReferenceSetMember> inactivationMembers = newArrayList();

        for (SnomedReferenceSetMember referringMember : referringMembers) {
            if (SnomedRefSetType.ASSOCIATION.equals(referringMember.type())) {
                associationMembers.add(referringMember);
            } else if (SnomedRefSetType.ATTRIBUTE_VALUE.equals(referringMember.type())) {
                inactivationMembers.add(referringMember);
            }
        }

        if (!inactivationMembers.isEmpty()) {
            final String valueId = (String) Iterables.getFirst(inactivationMembers, null).getProperties()
                    .get(SnomedRf2Headers.FIELD_VALUE_ID);
            setInactivationIndicator(result, valueId);
        }

        Multimap<AssociationType, String> associationTargets = HashMultimap.create();
        for (SnomedReferenceSetMember associationMember : associationMembers) {
            AssociationType type = AssociationType.getByConceptId(associationMember.getReferenceSetId());
            final SnomedCoreComponent target = (SnomedCoreComponent) associationMember.getProperties()
                    .get(SnomedRf2Headers.FIELD_TARGET_COMPONENT);
            associationTargets.put(type, target.getId());
        }

        if (!associationTargets.isEmpty()) {
            setAssociationTargets(result, associationTargets);
        }
    }
}

From source file:brooklyn.entity.rebind.InitialFullRebindIteration.java

@Override
protected void loadManifestFiles() throws Exception {
    checkEnteringPhase(1);/*from w  ww  .  ja v a 2 s  . c o m*/
    Preconditions.checkState(mementoRawData == null,
            "Memento raw data should not yet be set when calling this");
    mementoRawData = persistenceStoreAccess.loadMementoRawData(exceptionHandler);

    preprocessManifestFiles();

    if (mode != ManagementNodeState.HOT_STANDBY && mode != ManagementNodeState.HOT_BACKUP) {
        if (!isEmpty) {
            LOG.info("Rebinding from " + getPersister().getBackingStoreDescription() + " for "
                    + Strings.toLowerCase(Strings.toString(mode)) + " "
                    + managementContext.getManagementNodeId() + "...");
        } else {
            LOG.info("Rebind check: no existing state; will persist new items to "
                    + getPersister().getBackingStoreDescription());
        }

        if (!managementContext.getEntityManager().getEntities().isEmpty()
                || !managementContext.getLocationManager().getLocations().isEmpty()) {
            // this is discouraged if we were already master
            Entity anEntity = Iterables.getFirst(managementContext.getEntityManager().getEntities(), null);
            if (anEntity != null && !((EntityInternal) anEntity).getManagementSupport().isReadOnly()) {
                // NB: there is some complexity which can happen in this situation; "initial-full" rebind really expected everything is being
                // initially bound from persisted state, and completely so; "active-partial" is much more forgiving.
                // one big difference is in behaviour of management: it is recursive for most situations, and initial-full assumes recursive,
                // but primary-primary is *not* recursive;
                // as a result some "new" entities created during rebind might be left unmanaged; they should get GC'd,
                // but it's possible the new entity impl or even a new proxy could leak.
                // see HighAvailabilityManagerInMemoryTest.testLocationsStillManagedCorrectlyAfterDoublePromotion
                // (i've plugged the known such leaks, but still something to watch out for); -Alex 2015-02
                overwritingMaster = true;
                LOG.warn("Rebind requested for " + mode + " node " + managementContext.getManagementNodeId()
                        + " " + "when it already has active state; discouraged, " + "will likely overwrite: "
                        + managementContext.getEntityManager().getEntities() + " and "
                        + managementContext.getLocationManager().getLocations() + " and more");
            }
        }
    }
}

From source file:net.sourceforge.subsonic.service.VideoConversionService.java

public VideoConversion getVideoConversionForFile(int mediaFileId) {
    VideoConversion conversion = videoConversionDao.getVideoConversionForFile(mediaFileId);
    if (conversion == null) {
        return null;
    }/*from   w  w w .  j  a  va  2s.  c  om*/

    List<VideoConversion> conversions = deleteIfFileMissing(Collections.singletonList(conversion));
    return Iterables.getFirst(conversions, null);
}

From source file:com.b2international.commons.options.HashMapOptions.java

@Override
@SuppressWarnings("unchecked")
public final <T> List<T> getList(String key, Class<T> type) {
    final Object value = get(key);
    if (type.isInstance(value)) {
        return Collections.singletonList(type.cast(value));
    } else {/*  w  ww . ja v  a 2s  .co  m*/
        final List<Object> List = get(key, List.class);
        final Object first = List != null ? Iterables.getFirst(List, null) : null;
        if (first != null) {
            if (type.isInstance(first)) {
                return (List<T>) List;
            }
            throw new IllegalArgumentException(
                    String.format("The elements (%s) in the List are not the instance of the given type (%s)",
                            first.getClass(), type));
        }
        return emptyList();
    }
}

From source file:com.opengamma.financial.analytics.model.credit.ISDARiskMetricsVanillaCDSFunction.java

@Override
public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs,
        final ComputationTarget target, final Set<ValueRequirement> desiredValues)
        throws AsynchronousExecution {
    final ZonedDateTime now = ZonedDateTime.now(executionContext.getValuationClock());

    final LegacyVanillaCDSSecurity security = (LegacyVanillaCDSSecurity) target.getSecurity();
    LegacyVanillaCreditDefaultSwapDefinition cds = _converter.visitLegacyVanillaCDSSecurity(security);
    final ValueProperties properties = Iterables.getFirst(desiredValues, null).getConstraints().copy().get(); // all share same properties

    final Object cleanPVObject = inputs.getValue(ValueRequirementNames.CLEAN_PRESENT_VALUE);
    final double cleanPresentValue = ((Double) cleanPVObject).doubleValue();
    final Object dirtyPVObject = inputs.getValue(ValueRequirementNames.DIRTY_PRESENT_VALUE);
    final double dirtyPresentValue = ((Double) dirtyPVObject).doubleValue();
    final Object upfrontObject = inputs.getValue(ValueRequirementNames.UPFRONT_AMOUNT);
    final double upfrontAmount = ((Double) upfrontObject).doubleValue();

    cds = IMMDateGenerator.cdsModifiedForIMM(now, cds);

    final double accruedPremium = cleanPresentValue - dirtyPresentValue;
    final double accruedDays = Math
            .abs((accruedPremium * 360 / cds.getParSpread()) * (10000 / cds.getNotional()));
    final double cleanPrice = 100.0
            * ((cds.getNotional() - dirtyPresentValue - accruedPremium) / cds.getNotional());
    final double principal = accruedPremium + upfrontAmount;

    final ComputedValue accruedDaysSpec = new ComputedValue(
            new ValueSpecification(ValueRequirementNames.ACCRUED_DAYS, target.toSpecification(), properties),
            accruedDays);/*  w w  w  .j a v  a 2s.com*/
    final ComputedValue accruedPremiumSpec = new ComputedValue(
            new ValueSpecification(ValueRequirementNames.ACCRUED_PREMIUM, target.toSpecification(), properties),
            accruedPremium);
    final ComputedValue cleanPriceSpec = new ComputedValue(
            new ValueSpecification(ValueRequirementNames.CLEAN_PRICE, target.toSpecification(), properties),
            cleanPrice);
    final ComputedValue principalSpec = new ComputedValue(
            new ValueSpecification(ValueRequirementNames.PRINCIPAL, target.toSpecification(), properties),
            principal);

    return Sets.newHashSet(accruedDaysSpec, accruedPremiumSpec, cleanPriceSpec, principalSpec);
}

From source file:eu.numberfour.n4js.validation.validators.utils.MemberRedefinitionUtils.java

/**
 * Returns the class which is filled by the given static polyfill class definition.
 *
 * Returns {@code null} if staticPolyfillDefinition isn't a valid static polyfill class definition.
 *//*from w w w . j  ava  2 s  . co  m*/
public static TClass getFilledClass(N4ClassDefinition staticPolyfillDefinition) {
    if (!(staticPolyfillDefinition.getDefinedType() instanceof TClassifier)) {
        return null;
    }

    TClassifier classifier = (TClassifier) staticPolyfillDefinition.getDefinedType();
    if (!classifier.isStaticPolyfill()) {
        return null;
    }

    ParameterizedTypeRef superClassTypeRef = Iterables.getFirst(classifier.getSuperClassifierRefs(), null);
    if (null == superClassTypeRef) {
        return null;
    }

    Type superClassType = superClassTypeRef.getDeclaredType();
    if (superClassType instanceof TClass
            && ((TClass) superClassType).getContainingModule().isStaticPolyfillAware()) {
        return (TClass) superClassType;
    } else {
        return null;
    }
}

From source file:org.jclouds.cache.AptCache.java

@Override
public void enableCacheClientInNode(ComputeServiceContext ctx, NodeMetadata clientNode) {
    checkNotNull(server, "server cannot be null");
    try {/*w  ww  . j  a va  2 s.  c o m*/
        checkState(ctx.getComputeService()
                .submitScriptOnNode(clientNode.getId(),
                        new ClientStatement(
                                checkNotNull(Iterables.getFirst(server.getPrivateAddresses(), null))),
                        RunScriptOptions.NONE)
                .get(20, TimeUnit.MINUTES).getExitStatus() == 0);
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

From source file:org.obm.provisioning.dao.OperationDaoJdbcImpl.java

@Override
public Operation get(Operation.Id operationId) throws DaoException {
    Connection connection = null;
    PreparedStatement ps = null;// w  w  w .  ja v a2s  .  c  o m
    ResultSet rs = null;

    try {
        connection = dbcp.getConnection();
        ps = connection.prepareStatement("SELECT " + FIELDS + " FROM batch_operation o "
                + "LEFT JOIN batch_operation_param p ON p.operation = o.id " + "WHERE o.id = ? "
                + "ORDER BY o.id ASC");

        ps.setInt(1, operationId.getId());

        rs = ps.executeQuery();

        return Iterables.getFirst(operationsFromCursor(rs), null);
    } catch (SQLException e) {
        throw new DaoException(e);
    } finally {
        JDBCUtils.cleanup(connection, ps, rs);
    }
}