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

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

Introduction

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

Prototype

public static <T> T getLast(Iterable<T> iterable) 

Source Link

Document

Returns the last element of iterable .

Usage

From source file:brooklyn.util.mutex.SemaphoreForTasks.java

@Override
protected synchronized void onRequesting() {
    if (!owningTasks.isEmpty() || !requestingTasks.isEmpty()) {
        Tasks.setBlockingTask(!requestingTasks.isEmpty() ? Iterables.getLast(requestingTasks)
                : Iterables.getFirst(owningTasks, null));
        Tasks.setBlockingDetails(//from ww  w  .j  a  va2s. co m
                "Waiting on semaphore " + getName() + " (" + getDescription() + "); " + "queued at "
                        + Time.makeDateString() + " when " + getRequestingThreads().size() + " ahead in queue");
    }
    requestingTasks.addIfNotNull(Tasks.current());
    super.onRequesting();
}

From source file:io.crate.sql.tree.QualifiedName.java

public String getSuffix() {
    return Iterables.getLast(parts);
}

From source file:de.dobermai.mqttbot.BotController.java

@Override
protected void startUp() throws Exception {
    addShutdownHooks();/*from ww w . j  a  v  a2s . c  om*/

    mqttConnection.listener(new Listener() {
        @Override
        public void onConnected() {
            log.info("Connected to MQTT broker successfully");
        }

        @Override
        public void onDisconnected() {
            log.info("Disconnected from MQTT broker");
        }

        @Override
        public void onPublish(UTF8Buffer topic, Buffer body, Runnable ack) {

            final String channel = Iterables.getLast(Splitter.on("/").trimResults().split(topic.toString()))
                    .replace(mqttProperties.getMqttIrcChannelPrefix(), "#");

            ack.run();
            log.debug("Received message on topic {} with payload {}. Writing to IRC channel {}",
                    topic.toString(), body.utf8().toString(), channel);
            bot.sendMessage(channel, body.utf8().toString());
        }

        @Override
        public void onFailure(Throwable value) {
            log.error("An error occured", value);
        }
    });

    log.info("Connecting to MQTT Broker");
    mqttConnection.connect(new Callback<Void>() {
        @Override
        public void onSuccess(Void value) {
            log.debug("Connected to MQTT broker successfully");
        }

        @Override
        public void onFailure(Throwable value) {
            log.error("Could not connect to MQTT broker.", value);
        }
    });

    log.info("Connecting to IRC {} on port {}", ircProperties.getIrcHostName(), ircProperties.getPort());
    bot.connect(ircProperties.getIrcHostName(), ircProperties.getPort());

    for (String channel : ircProperties.getIrcChannels()) {
        bot.joinChannel(channel);
        log.info("Joined channel {}", channel);

        final String topic = replaceChannelPrefixes(
                MessageFormat.format("{0}/{1}", mqttProperties.getMqttTopicPrefix(), channel));
        log.info("Subscribing to MQTT topic {}", topic);
        mqttConnection.subscribe(new Topic[] { new Topic(topic, QoS.EXACTLY_ONCE) }, new Callback<byte[]>() {
            @Override
            public void onSuccess(byte[] value) {
                log.debug("Successfully subscribed to {}", topic);
            }

            @Override
            public void onFailure(Throwable value) {
                log.error("There was an error connecting to topic {}", topic, value);
            }
        });
    }
    log.info("Connected to IRC {} successfully", ircProperties.getIrcHostName());

}

From source file:org.apache.aurora.scheduler.updater.strategy.VariableBatchStrategy.java

private int determineCurGroupSize(int remaining) {
    // Calculate which groupIndex we are in by finding out how many instances we have left to update
    int modified = totalModInstanceCount.get() - remaining;
    int finalGroupSize = Iterables.getLast(groupSizes);

    LOG.debug(// w  w w. j  a  va2 s .c o  m
            "Variable Batch Update progress: {} instances have been modified, "
                    + "{} instances remain unmodified, and {} overall instances to be modified.",
            modified, remaining, totalModInstanceCount.get());

    if (rollingForward) {
        int sum = 0;
        for (Integer groupSize : groupSizes) {
            sum += groupSize;

            if (sum > modified) {
                return groupSize;
            }
        }
        // Return last step when number of instances > sum of all groups
        return finalGroupSize;
    } else {
        // To perform the update in reverse, we use the number of remaining tasks left to update
        // instead of using the number of already modified instances. In a rollback, the remaining
        // count represents the number of instances that were already modified while rolling forward
        // and need to be reverted.
        int curGroupSize = remaining;

        for (Integer groupSize : groupSizes) {
            // This handles an in between step. i.e.: updated instances = 4, update groups = [2,3]
            // which results in update groups 2 and 2 rolling forward at the time of failure.
            if (curGroupSize <= groupSize) {
                return curGroupSize;
            }

            curGroupSize -= groupSize;
        }

        // Handle the case where number of instances update were
        // greater than the sum of all update groups
        // Calculate the size of the last update group size performed while rolling forward.
        curGroupSize = curGroupSize % finalGroupSize;
        if (curGroupSize == 0) {
            return finalGroupSize;
        } else {
            return curGroupSize;
        }
    }
}

From source file:org.apache.flink.streaming.api.windowing.evictors.DeltaEvictor.java

private void evict(Iterable<TimestampedValue<T>> elements, int size, EvictorContext ctx) {
    TimestampedValue<T> lastElement = Iterables.getLast(elements);
    for (Iterator<TimestampedValue<T>> iterator = elements.iterator(); iterator.hasNext();) {
        TimestampedValue<T> element = iterator.next();
        if (deltaFunction.getDelta(element.getValue(), lastElement.getValue()) >= this.threshold) {
            iterator.remove();/*from   w w w. j av a 2 s . com*/
        }
    }
}

From source file:org.eclipse.xtend.ide.hover.XtendHoverSignatureProvider.java

@Override
protected String _signature(JvmGenericType clazz, boolean typeAtEnd) {
    if (clazz.isLocal()) {
        String rawName = Iterables.getLast(clazz.getSuperTypes()).getType().getSimpleName();
        return "new " + rawName + "(){}";
    }//  w  ww . jav a2 s .  c o m
    return super._signature(clazz, typeAtEnd);
}

From source file:com.google.idea.blaze.base.projectview.ProjectViewSet.java

/** Gets the last value from any scalar sections */
public <T> T getScalarValue(SectionKey<T, ScalarSection<T>> key, T defaultValue) {
    Collection<ScalarSection<T>> sections = getSections(key);
    if (sections.isEmpty()) {
        return defaultValue;
    } else {/*from  w ww . jav a2  s  .  c  om*/
        return Iterables.getLast(sections).getValue();
    }
}

From source file:org.cinchapi.concourse.lang.Parser.java

/**
 * Go through a list of symbols and group the expressions together in a
 * {@link Expression} object.// w  w  w . j  a v a2s  . c o m
 * 
 * @param symbols
 * @return the expression
 */
protected static List<Symbol> groupExpressions(List<Symbol> symbols) { // visible
                                                                       // for
                                                                       // testing
    try {
        List<Symbol> grouped = Lists.newArrayList();
        ListIterator<Symbol> it = symbols.listIterator();
        while (it.hasNext()) {
            Symbol symbol = it.next();
            if (symbol instanceof KeySymbol) {
                // NOTE: We are assuming that the list of symbols is well
                // formed, and, as such, the next elements will be an
                // operator and one or more symbols. If this is not the
                // case, this method will throw a ClassCastException
                OperatorSymbol operator = (OperatorSymbol) it.next();
                ValueSymbol value = (ValueSymbol) it.next();
                Expression expression;
                if (operator.getOperator() == Operator.BETWEEN) {
                    ValueSymbol value2 = (ValueSymbol) it.next();
                    expression = Expression.create((KeySymbol) symbol, operator, value, value2);
                } else {
                    expression = Expression.create((KeySymbol) symbol, operator, value);
                }
                grouped.add(expression);
            } else if (symbol instanceof TimestampSymbol) { // Add the
                                                            // timestamp to the
                                                            // previously
                                                            // generated
                                                            // Expression
                ((Expression) Iterables.getLast(grouped)).setTimestamp((TimestampSymbol) symbol);
            } else {
                grouped.add(symbol);
            }
        }
        return grouped;
    } catch (ClassCastException e) {
        throw new SyntaxException(e.getMessage());
    }
}

From source file:com.kurtraschke.ctatt.gtfsrealtime.services.TripMatchingService.java

public Trip matchTrip(String runNumber, String routeName, String destinationStationId,
        String destinationStationName, List<Eta> etas) throws TripMatchingException {
    GtfsRelationalDao dao = daoService.getGtfsRelationalDao();

    Collection<Trip> candidateTrips = daoService.getScheduledTripMapping().get("R" + runNumber);

    List<Trip> rightRouteTrips = new ArrayList<>();

    for (Trip candidateTrip : candidateTrips) {
        if (candidateTrip.getRoute().getId().getId().equalsIgnoreCase(routeName)) {
            rightRouteTrips.add(candidateTrip);
        }/*from   w  ww.  j a  v  a2s . c  o m*/
    }

    if (rightRouteTrips.isEmpty()) {
        throw new TripMatchingException("No trips on route found.");
    }

    List<Trip> rightDirectionTrips = new ArrayList<>();

    for (Trip t : rightRouteTrips) {
        List<StopTime> stopTimes = dao.getStopTimesForTrip(t);

        if (Iterables.getLast(stopTimes).getStop().getName().equals(destinationStationName)
                || Iterables.getLast(stopTimes).getStop().getId().getId().equals(destinationStationId)) {
            rightDirectionTrips.add(t);
        }
    }

    if (rightDirectionTrips.isEmpty()) {
        throw new TripMatchingException("No trips to destination found.");
    }

    Calendar c = new GregorianCalendar(daoService.getAgencyTimeZone());

    ServiceDate today = new ServiceDate(c);
    CalendarServiceData csd = daoService.getCalendarServiceData();

    Set<AgencyAndId> serviceIds = csd.getServiceIdsForDate(today);

    List<Trip> activeTrips = new ArrayList<>();

    for (Trip t : rightDirectionTrips) {
        if (serviceIds.contains(t.getServiceId())) {
            activeTrips.add(t);
        }
    }

    if (activeTrips.isEmpty()) {
        throw new TripMatchingException("No active trips found.");
    }

    Min<Trip> bestMatch = new Min<>();

    for (Trip t : activeTrips) {
        try {
            bestMatch.add(delta(today, dao.getStopTimesForTrip(t), etas), t);
        } catch (TripMatchingException ex) {
        }
    }

    return bestMatch.getMinElement();
}

From source file:com.google.errorprone.bugpatterns.ShouldHaveEvenArgs.java

@Override
public Description matchMethodInvocation(MethodInvocationTree methodInvocationTree, VisitorState state) {
    if (!MATCHER.matches(methodInvocationTree, state)) {
        return Description.NO_MATCH;
    }//from w  w w . ja  v  a2  s. c  o  m
    if (methodInvocationTree.getArguments().size() % 2 == 0) {
        return Description.NO_MATCH;
    }
    JCMethodInvocation methodInvocation = (JCMethodInvocation) methodInvocationTree;
    List<JCExpression> arguments = methodInvocation.getArguments();

    Type typeVargs = methodInvocation.varargsElement;
    if (typeVargs == null) {
        return Description.NO_MATCH;
    }
    Type typeVarargsArr = state.arrayTypeForType(typeVargs);
    Type lastArgType = ASTHelpers.getType(Iterables.getLast(arguments));
    if (typeVarargsArr.equals(lastArgType)) {
        return Description.NO_MATCH;
    }
    return describeMatch(methodInvocationTree);
}