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.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.EffectiveStatementBase.java

protected final <S extends EffectiveStatement<?, ?>> S firstEffective(final Class<S> type) {
    final Optional<? extends EffectiveStatement<?, ?>> possible = Iterables.tryFind(substatements,
            Predicates.instanceOf(type));
    return possible.isPresent() ? type.cast(possible.get()) : null;
}

From source file:com.codebutler.farebot.transit.clipper.ClipperTransitFactory.java

@NonNull
private static List<ClipperTrip> parseTrips(@NonNull DesfireCard card) {
    StandardDesfireFile file = (StandardDesfireFile) card.getApplication(0x9011f2).getFile(0x0e);
    /*//from   ww w  .ja  va  2 s. c  om
     *  This file reads very much like a record file but it professes to
     *  be only a regular file.  As such, we'll need to extract the records
     *  manually.
     */
    byte[] data = file.getData().bytes();
    int pos = data.length - RECORD_LENGTH;
    List<ClipperTrip> result = new ArrayList<>();
    while (pos > 0) {
        byte[] slice = ByteUtils.byteArraySlice(data, pos, RECORD_LENGTH);
        final ClipperTrip trip = createTrip(slice);
        if (trip != null) {
            // Some transaction types are temporary -- remove previous trip with the same timestamp.
            ClipperTrip existingTrip = Iterables.tryFind(result, new Predicate<ClipperTrip>() {
                @Override
                public boolean apply(ClipperTrip otherTrip) {
                    return trip.getTimestamp() == otherTrip.getTimestamp();
                }
            }).orNull();
            if (existingTrip != null) {
                if (existingTrip.getExitTimestamp() != 0) {
                    // Old trip has exit timestamp, and is therefore better.
                    pos -= RECORD_LENGTH;
                    continue;
                } else {
                    result.remove(existingTrip);
                }
            }
            result.add(trip);
        }
        pos -= RECORD_LENGTH;
    }

    Collections.sort(result, new Trip.Comparator());

    return result;
}

From source file:ru.org.linux.comment.DeleteCommentController.java

private Optional<Comment> findNextComment(final Comment comment) throws MessageNotFoundException {
    Topic updatedTopic = messageDao.getById(comment.getTopicId());
    CommentList commentList = commentService.getCommentList(updatedTopic, false);

    return Iterables.tryFind(commentList.getList(), new Predicate<Comment>() {
        @Override//from   w  ww  .j ava2 s.  c om
        public boolean apply(Comment input) {
            return input.getId() >= comment.getId();
        }
    });
}

From source file:org.apache.brooklyn.entity.monitoring.zabbix.ZabbixServerImpl.java

public void added(Entity member) {
    synchronized (mutex) {
        Optional<Location> location = Iterables.tryFind(member.getLocations(),
                Predicates.instanceOf(SshMachineLocation.class));
        if (location.isPresent() && member.getAttribute(Startable.SERVICE_UP)) {
            SshMachineLocation machine = (SshMachineLocation) location.get();
            if (!entityLocations.containsKey(machine)) {
                entityLocations.put(machine, member);
                // Configure the Zabbix agent
                List<String> commands = ImmutableList.<String>builder().add("sed -i.bk 's/\\$HOSTNAME/"
                        + machine.getDisplayName() + "/' /etc/zabbix/zabbix_agentd.conf").add("zabbix_agentd")
                        .build();/*from w  ww .  j  a  va2  s. c om*/
                int result = machine.execCommands("configuring zabbix_agentd", commands);
                if (result == 0) {
                    log.info("zabbix_agentd configured on {} at {}", member, machine);
                } else {
                    log.warn("failed to configure zabbix_agentd on {}, status {}", machine, result);
                }
            }
        } else {
            log.warn("zabbix added({}) called but no location or service not started", member);
        }
    }
}

From source file:org.apache.brooklyn.enricher.stock.reducer.Reducer.java

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override//from   w  w  w. jav a  2s. c om
public void setEntity(EntityLocal entity) {
    super.setEntity(entity);
    Preconditions.checkNotNull(getConfig(SOURCE_SENSORS), "source sensors");

    this.producer = getConfig(PRODUCER) == null ? entity : getConfig(PRODUCER);
    List<AttributeSensor<?>> sensorListTemp = Lists.newArrayList();

    for (Object sensorO : getConfig(SOURCE_SENSORS)) {
        AttributeSensor<?> sensor = Tasks.resolving(sensorO).as(AttributeSensor.class)
                .timeout(ValueResolver.REAL_QUICK_WAIT).context(producer).get();
        Optional<? extends Sensor<?>> foundSensor = Iterables.tryFind(sensorListTemp,
                SensorPredicates.nameEqualTo(sensor.getName()));

        if (!foundSensor.isPresent()) {
            sensorListTemp.add(sensor);
        }
    }

    String reducerName = config().get(REDUCER_FUNCTION_TRANSFORMATION);
    Function<Iterable<?>, ?> reducerFunction = (Function) config().get(REDUCER_FUNCTION);
    if (reducerFunction == null) {
        Map<String, ?> parameters = config().get(PARAMETERS);
        reducerFunction = createReducerFunction(reducerName, parameters);
    }

    this.reducerFunction = reducerFunction;
    Preconditions.checkState(sensorListTemp.size() > 0, "Nothing to reduce");

    for (Sensor<?> sensor : sensorListTemp) {
        subscribe(producer, sensor, this);
    }

    subscribedSensors = ImmutableList.copyOf(sensorListTemp);
}

From source file:org.apache.brooklyn.entity.nosql.redis.RedisStoreImpl.java

/**
 * Create a {@link Function} to retrieve a particular field value from a {@code redis-cli info}
 * command./*from   w w w  . j  av a 2  s .c o  m*/
 * 
 * @param field the info field to retrieve and convert
 * @return a new function that converts a {@link SshPollValue} to an {@link Integer}
 */
private static Function<SshPollValue, Integer> infoFunction(final String field) {
    return Functions.compose(new Function<String, Integer>() {
        @Override
        public Integer apply(@Nullable String input) {
            Optional<String> line = Iterables.tryFind(Splitter.on('\n').split(input),
                    Predicates.containsPattern(field + ":"));
            if (line.isPresent()) {
                String data = line.get().trim();
                int colon = data.indexOf(":");
                return Integer.parseInt(data.substring(colon + 1));
            } else {
                throw new IllegalStateException("Data for field " + field + " not found: " + input);
            }
        }
    }, SshValueFunctions.stdout());
}

From source file:com.keetip.versio.service.impl.VersioningServiceImpl.java

private Optional<Resource> getRevision(ResourceKey resourceKey, final Integer revision) {
    Collection<Resource> allRevisions = mResources.get(resourceKey);
    return Iterables.tryFind(allRevisions, new Predicate<Resource>() {
        public boolean apply(Resource resource) {
            return resource.getRevision().getRevisionNumber().equals(revision);
        }//from w  w w  .j a  v a 2  s  .  co  m
    });
}

From source file:org.killbill.billing.payment.core.sm.control.PaymentStateControlContext.java

public PaymentTransaction getCurrentTransaction() {
    if (result == null || result.getTransactions() == null) {
        return null;
    }/*from   w ww.ja v  a2s. c  om*/
    return Iterables.tryFind(result.getTransactions(), new Predicate<PaymentTransaction>() {
        @Override
        public boolean apply(final PaymentTransaction input) {
            final DefaultPaymentTransaction defaultPaymentTransaction = (DefaultPaymentTransaction) input;
            return defaultPaymentTransaction.getAttemptId() == null ? getAttemptId() == null
                    : defaultPaymentTransaction.getAttemptId().equals(getAttemptId());
        }
    }).orNull();
}

From source file:org.killbill.billing.beatrix.util.RefundChecker.java

private PaymentTransaction getRefundTransaction(final Payment payment) {
    return Iterables.tryFind(payment.getTransactions(), new Predicate<PaymentTransaction>() {
        @Override/*from   w  ww  .  j  a v a2  s . c  om*/
        public boolean apply(final PaymentTransaction input) {
            return input.getTransactionType() == TransactionType.REFUND;
        }
    }).get();
}

From source file:com.thinkbiganalytics.feedmgr.rest.model.FeedCategory.java

@JsonIgnore
public void removeRelatedFeed(final FeedMetadata feed) {
    FeedSummary match = Iterables.tryFind(feeds, new Predicate<FeedSummary>() {
        @Override//from   w  w  w.  j a v  a2  s  .com
        public boolean apply(FeedSummary metadata) {
            return feed.getFeedName().equalsIgnoreCase(metadata.getFeedName());
        }
    }).orNull();
    if (match != null) {
        getFeeds().remove(match);
    }
}