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.google.devtools.build.lib.packages.PackageFactory.java

/**
 * Returns a function-value implementing "package" in the specified package
 * context.//from  w  w w .j a v  a2  s. c om
 */
private static BaseFunction newPackageFunction(
        final ImmutableMap<String, PackageArgument<?>> packageArguments) {
    // Flatten the map of argument name of PackageArgument specifier in two co-indexed arrays:
    // one for the argument names, to create a FunctionSignature when we create the function,
    // one of the PackageArgument specifiers, over which to iterate at every function invocation
    // at the same time that we iterate over the function arguments.
    final int numArgs = packageArguments.size();
    final String[] argumentNames = new String[numArgs];
    final PackageArgument<?>[] argumentSpecifiers = new PackageArgument<?>[numArgs];
    int i = 0;
    for (Map.Entry<String, PackageArgument<?>> entry : packageArguments.entrySet()) {
        argumentNames[i] = entry.getKey();
        argumentSpecifiers[i++] = entry.getValue();
    }

    return new BaseFunction("package", FunctionSignature.namedOnly(0, argumentNames)) {
        @Override
        public Object call(Object[] arguments, FuncallExpression ast, Environment env) throws EvalException {

            Package.Builder pkgBuilder = getContext(env, ast).pkgBuilder;

            // Validate parameter list
            if (pkgBuilder.isPackageFunctionUsed()) {
                throw new EvalException(ast.getLocation(), "'package' can only be used once per BUILD file");
            }
            pkgBuilder.setPackageFunctionUsed();

            // Parse params
            boolean foundParameter = false;

            for (int i = 0; i < numArgs; i++) {
                Object value = arguments[i];
                if (value != null) {
                    foundParameter = true;
                    argumentSpecifiers[i].convertAndProcess(pkgBuilder, ast.getLocation(), value);
                }
            }

            if (!foundParameter) {
                throw new EvalException(ast.getLocation(),
                        "at least one argument must be given to the 'package' function");
            }

            return Runtime.NONE;
        }
    };
}

From source file:org.lanternpowered.server.block.state.LanternBlockState.java

LanternBlockState(LanternBlockStateMap baseState, ImmutableMap<BlockTrait<?>, Comparable<?>> traitValues) {
    this.traitValues = traitValues;
    this.baseState = baseState;

    ImmutableBiMap.Builder<Key<Value<?>>, BlockTrait<?>> builder = ImmutableBiMap.builder();
    for (BlockTrait trait : traitValues.keySet()) {
        builder.put(((LanternBlockTrait) trait).getKey(), trait);
    }//www .  j a  v a 2 s . c om
    this.keyToBlockTrait = builder.build();

    final StringBuilder idBuilder = new StringBuilder();
    idBuilder.append(
            baseState.getBlockType().getId().substring(baseState.getBlockType().getPluginId().length() + 1));
    if (!traitValues.isEmpty()) {
        idBuilder.append('[');
        final Joiner joiner = Joiner.on(',');
        final List<String> propertyValues = new ArrayList<>();
        for (Map.Entry<BlockTrait<?>, Comparable<?>> entry : traitValues.entrySet()) {
            propertyValues.add(
                    entry.getKey().getName() + "=" + entry.getValue().toString().toLowerCase(Locale.ENGLISH));
        }
        idBuilder.append(joiner.join(propertyValues));
        idBuilder.append(']');
    }
    this.name = idBuilder.toString();
    this.id = baseState.getBlockType().getPluginId() + ':' + this.name;
}

From source file:com.google.template.soy.soyparse.PluginResolver.java

public PluginResolver(Mode mode, ImmutableMap<String, SoyPrintDirective> soyPrintDirectives,
        ImmutableMap<String, SoyFunction> soyFunctions, ImmutableMap<String, SoySourceFunction> sourceFunctions,
        ErrorReporter reporter) {/*  w  ww . jav  a  2 s . com*/
    this.mode = checkNotNull(mode);
    this.printDirectives = checkNotNull(soyPrintDirectives);
    this.reporter = checkNotNull(reporter);
    for (String illegalName : ILLEGAL_PLUGIN_NAMES) {
        if (soyFunctions.containsKey(illegalName) || sourceFunctions.containsKey(illegalName)) {
            reporter.report(SourceLocation.UNKNOWN, PLUGIN_NAME_NOT_ALLOWED, illegalName);
        }
    }
    // Merge the SoyFunctions & SoySourceFunctions.  While merging, confirm that we only have
    // one implementation for each plugin. They can overlap, but impl must be the same. This
    // indicates a partially migrated plugin.
    // Also confirm that each SoySourceFunction has a @SoyFunctionSignature, which is required.
    ImmutableMap.Builder<String, Object> mergedFunctions = ImmutableMap.builder();
    for (Map.Entry<String, SoyFunction> entry : soyFunctions.entrySet()) {
        SoySourceFunction source = sourceFunctions.get(entry.getKey());
        if (source != null) {
            if (source != entry.getValue()) {
                reporter.report(SourceLocation.UNKNOWN, DIFFERENT_IMPLS_REGISTERED, entry.getKey(),
                        entry.getValue(), source);
            }
        } else {
            // We only insert non-duplicates into the merged map to avoid IllegalArugmentExceptions
            // building the map.
            mergedFunctions.put(entry.getKey(), entry.getValue());
        }
    }
    mergedFunctions.putAll(sourceFunctions);
    this.functions = mergedFunctions.build();

    // Go back over our merged functions and validate all the SoySourceFunction implementations.
    // We explicitly look *after* merging because SoySourceFunctions might be registered
    // as SoyFunctions if they also implemented other backends like SoyJsFunction.
    for (Object function : this.functions.values()) {
        if (function instanceof SoySourceFunction) {
            if (!function.getClass().isAnnotationPresent(SoyFunctionSignature.class)) {
                // Make sure a function sig exists.
                reporter.report(SourceLocation.UNKNOWN, MISSING_FUNCTION_SIGNATURE,
                        function.getClass().getName());
            } else if (function instanceof SoyJavaSourceFunction) {
                // Also make sure that the applyForJavaSource impl uses a single plugin instance.
                // We don't support multiple instances.
                Set<Class<?>> instances = PluginInstanceFinder.find((SoyJavaSourceFunction) function);
                if (instances.size() > 1) {
                    reporter.report(SourceLocation.UNKNOWN, MULTIPLE_PLUGIN_INSTANCES,
                            function.getClass().getName(), instances);
                }
            }
        }
    }
}

From source file:com.google.template.soy.passes.PluginResolver.java

public PluginResolver(Mode mode, ImmutableMap<String, SoyPrintDirective> soyPrintDirectives,
        ImmutableMap<String, SoyFunction> soyFunctions, ImmutableMap<String, SoySourceFunction> sourceFunctions,
        ErrorReporter reporter) {//from   ww w  .  j  a  v a 2 s. c  o  m
    this.mode = checkNotNull(mode);
    this.printDirectives = checkNotNull(soyPrintDirectives);
    this.reporter = checkNotNull(reporter);
    for (String illegalName : BaseUtils.ILLEGAL_PLUGIN_NAMES) {
        if (soyFunctions.containsKey(illegalName) || sourceFunctions.containsKey(illegalName)) {
            reporter.report(SourceLocation.UNKNOWN, PLUGIN_NAME_NOT_ALLOWED, illegalName);
        }
    }
    // Merge the SoyFunctions & SoySourceFunctions.  While merging, confirm that we only have
    // one implementation for each plugin. They can overlap, but impl must be the same. This
    // indicates a partially migrated plugin.
    // Also confirm that each SoySourceFunction has a @SoyFunctionSignature, which is required.
    ImmutableMap.Builder<String, Object> mergedFunctions = ImmutableMap.builder();
    for (Map.Entry<String, SoyFunction> entry : soyFunctions.entrySet()) {
        SoySourceFunction source = sourceFunctions.get(entry.getKey());
        if (source != null) {
            if (source != entry.getValue()) {
                reporter.report(SourceLocation.UNKNOWN, DIFFERENT_IMPLS_REGISTERED, entry.getKey(),
                        entry.getValue(), source);
            }
        } else {
            // We only insert non-duplicates into the merged map to avoid IllegalArugmentExceptions
            // building the map.
            mergedFunctions.put(entry.getKey(), entry.getValue());
        }
    }
    mergedFunctions.putAll(sourceFunctions);
    this.functions = mergedFunctions.build();

    // Go back over our merged functions and validate all the SoySourceFunction implementations.
    // We explicitly look *after* merging because SoySourceFunctions might be registered
    // as SoyFunctions if they also implemented other backends like SoyJsFunction.
    for (Object function : this.functions.values()) {
        if (function instanceof SoySourceFunction) {
            if (!function.getClass().isAnnotationPresent(SoyFunctionSignature.class)) {
                // Make sure a function sig exists.
                reporter.report(SourceLocation.UNKNOWN, MISSING_FUNCTION_SIGNATURE,
                        function.getClass().getName());
            } else if (function instanceof SoyJavaSourceFunction) {
                // Also make sure that the applyForJavaSource impl uses a single plugin instance.
                // We don't support multiple instances.
                Set<Class<?>> instances = PluginInstanceFinder.find((SoyJavaSourceFunction) function);
                if (instances.size() > 1) {
                    reporter.report(SourceLocation.UNKNOWN, MULTIPLE_PLUGIN_INSTANCES,
                            function.getClass().getName(), instances);
                }
            }
        }
    }
}

From source file:net.oneandone.troilus.DaoImpl.java

@Override
public SingleReadWithUnit<Optional<Record>, Record> readWithKey(ImmutableMap<String, Object> composedkey) {
    Map<String, ImmutableList<Object>> keys = Maps.newHashMap();
    for (Entry<String, Object> entry : composedkey.entrySet()) {
        keys.put(entry.getKey(), ImmutableList.of(entry.getValue()));
    }//from   ww w. jav  a 2 s .  com

    return new SingleReadQueryAdapter(ctx,
            new SingleReadQuery(ctx, new ReadQueryDataImpl(tablename).keys(ImmutableMap.copyOf(keys))));
}

From source file:org.basepom.mojo.duplicatefinder.DuplicateFinderMojo.java

@Override
public void execute() throws MojoExecutionException {
    try {/*from  ww w . j a v  a 2 s. c  o m*/
        if (skip) {
            LOG.report(quiet, "Skipping duplicate-finder execution!");
        } else if (!includePomProjects && "pom".equals(project.getArtifact().getType())) {
            LOG.report(quiet, "Ignoring POM project!");
        } else {
            if (printEqualFiles) {
                printState.add(CONFLICT_CONTENT_EQUAL);
            }

            if (failBuildInCaseOfConflict || failBuildInCaseOfEqualContentConflict) {
                printState.add(CONFLICT_CONTENT_EQUAL);

                failState.add(CONFLICT_CONTENT_EQUAL);
                failState.add(CONFLICT_CONTENT_DIFFERENT);
            }

            if (failBuildInCaseOfDifferentContentConflict) {
                failState.add(CONFLICT_CONTENT_DIFFERENT);
            }

            if (includeBootClasspath) {
                double jdkVersion = Double.parseDouble(System.getProperty("java.vm.specification.version"));
                if (jdkVersion > 1.8d) {
                    LOG.warn(
                            "<includeBootClasspath> is not supported on JDK 9 and beyond! Duplicates for JDK classes will not be detected!");
                }
            }

            try {
                // Prep conflicting dependencies
                MavenCoordinates projectCoordinates = new MavenCoordinates(project.getArtifact());

                for (ConflictingDependency conflictingDependency : conflictingDependencies) {
                    conflictingDependency.addProjectMavenCoordinates(projectCoordinates);
                }

                // Find boot classpath information

                ImmutableSet.Builder<File> bootClasspathBuilder = ImmutableSet.builder();

                if (includeBootClasspath) {
                    String value = System.getProperty(bootClasspathProperty);
                    if (value != null) {
                        for (String entry : Splitter.on(File.pathSeparatorChar).split(value)) {
                            File file = new File(entry);
                            if (file.exists()) {
                                LOG.debug("Adding '%s' as a boot classpath element", entry);
                                bootClasspathBuilder.add(file);
                            } else {
                                LOG.debug("Ignoring '%s', does not exist.", entry);
                            }
                        }
                    }
                }

                final ImmutableSet<File> bootClasspath = bootClasspathBuilder.build();

                final ArtifactFileResolver artifactFileResolver = new ArtifactFileResolver(project,
                        bootClasspath, preferLocal);
                final ImmutableMap.Builder<String, Entry<ResultCollector, ClasspathDescriptor>> classpathResultBuilder = ImmutableMap
                        .builder();

                if (checkCompileClasspath) {
                    LOG.report(quiet, "Checking compile classpath");
                    final ResultCollector resultCollector = new ResultCollector(printState, failState);
                    final ClasspathDescriptor classpathDescriptor = checkClasspath(resultCollector,
                            artifactFileResolver, COMPILE_SCOPE, bootClasspath, getOutputDirectory(project));
                    classpathResultBuilder.put("compile",
                            new SimpleImmutableEntry<ResultCollector, ClasspathDescriptor>(resultCollector,
                                    classpathDescriptor));
                }

                if (checkRuntimeClasspath) {
                    LOG.report(quiet, "Checking runtime classpath");
                    final ResultCollector resultCollector = new ResultCollector(printState, failState);
                    final ClasspathDescriptor classpathDescriptor = checkClasspath(resultCollector,
                            artifactFileResolver, RUNTIME_SCOPE, bootClasspath, getOutputDirectory(project));
                    classpathResultBuilder.put("runtime",
                            new SimpleImmutableEntry<ResultCollector, ClasspathDescriptor>(resultCollector,
                                    classpathDescriptor));
                }

                if (checkTestClasspath) {
                    LOG.report(quiet, "Checking test classpath");
                    final ResultCollector resultCollector = new ResultCollector(printState, failState);
                    final ClasspathDescriptor classpathDescriptor = checkClasspath(resultCollector,
                            artifactFileResolver, TEST_SCOPE, bootClasspath, getOutputDirectory(project),
                            getTestOutputDirectory(project));
                    classpathResultBuilder.put("test",
                            new SimpleImmutableEntry<ResultCollector, ClasspathDescriptor>(resultCollector,
                                    classpathDescriptor));
                }

                final ImmutableMap<String, Entry<ResultCollector, ClasspathDescriptor>> classpathResults = classpathResultBuilder
                        .build();

                if (useResultFile) {
                    checkState(resultFile != null, "resultFile must be set if useResultFile is true");
                    writeResultFile(resultFile, classpathResults);
                }

                boolean failed = false;

                for (Map.Entry<String, Entry<ResultCollector, ClasspathDescriptor>> classpathEntry : classpathResults
                        .entrySet()) {
                    String classpathName = classpathEntry.getKey();
                    ResultCollector resultCollector = classpathEntry.getValue().getKey();

                    for (final ConflictState state : printState) {
                        for (final ConflictType type : ConflictType.values()) {
                            if (resultCollector.hasConflictsFor(type, state)) {
                                final Map<String, Collection<ConflictResult>> results = resultCollector
                                        .getResults(type, state);
                                for (final Map.Entry<String, Collection<ConflictResult>> entry : results
                                        .entrySet()) {
                                    final String artifactNames = entry.getKey();
                                    final Collection<ConflictResult> conflictResults = entry.getValue();

                                    LOG.warn("Found duplicate %s %s in [%s]:", state.getHint(), type.getType(),
                                            artifactNames);
                                    for (final ConflictResult conflictResult : conflictResults) {
                                        LOG.warn("  %s", conflictResult.getName());
                                    }
                                }
                            }
                        }
                    }

                    failed |= resultCollector.isFailed();

                    if (resultCollector.isFailed()) {
                        LOG.warn("Found duplicate classes/resources in %s classpath.", classpathName);
                    }
                }

                if (failed) {
                    throw new MojoExecutionException("Found duplicate classes/resources!");
                }
            } catch (final DependencyResolutionRequiredException e) {
                throw new MojoExecutionException("Could not resolve dependencies", e);
            } catch (final InvalidVersionSpecificationException e) {
                throw new MojoExecutionException("Invalid version specified", e);
            } catch (final OverConstrainedVersionException e) {
                throw new MojoExecutionException("Version too constrained", e);
            }
        }
    } finally {
        MavenLogAppender.endPluginLog(this);
    }
}

From source file:com.facebook.buck.config.BuckConfig.java

/**
 * In a {@link BuckConfig}, an alias can either refer to a fully-qualified build target, or an
 * alias defined earlier in the {@code alias} section. The mapping produced by this method
 * reflects the result of resolving all aliases as values in the {@code alias} section.
 *///from   w  w w . j  a va 2  s. c  o m
private ImmutableSetMultimap<String, BuildTarget> createAliasToBuildTargetMap(
        ImmutableMap<String, String> rawAliasMap) {
    // We use a LinkedHashMap rather than an ImmutableMap.Builder because we want both (1) order to
    // be preserved, and (2) the ability to inspect the Map while building it up.
    SetMultimap<String, BuildTarget> aliasToBuildTarget = LinkedHashMultimap.create();
    for (Map.Entry<String, String> aliasEntry : rawAliasMap.entrySet()) {
        String alias = aliasEntry.getKey();
        validateAliasName(alias);

        // Determine whether the mapping is to a build target or to an alias.
        List<String> values = Splitter.on(' ').splitToList(aliasEntry.getValue());
        for (String value : values) {
            Set<BuildTarget> buildTargets;
            if (isValidAliasName(value)) {
                buildTargets = aliasToBuildTarget.get(value);
                if (buildTargets.isEmpty()) {
                    throw new HumanReadableException("No alias for: %s.", value);
                }
            } else if (value.isEmpty()) {
                continue;
            } else {
                // Here we parse the alias values with a BuildTargetParser to be strict. We could be
                // looser and just grab everything between "//" and ":" and assume it's a valid base path.
                buildTargets = ImmutableSet.of(BuildTargetParser.INSTANCE.parse(value,
                        BuildTargetPatternParser.fullyQualified(), getCellPathResolver()));
            }
            aliasToBuildTarget.putAll(alias, buildTargets);
        }
    }
    return ImmutableSetMultimap.copyOf(aliasToBuildTarget);
}

From source file:com.facebook.buck.apple.project_generator.WorkspaceAndProjectGenerator.java

private void writeWorkspaceSchemes(String workspaceName, Path outputDirectory,
        ImmutableMap<String, XcodeWorkspaceConfigDescription.Arg> schemeConfigs,
        ImmutableSetMultimap<String, Optional<TargetNode<?, ?>>> schemeNameToSrcTargetNode,
        ImmutableSetMultimap<String, TargetNode<?, ?>> buildForTestNodes,
        ImmutableSetMultimap<String, TargetNode<AppleTestDescription.Arg, ?>> ungroupedTests,
        ImmutableMap<PBXTarget, Path> targetToProjectPathMap,
        Function<TargetNode<?, ?>, Collection<PBXTarget>> targetNodeToPBXTargetTransformer,
        Function<BuildTarget, PBXTarget> buildTargetToPBXTargetTransformer) throws IOException {
    for (Map.Entry<String, XcodeWorkspaceConfigDescription.Arg> schemeConfigEntry : schemeConfigs.entrySet()) {
        String schemeName = schemeConfigEntry.getKey();
        XcodeWorkspaceConfigDescription.Arg schemeConfigArg = schemeConfigEntry.getValue();
        if (schemeConfigArg.srcTarget.isPresent() && !ProjectGenerator
                .shouldIncludeBuildTargetIntoFocusedProject(focusModules, schemeConfigArg.srcTarget.get())) {
            continue;
        }//from w  w w. ja  va2s . com
        Iterable<PBXTarget> orderedBuildTargets = schemeNameToSrcTargetNode.get(schemeName).stream().distinct()
                .flatMap(Optionals::toStream)
                .flatMap(targetNode -> targetNodeToPBXTargetTransformer.apply(targetNode).stream())
                .collect(MoreCollectors.toImmutableSet());
        FluentIterable<PBXTarget> orderedBuildTestTargets = FluentIterable
                .from(buildForTestNodes.get(schemeName)).transformAndConcat(targetNodeToPBXTargetTransformer);
        FluentIterable<PBXTarget> orderedRunTestTargets = FluentIterable.from(ungroupedTests.get(schemeName))
                .transformAndConcat(targetNodeToPBXTargetTransformer);
        Optional<String> runnablePath = schemeConfigArg.explicitRunnablePath;
        Optional<BuildTarget> targetToBuildWithBuck = getTargetToBuildWithBuck();
        if (buildWithBuck && targetToBuildWithBuck.isPresent() && !runnablePath.isPresent()) {
            Optional<String> productName = getProductName(schemeNameToSrcTargetNode.get(schemeName),
                    targetToBuildWithBuck);
            String binaryName = AppleBundle.getBinaryName(targetToBuildWithBuck.get(), productName);
            runnablePath = Optional.of(rootCell.getFilesystem()
                    .resolve(ProjectGenerator.getScratchPathForAppBundle(rootCell.getFilesystem(),
                            targetToBuildWithBuck.get(), binaryName))
                    .toString());
        }
        Optional<String> remoteRunnablePath;
        if (schemeConfigArg.isRemoteRunnable.orElse(false)) {
            // XXX TODO(bhamiltoncx): Figure out the actual name of the binary to launch
            remoteRunnablePath = Optional.of("/" + workspaceName);
        } else {
            remoteRunnablePath = Optional.empty();
        }
        SchemeGenerator schemeGenerator = new SchemeGenerator(rootCell.getFilesystem(),
                schemeConfigArg.srcTarget.map(buildTargetToPBXTargetTransformer::apply), orderedBuildTargets,
                orderedBuildTestTargets, orderedRunTestTargets, schemeName,
                combinedProject ? outputDirectory : outputDirectory.resolve(workspaceName + ".xcworkspace"),
                buildWithBuck, parallelizeBuild, runnablePath, remoteRunnablePath,
                XcodeWorkspaceConfigDescription.getActionConfigNamesFromArg(workspaceArguments),
                targetToProjectPathMap,
                schemeConfigArg.launchStyle.orElse(XCScheme.LaunchAction.LaunchStyle.AUTO));
        schemeGenerator.writeScheme();
        schemeGenerators.put(schemeName, schemeGenerator);
    }
}

From source file:com.google.template.soy.SoyFileSet.java

private ImmutableSetMultimap<String, String> getTransitiveIjs(SoyFileSetNode soyTree,
        TemplateRegistry registry) {//ww  w . ja v  a2 s .c  o m
    ImmutableMap<TemplateNode, IjParamsInfo> templateToIjParamsInfoMap = new FindIjParamsVisitor(registry,
            errorReporter).execOnAllTemplates(soyTree);
    ImmutableSetMultimap.Builder<String, String> templateToTranstivieIjParams = ImmutableSetMultimap.builder();
    for (Map.Entry<TemplateNode, IjParamsInfo> entry : templateToIjParamsInfoMap.entrySet()) {
        templateToTranstivieIjParams.putAll(entry.getKey().getTemplateName(), entry.getValue().ijParamSet);
    }
    return templateToTranstivieIjParams.build();
}

From source file:dagger.internal.codegen.MembersInjectorGenerator.java

@Override
Optional<TypeSpec.Builder> write(ClassName generatedTypeName, MembersInjectionBinding binding) {
    // Empty members injection bindings are special and don't need source files.
    if (binding.injectionSites().isEmpty()) {
        return Optional.empty();
    }//from  ww  w .  j  a v a  2  s . c  o m
    if (!injectValidator.isValidType(binding.key().type())) {
        return Optional.empty();
    }
    // We don't want to write out resolved bindings -- we want to write out the generic version.
    checkState(!binding.unresolved().isPresent(),
            "tried to generate a MembersInjector for a binding of a resolved generic type: %s", binding);

    ImmutableList<TypeVariableName> typeParameters = bindingTypeElementTypeVariableNames(binding);
    TypeSpec.Builder injectorTypeBuilder = classBuilder(generatedTypeName).addModifiers(PUBLIC, FINAL)
            .addTypeVariables(typeParameters);

    TypeName injectedTypeName = TypeName.get(binding.key().type());
    TypeName implementedType = membersInjectorOf(injectedTypeName);
    injectorTypeBuilder.addSuperinterface(implementedType);

    MethodSpec.Builder injectMembersBuilder = methodBuilder("injectMembers").returns(VOID).addModifiers(PUBLIC)
            .addAnnotation(Override.class).addParameter(injectedTypeName, "instance")
            .addCode("if (instance == null) {").addStatement("throw new $T($S)", NullPointerException.class,
                    "Cannot inject members into a null reference")
            .addCode("}");

    ImmutableMap<BindingKey, FrameworkField> fields = generateBindingFieldsForDependencies(binding);

    ImmutableMap.Builder<BindingKey, FieldSpec> dependencyFieldsBuilder = ImmutableMap.builder();

    MethodSpec.Builder constructorBuilder = constructorBuilder().addModifiers(PUBLIC);

    // We use a static create method so that generated components can avoid having
    // to refer to the generic types of the factory.
    // (Otherwise they may have visibility problems referring to the types.)
    MethodSpec.Builder createMethodBuilder = methodBuilder("create").returns(implementedType)
            .addModifiers(PUBLIC, STATIC).addTypeVariables(typeParameters);

    createMethodBuilder.addCode("return new $T(", parameterizedGeneratedTypeNameForBinding(binding));
    ImmutableList.Builder<CodeBlock> constructorInvocationParameters = ImmutableList.builder();

    boolean usesRawFrameworkTypes = false;
    UniqueNameSet fieldNames = new UniqueNameSet();
    for (Entry<BindingKey, FrameworkField> fieldEntry : fields.entrySet()) {
        BindingKey dependencyBindingKey = fieldEntry.getKey();
        FrameworkField bindingField = fieldEntry.getValue();

        // If the dependency type is not visible to this members injector, then use the raw framework
        // type for the field.
        boolean useRawFrameworkType = !isTypeAccessibleFrom(dependencyBindingKey.key().type(),
                generatedTypeName.packageName());

        String fieldName = fieldNames.getUniqueName(bindingField.name());
        TypeName fieldType = useRawFrameworkType ? bindingField.type().rawType : bindingField.type();
        FieldSpec.Builder fieldBuilder = FieldSpec.builder(fieldType, fieldName, PRIVATE, FINAL);
        ParameterSpec.Builder parameterBuilder = ParameterSpec.builder(fieldType, fieldName);

        // If we're using the raw type for the field, then suppress the injectMembers method's
        // unchecked-type warning and the field's and the constructor and create-method's
        // parameters' raw-type warnings.
        if (useRawFrameworkType) {
            usesRawFrameworkTypes = true;
            fieldBuilder.addAnnotation(suppressWarnings(RAWTYPES));
            parameterBuilder.addAnnotation(suppressWarnings(RAWTYPES));
        }
        constructorBuilder.addParameter(parameterBuilder.build());
        createMethodBuilder.addParameter(parameterBuilder.build());

        FieldSpec field = fieldBuilder.build();
        injectorTypeBuilder.addField(field);
        constructorBuilder.addStatement("assert $N != null", field);
        constructorBuilder.addStatement("this.$N = $N", field, field);
        dependencyFieldsBuilder.put(dependencyBindingKey, field);
        constructorInvocationParameters.add(CodeBlock.of("$N", field));
    }

    createMethodBuilder
            .addCode(constructorInvocationParameters.build().stream().collect(toParametersCodeBlock()));
    createMethodBuilder.addCode(");");

    injectorTypeBuilder.addMethod(constructorBuilder.build());
    injectorTypeBuilder.addMethod(createMethodBuilder.build());

    Set<String> delegateMethods = new HashSet<>();
    ImmutableMap<BindingKey, FieldSpec> dependencyFields = dependencyFieldsBuilder.build();
    List<MethodSpec> injectMethodsForSubclasses = new ArrayList<>();
    for (InjectionSite injectionSite : binding.injectionSites()) {
        injectMembersBuilder
                .addCode(isElementAccessibleFrom(injectionSite.element(), generatedTypeName.packageName())
                        ? directInjectMemberCodeBlock(binding, dependencyFields, injectionSite)
                        : delegateInjectMemberCodeBlock(dependencyFields, injectionSite));
        if (!injectionSite.element().getModifiers().contains(PUBLIC)
                && injectionSite.element().getEnclosingElement().equals(binding.membersInjectedType())
                && delegateMethods.add(injectionSiteDelegateMethodName(injectionSite.element()))) {
            injectMethodsForSubclasses.add(injectorMethodForSubclasses(dependencyFields, typeParameters,
                    injectedTypeName, injectionSite.element(), injectionSite.dependencies()));
        }
    }

    if (usesRawFrameworkTypes) {
        injectMembersBuilder.addAnnotation(suppressWarnings(UNCHECKED));
    }

    injectorTypeBuilder.addMethod(injectMembersBuilder.build());
    injectMethodsForSubclasses.forEach(injectorTypeBuilder::addMethod);

    gwtIncompatibleAnnotation(binding).ifPresent(injectorTypeBuilder::addAnnotation);

    return Optional.of(injectorTypeBuilder);
}