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

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

Introduction

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

Prototype

public static <T> Optional<T> tryFind(Iterable<T> iterable, Predicate<? super T> predicate) 

Source Link

Document

Returns an Optional containing the first element in iterable that satisfies the given predicate, if such an element exists.

Usage

From source file:org.jclouds.virtualbox.compute.VirtualBoxImageExtension.java

private Optional<NodeMetadata> getNodeById(final String id) {
    return Iterables.tryFind(Iterables.transform(vboxAdapter.listNodes(), machineToNode),
            new Predicate<NodeMetadata>() {
                @Override// www.  j  ava2s .  c o  m
                public boolean apply(NodeMetadata input) {
                    return input.getId().equals(id);
                }
            });
}

From source file:org.ow2.petals.cloud.manager.core.services.DefaultManagementService.java

/**
 * Get the provider from the platform//from   ww w  . java 2  s .c o  m
 *
 * @param provider
 * @return
 */
protected ProviderManager getProviderManager(final Provider provider) {
    if (provider == null) {
        return null;
    }

    return Iterables.tryFind(providers, new Predicate<ProviderManager>() {
        public boolean apply(ProviderManager input) {
            return provider.getType().equals(input.getProviderName());
        }
    }).orNull();
}

From source file:brooklyn.entity.nosql.mongodb.MongoDBReplicaSetImpl.java

@Override
public MongoDBServer getPrimary() {
    return Iterables.tryFind(getReplicas(), IS_PRIMARY).orNull();
}

From source file:org.apache.brooklyn.entity.nosql.etcd.EtcdClusterImpl.java

protected void onServerPoolMemberChanged(Entity member) {
    synchronized (memberMutex) {
        log.debug("For {}, considering membership of {} which is in locations {}",
                new Object[] { this, member, member.getLocations() });

        Map<Entity, String> nodes = sensors().get(ETCD_CLUSTER_NODES);
        if (belongsInServerPool(member)) {
            if (nodes == null) {
                nodes = Maps.newLinkedHashMap();
            }// w  w w. j a v a  2 s  . co m
            String name = Preconditions.checkNotNull(getNodeName(member));

            // Wait until node has been installed
            DynamicTasks
                    .queueIfPossible(
                            DependentConfiguration.attributeWhenReady(member, EtcdNode.ETCD_NODE_INSTALLED))
                    .orSubmitAndBlock(this).andWaitForSuccess();

            // Check for first node in the cluster.
            Duration timeout = config().get(BrooklynConfigKeys.START_TIMEOUT);
            Entity firstNode = sensors().get(DynamicCluster.FIRST);
            if (member.equals(firstNode)) {
                nodes.put(member, name);
                recalculateClusterAddresses(nodes);
                log.info("Adding first node {}: {}; {} to cluster", new Object[] { this, member, name });
                ((EntityInternal) member).sensors().set(EtcdNode.ETCD_NODE_HAS_JOINED_CLUSTER, Boolean.TRUE);
            } else {
                int retry = 3; // TODO use a configurable Repeater instead?
                while (retry-- > 0 && member.sensors().get(EtcdNode.ETCD_NODE_HAS_JOINED_CLUSTER) == null
                        && !nodes.containsKey(member)) {
                    Optional<Entity> anyNodeInCluster = Iterables.tryFind(nodes.keySet(),
                            Predicates.and(Predicates.instanceOf(EtcdNode.class), EntityPredicates
                                    .attributeEqualTo(EtcdNode.ETCD_NODE_HAS_JOINED_CLUSTER, Boolean.TRUE)));
                    if (anyNodeInCluster.isPresent()) {
                        DynamicTasks.queueIfPossible(DependentConfiguration.builder()
                                .attributeWhenReady(anyNodeInCluster.get(), Startable.SERVICE_UP)
                                .timeout(timeout).build()).orSubmitAndBlock(this).andWaitForSuccess();
                        Entities.invokeEffectorWithArgs(this, anyNodeInCluster.get(),
                                EtcdNode.JOIN_ETCD_CLUSTER, name, getNodeAddress(member))
                                .blockUntilEnded(timeout);
                        nodes.put(member, name);
                        recalculateClusterAddresses(nodes);
                        log.info("Adding node {}: {}; {} to cluster", new Object[] { this, member, name });
                        ((EntityInternal) member).sensors().set(EtcdNode.ETCD_NODE_HAS_JOINED_CLUSTER,
                                Boolean.TRUE);
                    } else {
                        log.info("Waiting for first node in cluster {}", this);
                        Time.sleep(Duration.seconds(15));
                    }
                }
            }
        } else {
            if (nodes != null && nodes.containsKey(member)) {
                Optional<Entity> anyNodeInCluster = Iterables.tryFind(nodes.keySet(),
                        Predicates.and(
                                Predicates.instanceOf(EtcdNode.class), EntityPredicates
                                        .attributeEqualTo(EtcdNode.ETCD_NODE_HAS_JOINED_CLUSTER, Boolean.TRUE),
                                Predicates.not(Predicates.equalTo(member))));
                if (anyNodeInCluster.isPresent()) {
                    Entities.invokeEffectorWithArgs(this, anyNodeInCluster.get(), EtcdNode.LEAVE_ETCD_CLUSTER,
                            getNodeName(member)).blockUntilEnded();
                }
                nodes.remove(member);
                recalculateClusterAddresses(nodes);
                log.info("Removing node {}: {}; {} from cluster",
                        new Object[] { this, member, getNodeName(member) });
                ((EntityInternal) member).sensors().set(EtcdNode.ETCD_NODE_HAS_JOINED_CLUSTER, Boolean.FALSE);
            }
        }

        ServiceNotUpLogic.updateNotUpIndicatorRequiringNonEmptyMap(this, ETCD_CLUSTER_NODES);
        log.debug("Done {} checkEntity {}", this, member);
    }
}

From source file:org.killbill.billing.payment.core.janitor.ErroredPaymentTask.java

@Override
public void doIteration(final PaymentModelDao item) {

    final InternalTenantContext internalTenantContext = internalCallContextFactory
            .createInternalTenantContext(item.getAccountId(), item.getId(), ObjectType.PAYMENT);
    final CallContext callContext = createCallContext("ErroredPaymentTask", internalTenantContext);
    final InternalCallContext internalCallContext = internalCallContextFactory
            .createInternalCallContext(item.getAccountId(), callContext);

    final List<PaymentTransactionModelDao> transactions = paymentDao.getTransactionsForPayment(item.getId(),
            internalTenantContext);/*from  www.  ja  v  a2  s .  com*/
    Preconditions.checkState(!transactions.isEmpty(),
            "Janitor ErroredPaymentTask found item " + item.getId() + " with no transactions, skipping");

    // We look for latest transaction in an UNKNOWN state, if not we skip
    final PaymentTransactionModelDao unknownTransaction = transactions.get(transactions.size() - 1);
    if (unknownTransaction.getTransactionStatus() != TransactionStatus.UNKNOWN) {
        return;
    }

    final PaymentMethodModelDao paymentMethod = paymentDao.getPaymentMethod(item.getPaymentMethodId(),
            internalCallContext);
    final PaymentPluginApi paymentPluginApi = getPaymentPluginApi(item, paymentMethod.getPluginName());

    PaymentTransactionInfoPlugin pluginErroredTransaction = null;
    try {
        final List<PaymentTransactionInfoPlugin> result = paymentPluginApi.getPaymentInfo(item.getAccountId(),
                item.getId(), ImmutableList.<PluginProperty>of(), callContext);

        pluginErroredTransaction = Iterables.tryFind(result, new Predicate<PaymentTransactionInfoPlugin>() {
            @Override
            public boolean apply(@Nullable final PaymentTransactionInfoPlugin input) {
                return input.getKbTransactionPaymentId().equals(unknownTransaction.getId());
            }
        }).orNull();
    } catch (PaymentPluginApiException ignored) {

    }

    // Compute new transactionStatus based on pluginInfo state; and if that did not change, bail early.
    final TransactionStatus transactionStatus = PaymentEnteringStateCallback
            .paymentPluginStatusToTransactionStatus(pluginErroredTransaction);
    if (transactionStatus == unknownTransaction.getTransactionStatus()) {
        return;
    }

    // This piece of logic is obviously outside of the state machine, and this is a bit of a hack; at least all the paymentStates internal config is
    // kept into paymentStateMachineHelper.
    final String newPaymentState;
    switch (transactionStatus) {
    case PENDING:
        newPaymentState = paymentStateMachineHelper
                .getPendingStateForTransaction(unknownTransaction.getTransactionType());
        break;
    case SUCCESS:
        newPaymentState = paymentStateMachineHelper
                .getSuccessfulStateForTransaction(unknownTransaction.getTransactionType());
        break;
    case PAYMENT_FAILURE:
        newPaymentState = paymentStateMachineHelper
                .getFailureStateForTransaction(unknownTransaction.getTransactionType());
        break;
    case PLUGIN_FAILURE:
    case UNKNOWN:
    default:
        newPaymentState = paymentStateMachineHelper
                .getErroredStateForTransaction(unknownTransaction.getTransactionType());
        break;
    }
    final String lastSuccessPaymentState = paymentStateMachineHelper.isSuccessState(newPaymentState)
            ? newPaymentState
            : null;

    final BigDecimal processedAmount = pluginErroredTransaction != null ? pluginErroredTransaction.getAmount()
            : null;
    final Currency processedCurrency = pluginErroredTransaction != null ? pluginErroredTransaction.getCurrency()
            : null;
    final String gatewayErrorCode = pluginErroredTransaction != null
            ? pluginErroredTransaction.getGatewayErrorCode()
            : null;
    final String gatewayError = pluginErroredTransaction != null ? pluginErroredTransaction.getGatewayError()
            : null;

    log.info("Janitor ErroredPaymentTask repairing payment {}, transaction {}", item.getId(),
            unknownTransaction.getId());

    paymentDao.updatePaymentAndTransactionOnCompletion(item.getAccountId(), item.getId(),
            unknownTransaction.getTransactionType(), newPaymentState, lastSuccessPaymentState,
            unknownTransaction.getId(), transactionStatus, processedAmount, processedCurrency, gatewayErrorCode,
            gatewayError, internalCallContext);

}

From source file:gobblin.data.management.conversion.hive.publisher.HiveConvertPublisher.java

@Override
public void publishData(Collection<? extends WorkUnitState> states) throws IOException {

    Set<String> cleanUpQueries = Sets.newLinkedHashSet();
    Set<String> publishQueries = Sets.newLinkedHashSet();
    List<String> directoriesToDelete = Lists.newArrayList();

    try {//from  w  w  w  . j  ava2s  . co m
        if (Iterables.tryFind(states, UNSUCCESSFUL_WORKUNIT).isPresent()) {
            /////////////////////////////////////////
            // Prepare cleanup and ignore publish
            /////////////////////////////////////////
            for (WorkUnitState wus : states) {
                QueryBasedHivePublishEntity publishEntity = HiveAvroORCQueryGenerator
                        .deserializePublishCommands(wus);

                // Add cleanup commands - to be executed later
                if (publishEntity.getCleanupQueries() != null) {
                    cleanUpQueries.addAll(publishEntity.getCleanupQueries());
                }

                if (publishEntity.getCleanupDirectories() != null) {
                    directoriesToDelete.addAll(publishEntity.getCleanupDirectories());
                }

                EventWorkunitUtils.setBeginPublishDDLExecuteTimeMetadata(wus, System.currentTimeMillis());
                wus.setWorkingState(WorkingState.FAILED);
                if (!wus.getPropAsBoolean(PartitionLevelWatermarker.IS_WATERMARK_WORKUNIT_KEY)) {
                    try {
                        new SlaEventSubmitter(eventSubmitter, EventConstants.CONVERSION_FAILED_EVENT,
                                wus.getProperties()).submit();
                    } catch (Exception e) {
                        log.error("Failed while emitting SLA event, but ignoring and moving forward to curate "
                                + "all clean up comamnds", e);
                    }
                }
            }
        } else {
            /////////////////////////////////////////
            // Prepare publish and cleanup commands
            /////////////////////////////////////////
            for (WorkUnitState wus : PARTITION_PUBLISH_ORDERING.sortedCopy(states)) {
                QueryBasedHivePublishEntity publishEntity = HiveAvroORCQueryGenerator
                        .deserializePublishCommands(wus);

                // Add cleanup commands - to be executed later
                if (publishEntity.getCleanupQueries() != null) {
                    cleanUpQueries.addAll(publishEntity.getCleanupQueries());
                }

                if (publishEntity.getCleanupDirectories() != null) {
                    directoriesToDelete.addAll(publishEntity.getCleanupDirectories());
                }

                if (publishEntity.getPublishDirectories() != null) {
                    // Publish snapshot / partition directories
                    Map<String, String> publishDirectories = publishEntity.getPublishDirectories();
                    for (Map.Entry<String, String> publishDir : publishDirectories.entrySet()) {
                        moveDirectory(publishDir.getKey(), publishDir.getValue());
                    }
                }

                if (publishEntity.getPublishQueries() != null) {
                    publishQueries.addAll(publishEntity.getPublishQueries());
                }
            }

            /////////////////////////////////////////
            // Core publish
            /////////////////////////////////////////

            // Update publish start timestamp on all workunits
            for (WorkUnitState wus : PARTITION_PUBLISH_ORDERING.sortedCopy(states)) {
                if (HiveAvroORCQueryGenerator.deserializePublishCommands(wus).getPublishQueries() != null) {
                    EventWorkunitUtils.setBeginPublishDDLExecuteTimeMetadata(wus, System.currentTimeMillis());
                }
            }

            // Actual publish: Register snapshot / partition
            executeQueries(Lists.newArrayList(publishQueries));

            // Update publish completion timestamp on all workunits
            for (WorkUnitState wus : PARTITION_PUBLISH_ORDERING.sortedCopy(states)) {
                if (HiveAvroORCQueryGenerator.deserializePublishCommands(wus).getPublishQueries() != null) {
                    EventWorkunitUtils.setEndPublishDDLExecuteTimeMetadata(wus, System.currentTimeMillis());
                }

                wus.setWorkingState(WorkingState.COMMITTED);
                this.watermarker.setActualHighWatermark(wus);

                // Emit an SLA event for conversion successful
                if (!wus.getPropAsBoolean(PartitionLevelWatermarker.IS_WATERMARK_WORKUNIT_KEY)) {
                    EventWorkunitUtils.setIsFirstPublishMetadata(wus);
                    try {
                        new SlaEventSubmitter(eventSubmitter, EventConstants.CONVERSION_SUCCESSFUL_SLA_EVENT,
                                wus.getProperties()).submit();
                    } catch (Exception e) {
                        log.error("Failed while emitting SLA event, but ignoring and moving forward to curate "
                                + "all clean up commands", e);
                    }
                }
            }
        }
    } finally {
        /////////////////////////////////////////
        // Preserving partition params
        /////////////////////////////////////////
        preservePartitionParams(states);

        /////////////////////////////////////////
        // Post publish cleanup
        /////////////////////////////////////////

        // Execute cleanup commands
        try {
            executeQueries(Lists.newArrayList(cleanUpQueries));
        } catch (Exception e) {
            log.error("Failed to cleanup staging entities in Hive metastore.", e);
        }
        try {
            deleteDirectories(directoriesToDelete);
        } catch (Exception e) {
            log.error("Failed to cleanup staging directories.", e);
        }
    }
}

From source file:com.m2dl.helloandroid.wastelocator.MapsActivity.java

private String getColorOfInterest(Interest interest, List<Tag> tags) {

    List<Long> tagIds = interest.getTagIds();
    if (tagIds != null && !tagIds.isEmpty()) {
        final Long firstTagId = tagIds.get(0);

        Tag myTag = Iterables.tryFind(tags, new Predicate<Tag>() {
            @Override//w  ww  .  j av  a  2s.c  o  m
            public boolean apply(Tag input) {
                return input.getId().equals(firstTagId);
            }
        }).orNull();

        if (myTag != null) {
            return myTag.getColor();
        }
    }
    return "#000000"; // Couleur par dfaut si on a rien trouv. L c'est du noir
}

From source file:org.killbill.billing.osgi.OSGIListener.java

private SystemNodeCommandType getSystemNodeCommandTypeOrNull(final String command) {
    return Iterables.tryFind(ImmutableList.copyOf(SystemNodeCommandType.values()),
            new Predicate<SystemNodeCommandType>() {
                @Override/*from  www  .  j  a v  a  2s .  co m*/
                public boolean apply(final SystemNodeCommandType input) {
                    return input.name().equals(command);
                }
            }).orNull();
}

From source file:brooklyn.entity.basic.AbstractGroupImpl.java

/**
 * Adds the given entity as a member of this group <em>and</em> this group as one of the groups of the child
 *//* w ww.j ava2s  .  co  m*/
@Override
public boolean addMember(Entity member) {
    synchronized (members) {
        if (Entities.isNoLongerManaged(member)) {
            // Don't add dead entities, as they could never be removed (because addMember could be called in
            // concurrent thread as removeMember triggered by the unmanage).
            // Not using Entities.isManaged here, as could be called in entity.init()
            log.debug("Group {} ignoring new member {}, because it is no longer managed", this, member);
            return false;
        }

        // FIXME do not set sensors on members; possibly we don't need FIRST at all, just look at the first in MEMBERS, and take care to guarantee order there
        Entity first = getAttribute(FIRST);
        if (first == null) {
            ((EntityLocal) member).setAttribute(FIRST_MEMBER, true);
            ((EntityLocal) member).setAttribute(FIRST, member);
            setAttribute(FIRST, member);
        } else {
            if (first.equals(member) || first.equals(member.getAttribute(FIRST))) {
                // do nothing (rebinding)
            } else {
                ((EntityLocal) member).setAttribute(FIRST_MEMBER, false);
                ((EntityLocal) member).setAttribute(FIRST, first);
            }
        }

        member.addGroup((Group) getProxyIfAvailable());
        boolean changed = addMemberInternal(member);
        if (changed) {
            log.debug("Group {} got new member {}", this, member);
            setAttribute(GROUP_SIZE, getCurrentSize());
            setAttribute(GROUP_MEMBERS, getMembers());
            // emit after the above so listeners can use getMembers() and getCurrentSize()
            emit(MEMBER_ADDED, member);

            if (Boolean.TRUE.equals(getConfig(MEMBER_DELEGATE_CHILDREN))) {
                Optional<Entity> result = Iterables.tryFind(getChildren(), Predicates.equalTo(member));
                if (!result.isPresent()) {
                    String nameFormat = Optional.fromNullable(getConfig(MEMBER_DELEGATE_NAME_FORMAT)).or("%s");
                    DelegateEntity child = addChild(EntitySpec.create(DelegateEntity.class)
                            .configure(DelegateEntity.DELEGATE_ENTITY, member)
                            .displayName(String.format(nameFormat, member.getDisplayName())));
                    Entities.manage(child);
                }
            }

            getManagementSupport().getEntityChangeListener().onMembersChanged();
        }
        return changed;
    }
}

From source file:com.eucalyptus.auth.euare.identity.region.RegionConfigurationManager.java

/**
 * Get the region information for the local region (if any)
 *
 * @return The optional region information
 *///from   ww w . j  a  va2s .  c o  m
public Optional<RegionInfo> getRegionInfo() {
    final Optional<RegionConfiguration> regionConfigurationOptional = regionConfigurationSupplier.get();
    return Iterables
            .tryFind(Iterables.concat(regionConfigurationOptional.asSet()),
                    propertyPredicate(RegionConfigurations.getRegionName().asSet(),
                            RegionNameTransform.INSTANCE))
            .transform(regionToRegionInfoTransform(regionConfigurationOptional));
}