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

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

Introduction

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

Prototype

V get(Object key);

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Usage

From source file:com.facebook.buck.model.MacroFinder.java

/**
 * Expand macros embedded in a string./*  ww  w. ja v  a2  s  .  co  m*/
 *
 * @param replacers a map of macro names to {@link MacroReplacer} objects used to expand them.
 * @param blob the input string containing macros to be expanded
 * @param resolveEscaping whether to drop characters used to escape literal uses of `$(...)`
 * @return a copy of the input string with all macros expanded
 */
public String replace(ImmutableMap<String, MacroReplacer> replacers, String blob, boolean resolveEscaping)
        throws MacroException {

    StringBuilder expanded = new StringBuilder();

    // Iterate over all macros found in the string, expanding each found macro.
    int lastEnd = 0;
    MacroFinderAutomaton matcher = new MacroFinderAutomaton(blob);
    while (matcher.hasNext()) {
        MacroMatchResult matchResult = matcher.next();
        // Add everything from the original string since the last match to this one.
        expanded.append(blob.substring(lastEnd, matchResult.getStartIndex()));

        // If the macro is escaped, add the macro text (but omit the escaping backslash)
        if (matchResult.isEscaped()) {
            expanded.append(blob.substring(matchResult.getStartIndex() + (resolveEscaping ? 1 : 0),
                    matchResult.getEndIndex()));
        } else {
            // Call the relevant expander and add the expanded value to the string.
            MacroReplacer replacer = replacers.get(matchResult.getMacroType());
            if (replacer == null) {
                throw new MacroException(String.format("expanding %s: no such macro \"%s\"",
                        blob.substring(matchResult.getStartIndex(), matchResult.getEndIndex()),
                        matchResult.getMacroType()));
            }
            try {
                expanded.append(replacer.replace(matchResult.getMacroInput()));
            } catch (MacroException e) {
                throw new MacroException(String.format("expanding %s: %s",
                        blob.substring(matchResult.getStartIndex(), matchResult.getEndIndex()), e.getMessage()),
                        e);
            }
        }
        lastEnd = matchResult.getEndIndex();
    }
    // Append the remaining part of the original string after the last match.
    expanded.append(blob.substring(lastEnd, blob.length()));
    return expanded.toString();
}

From source file:com.google.auto.value.processor.AutoValueProcessor.java

private TypeSimplifier defineVarsForType(TypeElement type, AutoValueTemplateVars vars,
        ImmutableSet<ExecutableElement> toBuilderMethods, ImmutableSet<ExecutableElement> propertyMethods,
        Optional<BuilderSpec.Builder> builder) {
    DeclaredType declaredType = MoreTypes.asDeclared(type.asType());
    Set<TypeMirror> types = new TypeMirrorSet();
    types.addAll(returnTypesOf(propertyMethods));
    if (builder.isPresent()) {
        types.addAll(builder.get().referencedTypes());
    }//from w  ww  . ja  v a  2s .co  m
    TypeElement generatedTypeElement = processingEnv.getElementUtils()
            .getTypeElement("javax.annotation.Generated");
    if (generatedTypeElement != null) {
        types.add(generatedTypeElement.asType());
    }
    TypeMirror javaUtilArrays = getTypeMirror(Arrays.class);
    if (containsArrayType(types)) {
        // If there are array properties then we will be referencing java.util.Arrays.
        // Arrange to import it unless that would introduce ambiguity.
        types.add(javaUtilArrays);
    }
    vars.toBuilderMethods = FluentIterable.from(toBuilderMethods).transform(SimpleMethodFunction.INSTANCE)
            .toList();
    ImmutableSetMultimap<ExecutableElement, String> excludedAnnotationsMap = allMethodExcludedAnnotations(
            propertyMethods);
    types.addAll(allMethodAnnotationTypes(propertyMethods, excludedAnnotationsMap));
    String pkg = TypeSimplifier.packageNameOf(type);
    TypeSimplifier typeSimplifier = new TypeSimplifier(typeUtils, pkg, types, declaredType);
    vars.imports = typeSimplifier.typesToImport();
    vars.generated = generatedTypeElement == null ? "" : typeSimplifier.simplify(generatedTypeElement.asType());
    vars.arrays = typeSimplifier.simplify(javaUtilArrays);
    ImmutableBiMap<ExecutableElement, String> methodToPropertyName = propertyNameToMethodMap(propertyMethods)
            .inverse();
    Map<ExecutableElement, String> methodToIdentifier = Maps.newLinkedHashMap(methodToPropertyName);
    fixReservedIdentifiers(methodToIdentifier);
    List<Property> props = new ArrayList<Property>();
    EclipseHack eclipseHack = eclipseHack();
    ImmutableMap<ExecutableElement, TypeMirror> returnTypes = eclipseHack.methodReturnTypes(propertyMethods,
            declaredType);
    for (ExecutableElement method : propertyMethods) {
        TypeMirror returnType = returnTypes.get(method);
        String propertyType = typeSimplifier.simplify(returnType);
        String propertyName = methodToPropertyName.get(method);
        String identifier = methodToIdentifier.get(method);
        ImmutableSet<String> excludedAnnotations = ImmutableSet.<String>builder()
                .addAll(excludedAnnotationsMap.get(method)).add(Override.class.getCanonicalName()).build();
        Property p = new Property(propertyName, identifier, method, propertyType, typeSimplifier,
                excludedAnnotations);
        props.add(p);
        if (p.isNullable() && returnType.getKind().isPrimitive()) {
            errorReporter.reportError("Primitive types cannot be @Nullable", method);
        }
    }
    vars.props = ImmutableSet.copyOf(props);
    vars.serialVersionUID = getSerialVersionUID(type);
    vars.formalTypes = typeSimplifier.formalTypeParametersString(type);
    vars.actualTypes = TypeSimplifier.actualTypeParametersString(type);
    vars.wildcardTypes = wildcardTypeParametersString(type);
    // Check for @AutoValue.Builder and add appropriate variables if it is present.
    if (builder.isPresent()) {
        builder.get().defineVars(vars, typeSimplifier, methodToPropertyName);
    }
    return typeSimplifier;
}

From source file:com.google.api.codegen.config.GapicInterfaceConfig.java

/**
 * Creates an instance of GapicInterfaceConfig based on ConfigProto, linking up method
 * configurations with specified methods in methodConfigMap. On errors, null will be returned, and
 * diagnostics are reported to the model.
 *//*from  w ww  . j a  v a 2s  .c  o m*/
@Nullable
static GapicInterfaceConfig createInterfaceConfig(DiagCollector diagCollector, TargetLanguage language,
        InterfaceConfigProto interfaceConfigProto, Interface apiInterface, String interfaceNameOverride,
        ResourceNameMessageConfigs messageConfigs,
        ImmutableMap<String, ResourceNameConfig> resourceNameConfigs) {

    ImmutableMap<String, ImmutableSet<String>> retryCodesDefinition = RetryDefinitionsTransformer
            .createRetryCodesDefinition(diagCollector, interfaceConfigProto);
    ImmutableMap<String, RetryParamsDefinitionProto> retrySettingsDefinition = RetryDefinitionsTransformer
            .createRetrySettingsDefinition(interfaceConfigProto);

    List<GapicMethodConfig> methodConfigs = null;
    ImmutableMap<String, GapicMethodConfig> methodConfigMap = null;
    if (retryCodesDefinition != null && retrySettingsDefinition != null) {
        methodConfigMap = createMethodConfigMap(diagCollector, language, interfaceConfigProto, apiInterface,
                messageConfigs, resourceNameConfigs, retryCodesDefinition.keySet(),
                retrySettingsDefinition.keySet());
        methodConfigs = createMethodConfigs(methodConfigMap, interfaceConfigProto);
    }

    SmokeTestConfig smokeTestConfig = createSmokeTestConfig(diagCollector, apiInterface, interfaceConfigProto);

    ImmutableList<FieldModel> iamResources = createIamResources(apiInterface.getModel(),
            interfaceConfigProto.getExperimentalFeatures().getIamResourcesList());

    ImmutableList<String> requiredConstructorParams = ImmutableList
            .<String>copyOf(interfaceConfigProto.getRequiredConstructorParamsList());
    for (String param : interfaceConfigProto.getRequiredConstructorParamsList()) {
        if (!CONSTRUCTOR_PARAMS.contains(param)) {
            diagCollector
                    .addDiag(Diag.error(SimpleLocation.TOPLEVEL, "Unsupported constructor param: %s", param));
        }
    }

    ImmutableList.Builder<SingleResourceNameConfig> resourcesBuilder = ImmutableList.builder();
    for (CollectionConfigProto collectionConfigProto : interfaceConfigProto.getCollectionsList()) {
        String entityName = collectionConfigProto.getEntityName();
        ResourceNameConfig resourceName = resourceNameConfigs.get(entityName);
        if (resourceName == null || !(resourceName instanceof SingleResourceNameConfig)) {
            diagCollector.addDiag(Diag.error(SimpleLocation.TOPLEVEL,
                    "Inconsistent configuration - single resource name %s specified for interface, "
                            + " but was not found in GapicProductConfig configuration.",
                    entityName));
            return null;
        }
        resourcesBuilder.add((SingleResourceNameConfig) resourceName);
    }
    ImmutableList<SingleResourceNameConfig> singleResourceNames = resourcesBuilder.build();

    String manualDoc = Strings
            .nullToEmpty(interfaceConfigProto.getLangDoc().get(language.toString().toLowerCase())).trim();

    if (diagCollector.hasErrors()) {
        return null;
    } else {
        return new AutoValue_GapicInterfaceConfig(interfaceNameOverride, new ProtoInterfaceModel(apiInterface),
                methodConfigs, smokeTestConfig, methodConfigMap, retryCodesDefinition, retrySettingsDefinition,
                iamResources, requiredConstructorParams, singleResourceNames, manualDoc);
    }
}

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

@Override
public <A extends ThriftConstructorArg> BuildRule createBuildRule(TargetGraph targetGraph,
        BuildRuleParams params, BuildRuleResolver resolver, A args) throws NoSuchBuildTargetException {

    BuildTarget target = params.getBuildTarget();

    // Extract the thrift language we're using from our build target.
    Optional<Map.Entry<Flavor, ThriftLanguageSpecificEnhancer>> enhancerFlavor = enhancers
            .getFlavorAndValue(target);/*w w  w  .j a  v  a2s  . c om*/
    SourcePathResolver pathResolver = new SourcePathResolver(new SourcePathRuleFinder(resolver));
    ImmutableMap<String, SourcePath> namedSources = pathResolver.getSourcePathNames(target, "srcs",
            args.srcs.keySet());

    // The dependencies listed in "deps", which should all be of type "ThriftLibrary".
    ImmutableSortedSet<ThriftLibrary> thriftDeps = resolveThriftDeps(target, resolver.getAllRules(args.deps));

    // The unflavored version of this rule is responsible for setting up the the various
    // build rules to facilitate dependents including it's thrift sources.
    if (!enhancerFlavor.isPresent()) {

        // Namespace the thrift files using our target's base path.
        ImmutableMap.Builder<Path, SourcePath> includesBuilder = ImmutableMap.builder();
        for (ImmutableMap.Entry<String, SourcePath> entry : namedSources.entrySet()) {
            includesBuilder.put(target.getBasePath().resolve(entry.getKey()), entry.getValue());
        }
        ImmutableMap<Path, SourcePath> includes = includesBuilder.build();

        // Create the symlink tree build rule and add it to the resolver.
        Path includeRoot = getIncludeRoot(target, params.getProjectFilesystem());
        BuildTarget symlinkTreeTarget = createThriftIncludeSymlinkTreeTarget(target);
        HeaderSymlinkTree symlinkTree = new HeaderSymlinkTree(params.copyWithChanges(symlinkTreeTarget,
                Suppliers.ofInstance(ImmutableSortedSet.of()), Suppliers.ofInstance(ImmutableSortedSet.of())),
                pathResolver, includeRoot, includes);
        resolver.addToIndex(symlinkTree);

        // Create a dummy rule that dependents can use to grab the information they need
        // about this rule from the action graph.
        return new ThriftLibrary(params, pathResolver, thriftDeps, symlinkTree, includes);
    }

    ThriftLanguageSpecificEnhancer enhancer = enhancerFlavor.get().getValue();
    String language = enhancer.getLanguage();
    ImmutableSet<String> options = enhancer.getOptions(target, args);
    ImmutableSet<BuildTarget> implicitDeps = enhancer.getImplicitDepsForTargetFromConstructorArg(target, args);

    // Lookup the thrift library corresponding to this rule.  We add an implicit dep onto
    // this rule in the findImplicitDepsFromParams method, so this should always exist by
    // the time we get here.
    ThriftLibrary thriftLibrary = (ThriftLibrary) resolver
            .getRule(BuildTarget.of(target.getUnflavoredBuildTarget()));

    // We implicitly pass the language-specific flavors of your thrift lib dependencies as
    // language specific deps to the language specific enhancer.
    ImmutableSortedSet<BuildRule> languageSpecificDeps = BuildRules.toBuildRulesFor(target, resolver,
            Iterables.concat(
                    BuildTargets.propagateFlavorDomains(target, ImmutableList.of(enhancers),
                            FluentIterable.from(thriftDeps).transform(HasBuildTarget::getBuildTarget)),
                    implicitDeps));

    // Form the set of generated sources, so that compiler rules know what output paths to record.
    ImmutableMap.Builder<String, ImmutableSortedSet<String>> generatedSourcesBuilder = ImmutableMap.builder();
    for (ImmutableMap.Entry<String, SourcePath> ent : namedSources.entrySet()) {
        String thriftName = ent.getKey();
        ImmutableList<String> services = Preconditions.checkNotNull(args.srcs.get(ent.getValue()));
        generatedSourcesBuilder.put(thriftName,
                enhancer.getGeneratedSources(target, args, thriftName, services));
    }
    ImmutableMap<String, ImmutableSortedSet<String>> generatedSources = generatedSourcesBuilder.build();

    // Create a a build rule for thrift source file, to compile the language specific sources.
    // They keys in this map are the logical names of the thrift files (e.g as specific in a BUCK
    // file, such as "test.thrift").
    ImmutableMap<String, ThriftCompiler> compilerRules = createThriftCompilerBuildRules(params, resolver,
            enhancer.getCompilerType(), args.flags, language, options, namedSources,
            ImmutableSortedSet.<ThriftLibrary>naturalOrder().add(thriftLibrary)
                    .addAll(getTransitiveThriftLibraryDeps(thriftDeps)).build(),
            generatedSources);
    resolver.addAllToIndex(compilerRules.values());

    // Build up the map of {@link ThriftSource} objects to pass the language specific enhancer.
    // They keys in this map are the logical names of the thrift files (e.g as specific in a BUCK
    // file, such as "test.thrift").
    ImmutableMap.Builder<String, ThriftSource> thriftSourceBuilder = ImmutableMap.builder();
    for (ImmutableMap.Entry<String, SourcePath> ent : namedSources.entrySet()) {
        ImmutableList<String> services = Preconditions.checkNotNull(args.srcs.get(ent.getValue()));
        ThriftCompiler compilerRule = Preconditions.checkNotNull(compilerRules.get(ent.getKey()));
        thriftSourceBuilder.put(ent.getKey(), new ThriftSource(compilerRule, services,
                getThriftCompilerOutputDir(params.getProjectFilesystem(), target, ent.getKey())));
    }
    ImmutableMap<String, ThriftSource> thriftSources = thriftSourceBuilder.build();

    // Generate language specific rules.
    return enhancer.createBuildRule(targetGraph, params, resolver, args, thriftSources, languageSpecificDeps);
}

From source file:org.chaston.oakfunds.storage.mgmt.SchemaValidator.java

Iterable<SchemaDiscrepancy> validateSchema() throws SQLException {
    ImmutableMap<String, TableDef> tableDefs = schemaBuilder.getTableDefs();
    ImmutableMap<String, FunctionDef> functionDefs = schemaBuilder.getFunctionDefs();
    ImmutableList.Builder<SchemaDiscrepancy> schemaDiscrepancies = ImmutableList.builder();
    Set<String> seenTables = new HashSet<>();
    Set<String> seenFunctions = new HashSet<>();
    try (Connection connection = dataSource.getConnection()) {
        DatabaseMetaData metaData = connection.getMetaData();

        if (databaseVariantHandler.requiresSchemaCreation()) {
            // Look for schema.
            ResultSet allSchemas = metaData.getSchemas(null,
                    databaseVariantHandler.toDatabaseForm(SystemColumnDefs.SCHEMA));
            if (!allSchemas.next()) {
                schemaDiscrepancies.add(new MissingSchema(SystemColumnDefs.SCHEMA));
            }/*from w  w  w  .j a  v a2s . c  om*/
        }

        // Look for tables.
        try (ResultSet allTables = metaData.getTables(null,
                databaseVariantHandler.toDatabaseForm(SystemColumnDefs.SCHEMA), null, null)) {
            while (allTables.next()) {
                String tableName = databaseVariantHandler.toNormalName(allTables.getString("TABLE_NAME"));
                TableDef tableDef = tableDefs.get(tableName);
                if (tableDef == null) {
                    // Table that the defs do not know (and hence care) about.
                    continue;
                }
                seenTables.add(tableName);
                validateTable(metaData, tableDef, schemaDiscrepancies);
            }
        }

        // Look for functions.
        try (ResultSet allFunctions = metaData.getFunctions(null,
                databaseVariantHandler.toDatabaseForm(SystemColumnDefs.SCHEMA), null)) {
            while (allFunctions.next()) {
                String functionName = databaseVariantHandler
                        .toNormalName(allFunctions.getString("FUNCTION_NAME"));
                FunctionDef functionDef = functionDefs.get(functionName);
                if (functionDef == null) {
                    // Function that the defs do not know (and hence care) about.
                    continue;
                }
                seenFunctions.add(functionName);
                // TODO: validate function (?)
            }
        }
    }
    for (TableDef expectedTable : tableDefs.values()) {
        if (!seenTables.contains(expectedTable.getName())) {
            schemaDiscrepancies.add(new MissingTable(expectedTable));
        }
    }
    for (FunctionDef expectedFunction : functionDefs.values()) {
        if (!seenFunctions.contains(expectedFunction.getName())) {
            schemaDiscrepancies.add(new MissingFunction(expectedFunction));
        }
    }
    return schemaDiscrepancies.build();
}

From source file:com.google.enterprise.connector.instantiator.ChangeDetectorImpl.java

/**
 * Iterates over the sorted sets of instance names to find additions
 * and deletions. When matching names are found, compare the version
 * stamps for changes in the individual persisted objects.
 *
 * @param mi the sorted keys to the in-memory instances
 * @param pi the sorted keys to the persistent instances
 * @param persistentInventory the persistent object stamps
 * @return a new inventory of stamps, derived from the
 *         persistentInventory, but reflecting instantiation failures.
 *///from ww w. j av  a  2s  . co m
private ImmutableMap<StoreContext, ConnectorStamps> compareInventoriesAndNotifyListeners(
        Iterator<StoreContext> mi, Iterator<StoreContext> pi,
        ImmutableMap<StoreContext, ConnectorStamps> persistentInventory) {
    // This map will accumulate items for the new in-memory inventory.
    // Generally, this map will end up being identical to the
    // persistentInventory. However, failed connector instantiations
    // may cause changes to be dropped from this map, so that they may
    // be retried next time around.
    ImmutableMap.Builder<StoreContext, ConnectorStamps> mapBuilder = new ImmutableMap.Builder<StoreContext, ConnectorStamps>();

    StoreContext m = getNext(mi);
    StoreContext p = getNext(pi);
    while (m != null && p != null) {
        // Compare instance names.
        int diff = m.getConnectorName().compareTo(p.getConnectorName());
        NDC.pushAppend((diff < 0 ? m : p).getConnectorName());
        try {
            if (diff == 0) {
                // Compare the inMemory vs inPStore ConnectorStamps for a
                // connector instance. Notify ChangeListeners for items whose
                // Stamps have changed.
                ConnectorStamps stamps = compareInstancesAndNotifyListeners(m, p, inMemoryInventory.get(m),
                        persistentInventory.get(p));

                // Remember the new ConnetorStamps for our new inMemory inventory.
                mapBuilder.put(p, stamps);

                // Advance to the next connector instance.
                m = getNext(mi);
                p = getNext(pi);
            } else if (diff < 0) {
                listener.connectorRemoved(m.getConnectorName());
                m = getNext(mi);
            } else { // diff > 0
                try {
                    listener.connectorAdded(p.getConnectorName(), store.getConnectorConfiguration(p));
                    mapBuilder.put(p, persistentInventory.get(p));
                } catch (InstantiatorException e) {
                    // Forget about this one and retry on the next time around.
                    pi.remove();
                }
                p = getNext(pi);
            }
        } finally {
            NDC.pop();
        }
    }
    while (m != null) {
        NDC.pushAppend(m.getConnectorName());
        try {
            listener.connectorRemoved(m.getConnectorName());
        } finally {
            NDC.pop();
        }
        m = getNext(mi);
    }
    while (p != null) {
        NDC.pushAppend(p.getConnectorName());
        try {
            listener.connectorAdded(p.getConnectorName(), store.getConnectorConfiguration(p));
            mapBuilder.put(p, persistentInventory.get(p));
        } catch (InstantiatorException e) {
            // Forget about this one and retry on the next time around.
            pi.remove();
        } finally {
            NDC.pop();
        }
        p = getNext(pi);
    }
    return mapBuilder.build();
}

From source file:org.apache.hadoop.hive.metastore.PartitionProjectionEvaluator.java

public PartitionProjectionEvaluator(PersistenceManager pm, ImmutableMap<String, String> fieldNameToTableName,
        List<String> projectionFields, boolean convertMapNullsToEmptyStrings, boolean isView,
        String includeParamKeyPattern, String excludeParamKeyPattern) throws MetaException {
    this.pm = pm;
    this.fieldNameToTableName = fieldNameToTableName;
    this.convertMapNullsToEmptyStrings = convertMapNullsToEmptyStrings;
    this.isView = isView;
    this.includeParamKeyPattern = includeParamKeyPattern;
    this.excludeParamKeyPattern = excludeParamKeyPattern;
    this.PARTITIONS = fieldNameToTableName.containsKey("PARTITIONS_TABLE_NAME")
            ? fieldNameToTableName.get("PARTITIONS_TABLE_NAME")
            : "PARTITIONS";
    this.SDS = fieldNameToTableName.containsKey("SDS_TABLE_NAME") ? fieldNameToTableName.get("SDS_TABLE_NAME")
            : "SDS";
    this.SERDES = fieldNameToTableName.containsKey("SERDES_TABLE_NAME")
            ? fieldNameToTableName.get("SERDES_TABLE_NAME")
            : "SERDES";
    this.PARTITION_PARAMS = fieldNameToTableName.containsKey("PARTITION_PARAMS")
            ? fieldNameToTableName.get("PARTITION_PARAMS")
            : "PARTITION_PARAMS";

    roots = parse(projectionFields);/*from  ww w  .j  a  v  a2s .  c  o  m*/

    // we always query PART_ID
    roots.add(partIdNode);
    if (find(SD_PATTERN)) {
        roots.add(sdIdNode);
    }
    if (find(SERDE_PATTERN)) {
        roots.add(serdeIdNode);
    }
    if (find(CD_PATTERN)) {
        roots.add(cdIdNode);
    }
}

From source file:com.facebook.buck.shell.AbstractGenruleStep.java

@Override
public ImmutableMap<String, String> getEnvironmentVariables(ExecutionContext context) {
    ImmutableMap.Builder<String, String> allEnvironmentVariablesBuilder = ImmutableMap.builder();
    addEnvironmentVariables(context, allEnvironmentVariablesBuilder);
    ImmutableMap<String, String> allEnvironmentVariables = allEnvironmentVariablesBuilder.build();

    // Long lists of environment variables can extend the length of the command such that it exceeds
    // exec()'s ARG_MAX limit. Defend against this by filtering out variables that do not appear in
    // the command string.
    String command = getCommandAndExecutionArgs(context).command;
    ImmutableMap.Builder<String, String> usedEnvironmentVariablesBuilder = ImmutableMap.builder();
    for (Map.Entry<String, String> environmentVariable : allEnvironmentVariables.entrySet()) {
        // We check for the presence of the variable without adornment for $ or %% so it works on both
        // Windows and non-Windows environments. Eventually, we will require $ in the command string
        // and modify the command directly rather than using environment variables.
        String environmentVariableName = environmentVariable.getKey();
        if (command.contains(environmentVariableName)) {
            // I hate this $DEPS variable so much...
            if ("DEPS".equals(environmentVariableName) && allEnvironmentVariables.containsKey("GEN_DIR")) {
                usedEnvironmentVariablesBuilder.put("GEN_DIR", allEnvironmentVariables.get("GEN_DIR"));
            }/*  ww w.j av a  2  s  .com*/
            usedEnvironmentVariablesBuilder.put(environmentVariable);
        }
    }
    return usedEnvironmentVariablesBuilder.build();
}

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

/**
 * A set of paths to subtrees that do not contain source files, build files or files that could
 * affect either (buck-out, .idea, .buckd, buck-cache, .git, etc.).  May return absolute paths
 * as well as relative paths.//from ww  w.  j a  v a2s .  co  m
 */
public ImmutableSet<Path> getIgnorePaths() {
    final ImmutableMap<String, String> projectConfig = getEntriesForSection("project");
    final String ignoreKey = "ignore";
    ImmutableSet.Builder<Path> builder = ImmutableSet.builder();

    builder.add(Paths.get(BuckConstant.BUCK_OUTPUT_DIRECTORY));
    builder.add(Paths.get(".idea"));

    // Take care not to ignore absolute paths.
    Path buckdDir = Paths.get(System.getProperty(BUCK_BUCKD_DIR_KEY, ".buckd"));
    Path cacheDir = getCacheDir();
    for (Path path : ImmutableList.of(buckdDir, cacheDir)) {
        if (!path.toString().isEmpty()) {
            builder.add(path);
        }
    }

    if (projectConfig.containsKey(ignoreKey)) {
        builder.addAll(MorePaths.asPaths(
                Splitter.on(',').omitEmptyStrings().trimResults().split(projectConfig.get(ignoreKey))));
    }

    // Normalize paths in order to eliminate trailing '/' characters and whatnot.
    return builder.build();
}

From source file:retrofacebook.processor.RetroFacebookProcessor.java

private void defineVarsForType(TypeElement type, RetroFacebookTemplateVars vars) {
    Types typeUtils = processingEnv.getTypeUtils();
    List<ExecutableElement> methods = new ArrayList<ExecutableElement>();
    findLocalAndInheritedMethods(type, methods);
    determineObjectMethodsToGenerate(methods, vars);
    ImmutableSet<ExecutableElement> methodsToImplement = methodsToImplement(methods);
    Set<TypeMirror> types = new TypeMirrorSet();
    types.addAll(returnTypesOf(methodsToImplement));
    //    TypeMirror javaxAnnotationGenerated = getTypeMirror(Generated.class);
    //    types.add(javaxAnnotationGenerated);
    TypeMirror javaUtilArrays = getTypeMirror(Arrays.class);
    if (containsArrayType(types)) {
        // If there are array properties then we will be referencing java.util.Arrays.
        // Arrange to import it unless that would introduce ambiguity.
        types.add(javaUtilArrays);//from   w ww. j  a  va  2 s.c o  m
    }
    BuilderSpec builderSpec = new BuilderSpec(type, processingEnv, errorReporter);
    Optional<BuilderSpec.Builder> builder = builderSpec.getBuilder();
    ImmutableSet<ExecutableElement> toBuilderMethods;
    if (builder.isPresent()) {
        types.add(getTypeMirror(BitSet.class));
        toBuilderMethods = builder.get().toBuilderMethods(typeUtils, methodsToImplement);
    } else {
        toBuilderMethods = ImmutableSet.of();
    }
    vars.toBuilderMethods = FluentIterable.from(toBuilderMethods).transform(SimpleNameFunction.INSTANCE)
            .toList();
    Set<ExecutableElement> propertyMethods = Sets.difference(methodsToImplement, toBuilderMethods);
    String pkg = TypeSimplifier.packageNameOf(type);
    TypeSimplifier typeSimplifier = new TypeSimplifier(typeUtils, pkg, types, type.asType());
    vars.imports = typeSimplifier.typesToImport();
    //    vars.generated = typeSimplifier.simplify(javaxAnnotationGenerated);
    vars.arrays = typeSimplifier.simplify(javaUtilArrays);
    vars.bitSet = typeSimplifier.simplifyRaw(getTypeMirror(BitSet.class));
    ImmutableMap<ExecutableElement, String> methodToPropertyName = methodToPropertyNameMap(propertyMethods);
    Map<ExecutableElement, String> methodToIdentifier = Maps.newLinkedHashMap(methodToPropertyName);
    fixReservedIdentifiers(methodToIdentifier);
    List<Property> props = new ArrayList<Property>();
    for (ExecutableElement method : propertyMethods) {
        String propertyType = typeSimplifier.simplify(method.getReturnType());
        String propertyName = methodToPropertyName.get(method);
        String identifier = methodToIdentifier.get(method);
        List<String> args = new ArrayList<String>();
        props.add(new Property(propertyName, identifier, method, propertyType, typeSimplifier, typeUtils));
    }
    // If we are running from Eclipse, undo the work of its compiler which sorts methods.
    eclipseHack().reorderProperties(props);
    vars.props = props;
    vars.serialVersionUID = getSerialVersionUID(type);
    vars.formalTypes = typeSimplifier.formalTypeParametersString(type);
    vars.actualTypes = TypeSimplifier.actualTypeParametersString(type);
    vars.wildcardTypes = wildcardTypeParametersString(type);

    TypeElement parcelable = processingEnv.getElementUtils().getTypeElement("android.os.Parcelable");
    vars.parcelable = parcelable != null
            && processingEnv.getTypeUtils().isAssignable(type.asType(), parcelable.asType());
    // Check for @RetroFacebook.Builder and add appropriate variables if it is present.
    if (builder.isPresent()) {
        builder.get().defineVars(vars, typeSimplifier, methodToPropertyName);
    }
}