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:org.glowroot.ui.SyntheticResultJsonService.java

private static List<SyntheticResult> rollUpSyntheticResults(
        List<SyntheticResult> orderedNonRolledUpSyntheticResults, Function<Long, Long> rollupCaptureTimeFn) {
    List<SyntheticResult> rolledUpSyntheticResults = Lists.newArrayList();
    double totalDurationNanos = 0;
    long executionCount = 0;
    ErrorIntervalCollector errorIntervalCollector = new ErrorIntervalCollector();
    long currRollupCaptureTime = Long.MIN_VALUE;
    for (SyntheticResult nonRolledUpSyntheticResult : orderedNonRolledUpSyntheticResults) {
        long captureTime = nonRolledUpSyntheticResult.captureTime();
        long rollupCaptureTime = rollupCaptureTimeFn.apply(captureTime);
        if (rollupCaptureTime != currRollupCaptureTime && executionCount > 0) {
            rolledUpSyntheticResults.add(ImmutableSyntheticResult.builder().captureTime(currRollupCaptureTime)
                    .totalDurationNanos(totalDurationNanos).executionCount(executionCount)
                    .errorIntervals(errorIntervalCollector.getMergedErrorIntervals()).build());
            totalDurationNanos = 0;//w w w . j  a  v  a 2 s .co m
            executionCount = 0;
            errorIntervalCollector = new ErrorIntervalCollector();
        }
        currRollupCaptureTime = rollupCaptureTime;
        totalDurationNanos += nonRolledUpSyntheticResult.totalDurationNanos();
        executionCount += nonRolledUpSyntheticResult.executionCount();
        List<ErrorInterval> errorIntervals = nonRolledUpSyntheticResult.errorIntervals();
        if (errorIntervals.isEmpty()) {
            errorIntervalCollector.addGap();
        } else {
            errorIntervalCollector.addErrorIntervals(errorIntervals);
        }
    }
    if (executionCount > 0) {
        // roll up final one
        long lastCaptureTime = Iterables.getLast(orderedNonRolledUpSyntheticResults).captureTime();
        rolledUpSyntheticResults.add(ImmutableSyntheticResult.builder().captureTime(lastCaptureTime)
                .totalDurationNanos(totalDurationNanos).executionCount(executionCount)
                .errorIntervals(errorIntervalCollector.getMergedErrorIntervals()).build());
    }
    return rolledUpSyntheticResults;
}

From source file:org.apache.cassandra.index.sasi.plan.Operation.java

@VisibleForTesting
protected static ListMultimap<ColumnDefinition, Expression> analyzeGroup(QueryController controller,
        OperationType op, List<RowFilter.Expression> expressions) {
    ListMultimap<ColumnDefinition, Expression> analyzed = ArrayListMultimap.create();

    // sort all of the expressions in the operation by name and priority of the logical operator
    // this gives us an efficient way to handle inequality and combining into ranges without extra processing
    // and converting expressions from one type to another.
    Collections.sort(expressions, (a, b) -> {
        int cmp = a.column().compareTo(b.column());
        return cmp == 0 ? -Integer.compare(getPriority(a.operator()), getPriority(b.operator())) : cmp;
    });/*  w ww. j  a v  a2  s  . co  m*/

    for (final RowFilter.Expression e : expressions) {
        ColumnIndex columnIndex = controller.getIndex(e);
        List<Expression> perColumn = analyzed.get(e.column());

        if (columnIndex == null)
            columnIndex = new ColumnIndex(controller.getKeyValidator(), e.column(), null);

        AbstractAnalyzer analyzer = columnIndex.getAnalyzer();
        analyzer.reset(e.getIndexValue());

        // EQ/LIKE_*/NOT_EQ can have multiple expressions e.g. text = "Hello World",
        // becomes text = "Hello" OR text = "World" because "space" is always interpreted as a split point (by analyzer),
        // NOT_EQ is made an independent expression only in case of pre-existing multiple EQ expressions, or
        // if there is no EQ operations and NOT_EQ is met or a single NOT_EQ expression present,
        // in such case we know exactly that there would be no more EQ/RANGE expressions for given column
        // since NOT_EQ has the lowest priority.
        boolean isMultiExpression = false;
        switch (e.operator()) {
        case EQ:
            isMultiExpression = false;
            break;

        case LIKE_PREFIX:
        case LIKE_SUFFIX:
        case LIKE_CONTAINS:
        case LIKE_MATCHES:
            isMultiExpression = true;
            break;

        case NEQ:
            isMultiExpression = (perColumn.size() == 0 || perColumn.size() > 1
                    || (perColumn.size() == 1 && perColumn.get(0).getOp() == Op.NOT_EQ));
            break;
        }

        if (isMultiExpression) {
            while (analyzer.hasNext()) {
                final ByteBuffer token = analyzer.next();
                perColumn.add(new Expression(controller, columnIndex).add(e.operator(), token));
            }
        } else
        // "range" or not-equals operator, combines both bounds together into the single expression,
        // iff operation of the group is AND, otherwise we are forced to create separate expressions,
        // not-equals is combined with the range iff operator is AND.
        {
            Expression range;
            if (perColumn.size() == 0 || op != OperationType.AND)
                perColumn.add((range = new Expression(controller, columnIndex)));
            else
                range = Iterables.getLast(perColumn);

            while (analyzer.hasNext())
                range.add(e.operator(), analyzer.next());
        }
    }

    return analyzed;
}

From source file:org.sonar.java.checks.StandardCharsetsConstantsCheck.java

private static Optional<ExpressionTree> getCharsetNameArgument(Symbol symbol, Arguments arguments) {
    List<ExpressionTree> stringArguments = arguments.stream()
            .filter(argument -> argument.symbolType().is(JAVA_LANG_STRING)).collect(Collectors.toList());
    if (stringArguments.isEmpty()) {
        return Optional.empty();
    }/*from   w w w  .j  a va  2s  .  c  o  m*/
    if (stringArguments.size() == 1) {
        return Optional.of(stringArguments.get(0));
    }
    switch (getMethodRef(symbol)) {
    case "FileUtils.writeStringToFile":
    case "IOUtils.toInputStream":
    case "IOUtils.write":
    case "IOUtils.writeLines":
        return Optional.of(Iterables.getLast(stringArguments));
    case "LockableFileWriter.<init>":
        return Optional.of(stringArguments.get(0));
    default:
        return Optional.empty();
    }
}

From source file:com.marand.thinkmed.medications.administration.impl.AdministrationTaskCreatorImpl.java

private List<NewTaskRequestDto> createTasksForVariableContinuousInfusion(final String patientId,
        final VariableComplexTherapyDto therapy, final Interval taskCreationInterval,
        final AdministrationTaskCreateActionEnum action, final DateTime lastTaskTimestamp,
        final DateTime actionTimestamp) {
    final DateTime therapyStart = therapy.getStart();

    final Map<HourMinuteDto, TherapyDoseDto> timesWithDosesMap = getTimesDosesMapForVariableTherapies(therapy);

    final HourMinuteDto lastChangeHourMinute = Iterables.getLast(timesWithDosesMap.keySet());

    final boolean isTwoDayInfusion = therapyStart.isAfter(
            therapyStart.withTime(lastChangeHourMinute.getHour(), lastChangeHourMinute.getMinute(), 0, 0));
    final DateTime lastChangeTime = isTwoDayInfusion
            ? therapyStart.withTime(lastChangeHourMinute.getHour(), lastChangeHourMinute.getMinute(), 0, 0)
                    .plusDays(1)/*from  w  w  w.  j a  v a 2  s.  com*/
            : therapyStart.withTime(lastChangeHourMinute.getHour(), lastChangeHourMinute.getMinute(), 0, 0);

    final HourMinuteDto firstChangeHourMinute = Iterables.getFirst(timesWithDosesMap.keySet(), null);

    final List<NewTaskRequestDto> taskRequests = new ArrayList<>();

    //noinspection OverlyComplexBooleanExpression
    final boolean createStartTask = action == AdministrationTaskCreateActionEnum.PRESCRIBE
            || action == AdministrationTaskCreateActionEnum.MODIFY_BEFORE_START
            || action == AdministrationTaskCreateActionEnum.PREVIEW_TIMES_ON_NEW_PRESCRIPTION
            || action == AdministrationTaskCreateActionEnum.MODIFY
            || (action == AdministrationTaskCreateActionEnum.AUTO_CREATE && lastTaskTimestamp == null);

    if (createStartTask) {
        final TherapyDoseDto dose = timesWithDosesMap.get(firstChangeHourMinute);

        final NewTaskRequestDto startTaskRequest = createMedicationTaskRequest(patientId, therapy,
                AdministrationTypeEnum.START, therapyStart, dose);
        taskRequests.add(startTaskRequest);
    } else if (action == AdministrationTaskCreateActionEnum.REISSUE) {
        final TherapyDoseDto dose;
        final DateTime restartTime;
        if (actionTimestamp.isBefore(therapyStart)) {
            dose = timesWithDosesMap.get(firstChangeHourMinute);
            restartTime = therapyStart;
        } else if (actionTimestamp.isAfter(lastChangeTime)) {
            dose = timesWithDosesMap.get(lastChangeHourMinute);
            restartTime = actionTimestamp;
        } else {
            dose = getPreviousAdministrationTimeWithDose(actionTimestamp, timesWithDosesMap, true).getSecond();
            restartTime = actionTimestamp;
        }
        final NewTaskRequestDto startTaskRequest = createMedicationTaskRequest(patientId, therapy,
                AdministrationTypeEnum.START, restartTime, dose);
        taskRequests.add(startTaskRequest);
    }

    Pair<DateTime, TherapyDoseDto> nextTimeWithDose = getNextAdministrationTimeWithDose(action, therapy,
            therapyStart, timesWithDosesMap, false);

    while (!nextTimeWithDose.getFirst().isAfter(taskCreationInterval.getEnd())
            && !nextTimeWithDose.getFirst().isAfter(lastChangeTime)) {
        if (nextTimeWithDose.getFirst().isAfter(taskCreationInterval.getStart())) {
            taskRequests
                    .add(createMedicationTaskRequest(patientId, therapy, AdministrationTypeEnum.ADJUST_INFUSION,
                            nextTimeWithDose.getFirst(), nextTimeWithDose.getSecond()));
        }
        nextTimeWithDose = getNextAdministrationTimeWithDose(action, therapy, nextTimeWithDose.getFirst(),
                timesWithDosesMap, false);
    }

    final DateTime therapyEnd = therapy.getEnd();
    if (therapyEnd != null && !therapyEnd.isAfter(taskCreationInterval.getEnd())) {
        final NewTaskRequestDto endTaskRequest = createMedicationTaskRequest(patientId, therapy,
                AdministrationTypeEnum.STOP, therapyEnd, null);
        taskRequests.add(endTaskRequest);
    }
    return taskRequests;
}

From source file:org.jclouds.gogrid.GoGridLiveTestDisabled.java

/**
 * Tests common server image operations.
 *//* www  .jav  a2s . c o m*/
@Test(enabled = true)
public void testImageLifecycle() {
    GetImageListOptions options = GetImageListOptions.Builder.publicDatabaseServers();
    Set<ServerImage> images = api.getImageServices().getImageList(options);

    Predicate<ServerImage> isDatabaseServer = new Predicate<ServerImage>() {
        @Override
        public boolean apply(@Nullable ServerImage serverImage) {
            return checkNotNull(serverImage).getType() == ServerImageType.DATABASE_SERVER;
        }
    };

    assert Iterables.all(images, isDatabaseServer) : "All of the images should've been of database type";

    ServerImage image = Iterables.getLast(images);
    ServerImage imageFromServer = Iterables
            .getOnlyElement(api.getImageServices().getImagesByName(image.getName()));
    assertEquals(image, imageFromServer);

    try {
        api.getImageServices().editImageDescription(image.getName(), "newDescription");
        throw new TestException(
                "An exception hasn't been thrown where expected; expected GoGridResponseException");
    } catch (GoGridResponseException e) {
        // expected situation - check and proceed
        assertTrue(e.getMessage().contains("GoGridIllegalArgumentException"));
    }

}

From source file:org.kiji.rest.ManagedKijiClient.java

/**
 * Update the instances served by this ManagedKijiClient.
 *
 * @throws IOException if an instance can not be added to the cache.
 *///  w  w w. j  a  va2 s  . c o m
public void refreshInstances() throws IOException {
    final State state = mState.get();
    Preconditions.checkState(state == State.STARTED, "Can not invalidate instance while in state %s.", state);
    LOG.info("Refreshing instances.");

    Set<String> instances = Sets.newHashSet();

    // If the visible instances configured is not specified OR it's not empty then
    // iterate on the ZK instances to find the valid instances and make them accessible
    // by KijiREST keeping only the ones that were specified in the config.
    if (mVisibleKijiInstances == null || !mVisibleKijiInstances.isEmpty()) {
        for (ChildData node : mZKInstances.getCurrentData()) {
            instances.add(Iterables.getLast(Splitter.on('/').split(node.getPath())));
        }

        if (mVisibleKijiInstances != null) {
            // Keep the intersection of the visible and actual sets.
            instances.retainAll(mVisibleKijiInstances);
        }
    }
    final ImmutableSet.Builder<String> instancesBuilder = ImmutableSet.builder();
    instancesBuilder.addAll(instances);
    mKijiInstances = instancesBuilder.build();
}

From source file:org.apache.cassandra.db.index.sasi.plan.Operation.java

@VisibleForTesting
protected static ListMultimap<ByteBuffer, Expression> analyzeGroup(QueryController controller,
        final AbstractType<?> comparator, OperationType op, List<IndexExpression> expressions) {
    ListMultimap<ByteBuffer, Expression> analyzed = ArrayListMultimap.create();

    // sort all of the expressions in the operation by name and priority of the logical operator
    // this gives us an efficient way to handle inequality and combining into ranges without extra processing
    // and converting expressions from one type to another.
    Collections.sort(expressions, new Comparator<IndexExpression>() {
        @Override/* w  w  w . ja  va2  s  . c o  m*/
        public int compare(IndexExpression a, IndexExpression b) {
            int cmp = comparator.compare(ByteBuffer.wrap(a.getColumn_name()),
                    ByteBuffer.wrap(b.getColumn_name()));
            return cmp == 0 ? -Integer.compare(getPriority(a.getOp()), getPriority(b.getOp())) : cmp;
        }
    });

    for (final IndexExpression e : expressions) {
        if (e.isSetLogicalOp())
            continue;

        ByteBuffer name = ByteBuffer.wrap(e.getColumn_name());
        ColumnIndex columnIndex = controller.getIndex(name);

        List<Expression> perColumn = analyzed.get(name);

        if (columnIndex == null) {
            ColumnDefinition nonIndexedColumn = controller.getColumn(name);
            columnIndex = new ColumnIndex(controller.getKeyValidator(), nonIndexedColumn,
                    controller.getComparator(nonIndexedColumn));
        }

        AbstractAnalyzer analyzer = columnIndex.getAnalyzer();
        analyzer.reset(ByteBuffer.wrap(e.getValue()));

        // EQ/NOT_EQ can have multiple expressions e.g. text = "Hello World",
        // becomes text = "Hello" OR text = "World" because "space" is always interpreted as a split point (by analyzer),
        // NOT_EQ is made an independent expression only in case of pre-existing multiple EQ expressions, or
        // if there is no EQ operations and NOT_EQ is met or a single NOT_EQ expression present,
        // in such case we know exactly that there would be no more EQ/RANGE expressions for given column
        // since NOT_EQ has the lowest priority.
        if (e.getOp() == IndexOperator.EQ || (e.getOp() == IndexOperator.NOT_EQ && (perColumn.size() == 0
                || perColumn.size() > 1 || (perColumn.size() == 1 && perColumn.get(0).getOp() == Op.NOT_EQ)))) {
            while (analyzer.hasNext()) {
                final ByteBuffer token = analyzer.next();
                perColumn.add(new Expression(controller, columnIndex) {
                    {
                        add(e.op, token);
                    }
                });
            }
        } else
        // "range" or not-equals operator, combines both bounds together into the single expression,
        // iff operation of the group is AND, otherwise we are forced to create separate expressions,
        // not-equals is combined with the range iff operator is AND.
        {
            Expression range;
            if (perColumn.size() == 0 || op != OperationType.AND)
                perColumn.add((range = new Expression(controller, columnIndex)));
            else
                range = Iterables.getLast(perColumn);

            while (analyzer.hasNext())
                range.add(e.op, analyzer.next());
        }
    }

    return analyzed;
}

From source file:org.apache.stratos.cloud.controller.iaases.ec2.EC2Iaas.java

@Override
public synchronized List<String> associateAddresses(NodeMetadata node) {
    IaasProvider iaasInfo = getIaasProvider();
    ComputeServiceContext context = iaasInfo.getComputeService().getContext();
    ElasticIPAddressApi elasticIPAddressApi = context.unwrapApi(AWSEC2Api.class).getElasticIPAddressApi().get();
    String region = ComputeServiceBuilderUtil.extractRegion(iaasInfo);
    String ip = null;// w w  w  .  j a  va2  s  . c om

    // first try to find an unassigned IP.
    ArrayList<PublicIpInstanceIdPair> unassignedIps = Lists.newArrayList(Iterables.filter(
            elasticIPAddressApi.describeAddressesInRegion(region), new Predicate<PublicIpInstanceIdPair>() {

                @Override
                public boolean apply(PublicIpInstanceIdPair arg0) {
                    return arg0.getInstanceId() == null;
                }

            }));

    if (!unassignedIps.isEmpty()) {
        // try to prevent multiple parallel launches from choosing the same
        // ip.
        Collections.shuffle(unassignedIps);
        ip = Iterables.getLast(unassignedIps).getPublicIp();
    }

    // if no unassigned IP is available, we'll try to allocate an IP.
    if (ip == null || ip.isEmpty()) {
        try {
            ip = elasticIPAddressApi.allocateAddressInRegion(region);
            log.info("Allocated ip [" + ip + "]");

        } catch (Exception e) {
            String msg = "Failed to allocate an IP address. All IP addresses are in use.";
            log.error(msg, e);
            throw new CloudControllerException(msg, e);
        }
    }

    String id = node.getProviderId();

    // wait till the fixed IP address gets assigned - this is needed before
    // we associate a
    // public IP

    while (node.getPrivateAddresses() == null) {
        CloudControllerUtil.sleep(1000);
    }

    int retries = 0;
    while (retries < 12 && !associatePublicIp(elasticIPAddressApi, region, ip, id)) {

        // wait for 5s
        CloudControllerUtil.sleep(5000);
        retries++;
    }

    log.debug("Successfully associated an IP address " + ip + " for node with id: " + node.getId());

    List<String> associatedIPs = new ArrayList<String>();
    associatedIPs.add(ip);
    return associatedIPs;

}

From source file:org.obm.push.mail.EmailViewPartsFetcherImpl.java

@VisibleForTesting
Organizer organizerFallback(EmailMetadata emailMetadata) {
    List<Address> fromList = emailMetadata.getEnvelope().getFrom();
    if (!fromList.isEmpty()) {
        return addressToOrganizer(Iterables.getLast(fromList));
    }/*from w ww.j  a v a  2s . c  o m*/
    return null;
}

From source file:com.haulmont.cuba.gui.components.EditorWindowDelegate.java

public void validateAdditionalRules(ValidationErrors errors) {
    // all previous validations return no errors
    if (crossFieldValidate && errors.isEmpty()) {
        BeanValidation beanValidation = AppBeans.get(BeanValidation.NAME);

        Validator validator = beanValidation.getValidator();
        Set<ConstraintViolation<Entity>> violations = validator.validate(getItem(), UiCrossFieldChecks.class);

        violations.stream().filter(violation -> {
            Path propertyPath = violation.getPropertyPath();

            Path.Node lastNode = Iterables.getLast(propertyPath);
            return lastNode.getKind() == ElementKind.BEAN;
        }).forEach(violation -> errors.add(violation.getMessage()));
    }/*from   w ww .  j  a v a  2s  .  co  m*/
}