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.apple.toolchain.impl.AppleSdkDiscovery.java

private static boolean buildSdkFromPath(Path sdkDir, AppleSdk.Builder sdkBuilder,
        ImmutableMap<String, AppleToolchain> xcodeToolchains, Optional<AppleToolchain> defaultToolchain,
        AppleConfig appleConfig) throws IOException {
    try (InputStream sdkSettingsPlist = Files.newInputStream(sdkDir.resolve("SDKSettings.plist"));
            BufferedInputStream bufferedSdkSettingsPlist = new BufferedInputStream(sdkSettingsPlist)) {
        NSDictionary sdkSettings;//from w w  w  .j  a  va  2s. c o  m
        try {
            sdkSettings = (NSDictionary) PropertyListParser.parse(bufferedSdkSettingsPlist);
        } catch (PropertyListFormatException | ParseException | SAXException e) {
            LOG.error(e, "Malformatted SDKSettings.plist. Skipping SDK path %s.", sdkDir);
            return false;
        } catch (ParserConfigurationException e) {
            throw new IOException(e);
        }
        String name = sdkSettings.objectForKey("CanonicalName").toString();
        String version = sdkSettings.objectForKey("Version").toString();
        NSDictionary defaultProperties = (NSDictionary) sdkSettings.objectForKey("DefaultProperties");
        NSString platformName = (NSString) defaultProperties.objectForKey("PLATFORM_NAME");

        Optional<ImmutableList<String>> toolchains = appleConfig
                .getToolchainsOverrideForSDKName(platformName.toString());
        boolean foundToolchain = false;
        if (!toolchains.isPresent()) {
            NSArray settingsToolchains = (NSArray) sdkSettings.objectForKey("Toolchains");
            if (settingsToolchains != null) {
                toolchains = Optional.of(Arrays.stream(settingsToolchains.getArray()).map(Object::toString)
                        .collect(ImmutableList.toImmutableList()));
            }
        }

        if (toolchains.isPresent()) {
            for (String toolchainId : toolchains.get()) {
                AppleToolchain toolchain = xcodeToolchains.get(toolchainId);
                if (toolchain != null) {
                    foundToolchain = true;
                    sdkBuilder.addToolchains(toolchain);
                } else {
                    LOG.debug("Specified toolchain %s not found for SDK path %s", toolchainId, sdkDir);
                }
            }
        }
        if (!foundToolchain && defaultToolchain.isPresent()) {
            foundToolchain = true;
            sdkBuilder.addToolchains(defaultToolchain.get());
        }
        if (!foundToolchain) {
            LOG.warn("No toolchains found and no default toolchain. Skipping SDK path %s.", sdkDir);
            return false;
        } else {
            ApplePlatform applePlatform = ApplePlatform.of(platformName.toString());
            sdkBuilder.setName(name).setVersion(version).setApplePlatform(applePlatform);
            ImmutableList<String> architectures = validArchitecturesForPlatform(applePlatform, sdkDir);
            sdkBuilder.addAllArchitectures(architectures);
            return true;
        }
    } catch (NoSuchFileException | NullPointerException e) {
        LOG.warn(e, "Skipping SDK at path %s, no SDKSettings.plist found", sdkDir);
        return false;
    }
}

From source file:com.facebook.buck.rules.macros.MacroFinder.java

public String replace(ImmutableMap<String, MacroReplacer> replacers, String blob) throws MacroException {

    StringBuilder expanded = new StringBuilder();

    // Iterate over all macros found in the string, expanding each found macro.
    int lastEnd = 0;
    Matcher matcher = MACRO_PATTERN.matcher(blob);
    while (matcher.find()) {

        // If the match is preceded by a backslash, skip this match but drop the backslash.
        if (matcher.start() > 0 && blob.charAt(matcher.start() - 1) == '\\') {
            expanded.append(blob.substring(lastEnd, matcher.start() - 1));
            expanded.append(blob.substring(matcher.start(), matcher.end()));

            // Otherwise we need to add the expanded value.
        } else {//from w ww .j av a 2  s  . c  om

            // Add everything from the original string since the last match to this one.
            expanded.append(blob.substring(lastEnd, matcher.start()));

            // Call the relevant expander and add the expanded value to the string.
            String name = matcher.group(1);
            MacroReplacer replacer = replacers.get(name);
            if (replacer == null) {
                throw new MacroException(
                        String.format("expanding %s: no such macro \"%s\"", matcher.group(), name));
            }

            String input = Optional.fromNullable(matcher.group(2)).or("");
            try {
                expanded.append(replacer.replace(input));
            } catch (MacroException e) {
                throw new MacroException(String.format("expanding %s: %s", matcher.group(), e.getMessage()), e);
            }
        }

        lastEnd = matcher.end();
    }

    // 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:auto.cursor.processor.AutoCursorProcessor.java

private void defineVarsForType(TypeElement type, AutoCursorTemplateVars 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  w  w.j a v a 2  s. co  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);
        props.add(new Property(propertyName, identifier, method, propertyType, typeSimplifier, processingEnv));
    }
    // 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 @AutoCursor.Builder and add appropriate variables if it is present.
    if (builder.isPresent()) {
        builder.get().defineVars(vars, typeSimplifier, methodToPropertyName);
    }
}

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

static DiscoGapicInterfaceConfig createInterfaceConfig(DiscoApiModel model, TargetLanguage language,
        InterfaceConfigProto interfaceConfigProto, String interfaceNameOverride,
        ResourceNameMessageConfigs messageConfigs,
        ImmutableMap<String, ResourceNameConfig> resourceNameConfigs) {

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

    List<DiscoGapicMethodConfig> methodConfigs = null;
    ImmutableMap<String, DiscoGapicMethodConfig> methodConfigMap = null;
    if (retryCodesDefinition != null && retrySettingsDefinition != null) {
        methodConfigMap = createMethodConfigMap(model, language, interfaceConfigProto, messageConfigs,
                resourceNameConfigs, retryCodesDefinition.keySet(), retrySettingsDefinition.keySet());
        methodConfigs = GapicInterfaceConfig.createMethodConfigs(methodConfigMap, interfaceConfigProto);
    }//from w  w w. jav a 2  s  .  c o m

    // TODO(andrealin)  Make non-null smokeTestConfig.
    SmokeTestConfig smokeTestConfig = null;

    // TODO(andrealin) IAM permissions configs.

    ImmutableList<String> requiredConstructorParams = ImmutableList
            .copyOf(interfaceConfigProto.getRequiredConstructorParamsList());
    for (String param : interfaceConfigProto.getRequiredConstructorParamsList()) {
        if (!CONSTRUCTOR_PARAMS.contains(param)) {
            model.getDiagCollector()
                    .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)) {
            model.getDiagCollector()
                    .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();

    ImmutableMap.Builder<MethodConfig, SingleResourceNameConfig> methodToSingleResourceNameMap = ImmutableMap
            .builder();
    if (methodConfigs != null) {
        for (MethodConfig methodConfig : methodConfigs) {
            Method method = ((DiscoveryMethodModel) methodConfig.getMethodModel()).getDiscoMethod();
            String canonicalMethodPath = DiscoGapicParser.getCanonicalPath(method.flatPath());
            for (SingleResourceNameConfig nameConfig : singleResourceNames) {
                if (nameConfig.getNamePattern().equals(canonicalMethodPath)) {
                    methodToSingleResourceNameMap.put(methodConfig, nameConfig);
                }
            }
        }
    }

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

    String interfaceName = interfaceNameOverride != null ? interfaceNameOverride
            : DiscoGapicParser.getInterfaceName(interfaceConfigProto.getName()).toUpperCamel();

    if (model.getDiagCollector().hasErrors()) {
        return null;
    } else {
        return new AutoValue_DiscoGapicInterfaceConfig(methodConfigs, retryCodesDefinition,
                retrySettingsDefinition, requiredConstructorParams, manualDoc, interfaceNameOverride,
                new DiscoInterfaceModel(interfaceName, model), smokeTestConfig,
                methodToSingleResourceNameMap.build(), methodConfigMap, singleResourceNames);
    }
}

From source file:org.sonar.java.it.ProfileGenerator.java

static void generate(Orchestrator orchestrator, String language, String repositoryKey,
        ImmutableMap<String, ImmutableMap<String, String>> rulesParameters, Set<String> excluded,
        Set<String> subsetOfEnabledRules, Set<String> activatedRuleKeys) {
    try {/*  ww w  .ja v  a  2s . c  om*/
        StringBuilder sb = new StringBuilder().append("<profile>").append("<name>rules</name>")
                .append("<language>").append(language).append("</language>").append("<alerts>")
                .append("<alert>").append("<metric>blocker_violations</metric>")
                .append("<operator>&gt;</operator>").append("<warning></warning>").append("<error>0</error>")
                .append("</alert>").append("<alert>").append("<metric>info_violations</metric>")
                .append("<operator>&gt;</operator>").append("<warning></warning>").append("<error>0</error>")
                .append("</alert>").append("</alerts>").append("<rules>");

        List<String> ruleKeys = Lists.newArrayList();
        String json = new HttpRequestFactory(orchestrator.getServer().getUrl()).get("/api/rules/search",
                ImmutableMap.<String, Object>of("languages", language, "repositories", repositoryKey, "ps",
                        "1000"));
        @SuppressWarnings("unchecked")
        List<Map> jsonRules = (List<Map>) ((Map) JSONValue.parse(json)).get("rules");
        for (Map jsonRule : jsonRules) {
            String key = (String) jsonRule.get("key");
            ruleKeys.add(key.split(":")[1]);
        }

        for (String key : ruleKeys) {
            if (excluded.contains(key)
                    || (!subsetOfEnabledRules.isEmpty() && !subsetOfEnabledRules.contains(key))) {
                continue;
            }
            activatedRuleKeys.add(key);
            sb.append("<rule>").append("<repositoryKey>").append(repositoryKey).append("</repositoryKey>")
                    .append("<key>").append(key).append("</key>").append("<priority>INFO</priority>");
            if (rulesParameters.containsKey(key)) {
                sb.append("<parameters>");
                for (Map.Entry<String, String> parameter : rulesParameters.get(key).entrySet()) {
                    sb.append("<parameter>").append("<key>").append(parameter.getKey()).append("</key>")
                            .append("<value>").append(parameter.getValue()).append("</value>")
                            .append("</parameter>");
                }
                sb.append("</parameters>");
            }
            sb.append("</rule>");
        }

        sb.append("</rules>").append("</profile>");

        File file = File.createTempFile("profile", ".xml");
        Files.write(sb, file, StandardCharsets.UTF_8);
        orchestrator.getServer().restoreProfile(FileLocation.of(file));
        file.delete();
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}

From source file:org.artifactory.storage.service.StorageServiceImpl.java

@Override
public StorageSummaryInfo getStorageSummaryInfo() {
    Set<RepoStorageSummary> summaries = fileService.getRepositoriesStorageSummary();
    filterGlobalRepoIfNeeded(summaries);
    List<RepoDescriptor> repos = Lists.newArrayList();
    repos.addAll(repositoryService.getLocalAndCachedRepoDescriptors());
    repos.addAll(repositoryService.getVirtualRepoDescriptors());
    final ImmutableMap<String, RepoDescriptor> reposMap = Maps.uniqueIndex(repos,
            new Function<RepoDescriptor, String>() {
                @Nullable/*from   w ww.  j a  va 2s . c  o m*/
                @Override
                public String apply(@Nullable RepoDescriptor input) {
                    if (input == null) {
                        return null;
                    }
                    return input.getKey();
                }
            });
    Iterable<RepoStorageSummaryInfo> infos = Iterables.transform(summaries,
            new Function<RepoStorageSummary, RepoStorageSummaryInfo>() {
                @Override
                public RepoStorageSummaryInfo apply(RepoStorageSummary r) {
                    RepositoryType repoType = getRepoType(r.getRepoKey(), reposMap);
                    RepoDescriptor repoDescriptor = reposMap.get(r.getRepoKey());
                    String repoTypeName = "UnKnown";
                    if (repoDescriptor != null) {
                        repoTypeName = repoDescriptor.getType().name();
                    }
                    RepoStorageSummaryInfo repoStorageSummaryInfo = new RepoStorageSummaryInfo(r.getRepoKey(),
                            repoType, r.getFoldersCount(), r.getFilesCount(), r.getUsedSpace(), repoTypeName);
                    return repoStorageSummaryInfo;
                }

                private RepositoryType getRepoType(String repoKey,
                        ImmutableMap<String, RepoDescriptor> repoDescriptors) {
                    RepoDescriptor repoDescriptor = repoDescriptors.get(repoKey);
                    if (repoDescriptor == null) {
                        return RepositoryType.BROKEN;
                    } else if (repoDescriptor instanceof RemoteRepoDescriptor) {
                        return RepositoryType.REMOTE;
                    } else if (repoDescriptor instanceof VirtualRepoDescriptor) {
                        return RepositoryType.VIRTUAL;
                    } else if (repoDescriptor instanceof LocalCacheRepoDescriptor) {
                        return RepositoryType.CACHE;
                    } else if (repoDescriptor instanceof LocalRepoDescriptor) {
                        return RepositoryType.LOCAL;
                    } else {
                        return RepositoryType.NA;
                    }
                }
            });

    BinariesInfo binariesInfo = binaryStore.getBinariesInfo();

    return new StorageSummaryInfo(Sets.newHashSet(infos), binariesInfo);
}

From source file:com.getbase.android.schema.Schemas.java

private ImmutableMap<String, ImmutableList<? extends TableDefinitionOperation>> merge(
        ImmutableMap<String, ImmutableList<? extends TableDefinitionOperation>> schema,
        ImmutableMap<String, ImmutableList<? extends TableDowngradeOperation>> downgrades, int targetRevision) {
    ImmutableMap.Builder<String, ImmutableList<? extends TableDefinitionOperation>> builder = ImmutableMap
            .builder();//from  w w w  . j  a  va2  s  . co m

    for (String unchangedTable : Sets.difference(schema.keySet(), downgrades.keySet())) {
        builder.put(unchangedTable, schema.get(unchangedTable));
    }

    for (String alteredTable : Sets.intersection(downgrades.keySet(), schema.keySet())) {
        ImmutableList<? extends TableDefinitionOperation> mergedOperations = MERGER.merge(
                schema.get(alteredTable), downgrades.get(alteredTable), alteredTable, targetRevision,
                mRevisionDescriptionBuilder);
        if (!mergedOperations.isEmpty()) {
            builder.put(alteredTable, mergedOperations);
        }
    }

    for (String addedTable : Sets.difference(downgrades.keySet(), schema.keySet())) {
        builder.put(addedTable, CONVERTER.convert(downgrades.get(addedTable), addedTable, targetRevision,
                mRevisionDescriptionBuilder));
    }

    return builder.build();
}

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) {//from  ww  w .j  av a2  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) {/* w w  w.ja  va2s  . co  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:com.qubole.quark.plugins.jdbc.JdbcDB.java

private ImmutableMap<String, Schema> getSchemaFromResultSet(ResultSet rs,
        ImmutableMap<String, Integer> dataTypes) throws SQLException {
    if (rs == null || !rs.next()) {
        return ImmutableMap.of();
    }//from   www  . j a  v  a  2 s  . c o  m
    ImmutableMap.Builder<String, Schema> schemaBuilder = new ImmutableMap.Builder<>();

    while (!rs.isAfterLast()) {
        String currentSchema = rs.getString(1);
        ImmutableMap.Builder<String, Table> tableBuilder = new ImmutableMap.Builder<>();
        while (!rs.isAfterLast() && rs.getString(1).equals(currentSchema)) {
            ImmutableList.Builder<QuarkColumn> columnBuilder = new ImmutableList.Builder<>();
            String currentTable = rs.getString(2);
            while (rs.getString(2).equals(currentTable)) {
                String columnName = rs.getString(3);
                if (!this.isCaseSensitive()) {
                    columnName = columnName.toUpperCase();
                }
                Integer dataType = null;
                for (String key : dataTypes.keySet()) {
                    if (rs.getString(4).toUpperCase().matches(key)) {
                        dataType = dataTypes.get(key);
                        break;
                    }
                }
                if (dataType == null) {
                    throw new SQLException("DataType `" + rs.getString(4) + "` is not supported");
                }
                columnBuilder.add(new QuarkColumn(columnName, dataType));
                LOG.debug("Adding column:  " + rs.getString(1) + " : " + rs.getString(2) + " : "
                        + rs.getString(3) + " : " + rs.getString(4));
                if (!rs.next()) {
                    break;
                }
            }

            if (!this.isCaseSensitive()) {
                currentTable = currentTable.toUpperCase();
            }
            tableBuilder.put(currentTable, new QuarkTable(columnBuilder.build()));
        }
        if (!this.isCaseSensitive()) {
            currentSchema = currentSchema.toUpperCase();
        }

        schemaBuilder.put(currentSchema,
                new com.qubole.quark.plugins.SimpleSchema(currentSchema.toUpperCase(), tableBuilder.build()));
    }
    return schemaBuilder.build();
}