Example usage for com.google.common.collect ImmutableList isEmpty

List of usage examples for com.google.common.collect ImmutableList isEmpty

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableList isEmpty.

Prototype

boolean isEmpty();

Source Link

Document

Returns true if this list contains no elements.

Usage

From source file:org.glowroot.agent.plugin.servlet.DetailCapture.java

static ImmutableMap<String, Object> captureRequestHeaders(HttpServletRequest request) {
    ImmutableList<Pattern> capturePatterns = ServletPluginProperties.captureRequestHeaders();
    if (capturePatterns.isEmpty()) {
        return ImmutableMap.of();
    }//from   www  .j a  v a  2s  .c o  m
    Map<String, Object> requestHeaders = Maps.newHashMap();
    Enumeration</*@Nullable*/ String> headerNames = request.getHeaderNames();
    if (headerNames == null) {
        return ImmutableMap.of();
    }
    for (Enumeration</*@Nullable*/ String> e = headerNames; e.hasMoreElements();) {
        String name = e.nextElement();
        if (name == null) {
            continue;
        }
        // converted to lower case for case-insensitive matching (patterns are lower case)
        String keyLowerCase = name.toLowerCase(Locale.ENGLISH);
        if (!matchesOneOf(keyLowerCase, capturePatterns)) {
            continue;
        }
        Enumeration</*@Nullable*/ String> values = request.getHeaders(name);
        if (values != null) {
            captureRequestHeader(name, values, requestHeaders);
        }
    }
    return ImmutableMap.copyOf(requestHeaders);
}

From source file:com.google.devtools.build.lib.rules.android.NativeLibs.java

public static NativeLibs fromLinkedNativeDeps(RuleContext ruleContext, String nativeDepsFileName,
        Multimap<String, TransitiveInfoCollection> depsByArchitecture,
        Map<String, CcToolchainProvider> toolchainMap, Map<String, BuildConfiguration> configurationMap)
        throws InterruptedException {
    Map<String, Iterable<Artifact>> result = new LinkedHashMap<>();
    String nativeDepsLibraryBasename = null;
    for (Map.Entry<String, Collection<TransitiveInfoCollection>> entry : depsByArchitecture.asMap()
            .entrySet()) {/*  ww w .  j a  va 2  s. c om*/
        CcLinkParams linkParams = AndroidCommon
                .getCcLinkParamsStore(entry.getValue(),
                        ImmutableList.of("-Wl,-soname=lib" + ruleContext.getLabel().getName()))
                .get(/* linkingStatically */ true, /* linkShared */ true);

        Artifact nativeDepsLibrary = NativeDepsHelper.linkAndroidNativeDepsIfPresent(ruleContext, linkParams,
                configurationMap.get(entry.getKey()), toolchainMap.get(entry.getKey()));

        ImmutableList.Builder<Artifact> librariesBuilder = ImmutableList.builder();
        if (nativeDepsLibrary != null) {
            librariesBuilder.add(nativeDepsLibrary);
            nativeDepsLibraryBasename = nativeDepsLibrary.getExecPath().getBaseName();
        }
        librariesBuilder
                .addAll(filterUniqueSharedLibraries(ruleContext, nativeDepsLibrary, linkParams.getLibraries()));
        ImmutableList<Artifact> libraries = librariesBuilder.build();

        if (!libraries.isEmpty()) {
            result.put(entry.getKey(), libraries);
        }
    }
    if (result.isEmpty()) {
        return NativeLibs.EMPTY;
    } else if (nativeDepsLibraryBasename == null) {
        return new NativeLibs(ImmutableMap.copyOf(result), null);
    } else {
        // The native deps name file must be the only file in its directory because ApkBuilder does
        // not have an option to add a particular file to the .apk, only one to add every file in a
        // particular directory.
        Artifact nativeDepsName = ruleContext.getUniqueDirectoryArtifact("nativedeps_filename",
                nativeDepsFileName, ruleContext.getBinOrGenfilesDirectory());
        ruleContext.registerAction(
                FileWriteAction.create(ruleContext, nativeDepsName, nativeDepsLibraryBasename, false));

        return new NativeLibs(ImmutableMap.copyOf(result), nativeDepsName);
    }
}

From source file:com.google.devtools.build.lib.analysis.actions.CommandLine.java

/**
 * Returns a {@link CommandLine} that is constructed by prepending the {@code executableArgs} to
 * {@code commandLine}.// w ww  . jav  a 2s  . c o m
 */
static CommandLine ofMixed(final ImmutableList<String> executableArgs, final CommandLine commandLine,
        final boolean isShellCommand) {
    Preconditions.checkState(!executableArgs.isEmpty());
    return new CommandLine() {
        @Override
        public Iterable<String> arguments() {
            return Iterables.concat(executableArgs, commandLine.arguments());
        }

        @Override
        public Iterable<String> arguments(ArtifactExpander artifactExpander) {
            return Iterables.concat(executableArgs, commandLine.arguments(artifactExpander));
        }

        @Override
        public boolean isShellCommand() {
            return isShellCommand;
        }
    };
}

From source file:org.sosy_lab.cpachecker.util.resources.ResourceLimitChecker.java

/**
 * Create an instance of this class from some configuration options.
 * The returned instance is not started yet.
 *//*from   w ww .j  a  v a 2  s. co  m*/
public static ResourceLimitChecker fromConfiguration(Configuration config, LogManager logger,
        ShutdownNotifier notifier) throws InvalidConfigurationException {

    ResourceLimitOptions options = new ResourceLimitOptions();
    config.inject(options);

    ImmutableList.Builder<ResourceLimit> limits = ImmutableList.builder();
    if (options.walltime.compareTo(TimeSpan.empty()) >= 0) {
        limits.add(WalltimeLimit.fromNowOn(options.walltime));
    }
    if (options.cpuTime.compareTo(TimeSpan.empty()) >= 0) {
        try {
            limits.add(ProcessCpuTimeLimit.fromNowOn(options.cpuTime));
        } catch (JMException e) {
            logger.logDebugException(e, "Querying cpu time failed");
            logger.log(Level.WARNING,
                    "Your Java VM does not support measuring the cpu time, cpu time threshold disabled.");
        }
    }

    ImmutableList<ResourceLimit> limitsList = limits.build();
    if (!limitsList.isEmpty()) {
        logger.log(Level.INFO, "Using the following resource limits:",
                Joiner.on(", ").join(Lists.transform(limitsList, new Function<ResourceLimit, String>() {
                    @Override
                    public String apply(@Nonnull ResourceLimit pInput) {
                        return pInput.getName();
                    }
                })));
    }
    return new ResourceLimitChecker(notifier, limitsList);
}

From source file:com.google.errorprone.bugpatterns.time.JavaDurationGetSecondsGetNano.java

/**
 * Returns whether or not there is a "nearby" {@code getSeconds()} method call.
 *
 * @param nanoTree the tree that contains the {@code getNanos()} method call
 * @param state the visitor state of this matcher
 * @param secondsMatcher the matcher that matches the appropriate {@code getSeconds()} call
 * @param checkProtoChains whether or not to check a chain of protobuf getter methods for equality
 *     (e.g., {@code a.getB().getC().getSeconds()} and {@code a.getB().getC().getNanos()}
 *//*from  w  ww  . j a  v a 2s  . c om*/
static boolean containsGetSecondsCallInNearbyCode(MethodInvocationTree nanoTree, VisitorState state,
        Matcher<ExpressionTree> secondsMatcher, boolean checkProtoChains) {
    ExpressionTree getNanoReceiver = ASTHelpers.getReceiver(nanoTree);
    TreeScanner<Boolean, Void> scanner = new TreeScanner<Boolean, Void>() {
        @Override
        public Boolean reduce(Boolean r1, Boolean r2) {
            return (r1 == null ? false : r1) || (r2 == null ? false : r2);
        }

        @Override
        public Boolean visitLambdaExpression(LambdaExpressionTree node, Void unused) {
            return false;
        }

        @Override
        public Boolean visitMethodInvocation(MethodInvocationTree tree, Void unused) {
            if (super.visitMethodInvocation(tree, unused)) {
                return true;
            }
            if (tree != null && secondsMatcher.matches(tree, state)) {
                ExpressionTree getSecondsReceiver = ASTHelpers.getReceiver(tree);
                if (getSecondsReceiver != null) {
                    // if the methods are being invoked directly on the same variable...
                    if (ASTHelpers.sameVariable(getNanoReceiver, getSecondsReceiver)) {
                        return true;
                    }
                    if (!checkProtoChains) {
                        return false;
                    }
                    // now check if the root variables of the invocations are the same...
                    ExpressionTree treeRootAssignable = ASTHelpers.getRootAssignable(tree);
                    ExpressionTree nanoTreeRootAssignable = ASTHelpers.getRootAssignable(nanoTree);
                    if (treeRootAssignable != null && nanoTreeRootAssignable != null
                            && ASTHelpers.sameVariable(treeRootAssignable, nanoTreeRootAssignable)) {

                        // build up a list of method invocations for both invocations

                        List<Symbol> secondsChain = new ArrayList<>();
                        boolean allProtoGettersForSeconds = buildChain(tree, state, secondsChain);

                        List<Symbol> nanosChain = new ArrayList<>();
                        boolean allProtoGettersForNanos = buildChain(nanoTree, state, nanosChain);

                        // if we saw a non protobuf getter in the chain, we have to return false
                        if (!allProtoGettersForSeconds || !allProtoGettersForNanos) {
                            return false;
                        }

                        if (secondsChain.equals(nanosChain)) {
                            return true;
                        }
                    }
                }
            }
            return false;
        }
    };
    ImmutableList<Tree> treesToScan = getNearbyTreesToScan(state);
    return treesToScan.isEmpty() ? false : scanner.scan(treesToScan, null);
}

From source file:com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder.java

/**
 * Creates a nested set from a given list of items.
 *///  w  w  w .  j a v  a2 s .c  om
@SuppressWarnings("unchecked")
public static <E> NestedSet<E> wrap(Order order, Iterable<E> wrappedItems) {
    ImmutableList<E> wrappedList = ImmutableList.copyOf(wrappedItems);
    if (wrappedList.isEmpty()) {
        return order.emptySet();
    } else if (order == Order.STABLE_ORDER && wrappedList == wrappedItems && wrappedList.size() > 1) {
        NestedSet<?> cached = immutableListCache.get(wrappedList);
        if (cached != null) {
            return (NestedSet<E>) cached;
        }
        NestedSet<E> built = new NestedSetBuilder<E>(order).addAll(wrappedList).build();
        immutableListCache.putIfAbsent(wrappedList, built);
        return built;
    } else {
        return new NestedSetBuilder<E>(order).addAll(wrappedList).build();
    }
}

From source file:com.google.devtools.build.lib.rules.proto.ProtoCommon.java

/**
 * Returns the .proto files that are the direct srcs of the direct-dependencies of this rule. If
 * the current rule is an alias proto_library (=no srcs), we use the direct srcs of the
 * direct-dependencies of our direct-dependencies.
 *//*from w w  w . ja va2  s .c  o  m*/
@Nullable
public static NestedSet<Artifact> computeProtosInDirectDeps(RuleContext ruleContext) {
    NestedSetBuilder<Artifact> result = NestedSetBuilder.stableOrder();
    ImmutableList<Artifact> srcs = ruleContext.getPrerequisiteArtifacts("srcs", TARGET).list();
    if (srcs.isEmpty()) {
        for (ProtoSupportDataProvider provider : ruleContext.getPrerequisites("deps", TARGET,
                ProtoSupportDataProvider.class)) {
            result.addTransitive(provider.getSupportData().getProtosInDirectDeps());
        }
    } else {
        for (ProtoSourcesProvider provider : ruleContext.getPrerequisites("deps", TARGET,
                ProtoSourcesProvider.class)) {
            result.addTransitive(provider.getCheckDepsProtoSources());
        }
        result.addAll(srcs);
    }
    return result.build();
}

From source file:de.metas.ui.web.window.descriptor.filters.CompositeDocumentFilterDescriptorsProvider.java

public static DocumentFilterDescriptorsProvider compose(final DocumentFilterDescriptorsProvider... providers) {
    if (providers == null || providers.length <= 0) {
        return NullDocumentFilterDescriptorsProvider.instance;
    }/*from   w  w  w  . j  ava  2s . c om*/

    final ImmutableList<DocumentFilterDescriptorsProvider> providersList = Stream.of(providers)
            .filter(provider -> !NullDocumentFilterDescriptorsProvider.isNull(provider))
            .collect(GuavaCollectors.toImmutableList());

    if (providersList.isEmpty()) {
        return NullDocumentFilterDescriptorsProvider.instance;
    } else if (providersList.size() == 1) {
        return providersList.get(0);
    }

    return new CompositeDocumentFilterDescriptorsProvider(providersList);
}

From source file:co.cask.cdap.data2.dataset2.lib.table.hbase.HBaseTableAdmin.java

public static CoprocessorJar createCoprocessorJarInternal(CConfiguration conf, LocationFactory locationFactory,
        HBaseTableUtil tableUtil, boolean transactional, boolean supportsReadlessIncrement) throws IOException {
    // create the jar for the data janitor coprocessor.
    Location jarDir = locationFactory.create(conf.get(Constants.CFG_HDFS_LIB_DIR));
    Class<? extends Coprocessor> dataJanitorClass = tableUtil.getTransactionDataJanitorClassForVersion();
    Class<? extends Coprocessor> incrementClass = tableUtil.getIncrementHandlerClassForVersion();
    ImmutableList.Builder<Class<? extends Coprocessor>> coprocessors = ImmutableList.builder();
    if (transactional) {
        // tx janitor
        if (conf.getBoolean(TxConstants.DataJanitor.CFG_TX_JANITOR_ENABLE,
                TxConstants.DataJanitor.DEFAULT_TX_JANITOR_ENABLE)) {
            coprocessors.add(dataJanitorClass);
        }/*from w w w. j  ava  2 s. c o  m*/
    }
    // readless increments
    if (supportsReadlessIncrement) {
        coprocessors.add(incrementClass);
    }

    ImmutableList<Class<? extends Coprocessor>> coprocessorList = coprocessors.build();
    if (coprocessorList.isEmpty()) {
        return CoprocessorJar.EMPTY;
    }
    Location jarFile = HBaseTableUtil.createCoProcessorJar("table", jarDir, coprocessorList);
    return new CoprocessorJar(coprocessorList, jarFile);
}

From source file:com.android.manifmerger.PreValidator.java

/**
 * Checks that an element which is supposed to have a key does have one.
 * @param mergingReport report to log warnings and errors.
 * @param xmlElement xml element to check for key presence.
 * @return true if the element has a valid key or false it does not need one or it is invalid.
 */// ww  w .  j a  va  2  s  .co m
private static boolean checkKeyPresence(MergingReport.Builder mergingReport, XmlElement xmlElement) {
    ManifestModel.NodeKeyResolver nodeKeyResolver = xmlElement.getType().getNodeKeyResolver();
    ImmutableList<String> keyAttributesNames = nodeKeyResolver.getKeyAttributesNames();
    if (keyAttributesNames.isEmpty()) {
        return false;
    }
    if (Strings.isNullOrEmpty(xmlElement.getKey())) {
        // we should have a key but we don't.
        String message = keyAttributesNames.size() > 1
                ? String.format("Missing one of the key attributes '%1$s' on element %2$s at %3$s",
                        Joiner.on(',').join(keyAttributesNames), xmlElement.getId(), xmlElement.printPosition())
                : String.format("Missing '%1$s' key attribute on element %2$s at %3$s",
                        keyAttributesNames.get(0), xmlElement.getId(), xmlElement.printPosition());
        xmlElement.addMessage(mergingReport, ERROR, message);
        return false;
    }
    return true;
}