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.peletomi.vax.impl.StringArrayExtractorFrontEnd.java

@Override
public Map<String, String[]> getExtracted() {
    final Map<String, LinkedList<String>> result = new HashMap<String, LinkedList<String>>();
    for (final ImmutableList<String> keys : values.keySet()) {
        String key;/*from w  w  w.ja v a  2 s .c om*/
        if (qualified) {
            key = Joiner.on(keySeparator).join(keys);
        } else {
            key = Iterables.getLast(keys);
        }
        if (!result.containsKey(key)) {
            result.put(key, new LinkedList<String>());
        }
        result.put(key, values.get(keys));
    }
    return Maps.transformValues(result, TO_ARRAY);
}

From source file:com.lyndir.lhunath.snaplog.model.service.impl.AWSSourceServiceImpl.java

@Override
public void loadMedia(final SSecurityToken token, final S3Source source) throws PermissionDeniedException {

    checkNotNull(source, "Given source must not be null.");
    securityService.assertAccess(Permission.ADMINISTER, token, source);

    // Fetch objects at all qualities from S3
    Map<String, Map<Quality, S3Object>> mediaObjects = Maps.newHashMap();
    for (final Quality quality : Quality.values()) {

        for (final S3Object s3Object : awsService.listObjects(getObjectKey(source, quality))) {

            if (!s3Object.getKey().endsWith(".jpg"))
                // Ignore files that don't have a valid media name.
                continue;

            String mediaName = Iterables.getLast(Splitter.on('/').split(s3Object.getKey()));
            if (mediaName.startsWith("."))
                // Ignore hidden files.
                continue;

            Map<Quality, S3Object> qualityObjects = mediaObjects.get(mediaName);
            if (qualityObjects == null)
                mediaObjects.put(mediaName, qualityObjects = Maps.newHashMap());
            qualityObjects.put(quality, s3Object);
        }//from w w  w .j  a  va2  s .c  o m
    }

    // Find all existing media that is not contained in the set of media fetched from S3
    // These are media that have been removed from S3 since the last sync; purge them.
    logger.dbg("Looking for media to purge...");
    ImmutableMap.Builder<String, Media> existingMediaBuilder = ImmutableMap.builder();
    for (final Media media : mediaDAO.listMedia(source, true))
        existingMediaBuilder.put(media.getName(), media);
    ImmutableMap<String, Media> existingMedia = existingMediaBuilder.build();
    Set<Media> purgeMedia = Sets.newHashSet(existingMedia.values());
    for (final String mediaName : mediaObjects.keySet()) {
        Media media = existingMedia.get(mediaName);
        if (media != null)
            // This media was found in S3's list of current media data; don't purge it.
            purgeMedia.remove(media);
    }
    logger.dbg("Purging %d / %d media from db", purgeMedia.size(), existingMedia.size());
    mediaDAO.delete(purgeMedia);

    int o = 0;
    for (final Map.Entry<String, Map<Quality, S3Object>> mediaObjectsEntry : mediaObjects.entrySet()) {
        if (o++ % 100 == 0)
            logger.dbg("Loading media %d / %d", ++o, mediaObjects.size());

        String mediaName = mediaObjectsEntry.getKey();
        Map<Quality, S3Object> qualityObjects = mediaObjectsEntry.getValue();

        S3Media media = mediaDAO.findMedia(source, mediaName);
        if (media == null)
            media = new S3Media(source, mediaName);

        // Create/update mediaData for the object.
        for (final Map.Entry<Quality, S3Object> qualityObjectsEntry : qualityObjects.entrySet()) {
            Quality quality = qualityObjectsEntry.getKey();
            S3Object mediaObject = qualityObjectsEntry.getValue();

            setMediaData(media, quality, mediaObject);
        }
    }
}

From source file:org.sonar.javascript.checks.ExpressionComplexityCheck.java

@Override
public void visitNode(Tree tree) {
    if (tree.is(CONDITIONAL_EXPRS)) {
        Iterables.getLast(statementLevel).incrementNestedExprLevel();
        Iterables.getLast(statementLevel).addOperator(getOperatorToken(tree));

    } else if (tree.is(SCOPES)) {
        statementLevel.add(new ExpressionComplexity());
    }//from ww w  .  ja  va 2  s .  c om
}

From source file:com.google.auto.value.processor.escapevelocity.Reparser.java

/**
 * Returns a copy of the given list where spaces have been moved where appropriate after {@code
 * #set}. This hack is needed to match what appears to be special treatment in Apache Velocity of
 * spaces before {@code #set} directives. If you have <i>thing</i> <i>whitespace</i> {@code #set},
 * then the whitespace is deleted if the <i>thing</i> is a comment ({@code ##...\n}); a reference
 * ({@code $x} or {@code $x.foo} etc); a macro definition; or another {@code #set}.
 *///from w ww  .j  a v  a2s  .  co m
private static ImmutableList<Node> removeSpaceBeforeSet(ImmutableList<Node> nodes) {
    assert Iterables.getLast(nodes) instanceof EofNode;
    // Since the last node is EofNode, the i + 1 and i + 2 accesses below are safe.
    ImmutableList.Builder<Node> newNodes = ImmutableList.builder();
    for (int i = 0; i < nodes.size(); i++) {
        Node nodeI = nodes.get(i);
        newNodes.add(nodeI);
        if (shouldDeleteSpaceBetweenThisAndSet(nodeI) && isWhitespaceLiteral(nodes.get(i + 1))
                && nodes.get(i + 2) instanceof SetNode) {
            // Skip the space.
            i++;
        }
    }
    return newNodes.build();
}

From source file:com.github.fge.jsonpatch.operation.AddOperation.java

protected JsonNode addToObject(final JsonPointer path, final JsonNode node) {
    final JsonNode ret = node.deepCopy();
    final ObjectNode target = (ObjectNode) path.parent().get(ret);
    target.put(Iterables.getLast(path).getToken().getRaw(), value);
    return ret;//from  w w w  . ja va 2s.  c  o  m
}

From source file:com.android.tools.idea.editors.theme.attributes.editors.DrawableRendererEditor.java

@Override
protected void updateComponent(@NotNull ThemeEditorContext context, @NotNull ResourceComponent component,
        @NotNull EditedStyleItem item) {
    assert context.getResourceResolver() != null;

    // Set a maximum size to avoid rendering big previews that then we will scale down to the size of the swatch icon.
    Dimension iconSize = component.getSwatchIconSize();
    // When the component it's been created but hasn't been added to the table yet, it might report a 0 size, so we set a minimum size.
    int iconWidth = Math.max(iconSize.width, MIN_DRAWABLE_PREVIEW_SIZE);
    int iconHeight = Math.max(iconSize.height, MIN_DRAWABLE_PREVIEW_SIZE);

    if (myRenderTask == null || myRenderTask.getModule() != context.getCurrentContextModule()) {
        myRenderTask = configureRenderTask(context.getCurrentContextModule(), context.getConfiguration());
    }//from   w w  w.j  av a2s.c o m

    myRenderTask.setMaxRenderSize(iconWidth, iconHeight);
    List<BufferedImage> images = myRenderTask.renderDrawableAllStates(item.getSelectedValue());
    SwatchComponent.SwatchIcon icon;
    if (images.isEmpty()) {
        icon = SwatchComponent.WARNING_ICON;
    } else {
        icon = new SwatchComponent.SquareImageIcon(Iterables.getLast(images));
        icon.setIsStack(images.size() > 1);
    }
    component.setSwatchIcon(icon);

    String nameText = String.format(ThemeEditorConstants.ATTRIBUTE_LABEL_TEMPLATE,
            ColorUtil.toHex(ThemeEditorConstants.RESOURCE_ITEM_COLOR), ThemeEditorUtils.getDisplayHtml(item));
    component.setNameText(nameText);
    component.setValueText(item.getValue());
}

From source file:brooklyn.location.waratek.WaratekMachineLocation.java

@Override
public WaratekContainerLocation obtain(Map<?, ?> flags) throws NoMachinesAvailableException {
    Integer maxSize = jvm.getConfig(JavaVirtualMachine.JVC_CLUSTER_MAX_SIZE);
    Integer currentSize = jvm.getAttribute(WaratekAttributes.JVC_COUNT);
    Iterable<Entity> available = jvm.getAvailableJvcs();
    Entity entity = (Entity) flags.get("entity");
    if (LOG.isDebugEnabled()) {
        LOG.debug("JVM {}: {} containers, {} available, max {}",
                new Object[] { jvm.getJvmName(), currentSize, Iterables.size(available), maxSize });
    }//from w w w . j ava2s.c  o m

    // also try to satisfy the affinty rules etc.

    // If there are no stopped JVCs then add a new one
    if (Iterables.isEmpty(available)) {
        if (currentSize != null && currentSize >= maxSize) {
            throw new NoMachinesAvailableException(
                    String.format("Limit of %d containers reached at %s", maxSize, jvm.getJvmName()));
        }

        // increase size of JVC cluster
        DynamicCluster cluster = jvm.getJvcCluster();
        Optional<Entity> added = cluster.addInSingleLocation(this, MutableMap.of("entity", entity));
        if (!added.isPresent()) {
            throw new NoMachinesAvailableException(
                    String.format("Failed to create containers reached in %s", jvm.getJvmName()));
        }
        return ((JavaVirtualContainer) added.get()).getDynamicLocation();
    } else {
        WaratekContainerLocation container = ((JavaVirtualContainer) Iterables.getLast(available))
                .getDynamicLocation();
        container.setEntity(entity);
        return container;
    }
}

From source file:org.apache.aurora.scheduler.async.TaskHistoryPruner.java

/**
 * When triggered, records an inactive task state change.
 *
 * @param change Event when a task changes state.
 *///  w w w  .  j a  va  2  s  .com
@Subscribe
public void recordStateChange(TaskStateChange change) {
    if (Tasks.isTerminated(change.getNewState())) {
        long timeoutBasis = change.isTransition() ? clock.nowMillis()
                : Iterables.getLast(change.getTask().getTaskEvents()).getTimestamp();
        registerInactiveTask(Tasks.SCHEDULED_TO_JOB_KEY.apply(change.getTask()), change.getTaskId(),
                calculateTimeout(timeoutBasis));
    }
}

From source file:com.netflix.paas.cassandra.resources.AstyanaxThriftDataTableResource.java

@Override
public QueryResult listRows(String cursor, Integer rowLimit, Integer columnLimit) throws PaasException {
    try {/* ww w  .  j  ava 2s  . com*/
        invariant();

        // Execute the query
        Partitioner partitioner = keyspace.getPartitioner();
        Rows<ByteBuffer, ByteBuffer> result = keyspace.prepareQuery(columnFamily).getKeyRange(null, null,
                cursor != null ? cursor : partitioner.getMinToken(), partitioner.getMaxToken(), rowLimit)
                .execute().getResult();

        // Convert raw data into a simple sparse tree
        SchemalessRows.Builder builder = SchemalessRows.builder();
        for (Row<ByteBuffer, ByteBuffer> row : result) {
            Map<String, String> columns = Maps.newHashMap();
            for (Column<ByteBuffer> column : row.getColumns()) {
                columns.put(serializers.columnAsString(column.getRawName()),
                        serializers.valueAsString(column.getRawName(), column.getByteBufferValue()));
            }
            builder.addRow(serializers.keyAsString(row.getKey()), columns);
        }

        QueryResult dr = new QueryResult();
        dr.setSrows(builder.build());

        if (!result.isEmpty()) {
            dr.setCursor(partitioner.getTokenForKey(Iterables.getLast(result).getKey()));
        }
        return dr;
    } catch (ConnectionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

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

@Override
public Description matchClass(ClassTree tree, VisitorState state) {
    if (!IS_BUGCHECKER.matches(tree, state)) {
        return NO_MATCH;
    }//from   ww w . ja v  a  2 s  .c  om

    AnnotationTree bugPatternAnnotation = ASTHelpers
            .getAnnotationWithSimpleName(tree.getModifiers().getAnnotations(), "BugPattern");
    if (bugPatternAnnotation == null) {
        return NO_MATCH;
    }

    if (!providesFix(tree, state)) {
        // N.B. BugCheckers can provide a fix in ways we cannot detect.
        // Ignore checkers that don't appear to have a fix, but are labeled as having one.
        return NO_MATCH;
    }

    SuggestedFix.Builder fixBuilder = SuggestedFix.builder()
            .addImport("com.google.errorprone.BugPattern.ProvidesFix");
    ExpressionTree providesFixArgument = AnnotationMatcherUtils.getArgument(bugPatternAnnotation,
            "providesFix");
    if (providesFixArgument == null) {
        // If providesFix argument not already present, add it to the end of @BugPattern args.
        fixBuilder.postfixWith(Iterables.getLast(bugPatternAnnotation.getArguments()),
                ", providesFix = ProvidesFix." + REQUIRES_HUMAN_ATTENTION.name());
    } else {
        if (!getSymbol(providesFixArgument).getSimpleName().contentEquals(NO_FIX.name())) {
            // If providesFix arg already states there is a fix, we're good.
            return NO_MATCH;
        }
        // If providesFix arg incorrectly states there is no fix, correct it.
        fixBuilder.replace(providesFixArgument, "ProvidesFix." + REQUIRES_HUMAN_ATTENTION.name());
    }
    return describeMatch(bugPatternAnnotation, fixBuilder.build());
}