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:com.google.errorprone.bugpatterns.collectionincompatibletype.CompatibleWithMisuse.java

@Override
public Description matchAnnotation(AnnotationTree annoTree, VisitorState state) {
    if (!IS_COMPATIBLE_WITH_ANNOTATION.matches(annoTree, state)) {
        return Description.NO_MATCH;
    }/*w  ww.  ja va  2 s .c  o m*/

    // Hunt for type args on the declared method
    // TODO(glorioso): Once annotation is TYPE_USE, make sure that the node is actually a method
    // parameter
    MethodTree methodTree = ASTHelpers.findEnclosingNode(state.getPath(), MethodTree.class);
    VariableTree paramTree = ASTHelpers.findEnclosingNode(state.getPath(), VariableTree.class);
    MethodSymbol declaredMethod = ASTHelpers.getSymbol(methodTree);

    // We're disallowing tags on varargs methods for now, but we may revisit it in the future.
    if (declaredMethod.isVarArgs() && Iterables.getLast(methodTree.getParameters()) == paramTree) {
        return describeWithMessage(annoTree, "@CompatibleWith can't be used on a varargs parameter");
    }

    // If this method overrides other methods, ensure that none of them have @CompatibleWith.
    // This restriction may need to be removed to allow more complex declaration hierarchies.
    for (MethodSymbol methodSymbol : ASTHelpers.findSuperMethods(declaredMethod, state.getTypes())) {
        if (methodSymbol.params().stream()
                .anyMatch(p -> ASTHelpers.hasAnnotation(p, CompatibleWith.class, state))) {
            return describeWithMessage(annoTree,
                    String.format("This method overrides a method in %s that already has @CompatibleWith",
                            methodSymbol.owner.getSimpleName()));
        }
    }

    List<TypeVariableSymbol> potentialTypeVars = new ArrayList<>(declaredMethod.getTypeParameters());

    // Check enclosing types (not superclasses)
    ClassSymbol cs = (ClassSymbol) declaredMethod.owner;
    do {
        potentialTypeVars.addAll(cs.getTypeParameters());
        cs = cs.isInner() ? cs.owner.enclClass() : null;
    } while (cs != null);

    if (potentialTypeVars.isEmpty()) {
        return describeWithMessage(annoTree, "There are no type arguments in scope to match against.");
    }

    Set<String> validNames = potentialTypeVars.stream().map(TypeVariableSymbol::getSimpleName)
            .map(Object::toString).collect(Collectors.toCollection(LinkedHashSet::new));
    String constValue = valueArgumentFromCompatibleWithAnnotation(annoTree);

    if (constValue == null || constValue.isEmpty()) {
        return describeWithMessage(annoTree,
                String.format("The value of @CompatibleWith must not be empty (valid arguments are %s)",
                        printTypeArgs(validNames)));
    }

    return validNames.contains(constValue) ? Description.NO_MATCH
            : describeWithMessage(annoTree,
                    String.format("%s is not a valid type argument. Valid arguments are: %s", constValue,
                            printTypeArgs(validNames)));
}

From source file:com.cloudera.cdk.data.filesystem.PathConversion.java

public String valueStringForDirname(String name) {
    return Iterables.getLast(PART_SEP.split(name));
}

From source file:is.illuminati.block.spyros.garmin.model.Activity.java

private TrackPoint getLastTrackPoint() {
    Lap lastLap = Iterables.getLast(laps);
    return Iterables.getLast(lastLap.getTrackPoints());
}

From source file:com.github.tmyroadctfig.icloud4j.DriveNode.java

/**
 * Downloads the file data for the item into the given output stream.
 *
 * @param outputStream the output stream to write to.
 */// w  w w.  j a  va  2  s .  co  m
public void downloadFileData(OutputStream outputStream) {
    try {
        URIBuilder uriBuilder = new URIBuilder(
                String.format("%s/ws/%s/download/by_id", driveService.getDocsServiceUrl(), nodeDetails.zone));
        iCloudService.populateUriParameters(uriBuilder);
        uriBuilder.addParameter("clientMasteringNumber", iCloudService.getClientBuildNumber());
        uriBuilder.addParameter("document_id", Iterables.getLast(Splitter.on(":").splitToList(id)));
        uriBuilder.addParameter("token", downloadUrlToken);
        URI contentUrlLookupUrl = uriBuilder.build();

        // Get the download URL for the item
        HttpGet contentUrlGetRequest = new HttpGet(contentUrlLookupUrl);
        iCloudService.populateRequestHeadersParameters(contentUrlGetRequest);

        Map<String, Object> result = iCloudService.getHttpClient().execute(contentUrlGetRequest,
                new JsonToMapResponseHandler());
        @SuppressWarnings("unchecked")
        Map<String, Object> dataTokenMap = (Map<String, Object>) result.get("data_token");

        String contentUrl = (String) dataTokenMap.get("url");
        HttpGet contentRequest = new HttpGet(contentUrl);

        try (InputStream inputStream = iCloudService.getHttpClient().execute(contentRequest).getEntity()
                .getContent()) {
            IOUtils.copyLarge(inputStream, outputStream, new byte[0x10000]);
        }
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

From source file:com.google.template.soy.passes.ResolvePackageRelativeCssNamesPass.java

private void resolveSelector(TemplateNode template, FunctionNode node, @Nullable String packagePrefix) {
    if (node.getSoyFunction() != BuiltinFunction.CSS) {
        return;//from   w  ww  .  j av a 2s .co  m
    }

    ExprNode lastChild = Iterables.getLast(node.getChildren());
    if (!(lastChild instanceof StringNode)) {
        // this will generate an error in CheckFunctionCallsVisitor
        return;
    }

    StringNode selector = (StringNode) Iterables.getLast(node.getChildren());
    String selectorText = selector.getValue();
    if (!selectorText.startsWith(RELATIVE_SELECTOR_PREFIX)) {
        return;
    }

    if (node.numChildren() > 1) {
        errorReporter.report(selector.getSourceLocation(), PACKAGE_RELATIVE_CLASS_NAME_USED_WITH_COMPONENT_NAME,
                selectorText);
    }

    if (packagePrefix == null) {
        errorReporter.report(selector.getSourceLocation(), NO_CSS_PACKAGE, selectorText,
                template.getRequiredCssNamespaces().isEmpty() ? ""
                        : " NOTE: ''requirecss'' on a template is not used to infer the CSS package.");
    }

    // Replace the selector text with resolved selector text
    String prefixed = packagePrefix + selectorText.substring(RELATIVE_SELECTOR_PREFIX.length());
    StringNode newSelector = new StringNode(prefixed, QuoteStyle.SINGLE, selector.getSourceLocation());
    node.replaceChild(selector, newSelector);
}

From source file:org.sonar.php.checks.formatting.NamespaceAndUseStatementCheck.java

private void checkBlankLineAfterUses(UseStatementTree useStatement) {
    if (check.hasUseBlankLine && !isFollowedWithBlankLine(useStatement)) {
        reportIssue(BLANK_LINE_USE_MESSAGE, Iterables.getLast(useStatements));
    }//www .  j  a va2s .  co m
}

From source file:org.apache.aurora.scheduler.base.Tasks.java

public static ITaskEvent getLatestEvent(IScheduledTask task) {
    return Iterables.getLast(task.getTaskEvents());
}

From source file:com.comphenix.xp.parser.Utility.java

/**
 * Creates a shallow copy of the given section that is not referenced by the parent node.
 * @param section - the section to copy.
 * @return A copied configuration section.
 *///from w ww.  j a va2  s.co m
public static ConfigurationSection cloneSection(ConfigurationSection section) {

    MemorySection copy = null;

    // Is this the root node?
    if (section.getParent() == null) {
        if (!(section instanceof MemorySection)) {
            throw new IllegalArgumentException("Only memory configurations can be cloned.");
        }

        Configuration sourceConfig = (Configuration) section;
        Configuration copyConfig = new MemoryConfiguration(sourceConfig.getDefaults());

        try {
            // We're very unlikely to clone a root node in the first place, so who cares
            FieldUtils.writeField(copyConfig, "options", sourceConfig.options(), true);

        } catch (IllegalAccessException e) {
            throw new RuntimeException("Cannot modify options.", e);
        }

    } else {

        String path = Iterables.getLast(
                Splitter.on(section.getRoot().options().pathSeparator()).split(section.getCurrentPath()));
        copy = new ClonableMemorySection(section.getParent(), path);
    }

    // Copy every stored value
    for (String key : section.getKeys(false)) {
        copy.set(key, section.get(key));
    }

    return copy;
}

From source file:org.apache.stratos.cloud.controller.iaases.openstack.networking.NovaNetworkingApi.java

@Override
public List<String> associateAddresses(NodeMetadata node) {

    ComputeServiceContext context = iaasProvider.getComputeService().getContext();
    String region = ComputeServiceBuilderUtil.extractRegion(iaasProvider);

    if (StringUtils.isEmpty(region)) {
        throw new RuntimeException("Could not find region in iaas provider: " + iaasProvider.getName());
    }/* w ww  .j  a v  a2 s. c om*/

    NovaApi novaApi = context.unwrapApi(NovaApi.class);
    FloatingIPApi floatingIPApi = novaApi.getFloatingIPExtensionForZone(region).get();

    String ip = null;
    // first try to find an unassigned IP.
    FluentIterable<FloatingIP> floatingIPs = floatingIPApi.list();
    ArrayList<FloatingIP> unassignedIps = Lists
            .newArrayList(Iterables.filter(floatingIPs, new Predicate<FloatingIP>() {
                @Override
                public boolean apply(FloatingIP floatingIP) {
                    return floatingIP.getInstanceId() == null;
                }
            }));

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

    // if no unassigned IP is available, we'll try to allocate an IP.
    if (StringUtils.isEmpty(ip)) {
        String floatingIpPool = iaasProvider.getProperty(CloudControllerConstants.DEFAULT_FLOATING_IP_POOL);
        FloatingIP allocatedFloatingIP;
        if (StringUtils.isEmpty(floatingIpPool)) {
            allocatedFloatingIP = floatingIPApi.create();
        } else {
            log.debug(
                    String.format("Trying to allocate a floating IP address from IP pool %s", floatingIpPool));
            allocatedFloatingIP = floatingIPApi.allocateFromPool(floatingIpPool);
        }
        if (allocatedFloatingIP == null) {
            String msg = String.format("Floating IP API did not return a floating IP address from IP pool %s",
                    floatingIpPool);
            log.error(msg);
            throw new CloudControllerException(msg);
        }
        ip = allocatedFloatingIP.getIp();
    }

    // wait till the fixed IP address gets assigned - this is needed before
    // we associate a public IP
    log.info(String.format("Waiting for private IP addresses get allocated: [node-id] %s", node.getId()));
    while (node.getPrivateAddresses() == null) {
        CloudControllerUtil.sleep(1000);
    }
    log.info(String.format("Private IP addresses allocated: %s", node.getPrivateAddresses()));

    if ((node.getPublicAddresses() != null) && (node.getPublicAddresses().iterator().hasNext())) {
        log.info("Public IP address " + node.getPublicAddresses().iterator().next()
                + " is already allocated to the instance: [node-id]  " + node.getId());
        return null;
    }

    int retries = 0;
    int retryCount = Integer.getInteger("stratos.public.ip.association.retry.count", 5);
    while ((retries < retryCount) && (!associateIp(floatingIPApi, ip, node.getProviderId()))) {
        // wait for 5s
        CloudControllerUtil.sleep(5000);
        retries++;
    }

    log.info(String.format("Successfully associated an IP address: [node-id] %s [ip] %s", node.getId(), ip));

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

From source file:org.apache.metron.spout.pcap.HDFSWriterConfig.java

public Integer getZookeeperPort() {
    if (zookeeperQuorum != null) {
        String hostPort = Iterables.getFirst(Splitter.on(',').split(zookeeperQuorum), null);
        String portStr = Iterables.getLast(Splitter.on(':').split(hostPort));
        return Integer.parseInt(portStr);
    }/* www.  j  a  v a 2s .  c  om*/
    return null;
}