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

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

Introduction

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

Prototype

Set<Map.Entry<K, V>> entrySet();

Source Link

Document

Returns a Set view of the mappings contained in this map.

Usage

From source file:org.gradle.api.internal.OverlappingOutputs.java

@Nullable
public static OverlappingOutputs detect(
        @Nullable ImmutableSortedMap<String, FileCollectionFingerprint> previous,
        ImmutableSortedMap<String, CurrentFileCollectionFingerprint> current) {
    for (Map.Entry<String, CurrentFileCollectionFingerprint> entry : current.entrySet()) {
        String propertyName = entry.getKey();
        CurrentFileCollectionFingerprint beforeExecution = entry.getValue();
        FileCollectionFingerprint afterPreviousExecution = getFingerprintAfterPreviousExecution(previous,
                propertyName);/*from  w  w  w .j a  va 2s.c  om*/
        OverlappingOutputs overlappingOutputs = OverlappingOutputs.detect(propertyName, afterPreviousExecution,
                beforeExecution);
        if (overlappingOutputs != null) {
            return overlappingOutputs;
        }
    }
    return null;
}

From source file:com.facebook.buck.android.DexProducedFromJavaLibrary.java

@VisibleForTesting
static Sha1HashCode computeAbiKey(ImmutableSortedMap<String, HashCode> classNames) {
    Hasher hasher = Hashing.sha1().newHasher();
    for (Map.Entry<String, HashCode> entry : classNames.entrySet()) {
        hasher.putUnencodedChars(entry.getKey());
        hasher.putByte((byte) 0);
        hasher.putUnencodedChars(entry.getValue().toString());
        hasher.putByte((byte) 0);
    }/*from  w  w  w  .  ja  va  2s  . com*/
    return new Sha1HashCode(hasher.hash().toString());
}

From source file:com.facebook.buck.cli.AuditActionGraphCommand.java

private static void writeJsonObjectForBuildRule(JsonGenerator json, BuildRule node,
        ActionGraphBuilder actionGraphBuilder, SourcePathRuleFinder ruleFinder, SourcePathResolver pathResolver,
        boolean includeRuntimeDeps, NodeView nodeView) throws IOException {
    json.writeStartObject();//from w  ww  . j ava  2s. co m
    json.writeStringField("name", node.getFullyQualifiedName());
    json.writeStringField("type", node.getType());
    {
        json.writeArrayFieldStart("buildDeps");
        for (BuildRule dep : node.getBuildDeps()) {
            json.writeString(dep.getFullyQualifiedName());
        }
        json.writeEndArray();
        if (includeRuntimeDeps) {
            json.writeArrayFieldStart("runtimeDeps");
            for (BuildRule dep : getRuntimeDeps(node, actionGraphBuilder, ruleFinder)) {
                json.writeString(dep.getFullyQualifiedName());
            }
            json.writeEndArray();
        }
        SourcePath sourcePathToOutput = node.getSourcePathToOutput();
        if (sourcePathToOutput != null) {
            Path outputPath = pathResolver.getAbsolutePath(sourcePathToOutput);
            json.writeStringField("outputPath", outputPath.toString());
        }
    }
    if (nodeView == NodeView.Extended) {
        ImmutableSortedMap<String, String> attrs = getNodeAttributes(node);
        for (ImmutableSortedMap.Entry<String, String> attr : attrs.entrySet()) {
            // add 'buck_' prefix to avoid name collisions and make it compatible with DOT output
            json.writeStringField("buck_" + attr.getKey(), attr.getValue());
        }
    }
    json.writeEndObject();
}

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(","));
    }// www . j  a v a2 s . com
    return String.format("  %s [style=filled,color=%s%s];%n", escape(source), Dot.colorFromType(sourceType),
            extraAttributes);
}

From source file:com.google.caliper.runner.CaliperMain.java

public static void exitlessMain(String[] args, PrintWriter stdout, PrintWriter stderr)
        throws InvalidCommandException, InvalidBenchmarkException, InvalidConfigurationException {
    @Nullable/*ww w .j ava2  s  .co  m*/
    String legacyCaliperEnv = System.getenv(LEGACY_ENV);
    if (!Strings.isNullOrEmpty(legacyCaliperEnv)) {
        System.err.println("Legacy Caliper is no more. " + LEGACY_ENV + " has no effect.");
    }
    try {
        // TODO(gak): see if there's a better way to deal with options. probably a module
        Injector optionsInjector = Guice.createInjector(new OptionsModule(args));
        CaliperOptions options = optionsInjector.getInstance(CaliperOptions.class);
        Module runnerModule = new ExperimentingRunnerModule();
        Class<?> benchmarkClass = benchmarkClassForName(options.benchmarkClassName());
        Injector injector = optionsInjector.createChildInjector(new BenchmarkClassModule(benchmarkClass),
                new OutputModule(stdout, stderr), new BridgeModule(), new GsonModule(), new ConfigModule(),
                new ServiceModule(), runnerModule);
        if (options.printConfiguration()) {
            stdout.println("Configuration:");
            ImmutableSortedMap<String, String> sortedProperties = ImmutableSortedMap
                    .copyOf(injector.getInstance(CaliperConfig.class).properties());
            for (Entry<String, String> entry : sortedProperties.entrySet()) {
                stdout.printf("  %s = %s%n", entry.getKey(), entry.getValue());
            }
        }
        // check that the parameters are valid
        injector.getInstance(BenchmarkClass.class).validateParameters(options.userParameters());
        ServiceManager serviceManager = injector.getInstance(ServiceManager.class);
        serviceManager.startAsync().awaitHealthy();
        try {
            CaliperRun run = injector.getInstance(CaliperRun.class); // throws wrapped ICE, IBE
            run.run(); // throws IBE
        } finally {
            try {
                // We have some shutdown logic to ensure that files are cleaned up so give it a chance to
                // run
                serviceManager.stopAsync().awaitStopped(10, TimeUnit.SECONDS);
            } catch (TimeoutException e) {
                // Thats fine
            }
        }
    } catch (CreationException e) {
        propogateIfCaliperException(e.getCause());
        throw e;
    } catch (ProvisionException e) {
        propogateIfCaliperException(e.getCause());
        for (Message message : e.getErrorMessages()) {
            propogateIfCaliperException(message.getCause());
        }
        throw e;
    }

    // courtesy flush
    stderr.flush();
    stdout.flush();
}

From source file:com.facebook.buck.json.JsonObjectHashing.java

/**
 * Given a {@link Hasher} and a parsed BUCK file object, updates the Hasher
 * with the contents of the JSON object.
 *///from   w  ww . ja  v  a2s  .c om
public static void hashJsonObject(Hasher hasher, @Nullable Object obj) {
    if (obj instanceof Map) {
        Map<?, ?> map = (Map<?, ?>) obj;
        ImmutableSortedMap.Builder<String, Optional<Object>> sortedMapBuilder = ImmutableSortedMap
                .naturalOrder();
        for (Map.Entry<?, ?> entry : map.entrySet()) {
            Object key = entry.getKey();
            if (!(key instanceof String)) {
                throw new RuntimeException(String.format(
                        "Keys of JSON maps are expected to be strings. Actual type: %s, contents: %s",
                        key.getClass().getName(), key));
            }
            Object value = entry.getValue();
            if (value != null) {
                sortedMapBuilder.put((String) key, Optional.of(value));
            }
        }
        ImmutableSortedMap<String, Optional<Object>> sortedMap = sortedMapBuilder.build();
        hasher.putInt(HashedObjectType.MAP.ordinal());
        hasher.putInt(sortedMap.size());
        for (Map.Entry<String, Optional<Object>> entry : sortedMap.entrySet()) {
            hashJsonObject(hasher, entry.getKey());
            if (entry.getValue().isPresent()) {
                hashJsonObject(hasher, entry.getValue().get());
            } else {
                hashJsonObject(hasher, null);
            }
        }
    } else if (obj instanceof Collection) {
        Collection<?> collection = (Collection<?>) obj;
        hasher.putInt(HashedObjectType.LIST.ordinal());
        hasher.putInt(collection.size());
        for (Object collectionEntry : collection) {
            hashJsonObject(hasher, collectionEntry);
        }
    } else if (obj instanceof String) {
        hasher.putInt(HashedObjectType.STRING.ordinal());
        byte[] stringBytes = ((String) obj).getBytes(Charsets.UTF_8);
        hasher.putInt(stringBytes.length);
        hasher.putBytes(stringBytes);
    } else if (obj instanceof Boolean) {
        hasher.putInt(HashedObjectType.BOOLEAN.ordinal());
        hasher.putBoolean((boolean) obj);
    } else if (obj instanceof Number) {
        // This is gross, but it mimics the logic originally in RawParser.
        Number number = (Number) obj;
        if (number.longValue() == number.doubleValue()) {
            hasher.putInt(HashedObjectType.LONG.ordinal());
            hasher.putLong(number.longValue());
        } else {
            hasher.putInt(HashedObjectType.DOUBLE.ordinal());
            hasher.putDouble(number.doubleValue());
        }
    } else if (obj instanceof Void || obj == null) {
        hasher.putInt(HashedObjectType.NULL.ordinal());
    } else {
        throw new RuntimeException(String.format("Unsupported object %s (class %s)", obj, obj.getClass()));
    }
}

From source file:com.google.devtools.kythe.analyzers.base.EntrySet.java

protected static String buildSignature(ImmutableList<String> salts,
        ImmutableSortedMap<String, byte[]> properties) {
    Hasher signature = SIGNATURE_HASH_FUNCTION.newHasher();
    for (String salt : salts) {
        signature.putString(salt, PROPERTY_VALUE_CHARSET);
    }//from  w  w  w  . j a v a2 s.  c om
    for (Map.Entry<String, byte[]> property : properties.entrySet()) {
        signature.putString(property.getKey(), PROPERTY_VALUE_CHARSET).putBytes(property.getValue());
    }
    return signature.hash().toString();
}

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);// w  w  w .j a v  a2 s  .c  om
    }
    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:org.locationtech.geogig.storage.datastream.FormatCommonV2.java

public static void writeTree(RevTree tree, DataOutput data) throws IOException {

    writeUnsignedVarLong(tree.size(), data);
    writeUnsignedVarInt(tree.numTrees(), data);

    Envelope envBuff = new Envelope();

    final int nFeatures = tree.features().isPresent() ? tree.features().get().size() : 0;
    writeUnsignedVarInt(nFeatures, data);
    if (nFeatures > 0) {
        for (Node feature : tree.features().get()) {
            writeNode(feature, data, envBuff);
        }//from   w w w  .  j  a  v a2  s .  c  o  m
    }
    final int nTrees = tree.trees().isPresent() ? tree.trees().get().size() : 0;
    writeUnsignedVarInt(nTrees, data);
    if (nTrees > 0) {
        for (Node subTree : tree.trees().get()) {
            writeNode(subTree, data, envBuff);
        }
    }

    final int nBuckets = tree.buckets().isPresent() ? tree.buckets().get().size() : 0;
    writeUnsignedVarInt(nBuckets, data);
    if (tree.buckets().isPresent()) {
        ImmutableSortedMap<Integer, Bucket> buckets = tree.buckets().get();
        for (Map.Entry<Integer, Bucket> bucket : buckets.entrySet()) {
            writeBucket(bucket.getKey(), bucket.getValue(), data, envBuff);
        }
    }
}

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 www  . j a  v  a  2s  .c om*/
    }
    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);
    }
}