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

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

Introduction

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

Prototype

public final ImmutableSet<Entry<K, V>> entrySet() 

Source Link

Usage

From source file:com.facebook.buck.util.versioncontrol.VersionControlStatsGenerator.java

private void generateStats() throws InterruptedException, VersionControlCommandFailedException {
    LOG.info("Starting generation of version control stats.");

    VersionControlCmdLineInterface vcCmdLineInterface = versionControlCmdLineInterfaceFactory
            .createCmdLineInterface();/* ww  w  .ja v a2s  . c  om*/

    if (!vcCmdLineInterface.isSupportedVersionControlSystem()) {
        LOG.warn("Skipping generation of version control stats as unsupported repository type.");
        return;
    }

    VersionControlStats.Builder versionControlStats = VersionControlStats.builder();
    try (SimplePerfEvent.Scope ignored = SimplePerfEvent.scope(buckEventBus, "gen_source_control_info")) {
        try {
            // Get a list of the revision ids of all the tracked bookmarks.
            ImmutableMap<String, String> bookmarksRevisionIds = vcCmdLineInterface
                    .bookmarksRevisionsId(TRACKED_BOOKMARKS);
            // Get the current revision id.
            String currentRevisionId = vcCmdLineInterface.currentRevisionId();
            // Get the common ancestor of master and current revision
            String branchedFromMasterRevisionId = vcCmdLineInterface.commonAncestor(currentRevisionId,
                    bookmarksRevisionIds.get("remote/master"));
            // Get the list of tracked changes files.
            ImmutableSet<String> changedFiles = vcCmdLineInterface.changedFiles(".");

            ImmutableSet.Builder<String> baseBookmarks = ImmutableSet.builder();
            for (Map.Entry<String, String> bookmark : bookmarksRevisionIds.entrySet()) {
                if (bookmark.getValue().startsWith(currentRevisionId)) {
                    baseBookmarks.add(bookmark.getKey());
                }
            }

            versionControlStats.setPathsChangedInWorkingDirectory(changedFiles)
                    .setCurrentRevisionId(currentRevisionId)
                    .setBranchedFromMasterRevisionId(branchedFromMasterRevisionId)
                    .setBaseBookmarks(baseBookmarks.build()).build();
        } catch (VersionControlCommandFailedException e) {
            LOG.warn("Failed to gather source control stats.");
        }
    }

    LOG.info("Stats generated successfully. \n%s", versionControlStats);
    buckEventBus.post(new VersionControlStatsEvent(versionControlStats.build()));
}

From source file:com.google.api.server.spi.swagger.SwaggerGenerator.java

private void writeAudiences(Swagger swagger, ApiMethodConfig methodConfig, boolean writeInternal,
        Operation operation) throws ApiConfigException {
    ApiIssuerAudienceConfig issuerAudiences = methodConfig.getIssuerAudiences();
    boolean issuerAudiencesIsEmpty = !issuerAudiences.isSpecified() || issuerAudiences.isEmpty();
    List<String> legacyAudiences = methodConfig.getAudiences();
    boolean legacyAudiencesIsEmpty = legacyAudiences == null || legacyAudiences.isEmpty();
    if (issuerAudiencesIsEmpty && legacyAudiencesIsEmpty) {
        return;//from www  .  j a v a 2 s  . c  om
    }
    ImmutableMap<String, Collection<String>> audiences = issuerAudiences.asMap();
    // For reversability purposes, we can't use helper data structures here. When Swagger reads
    // the document back in, it uses primitive data structures.
    ImmutableList.Builder<ImmutableMap<String, ImmutableMap<String, List<String>>>> xSecurity = ImmutableList
            .builder();
    if (!issuerAudiencesIsEmpty) {
        for (Map.Entry<String, Collection<String>> entry : audiences.entrySet()) {
            operation.addSecurity(entry.getKey(), ImmutableList.<String>of());
            if (writeInternal) {
                xSecurity.add(ImmutableMap.of(entry.getKey(), createAudiences(entry.getValue())));
            }
        }
    }
    if (!legacyAudiencesIsEmpty) {
        addNonConflictingSecurityDefinition(swagger, ApiIssuerConfigs.GOOGLE_ID_TOKEN_ISSUER);
        addNonConflictingSecurityDefinition(swagger, ApiIssuerConfigs.GOOGLE_ID_TOKEN_ISSUER_ALT);
        operation.addSecurity(Constant.GOOGLE_ID_TOKEN_NAME, ImmutableList.<String>of());
        operation.addSecurity(Constant.GOOGLE_ID_TOKEN_NAME_HTTPS, ImmutableList.<String>of());
        if (writeInternal) {
            ImmutableMap<String, List<String>> legacySwaggerAudiences = createAudiences(legacyAudiences);
            xSecurity.add(ImmutableMap.of(Constant.GOOGLE_ID_TOKEN_NAME, legacySwaggerAudiences));
            xSecurity.add(ImmutableMap.of(Constant.GOOGLE_ID_TOKEN_NAME_HTTPS, legacySwaggerAudiences));
        }
    }
    if (writeInternal) {
        operation.setVendorExtension("x-security", xSecurity.build());
    }
}

From source file:com.pinterest.pinlater.backends.mysql.PinLaterMySQLBackend.java

private ImmutableMap.Entry<String, MySQLDataSources> getRandomShard() {
    ImmutableMap<String, MySQLDataSources> shardMap = shardMapRef.get();
    if (shardMap == null || shardMap.isEmpty()) {
        return null;
    }//from w ww.  j  a va 2  s .  co m
    int rand = RANDOM.nextInt(shardMap.size());
    return shardMap.entrySet().asList().get(rand);
}

From source file:org.trnltk.morphology.contextless.rootfinder.BruteForceVerbRootFinder.java

private Set<DynamicRoot> getPossiblePassiveRoots(TurkicLetter lastLetter, TurkishSequence partialInput,
        TurkishSequence wholeSurface, DynamicRoot noAttrRoot) {
    final String wholeSurfaceStr = wholeSurface.getUnderlyingString();
    final String partialInputStr = partialInput.getUnderlyingString();

    final boolean mightHavePassive_Il = (!lastLetter.isVowel() && this.strStartsWithAnyAdditionOfStr(
            wholeSurfaceStr, partialInputStr, Arrays.asList("l", "il", "ul", "l")))
            || (lastLetter.isVowel() && wholeSurfaceStr.startsWith(partialInputStr + 'l'));

    final boolean mightHavePassive_In = (!lastLetter.isVowel() && this.strStartsWithAnyAdditionOfStr(
            wholeSurfaceStr, partialInputStr, Arrays.asList("n", "in", "un", "n")))
            || (lastLetter.isVowel() && wholeSurfaceStr.startsWith(partialInputStr + 'n'));

    final boolean mightHavePassive_InIl = (!lastLetter.isVowel() && this.strStartsWithAnyAdditionOfStr(
            wholeSurfaceStr, partialInputStr, Arrays.asList("nl", "inil", "unul", "nl")))
            || (lastLetter.isVowel() && this.strStartsWithAnyAdditionOfStr(wholeSurfaceStr, partialInputStr,
                    Arrays.asList("nl", "nil", "nul", "nl")));

    final ImmutableMap<LexemeAttribute, Boolean> mightHavePassives = new ImmutableMap.Builder<LexemeAttribute, Boolean>()
            .put(LexemeAttribute.Passive_Il, mightHavePassive_Il)
            .put(LexemeAttribute.Passive_In, mightHavePassive_In)
            .put(LexemeAttribute.Passive_InIl, mightHavePassive_InIl).build();

    final HashSet<DynamicRoot> passiveRoots = new HashSet<DynamicRoot>();

    for (Map.Entry<LexemeAttribute, Boolean> lexemeAttributeBooleanEntry : mightHavePassives.entrySet()) {
        final LexemeAttribute passiveAttr = lexemeAttributeBooleanEntry.getKey();
        final Boolean mightHaveHappened = lexemeAttributeBooleanEntry.getValue();

        if (!mightHaveHappened)
            continue;

        // cannot have other passives at the same time
        // cannot have any other causative at the same time
        // cannot have progressive vowel drop at the same time
        // cannot have aorist_A or aorist_I at the same time

        final DynamicRoot generatedRoot = new DynamicRoot(noAttrRoot);

        generatedRoot.getLexeme().setAttributes(EnumSet.of(passiveAttr));

        generatedRoot.setPhoneticAttributes(this.phoneticsAnalyzer.calculatePhoneticAttributes(partialInput,
                generatedRoot.getLexeme().getAttributes()));

        passiveRoots.add(generatedRoot);

    }// w ww .  j a  va  2 s . c  om

    return passiveRoots;
}

From source file:com.google.javascript.jscomp.TypeTransformation.java

private JSType createRecordType(ImmutableMap<String, JSType> props) {
    RecordTypeBuilder builder = new RecordTypeBuilder(typeRegistry);
    for (Entry<String, JSType> e : props.entrySet()) {
        builder.addProperty(e.getKey(), e.getValue(), null);
    }/*from  w ww  .  ja  v  a 2  s . c  o  m*/
    return builder.build();
}

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

private ImmutableMap<CxxPreprocessAndCompile, SourcePath> requirePreprocessAndCompileRules(
        BuildRuleResolver resolver, CxxPreprocessMode strategy, ImmutableMap<String, CxxSource> sources,
        PicType pic) {/*from w w w .  j  a v  a  2 s .c  o  m*/

    ImmutableList.Builder<CxxPreprocessAndCompile> objects = ImmutableList.builder();

    for (Map.Entry<String, CxxSource> entry : sources.entrySet()) {
        String name = entry.getKey();
        CxxSource source = entry.getValue();

        Preconditions.checkState(CxxSourceTypes.isPreprocessableType(source.getType())
                || CxxSourceTypes.isCompilableType(source.getType()));

        switch (strategy) {

        case PIPED:
        case COMBINED: {
            CxxPreprocessAndCompile rule;

            // If it's a preprocessable source, use a combine preprocess-and-compile build rule.
            // Otherwise, use a regular compile rule.
            if (CxxSourceTypes.isPreprocessableType(source.getType())) {
                rule = requirePreprocessAndCompileBuildRule(resolver, name, source, pic, strategy);
            } else {
                rule = requireCompileBuildRule(resolver, name, source, pic);
            }

            objects.add(rule);
            break;
        }

        case SEPARATE: {

            // If this is a preprocessable source, first create the preprocess build rule and
            // update the source and name to represent its compilable output.
            if (CxxSourceTypes.isPreprocessableType(source.getType())) {
                CxxPreprocessAndCompile rule = requirePreprocessBuildRule(resolver, name, source, pic);
                source = CxxSource.copyOf(source)
                        .withType(CxxSourceTypes.getPreprocessorOutputType(source.getType()))
                        .withPath(new BuildTargetSourcePath(rule.getBuildTarget()));
            }

            // Now build the compile build rule.
            CxxPreprocessAndCompile rule = requireCompileBuildRule(resolver, name, source, pic);
            objects.add(rule);

            break;
        }

        // $CASES-OMITTED$
        default:
            throw new IllegalStateException();
        }
    }

    return FluentIterable.from(objects.build()).toMap(new Function<CxxPreprocessAndCompile, SourcePath>() {
        @Override
        public SourcePath apply(CxxPreprocessAndCompile input) {
            return new BuildTargetSourcePath(input.getBuildTarget());
        }
    });
}

From source file:com.pinterest.pinlater.backends.mysql.PinLaterMySQLBackend.java

private ImmutableMap.Entry<String, MySQLDataSources> getRandomEnqueueableShard() {
    ImmutableMap<String, MySQLDataSources> enqueueableShardMap = getEnqueueableShards();
    if (enqueueableShardMap.isEmpty()) {
        return null;
    }/*from   ww  w  .  jav  a  2s  .co m*/
    int rand = RANDOM.nextInt(enqueueableShardMap.size());
    return enqueueableShardMap.entrySet().asList().get(rand);
}

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

public ImmutableSet<CxxInferCapture> createInferCaptureBuildRules(ImmutableMap<String, CxxSource> sources,
        PicType pic, CxxInferTools inferTools, CxxInferSourceFilter sourceFilter) {

    ImmutableSet.Builder<CxxInferCapture> objects = ImmutableSet.builder();

    for (Map.Entry<String, CxxSource> entry : sources.entrySet()) {
        String name = entry.getKey();
        CxxSource source = entry.getValue();

        Preconditions.checkState(CxxSourceTypes.isPreprocessableType(source.getType()),
                "Only preprocessable source types are currently supported");

        if (sourceFilter.isBlacklisted(source)) {
            continue;
        }/*from  w ww  .  j  a  v a  2s.  c om*/

        CxxInferCapture rule = requireInferCaptureBuildRule(name, source, pic, inferTools);
        objects.add(rule);
    }

    return objects.build();
}

From source file:com.facebook.buck.thrift.ThriftCompiler.java

public ThriftCompiler(BuildRuleParams params, Tool compiler, ImmutableList<String> flags, Path outputDir,
        SourcePath input, String language, ImmutableSet<String> options, ImmutableList<Path> includeRoots,
        ImmutableSet<Path> headerMaps, ImmutableMap<Path, SourcePath> includes,
        ImmutableSortedSet<String> generatedSources) {
    super(params);
    this.compiler = compiler;
    this.flags = flags;
    this.outputDir = outputDir;
    this.input = input;
    this.language = language;
    this.options = options;
    this.includeRoots = includeRoots;
    this.headerMaps = headerMaps;
    this.generatedSources = generatedSources;

    // Hash the layout of each potentially included thrift file dependency and it's contents.
    // We do this here, rather than returning them from `getInputsToCompareToOutput` so that
    // we can match the contents hash up with where it was laid out in the include search path.
    ImmutableMap.Builder<String, SourcePath> builder = ImmutableMap.builder();
    for (Map.Entry<Path, SourcePath> entry : includes.entrySet()) {
        builder.put(entry.getKey().toString(), entry.getValue());
    }//from w  w w  .  j a  v  a 2  s . c om
    this.includes = builder.build();
}

From source file:codes.writeonce.maven.plugins.soy.CompileMojo.java

private void generateJs(List<Path> soyFiles, List<Path> xliffFiles, byte[] sourceDigestBytes)
        throws IOException, NoSuchAlgorithmException {

    final Path outputRootPath = jsOutputDirectory.toPath();

    FileUtils.deleteDirectory(jsOutputDirectory);
    Files.createDirectories(outputRootPath);

    FileUtils.deleteDirectory(javaOutputDirectory);

    final Path javaSourceOutputPath = getJavaSourceOutputPath();
    Files.createDirectories(javaSourceOutputPath);

    final SoyFileSet soyFileSet = getSoyFileSet(soyFiles);

    if (xliffFiles.isEmpty()) {
        getLog().info("No translations detected. Using default messages.");
        generateJs(soyFiles, soyFileSet, null, outputRootPath);
    } else {/*from www.  j  ava 2  s .c om*/
        final SoyMsgBundleHandler smbh = new SoyMsgBundleHandler(new XliffMsgPlugin());
        for (final Path xliffFilePath : xliffFiles) {
            final SoyMsgBundle smb = smbh.createFromFile(translations.toPath().resolve(xliffFilePath).toFile());
            final Path outputPath = Utils.removeSuffix(outputRootPath.resolve(xliffFilePath), XLIFF_EXTENSION);
            generateJs(soyFiles, soyFileSet, smb, outputPath);
        }
    }

    final ImmutableMap<String, String> parseInfo = SoyFileSetAccessor.generateParseInfo(soyFileSet, javaPackage,
            javaClassNameSource.getValue());

    final Charset classSourceCharset;
    if (StringUtils.isEmpty(javaOutputCharsetName)) {
        classSourceCharset = Charset.defaultCharset();
        getLog().warn("Using platform encoding (" + classSourceCharset.displayName()
                + " actually) to generate SOY sources, i.e. build is platform dependent!");
    } else {
        classSourceCharset = Charset.forName(javaOutputCharsetName);
    }

    for (final Map.Entry<String, String> entry : parseInfo.entrySet()) {
        final String classFileName = entry.getKey();
        final String classSource = entry.getValue();
        try (FileOutputStream out = new FileOutputStream(javaSourceOutputPath.resolve(classFileName).toFile());
                OutputStreamWriter writer = new OutputStreamWriter(out, classSourceCharset)) {
            writer.write(classSource);
        }
    }

    final byte[] targetDigestBytes = getGeneratedFilesDigest();

    final Path statusFilePath = getStatusFilePath();
    Files.createDirectories(statusFilePath.getParent());
    try (FileOutputStream out = new FileOutputStream(statusFilePath.toFile());
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(out, TEXT_DIGEST_CHARSET);
            BufferedWriter writer = new BufferedWriter(outputStreamWriter)) {
        writer.write(Hex.encodeHex(sourceDigestBytes));
        writer.newLine();
        writer.write(Hex.encodeHex(targetDigestBytes));
        writer.newLine();
    }
}