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

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

Introduction

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

Prototype

public static <K, V> ImmutableSortedMap<K, V> copyOf(
            Iterable<? extends Entry<? extends K, ? extends V>> entries) 

Source Link

Usage

From source file:com.facebook.buck.features.project.intellij.ModuleBuildContext.java

public ImmutableMap<BuildTarget, DependencyType> getDependencies() {
    // Some targets may introduce dependencies without contributing to the IjFolder set. These
    // are recorded in the dependencyTypeMap.
    // Dependencies associated with source paths inherit the type from the folder. This is because
    // IntelliJ only operates on folders and so it is impossible to distinguish between test and
    // production code if it's in the same folder. That in turn means test-only dependencies need
    // to be "promoted" to production dependencies in the above scenario to keep code compiling.
    // It is also possible that a target is included in both maps, in which case the type gets
    // merged anyway.
    // Merging types does not back-propagate: if TargetA depends on TargetB and the type of
    // TargetB has been changed that does not mean the dependency type of TargetA is changed too.
    Map<BuildTarget, DependencyType> result = new HashMap<>(dependencyTypeMap);
    for (Path path : dependencyOriginMap.keySet()) {
        DependencyType dependencyType = Objects
                .requireNonNull(sourceFoldersMergeMap.get(path)) instanceof TestFolder ? DependencyType.TEST
                        : DependencyType.PROD;
        for (BuildTarget buildTarget : dependencyOriginMap.get(path)) {
            DependencyType.putWithMerge(result, buildTarget, dependencyType);
        }//from  w w  w .  j  a  v a 2  s  .com
    }
    return ImmutableSortedMap.copyOf(result);
}

From source file:com.facebook.buck.cxx.NativeLinkables.java

/**
 * Collect all the shared libraries generated by {@link NativeLinkable}s found by transitively
 * traversing all unbroken dependency chains of {@link com.facebook.buck.cxx.NativeLinkable}
 * objects found via the passed in {@link com.facebook.buck.rules.BuildRule} roots.
 *
 * @return a mapping of library name to the library {@link SourcePath}.
 *///from   w w  w .  j  a v  a2s .c  o  m
public static ImmutableSortedMap<String, SourcePath> getTransitiveSharedLibraries(CxxPlatform cxxPlatform,
        Iterable<? extends BuildRule> inputs, Predicate<Object> traverse, Predicate<Object> skip)
        throws NoSuchBuildTargetException {

    ImmutableMap<BuildTarget, NativeLinkable> roots = getNativeLinkableRoots(inputs, traverse, skip);
    ImmutableMap<BuildTarget, NativeLinkable> nativeLinkables = getTransitiveNativeLinkables(cxxPlatform,
            roots.values());

    Map<String, SourcePath> libraries = new LinkedHashMap<>();
    for (NativeLinkable nativeLinkable : nativeLinkables.values()) {
        NativeLinkable.Linkage linkage = nativeLinkable.getPreferredLinkage(cxxPlatform);
        if (linkage != NativeLinkable.Linkage.STATIC) {
            ImmutableMap<String, SourcePath> libs = nativeLinkable.getSharedLibraries(cxxPlatform);
            for (Map.Entry<String, SourcePath> lib : libs.entrySet()) {
                SourcePath prev = libraries.put(lib.getKey(), lib.getValue());
                if (prev != null && !prev.equals(lib.getValue())) {
                    throw new HumanReadableException("conflicting libraries for key %s: %s != %s", lib.getKey(),
                            lib.getValue(), prev);
                }
            }
        }
    }
    return ImmutableSortedMap.copyOf(libraries);
}

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

private RevTree createNodeTree(long size, int numTrees, TreeMap<Integer, Bucket> buckets) {

    ImmutableSortedMap<Integer, Bucket> innerTrees = ImmutableSortedMap.copyOf(buckets);

    final ObjectId id = HashObject.hashTree(null, null, innerTrees);

    return RevTreeBuilder.create(id, size, numTrees, null, null, innerTrees);
}

From source file:co.cask.cdap.internal.app.runtime.spark.ExecutionSparkContext.java

@Override
public synchronized <T extends Dataset> T getDataset(String name, Map<String, String> arguments) {
    Map<String, String> datasetArgs = RuntimeArguments.extractScope(Scope.DATASET, name, getRuntimeArguments());
    datasetArgs.putAll(arguments);/* w ww  .j  ava2 s  .co m*/

    String key = name + ImmutableSortedMap.copyOf(datasetArgs).toString();

    @SuppressWarnings("unchecked")
    T dataset = (T) datasets.get(key);
    if (dataset == null) {
        dataset = instantiateDataset(name, datasetArgs);
        datasets.put(key, dataset);
    }
    return dataset;
}

From source file:com.google.gcloud.datastore.BaseEntity.java

BaseEntity(Builder<K, ?> builder) {
    this.key = builder.key;
    this.properties = ImmutableSortedMap.copyOf(builder.properties);
}

From source file:ezbake.security.common.core.EzSecurityTokenUtils.java

public static byte[] serializeToken(final EzSecurityToken token) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream dataOutputStream = new DataOutputStream(baos);

    // Validity caveats - who, what, when
    putStringToOutputStream(dataOutputStream, token.getValidity().getIssuedTo(), EzSecurityConstant.CHARSET);
    if (token.getValidity().getIssuedFor() != null && !token.getValidity().getIssuedFor().isEmpty()) {
        putStringToOutputStream(dataOutputStream, token.getValidity().getIssuedFor(),
                EzSecurityConstant.CHARSET);
    }/*from   w  ww .  ja  v a  2  s. c  o m*/
    putStringToOutputStream(dataOutputStream, String.valueOf(token.getValidity().getNotAfter()),
            EzSecurityConstant.CHARSET);
    putStringToOutputStream(dataOutputStream, String.valueOf(token.getValidity().getNotBefore()),
            EzSecurityConstant.CHARSET);
    putStringToOutputStream(dataOutputStream, String.valueOf(token.getValidity().getIssuedTime()),
            EzSecurityConstant.CHARSET);

    // Token Type
    putStringToOutputStream(dataOutputStream, token.getType().toString(), EzSecurityConstant.CHARSET);

    // Principal - just the identifying information. The principal has it's own signature that should verify the rest
    putStringToOutputStream(dataOutputStream, token.getTokenPrincipal().getPrincipal(),
            EzSecurityConstant.CHARSET);
    if (token.getTokenPrincipal().getIssuer() != null) {
        dataOutputStream.write(token.getTokenPrincipal().getIssuer().getBytes(StandardCharsets.UTF_8));
    }
    if (token.getTokenPrincipal().getRequestChain() != null) {
        for (String chain : token.getTokenPrincipal().getRequestChain()) {
            putStringToOutputStream(dataOutputStream, chain, EzSecurityConstant.CHARSET);
        }
    }

    // Authorizations
    if (token.getAuthorizationLevel() != null && !token.getAuthorizationLevel().isEmpty()) {
        putStringToOutputStream(dataOutputStream, token.getAuthorizationLevel(), EzSecurityConstant.CHARSET);
    }
    if (token.getAuthorizations() != null) {
        if (token.getAuthorizations().getFormalAuthorizations() != null) {
            Set<String> auths = ImmutableSortedSet.copyOf(token.getAuthorizations().getFormalAuthorizations());
            for (String auth : auths) {
                putStringToOutputStream(dataOutputStream, auth, EzSecurityConstant.CHARSET);
            }
        }
        if (token.getAuthorizations().getExternalCommunityAuthorizations() != null) {
            Set<String> auths = ImmutableSortedSet
                    .copyOf(token.getAuthorizations().getExternalCommunityAuthorizations());
            for (String auth : auths) {
                putStringToOutputStream(dataOutputStream, auth, EzSecurityConstant.CHARSET);
            }
        }
        if (token.getAuthorizations().getPlatformObjectAuthorizations() != null) {
            Set<Long> auths = ImmutableSortedSet
                    .copyOf(token.getAuthorizations().getPlatformObjectAuthorizations());
            for (Long auth : auths) {
                putStringToOutputStream(dataOutputStream, Long.toString(auth), EzSecurityConstant.CHARSET);
            }
        }
    }

    if (token.getExternalProjectGroups() != null) {
        token.setExternalProjectGroups(ImmutableSortedMap.copyOf(token.getExternalProjectGroups()));
        for (Map.Entry<String, List<String>> project : token.getExternalProjectGroups().entrySet()) {
            putStringToOutputStream(dataOutputStream, project.getKey(), EzSecurityConstant.CHARSET);
            Collections.sort(project.getValue());
            for (String group : project.getValue()) {
                putStringToOutputStream(dataOutputStream, group, EzSecurityConstant.CHARSET);
            }
        }
    }

    if (token.getExternalCommunities() != null) {
        for (Map.Entry<String, CommunityMembership> entry : token.getExternalCommunities().entrySet()) {
            CommunityMembership community = entry.getValue();
            putStringToOutputStream(dataOutputStream, community.getName(), EzSecurityConstant.CHARSET);
            putStringToOutputStream(dataOutputStream, community.getType(), EzSecurityConstant.CHARSET);
            putStringToOutputStream(dataOutputStream, community.getOrganization(), EzSecurityConstant.CHARSET);
            Collections.sort(community.getGroups());
            for (String groups : community.getGroups()) {
                putStringToOutputStream(dataOutputStream, groups, EzSecurityConstant.CHARSET);
            }
            Collections.sort(community.getTopics());
            for (String topics : community.getTopics()) {
                putStringToOutputStream(dataOutputStream, topics, EzSecurityConstant.CHARSET);
            }
            Collections.sort(community.getRegions());
            for (String regions : community.getRegions()) {
                putStringToOutputStream(dataOutputStream, regions, EzSecurityConstant.CHARSET);
            }
            if (entry.getValue().getFlags() != null) {
                Map<String, Boolean> flags = ImmutableSortedMap.copyOf(entry.getValue().getFlags());
                for (Map.Entry<String, Boolean> fentry : flags.entrySet()) {
                    dataOutputStream.write(fentry.getKey().getBytes(StandardCharsets.UTF_8));
                    dataOutputStream
                            .write(Boolean.toString(fentry.getValue()).getBytes(StandardCharsets.UTF_8));
                }
            }
        }
    }

    putStringToOutputStream(dataOutputStream, String.valueOf(token.isValidForExternalRequest()),
            EzSecurityConstant.CHARSET);
    putStringToOutputStream(dataOutputStream, token.getCitizenship(), EzSecurityConstant.CHARSET);
    putStringToOutputStream(dataOutputStream, token.getOrganization(), EzSecurityConstant.CHARSET);

    dataOutputStream.flush();
    return baos.toByteArray();
}

From source file:se.sics.caracaldb.paxos.Paxos.java

private void decide(Instance i) {
    Value value = i.value;/*  ww w  .j  a  v a2  s  . c o m*/

    highestDecidedId = i.id;
    acceptedInstances.removeAll(i.id);
    acceptedSet.removeAll(i);
    votes.remove(i.id);
    //        if (value instanceof Noop) {
    //            LOG.debug("{}: Decided instance {} with Noop", self, i);
    //            // do nothing^^
    //            return;
    //        }
    if (!proposals.remove(value) && !(value instanceof Noop)) {
        LOG.warn("{}: Decided value was not in proposals: {}", self, value);
    }
    if (value instanceof Reconfigure) {
        Reconfigure rconf = (Reconfigure) value;
        if (rconf.view.compareTo(view) < 0) {
            LOG.error("{}: Reconfiguring from {} to outdated view: {}",
                    new Object[] { self, view, rconf.view });
            //return; // already installed this view
        }
        for (Address adr : Sets.difference(rconf.view.members, view.members)) {
            // for all newly added nodes
            trigger(new Install(self, adr, b, rconf, highestDecidedId, ImmutableSortedMap.copyOf(decidedLog)),
                    net);
        }
        trigger(toELDReconf(rconf), eld);
        view = rconf.view;
        quorum = rconf.quorum;
        if (view.members.size() < quorum) {
            LOG.warn(
                    "{}: Reconfiguring with less nodes in group than "
                            + "required for quorum (Group: {} - Quorum: {})",
                    new Object[] { self, view.members.size(), quorum });
        }

    }
    trigger(new Decide(i.id, value), rLog);
    LOG.debug("{}: Decided {}", self, value);
}

From source file:monasca.thresh.infrastructure.persistence.hibernate.AlarmSqlImpl.java

private byte[] calculateDimensionSHA1(final Map<String, String> dimensions) {
    // Calculate dimensions sha1 hash id.
    final StringBuilder dimensionIdStringToHash = new StringBuilder("");
    if (dimensions != null && !dimensions.isEmpty()) {
        // Sort the dimensions on name and value.
        final Map<String, String> dimensionTreeMap = Maps.newTreeMap(ImmutableSortedMap.copyOf(dimensions));
        for (final String dimensionName : dimensionTreeMap.keySet()) {
            if (dimensionName != null && !dimensionName.isEmpty()) {
                final String dimensionValue = dimensionTreeMap.get(dimensionName);
                if (dimensionValue != null && !dimensionValue.isEmpty()) {
                    dimensionIdStringToHash.append(this.truncateString(dimensionName, MAX_COLUMN_LENGTH))
                            .append(this.truncateString(dimensionValue, MAX_COLUMN_LENGTH));
                }//from ww w. j  ava 2  s.  co  m
            }
        }
    }
    return DigestUtils.sha(dimensionIdStringToHash.toString());
}

From source file:org.glowroot.ui.JvmJsonService.java

@GET(path = "/backend/jvm/system-properties", permission = "agent:jvm:systemProperties")
String getSystemProperties(@BindAgentId String agentId) throws Exception {
    checkNotNull(liveJvmService);/*from  ww  w  . j a va 2s  . co  m*/
    Map<String, String> properties;
    try {
        properties = liveJvmService.getSystemProperties(agentId);
    } catch (AgentNotConnectedException e) {
        logger.debug(e.getMessage(), e);
        return "{\"agentNotConnected\":true}";
    } catch (AgentUnsupportedOperationException e) {
        // this operation introduced in 0.9.2
        logger.debug(e.getMessage(), e);
        return getAgentUnsupportedOperationResponse(agentId);
    }
    // mask here to provide support in central for agents prior to 0.10.0
    List<String> maskSystemProperties = getJvmMaskSystemProperties(agentId);
    properties = Masking.maskSystemProperties(properties, maskSystemProperties);

    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
    try {
        jg.writeStartObject();
        jg.writeArrayFieldStart("properties");
        for (Map.Entry<String, String> entry : ImmutableSortedMap.copyOf(properties).entrySet()) {
            jg.writeStartObject();
            String propertyName = entry.getKey();
            jg.writeStringField("name", propertyName);
            if (PATH_SEPARATED_SYSTEM_PROPERTIES.contains(propertyName)) {
                jg.writeArrayFieldStart("value");
                for (String item : Splitter.on(File.pathSeparatorChar).splitToList(entry.getValue())) {
                    jg.writeString(item);
                }
                jg.writeEndArray();
            } else {
                jg.writeStringField("value", entry.getValue());
            }
            jg.writeEndObject();
        }
        jg.writeEndArray();
        jg.writeEndObject();
    } finally {
        jg.close();
    }
    return sb.toString();
}

From source file:com.facebook.buck.features.lua.LuaBinaryDescription.java

/**
 * @return the native library map with additional entries for library names with the version
 *     suffix stripped (e.g. libfoo.so.1.0 -> libfoo.so) to appease LuaJIT, which wants to load
 *     libraries using the build-time name.
 *///w ww.  ja v a  2  s  .c o  m
private ImmutableSortedMap<String, SourcePath> addVersionLessLibraries(CxxPlatform cxxPlatform,
        ImmutableSortedMap<String, SourcePath> libraries) {
    Pattern versionedExtension = Pattern.compile(Joiner.on("[.\\d]*")
            .join(Iterables.transform(
                    Splitter.on("%s").split(cxxPlatform.getSharedLibraryVersionedExtensionFormat()),
                    input -> input.isEmpty() ? input : Pattern.quote(input))));
    Map<String, SourcePath> librariesPaths = new HashMap<>();
    for (Map.Entry<String, SourcePath> ent : libraries.entrySet()) {
        String name = ent.getKey();

        if (librariesPaths.containsKey(name) && librariesPaths.get(name) != ent.getValue()) {
            throw new HumanReadableException("Library %s has multiple possible paths: %s and %s", name,
                    ent.getValue(), librariesPaths.get(name));
        }

        librariesPaths.put(name, ent.getValue());
        Matcher matcher = versionedExtension.matcher(name);
        String versionLessName = matcher.replaceAll(cxxPlatform.getSharedLibraryExtension());
        if (!versionLessName.equals(ent.getKey()) && !libraries.containsKey(versionLessName)) {
            librariesPaths.put(versionLessName, ent.getValue());
        }
    }
    return ImmutableSortedMap.copyOf(librariesPaths);
}