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

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

Introduction

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

Prototype

boolean isEmpty();

Source Link

Document

Returns true if this map contains no key-value mappings.

Usage

From source file:com.google.idea.blaze.android.sync.importer.problems.GeneratedResourceWarnings.java

public static void submit(Project project, BlazeContext context, ProjectViewSet projectViewSet,
        ArtifactLocationDecoder artifactLocationDecoder, Set<ArtifactLocation> generatedResourceLocations,
        Set<String> whitelistedLocations) {
    if (generatedResourceLocations.isEmpty()) {
        return;/*from  w ww  .  j  a  va2s  .  com*/
    }
    Set<ArtifactLocation> nonWhitelistedLocations = new HashSet<>();
    Set<String> unusedWhitelistEntries = new HashSet<>();
    filterWhitelistedEntries(generatedResourceLocations, whitelistedLocations, nonWhitelistedLocations,
            unusedWhitelistEntries);
    // Tag any warnings with the project view file.
    File projectViewFile = projectViewSet.getTopLevelProjectViewFile().projectViewFile;
    if (!nonWhitelistedLocations.isEmpty()) {
        GeneratedResourceClassifier classifier = new GeneratedResourceClassifier(nonWhitelistedLocations,
                artifactLocationDecoder, BlazeExecutor.getInstance().getExecutor());
        ImmutableSortedMap<ArtifactLocation, Integer> interestingDirectories = classifier
                .getInterestingDirectories();
        if (!interestingDirectories.isEmpty()) {
            IssueOutput
                    .warn(String.format(
                            "Dropping %d generated resource directories.\n"
                                    + "R classes will not contain resources from these directories.\n"
                                    + "Double-click to add to project view if needed to resolve references.",
                            interestingDirectories.size()))
                    .inFile(projectViewFile).onLine(1).inColumn(1).submit(context);
            for (Map.Entry<ArtifactLocation, Integer> entry : interestingDirectories.entrySet()) {
                IssueOutput
                        .warn(String.format("Dropping generated resource directory '%s' w/ %d subdirs",
                                entry.getKey(), entry.getValue()))
                        .inFile(projectViewFile)
                        .navigatable(new AddGeneratedResourceDirectoryNavigatable(project, projectViewFile,
                                entry.getKey()))
                        .submit(context);
            }
        }
    }
    // Warn about unused parts of the whitelist.
    if (!unusedWhitelistEntries.isEmpty()) {
        IssueOutput.warn(String.format("%d unused entries in project view section \"%s\":\n%s",
                unusedWhitelistEntries.size(), GeneratedAndroidResourcesSection.KEY.getName(),
                String.join("\n  ", unusedWhitelistEntries))).inFile(projectViewFile).submit(context);
    }
}

From source file:org.locationtech.geogig.model.impl.RevTreeImpl.java

public static RevTree create(final ObjectId id, final long size, final int childTreeCount,
        @Nullable ImmutableList<Node> trees, @Nullable ImmutableList<Node> features,
        @Nullable ImmutableSortedMap<Integer, Bucket> buckets) {

    checkNotNull(id);//w w  w . j a  v a2  s .co  m

    if (buckets == null || buckets.isEmpty()) {
        return new LeafTree(id, size, features, trees);
    }

    if ((features == null || features.isEmpty()) && (trees == null || trees.isEmpty())) {
        return new NodeTree(id, size, childTreeCount, buckets);
    }
    return new MixedTree(id, size, childTreeCount, trees, features, buckets);
}

From source file:com.facebook.buck.core.util.graph.Dot.java

private static <T> String printNode(T node, Function<T, String> nodeToName, Function<T, String> nodeToTypeName,
        Function<T, ImmutableSortedMap<String, String>> nodeToAttributes) {
    String source = nodeToName.apply(node);
    String sourceType = nodeToTypeName.apply(node);
    String extraAttributes = "";
    ImmutableSortedMap<String, String> nodeAttributes = nodeToAttributes.apply(node);
    if (!nodeAttributes.isEmpty()) {
        extraAttributes = "," + nodeAttributes.entrySet().stream()
                .map(entry -> escape("buck_" + entry.getKey()) + "=" + escape(entry.getValue()))
                .collect(Collectors.joining(","));
    }/*w w w. ja v a2 s .com*/
    return String.format("  %s [style=filled,color=%s%s];%n", escape(source), Dot.colorFromType(sourceType),
            extraAttributes);
}

From source file:org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.java

private static TaskOutputCachingState getCachingStateForInvalidCacheKey(
        TaskOutputCachingBuildCacheKey buildCacheKey) {
    BuildCacheKeyInputs buildCacheKeyInputs = buildCacheKey.getInputs();
    ImplementationSnapshot taskImplementation = buildCacheKeyInputs.getTaskImplementation();
    if (taskImplementation != null && taskImplementation.isUnknown()) {
        return DefaultTaskOutputCachingState.disabled(NON_CACHEABLE_TASK_IMPLEMENTATION,
                "Task class " + taskImplementation.getUnknownReason());
    }//  w ww .ja va  2  s  .  c om

    List<ImplementationSnapshot> actionImplementations = buildCacheKeyInputs.getActionImplementations();
    if (actionImplementations != null && !actionImplementations.isEmpty()) {
        for (ImplementationSnapshot actionImplementation : actionImplementations) {
            if (actionImplementation.isUnknown()) {
                return DefaultTaskOutputCachingState.disabled(NON_CACHEABLE_TASK_ACTION,
                        "Task action " + actionImplementation.getUnknownReason());
            }
        }
    }

    ImmutableSortedMap<String, String> invalidInputProperties = buildCacheKeyInputs
            .getNonCacheableInputProperties();
    if (invalidInputProperties != null && !invalidInputProperties.isEmpty()) {
        StringBuilder builder = new StringBuilder();
        builder.append("Non-cacheable inputs: ");
        boolean first = true;
        for (Map.Entry<String, String> entry : Preconditions.checkNotNull(invalidInputProperties).entrySet()) {
            if (!first) {
                builder.append(", ");
            }
            first = false;
            builder.append("property '").append(entry.getKey()).append("' ").append(entry.getValue());
        }
        return DefaultTaskOutputCachingState.disabled(NON_CACHEABLE_INPUTS, builder.toString());
    }
    throw new IllegalStateException("Cache key is invalid without a known reason: " + buildCacheKey);
}

From source file:org.apache.kylin.query.util.ConvertToComputedColumn.java

static String replaceComputedColumn(String inputSql, ImmutableSortedMap<String, String> computedColumn) {
    if (inputSql == null) {
        return "";
    }// www  . j  a v  a  2 s  .c  om

    if (computedColumn == null || computedColumn.isEmpty()) {
        return inputSql;
    }
    String result = inputSql;
    String[] lines = inputSql.split("\n");
    List<Pair<String, String>> toBeReplacedExp = new ArrayList<>(); //{"alias":"expression"}, like {"t1":"t1.a+t1.b+t1.c"}

    for (String ccExp : computedColumn.keySet()) {
        List<SqlNode> matchedNodes = new ArrayList<>();
        try {
            matchedNodes = getMatchedNodes(inputSql, computedColumn.get(ccExp));
        } catch (SqlParseException e) {
            logger.error("Convert to computedColumn Fail,parse sql fail ", e.getMessage());
        }
        for (SqlNode node : matchedNodes) {
            Pair<Integer, Integer> startEndPos = CalciteParser.getReplacePos(node, lines);
            int start = startEndPos.getLeft();
            int end = startEndPos.getRight();
            //add table alias like t1.column,if exists alias
            String alias = getTableAlias(node);
            toBeReplacedExp.add(Pair.of(alias, inputSql.substring(start, end)));
        }
        logger.debug("Computed column: " + ccExp + "'s matched list:" + toBeReplacedExp);
        //replace user's input sql
        for (Pair<String, String> toBeReplaced : toBeReplacedExp) {
            result = result.replace(toBeReplaced.getRight(), toBeReplaced.getLeft() + ccExp);
        }
    }
    return result;
}

From source file:edu.mit.streamjit.util.bytecode.methodhandles.Combinators.java

private static MethodHandle lookupswitch(ImmutableSortedMap<Integer, MethodHandle> cases,
        MethodHandle defaultCase) {
    if (cases.isEmpty()) {
        checkArgument(defaultCase.type().parameterList().equals(ImmutableList.of(int.class)),
                "bad type for default case %s", defaultCase.type());
        return defaultCase;
    }/*from ww w . j  av a2 s.  co  m*/
    MethodType type = cases.values().iterator().next().type();
    for (MethodHandle mh : cases.values())
        checkArgument(mh.type().equals(type), "type mismatch in %s", cases.values());
    checkArgument(defaultCase.type().equals(type.insertParameterTypes(0, int.class)),
            "bad type for default case %s, other cases %s", defaultCase.type(), type);
    return lookupswitch0(cases, defaultCase);
}

From source file:edu.mit.streamjit.util.bytecode.methodhandles.Combinators.java

private static MethodHandle lookupswitch0(ImmutableSortedMap<Integer, MethodHandle> cases,
        MethodHandle defaultCase) {
    if (cases.isEmpty())
        return defaultCase;
    if (cases.size() == 1) {
        Map.Entry<Integer, MethodHandle> next = cases.entrySet().iterator().next();
        return MethodHandles.guardWithTest(eq(next.getKey()),
                MethodHandles.dropArguments(next.getValue(), 0, int.class), //discard the case index
                defaultCase);/*from w ww. j  a v  a  2 s  .co m*/
    }
    int median = median(cases.keySet().asList());
    return MethodHandles.guardWithTest(le(median), lookupswitch0(cases.headMap(median, true), defaultCase),
            lookupswitch0(cases.tailMap(median, false), defaultCase));
}

From source file:google.registry.model.translators.ImmutableSortedMapTranslatorFactory.java

@Override
public final Translator<ImmutableSortedMap<K, V>> create(Path path, Property property, Type type,
        CreateContext ctx) {//w  w w . j  a  v  a  2s . co  m
    if (!ImmutableSortedMap.class.equals(erase(type))) {
        return null; // skip me and try to find another matching translator
    }
    Type fieldKeyType = getTypeParameter(type, ImmutableSortedMap.class.getTypeParameters()[0]);
    Type fieldValueType = getTypeParameter(type, ImmutableSortedMap.class.getTypeParameters()[1]);
    if (fieldKeyType == null || fieldValueType == null) {
        return null; // no type information is available
    }
    if (!keyType.isSupertypeOf(fieldKeyType) || !valueType.isSupertypeOf(fieldValueType)) {
        return null; // this ImmutableSortedMap does not have the same concrete component types
    }
    ctx.enterCollection(path);
    ctx.enterEmbed(path);
    try {
        // The component types can also be translated by Objectify!
        TranslatorRegistry translators = ctx.getFactory().getTranslators();
        final Translator<K> keyTranslator = translators.create(path.extend(keyProperty), property, fieldKeyType,
                ctx);
        final Translator<V> valueTranslator = translators.create(path.extend(valueProperty), property,
                fieldValueType, ctx);
        return new ListNodeTranslator<ImmutableSortedMap<K, V>>() {
            @Override
            protected ImmutableSortedMap<K, V> loadList(Node node, LoadContext ctx) {
                ImmutableSortedMap.Builder<K, V> map = new ImmutableSortedMap.Builder<>(Ordering.natural());
                for (Node child : node) {
                    try {
                        map.put(keyTranslator.load(child.get(keyProperty), ctx),
                                valueTranslator.load(child.get(valueProperty), ctx));
                    } catch (SkipException e) {
                        // no problem, just skip that one
                    }
                }
                return map.build();
            }

            @Override
            protected Node saveList(@Nullable ImmutableSortedMap<K, V> mapFromPojo, Path path, boolean index,
                    SaveContext ctx) {
                checkState(!index, "At path %s: Index not allowed", path);
                ImmutableSortedMap<K, V> mapToSave = transformBeforeSave(
                        ImmutableSortedMap.copyOfSorted(nullToEmpty(mapFromPojo)));
                if (mapToSave.isEmpty()) {
                    throw new SkipException(); // the datastore doesn't store empty lists
                }
                Node node = new Node(path);
                for (Map.Entry<K, V> entry : mapToSave.entrySet()) {
                    Node item = new Node(path);
                    item.put(keyProperty,
                            keyTranslator.save(entry.getKey(), path.extend(keyProperty), index, ctx));
                    item.put(valueProperty,
                            valueTranslator.save(entry.getValue(), path.extend(valueProperty), index, ctx));
                    node.addToList(item);
                }
                return node;
            }
        };
    } finally {
        ctx.exitEmbed();
        ctx.exitCollection();
    }
}

From source file:org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.java

public TaskExecuterResult execute(TaskInternal task, TaskStateInternal state,
        final TaskExecutionContext context) {
    TaskProperties taskProperties = context.getTaskProperties();
    FileCollection sourceFiles = taskProperties.getSourceFiles();
    if (taskProperties.hasSourceFiles() && sourceFiles.isEmpty()) {
        AfterPreviousExecutionState previousExecution = context.getAfterPreviousExecution();
        @SuppressWarnings("RedundantTypeArguments")
        ImmutableSortedMap<String, FileCollectionFingerprint> outputFiles = previousExecution == null
                ? ImmutableSortedMap.<String, FileCollectionFingerprint>of()
                : previousExecution.getOutputFileProperties();
        if (outputFiles.isEmpty()) {
            state.setOutcome(TaskExecutionOutcome.NO_SOURCE);
            LOGGER.info("Skipping {} as it has no source files and no previous output files.", task);
        } else {/*from w w  w .  j a va2 s.  co m*/
            TaskArtifactState taskArtifactState = context.getTaskArtifactState();
            boolean cleanupDirectories = taskArtifactState.getOverlappingOutputs() == null;
            if (!cleanupDirectories) {
                LOGGER.info(
                        "No leftover directories for {} will be deleted since overlapping outputs were detected.",
                        task);
            }
            outputChangeListener.beforeOutputChange();
            boolean deletedFiles = false;
            boolean debugEnabled = LOGGER.isDebugEnabled();

            for (FileCollectionFingerprint outputFingerprints : outputFiles.values()) {
                for (String outputPath : outputFingerprints.getFingerprints().keySet()) {
                    File file = new File(outputPath);
                    if (file.exists() && buildOutputCleanupRegistry.isOutputOwnedByBuild(file)) {
                        if (!cleanupDirectories && file.isDirectory()) {
                            continue;
                        }
                        if (debugEnabled) {
                            LOGGER.debug("Deleting stale output file '{}'.", file.getAbsolutePath());
                        }
                        GFileUtils.forceDelete(file);
                        deletedFiles = true;
                    }
                }
            }
            if (deletedFiles) {
                LOGGER.info("Cleaned previous output of {} as it has no source files.", task);
                state.setOutcome(TaskExecutionOutcome.EXECUTED);
            } else {
                state.setOutcome(TaskExecutionOutcome.NO_SOURCE);
            }
            // TODO Create new current execution with new outputs
            // taskArtifactState.snapshotAfterTaskExecution(true, buildInvocationScopeId.getId(), context);
        }
        taskInputsListener.onExecute(task, Cast.cast(FileCollectionInternal.class, sourceFiles));
        return new TaskExecuterResult() {
            @Override
            public OriginMetadata getOriginMetadata() {
                return OriginMetadata.fromCurrentBuild(buildInvocationScopeId.getId(),
                        context.markExecutionTime());
            }
        };
    } else {
        taskInputsListener.onExecute(task,
                Cast.cast(FileCollectionInternal.class, taskProperties.getInputFiles()));
    }
    return executer.execute(task, state, context);
}