Example usage for com.google.common.collect ImmutableSet isEmpty

List of usage examples for com.google.common.collect ImmutableSet isEmpty

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableSet isEmpty.

Prototype

boolean isEmpty();

Source Link

Document

Returns true if this set contains no elements.

Usage

From source file:com.facebook.buck.io.filesystem.impl.DefaultProjectFilesystem.java

public DefaultProjectFilesystem(FileSystem vfs, Path root, ImmutableSet<PathMatcher> blackListedPaths,
        BuckPaths buckPaths, ProjectFilesystemDelegate delegate, @Nullable WindowsFS winFSInstance) {
    if (shouldVerifyConstructorArguments()) {
        Preconditions.checkArgument(Files.isDirectory(root), "%s must be a directory", root);
        Preconditions.checkState(vfs.equals(root.getFileSystem()));
        Preconditions.checkArgument(root.isAbsolute(), "Expected absolute path. Got <%s>.", root);
    }//  www . j ava2 s.c  o  m

    this.projectRoot = MorePaths.normalize(root);
    this.delegate = delegate;
    this.ignoreValidityOfPaths = false;
    this.blackListedPaths = FluentIterable.from(blackListedPaths).append(FluentIterable.from(
            // "Path" is Iterable, so avoid adding each segment.
            // We use the default value here because that's what we've always done.
            MorePaths.filterForSubpaths(
                    ImmutableSet
                            .of(getCacheDir(root, Optional.of(buckPaths.getCacheDir().toString()), buckPaths)),
                    root))
            .append(ImmutableSet.of(buckPaths.getTrashDir())).transform(RecursiveFileMatcher::of)).toSet();
    this.buckPaths = buckPaths;

    this.blackListedDirectories = FluentIterable.from(this.blackListedPaths).filter(RecursiveFileMatcher.class)
            .transform(matcher -> {
                Path path = matcher.getPath();
                ImmutableSet<Path> filtered = MorePaths.filterForSubpaths(ImmutableSet.of(path), root);
                if (filtered.isEmpty()) {
                    return path;
                }
                return Iterables.getOnlyElement(filtered);
            })
            // TODO(#10068334) So we claim to ignore this path to preserve existing behaviour, but
            // we really don't end up ignoring it in reality (see extractIgnorePaths).
            .append(ImmutableSet.of(buckPaths.getBuckOut())).transform(RecursiveFileMatcher::of)
            .transform(matcher -> (PathMatcher) matcher).append(
                    // RecursiveFileMatcher instances are handled separately above because they all
                    // must be relative to the project root, but all other matchers are not relative
                    // to the root and do not require any special treatment.
                    Iterables.filter(this.blackListedPaths,
                            matcher -> !(matcher instanceof RecursiveFileMatcher)))
            .toSet();
    this.tmpDir = MoreSuppliers.memoize(() -> {
        Path relativeTmpDir = DefaultProjectFilesystem.this.buckPaths.getTmpDir();
        try {
            mkdirs(relativeTmpDir);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return relativeTmpDir;
    });

    this.winFSInstance = winFSInstance;
    if (Platform.detect() == Platform.WINDOWS) {
        Objects.requireNonNull(this.winFSInstance);
    }
}

From source file:com.facebook.buck.io.ProjectFilesystem.java

private ProjectFilesystem(FileSystem vfs, final Path root, ImmutableSet<PathOrGlobMatcher> blackListedPaths,
        BuckPaths buckPaths, ProjectFilesystemDelegate delegate) {
    if (shouldVerifyConstructorArguments()) {
        Preconditions.checkArgument(Files.isDirectory(root), "%s must be a directory", root);
        Preconditions.checkState(vfs.equals(root.getFileSystem()));
        Preconditions.checkArgument(root.isAbsolute());
    }//from  w w w.ja v  a  2  s  . co m
    this.projectRoot = MorePaths.normalize(root);
    this.delegate = delegate;
    this.ignoreValidityOfPaths = false;
    this.blackListedPaths = FluentIterable.from(blackListedPaths).append(FluentIterable.from(
            // "Path" is Iterable, so avoid adding each segment.
            // We use the default value here because that's what we've always done.
            ImmutableSet.of(getCacheDir(root, Optional.of(buckPaths.getCacheDir().toString()), buckPaths)))
            .append(ImmutableSet.of(buckPaths.getTrashDir())).transform(PathOrGlobMatcher::new)).toSet();
    this.buckPaths = buckPaths;

    this.blackListedDirectories = FluentIterable.from(this.blackListedPaths)
            .filter(matcher -> matcher.getType() == PathOrGlobMatcher.Type.PATH).transform(matcher -> {
                Path path = matcher.getPath();
                ImmutableSet<Path> filtered = MorePaths.filterForSubpaths(ImmutableSet.of(path), root);
                if (filtered.isEmpty()) {
                    return path;
                }
                return Iterables.getOnlyElement(filtered);
            })
            // TODO(#10068334) So we claim to ignore this path to preserve existing behaviour, but we
            // really don't end up ignoring it in reality (see extractIgnorePaths).
            .append(ImmutableSet.of(buckPaths.getBuckOut())).transform(PathOrGlobMatcher::new).append(Iterables
                    .filter(this.blackListedPaths, input -> input.getType() == PathOrGlobMatcher.Type.GLOB))
            .toSet();
    this.tmpDir = Suppliers.memoize(() -> {
        Path relativeTmpDir = ProjectFilesystem.this.buckPaths.getTmpDir();
        try {
            mkdirs(relativeTmpDir);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return relativeTmpDir;
    });
}

From source file:org.xolstice.maven.plugin.protobuf.AbstractProtocMojo.java

/**
 * Executes the mojo./*from  ww w . j  a  v  a2  s.  c om*/
 */
@Override
public void execute() throws MojoExecutionException, MojoFailureException {

    if (skipMojo()) {
        return;
    }

    checkParameters();
    final File protoSourceRoot = getProtoSourceRoot();
    if (protoSourceRoot.exists()) {
        try {
            final ImmutableSet<File> protoFiles = findProtoFilesInDirectory(protoSourceRoot);
            final File outputDirectory = getOutputDirectory();
            final ImmutableSet<File> outputFiles = findGeneratedFilesInDirectory(getOutputDirectory());

            if (protoFiles.isEmpty()) {
                getLog().info("No proto files to compile.");
            } else if (!hasDelta(protoFiles)) {
                getLog().info("Skipping compilation because build context has no changes.");
                doAttachFiles();
            } else if (checkStaleness && checkFilesUpToDate(protoFiles, outputFiles)) {
                getLog().info("Skipping compilation because target directory newer than sources.");
                doAttachFiles();
            } else {
                final ImmutableSet<File> derivedProtoPathElements = makeProtoPathFromJars(
                        temporaryProtoFileDirectory, getDependencyArtifactFiles());
                FileUtils.mkdir(outputDirectory.getAbsolutePath());

                if (clearOutputDirectory) {
                    cleanDirectory(outputDirectory);
                }

                if (writeDescriptorSet) {
                    final File descriptorSetOutputDirectory = getDescriptorSetOutputDirectory();
                    FileUtils.mkdir(descriptorSetOutputDirectory.getAbsolutePath());
                    if (clearOutputDirectory) {
                        cleanDirectory(descriptorSetOutputDirectory);
                    }
                }

                if (protocPlugins != null) {
                    createProtocPlugins();
                }

                //get toolchain from context
                final Toolchain tc = toolchainManager.getToolchainFromBuildContext("protobuf", session); //NOI18N
                if (tc != null) {
                    getLog().info("Toolchain in protobuf-maven-plugin: " + tc);
                    //when the executable to use is explicitly set by user in mojo's parameter, ignore toolchains.
                    if (protocExecutable != null) {
                        getLog().warn("Toolchains are ignored, 'protocExecutable' parameter is set to "
                                + protocExecutable);
                    } else {
                        //assign the path to executable from toolchains
                        protocExecutable = tc.findTool("protoc"); //NOI18N
                    }
                }
                if (protocExecutable == null && protocArtifact != null) {
                    final Artifact artifact = createDependencyArtifact(protocArtifact);
                    final File file = resolveBinaryArtifact(artifact);
                    protocExecutable = file.getAbsolutePath();
                }
                if (protocExecutable == null) {
                    // Try to fall back to 'protoc' in $PATH
                    getLog().warn("No 'protocExecutable' parameter is configured, using the default: 'protoc'");
                    protocExecutable = "protoc";
                }

                final Protoc.Builder protocBuilder = new Protoc.Builder(protocExecutable)
                        .addProtoPathElement(protoSourceRoot).addProtoPathElements(derivedProtoPathElements)
                        .addProtoPathElements(asList(additionalProtoPathElements)).addProtoFiles(protoFiles);
                addProtocBuilderParameters(protocBuilder);
                final Protoc protoc = protocBuilder.build();

                if (getLog().isDebugEnabled()) {
                    getLog().debug("Proto source root:");
                    getLog().debug(" " + protoSourceRoot);

                    if (derivedProtoPathElements != null && !derivedProtoPathElements.isEmpty()) {
                        getLog().debug("Derived proto paths:");
                        for (final File path : derivedProtoPathElements) {
                            getLog().debug(" " + path);
                        }
                    }

                    if (additionalProtoPathElements != null && additionalProtoPathElements.length > 0) {
                        getLog().debug("Additional proto paths:");
                        for (final File path : additionalProtoPathElements) {
                            getLog().debug(" " + path);
                        }
                    }
                }
                protoc.logExecutionParameters(getLog());

                getLog().info(format("Compiling %d proto file(s) to %s", protoFiles.size(), outputDirectory));

                final int exitStatus = protoc.execute();
                if (StringUtils.isNotBlank(protoc.getOutput())) {
                    getLog().info("PROTOC: " + protoc.getOutput());
                }
                if (exitStatus != 0) {
                    getLog().error("PROTOC FAILED: " + protoc.getError());
                    for (File pf : protoFiles) {
                        buildContext.removeMessages(pf);
                        buildContext.addMessage(pf, 0, 0, protoc.getError(), BuildContext.SEVERITY_ERROR, null);
                    }
                    throw new MojoFailureException(
                            "protoc did not exit cleanly. Review output for more information.");
                } else if (StringUtils.isNotBlank(protoc.getError())) {
                    getLog().warn("PROTOC: " + protoc.getError());
                }
                doAttachFiles();
            }
        } catch (IOException e) {
            throw new MojoExecutionException("An IO error occured", e);
        } catch (IllegalArgumentException e) {
            throw new MojoFailureException("protoc failed to execute because: " + e.getMessage(), e);
        } catch (CommandLineException e) {
            throw new MojoExecutionException("An error occurred while invoking protoc.", e);
        }
    } else {
        getLog().info(format("%s does not exist. Review the configuration or consider disabling the plugin.",
                protoSourceRoot));
    }
}

From source file:dagger2.internal.codegen.BindingGraphValidator.java

/**
 * Validates that among the dependencies are at most one scoped dependency,
 * that there are no cycles within the scoping chain, and that singleton
 * components have no scoped dependencies.
 *///from  w  w w. j a  v  a 2 s  .com
private void validateDependencyScopes(BindingGraph subject, Builder<BindingGraph> reportBuilder) {
    ComponentDescriptor descriptor = subject.componentDescriptor();
    Optional<AnnotationMirror> scope = subject.componentDescriptor().scope();
    ImmutableSet<TypeElement> scopedDependencies = scopedTypesIn(descriptor.dependencies());
    if (scope.isPresent()) {
        // Dagger 1.x scope compatibility requires this be suppress-able.
        if (scopeCycleValidationType.diagnosticKind().isPresent()
                && isTypeOf(Singleton.class, scope.get().getAnnotationType())) {
            // Singleton is a special-case representing the longest lifetime, and therefore
            // @Singleton components may not depend on scoped components
            if (!scopedDependencies.isEmpty()) {
                StringBuilder message = new StringBuilder(
                        "This @Singleton component cannot depend on scoped components:\n");
                appendIndentedComponentsList(message, scopedDependencies);
                reportBuilder.addItem(message.toString(), scopeCycleValidationType.diagnosticKind().get(),
                        descriptor.componentDefinitionType(), descriptor.componentAnnotation());
            }
        } else if (scopedDependencies.size() > 1) {
            // Scoped components may depend on at most one scoped component.
            StringBuilder message = new StringBuilder(ErrorMessages.format(scope.get())).append(' ')
                    .append(descriptor.componentDefinitionType().getQualifiedName())
                    .append(" depends on more than one scoped component:\n");
            appendIndentedComponentsList(message, scopedDependencies);
            reportBuilder.addItem(message.toString(), descriptor.componentDefinitionType(),
                    descriptor.componentAnnotation());
        } else {
            // Dagger 1.x scope compatibility requires this be suppress-able.
            if (!scopeCycleValidationType.equals(ValidationType.NONE)) {
                validateScopeHierarchy(descriptor.componentDefinitionType(),
                        descriptor.componentDefinitionType(), reportBuilder,
                        new ArrayDeque<Equivalence.Wrapper<AnnotationMirror>>(), new ArrayDeque<TypeElement>());
            }
        }
    } else {
        // Scopeless components may not depend on scoped components.
        if (!scopedDependencies.isEmpty()) {
            StringBuilder message = new StringBuilder(descriptor.componentDefinitionType().getQualifiedName())
                    .append(" (unscoped) cannot depend on scoped components:\n");
            appendIndentedComponentsList(message, scopedDependencies);
            reportBuilder.addItem(message.toString(), descriptor.componentDefinitionType(),
                    descriptor.componentAnnotation());
        }
    }
}

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

private void processType(TypeElement type) {
    AutoValue autoValue = type.getAnnotation(AutoValue.class);
    if (autoValue == null) {
        // This shouldn't happen unless the compilation environment is buggy,
        // but it has happened in the past and can crash the compiler.
        errorReporter.abortWithError("annotation processor for @AutoValue was invoked with a type"
                + " that does not have that annotation; this is probably a compiler bug", type);
    }/* ww w  .ja v a 2 s .  c  o m*/
    if (type.getKind() != ElementKind.CLASS) {
        errorReporter.abortWithError("@" + AutoValue.class.getName() + " only applies to classes", type);
    }
    if (ancestorIsAutoValue(type)) {
        errorReporter.abortWithError("One @AutoValue class may not extend another", type);
    }
    if (implementsAnnotation(type)) {
        errorReporter.abortWithError("@AutoValue may not be used to implement an annotation"
                + " interface; try using @AutoAnnotation instead", type);
    }
    checkModifiersIfNested(type);

    // We are going to classify the methods of the @AutoValue class into several categories.
    // This covers the methods in the class itself and the ones it inherits from supertypes.
    // First, the only concrete (non-abstract) methods we are interested in are overrides of
    // Object methods (equals, hashCode, toString), which signal that we should not generate
    // an implementation of those methods.
    // Then, each abstract method is one of the following:
    // (1) A property getter, like "abstract String foo()" or "abstract String getFoo()".
    // (2) A toBuilder() method, which is any abstract no-arg method returning the Builder for
    //     this @AutoValue class.
    // (3) An abstract method that will be consumed by an extension, such as
    //     Parcelable.describeContents() or Parcelable.writeToParcel(Parcel, int).
    // The describeContents() example shows a quirk here: initially we will identify it as a
    // property, which means that we need to reconstruct the list of properties after allowing
    // extensions to consume abstract methods.
    // If there are abstract methods that don't fit any of the categories above, that is an error
    // which we signal explicitly to avoid confusion.

    ImmutableSet<ExecutableElement> methods = getLocalAndInheritedMethods(type, processingEnv.getTypeUtils(),
            processingEnv.getElementUtils());
    ImmutableSet<ExecutableElement> abstractMethods = abstractMethodsIn(methods);

    BuilderSpec builderSpec = new BuilderSpec(type, processingEnv, errorReporter);
    Optional<BuilderSpec.Builder> builder = builderSpec.getBuilder();
    ImmutableSet<ExecutableElement> toBuilderMethods;
    if (builder.isPresent()) {
        toBuilderMethods = builder.get().toBuilderMethods(typeUtils, abstractMethods);
    } else {
        toBuilderMethods = ImmutableSet.of();
    }

    ImmutableSet<ExecutableElement> propertyMethods = propertyMethodsIn(
            immutableSetDifference(abstractMethods, toBuilderMethods));
    ImmutableBiMap<String, ExecutableElement> properties = propertyNameToMethodMap(propertyMethods);

    ExtensionContext context = new ExtensionContext(processingEnv, type, properties, abstractMethods);
    ImmutableList<AutoValueExtension> applicableExtensions = applicableExtensions(type, context);
    ImmutableSet<ExecutableElement> consumedMethods = methodsConsumedByExtensions(type, applicableExtensions,
            context, abstractMethods, properties);

    if (!consumedMethods.isEmpty()) {
        ImmutableSet<ExecutableElement> allAbstractMethods = abstractMethods;
        abstractMethods = immutableSetDifference(abstractMethods, consumedMethods);
        toBuilderMethods = immutableSetDifference(toBuilderMethods, consumedMethods);
        propertyMethods = propertyMethodsIn(immutableSetDifference(abstractMethods, toBuilderMethods));
        properties = propertyNameToMethodMap(propertyMethods);
        context = new ExtensionContext(processingEnv, type, properties, allAbstractMethods);
    }

    boolean extensionsPresent = !applicableExtensions.isEmpty();
    validateMethods(type, abstractMethods, toBuilderMethods, propertyMethods, extensionsPresent);

    String finalSubclass = generatedSubclassName(type, 0);
    AutoValueTemplateVars vars = new AutoValueTemplateVars();
    vars.pkg = TypeSimplifier.packageNameOf(type);
    vars.origClass = TypeSimplifier.classNameOf(type);
    vars.simpleClassName = TypeSimplifier.simpleNameOf(vars.origClass);
    vars.finalSubclass = TypeSimplifier.simpleNameOf(finalSubclass);
    vars.types = processingEnv.getTypeUtils();
    determineObjectMethodsToGenerate(methods, vars);
    TypeSimplifier typeSimplifier = defineVarsForType(type, vars, toBuilderMethods, propertyMethods, builder);

    // Only copy annotations from a class if it has @AutoValue.CopyAnnotations.
    if (isAnnotationPresent(type, AutoValue.CopyAnnotations.class)) {
        Set<String> excludedAnnotations = union(getFieldOfClasses(type, AutoValue.CopyAnnotations.class,
                "exclude", processingEnv.getElementUtils()), getAnnotationsMarkedWithInherited(type));

        vars.annotations = copyAnnotations(type, typeSimplifier, excludedAnnotations);
    } else {
        vars.annotations = ImmutableList.of();
    }

    GwtCompatibility gwtCompatibility = new GwtCompatibility(type);
    vars.gwtCompatibleAnnotation = gwtCompatibility.gwtCompatibleAnnotationString();

    int subclassDepth = writeExtensions(type, context, applicableExtensions);
    String subclass = generatedSubclassName(type, subclassDepth);
    vars.subclass = TypeSimplifier.simpleNameOf(subclass);
    vars.isFinal = (subclassDepth == 0);

    String text = vars.toText();
    text = Reformatter.fixup(text);
    writeSourceFile(subclass, text, type);
    GwtSerialization gwtSerialization = new GwtSerialization(gwtCompatibility, processingEnv, type);
    gwtSerialization.maybeWriteGwtSerializer(vars);
}

From source file:org.apache.james.mailbox.lucene.search.LuceneMessageSearchIndex.java

private Query buildQueryFromMailboxes(ImmutableSet<MailboxId> mailboxIds) {
    if (mailboxIds.isEmpty()) {
        return new MatchAllDocsQuery();
    }/*from   w  w  w.  ja  va  2  s. c  o  m*/
    BooleanQuery query = new BooleanQuery();
    for (MailboxId id : mailboxIds) {
        String idAsString = id.serialize();
        query.add(new TermQuery(new Term(MAILBOX_ID_FIELD, idAsString)), BooleanClause.Occur.SHOULD);
    }
    return query;
}

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

public int parseTargetsAndRunXCodeGenerator(ListeningExecutorService executor)
        throws IOException, InterruptedException {
    ImmutableSet<BuildTarget> passedInTargetsSet;
    TargetGraph projectGraph;//from  ww w  .ja  va  2 s.co m

    try {
        ParserConfig parserConfig = buckConfig.getView(ParserConfig.class);
        passedInTargetsSet = ImmutableSet.copyOf(Iterables.concat(parser.resolveTargetSpecs(buckEventBus, cell,
                enableParserProfiling, executor, argsParser.apply(arguments), SpeculativeParsing.of(true),
                parserConfig.getDefaultFlavorsMode())));
        projectGraph = getProjectGraphForIde(executor, passedInTargetsSet);
    } catch (BuildTargetException | BuildFileParseException | HumanReadableException e) {
        buckEventBus.post(ConsoleEvent.severe(MoreExceptions.getHumanReadableOrLocalizedMessage(e)));
        return 1;
    }

    checkForAndKillXcodeIfRunning(getIdePrompt(buckConfig));

    ImmutableSet<BuildTarget> graphRoots;
    if (passedInTargetsSet.isEmpty()) {
        graphRoots = getRootsFromPredicate(projectGraph,
                node -> node.getDescription() instanceof XcodeWorkspaceConfigDescription);
    } else {
        graphRoots = passedInTargetsSet;
    }

    TargetGraphAndTargets targetGraphAndTargets;
    try {
        targetGraphAndTargets = createTargetGraph(projectGraph, graphRoots, isWithTests(buckConfig),
                isWithDependenciesTests(buckConfig), passedInTargetsSet.isEmpty(), executor);
    } catch (BuildFileParseException | TargetGraph.NoSuchNodeException | BuildTargetException
            | HumanReadableException e) {
        buckEventBus.post(ConsoleEvent.severe(MoreExceptions.getHumanReadableOrLocalizedMessage(e)));
        return 1;
    }

    if (dryRun) {
        for (TargetNode<?, ?> targetNode : targetGraphAndTargets.getTargetGraph().getNodes()) {
            console.getStdOut().println(targetNode.toString());
        }

        return 0;
    }

    return runXcodeProjectGenerator(executor, targetGraphAndTargets, passedInTargetsSet);
}

From source file:com.google.devtools.build.lib.rules.objc.ReleaseBundlingSupport.java

/** Returns this target's Xcode build settings. */
private Iterable<XcodeprojBuildSetting> buildSettings() {
    ImmutableList.Builder<XcodeprojBuildSetting> buildSettings = new ImmutableList.Builder<>();
    if (releaseBundling.getAppIcon() != null) {
        buildSettings.add(XcodeprojBuildSetting.newBuilder().setName("ASSETCATALOG_COMPILER_APPICON_NAME")
                .setValue(releaseBundling.getAppIcon()).build());
    }/*  w w w  .  jav a 2s  .  c  om*/
    if (releaseBundling.getLaunchImage() != null) {
        buildSettings.add(XcodeprojBuildSetting.newBuilder().setName("ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME")
                .setValue(releaseBundling.getLaunchImage()).build());
    }

    // Convert names to a sequence containing "1" and/or "2" for iPhone and iPad, respectively.
    ImmutableSet<TargetDeviceFamily> families;
    if (bundleSupport.isBuildingForWatch()) {
        families = ImmutableSet.of(TargetDeviceFamily.WATCH);
    } else {
        families = bundleSupport.targetDeviceFamilies();
    }
    Iterable<Integer> familyIndexes = families.isEmpty() ? ImmutableList.<Integer>of()
            : UI_DEVICE_FAMILY_VALUES.get(families);
    buildSettings.add(XcodeprojBuildSetting.newBuilder().setName("TARGETED_DEVICE_FAMILY")
            .setValue(Joiner.on(',').join(familyIndexes)).build());

    Artifact entitlements = releaseBundling.getEntitlements();
    if (entitlements != null) {
        buildSettings.add(XcodeprojBuildSetting.newBuilder().setName("CODE_SIGN_ENTITLEMENTS")
                .setValue("$(WORKSPACE_ROOT)/" + entitlements.getExecPathString()).build());
    }

    return buildSettings.build();
}

From source file:org.elasticsearch.search.facet.terms.strings.TermsStringFacetCollector.java

public TermsStringFacetCollector(String facetName, String fieldName, int size,
        TermsFacet.ComparatorType comparatorType, boolean allTerms, SearchContext context,
        ImmutableSet<BytesRef> excluded, Pattern pattern, String scriptLang, String script,
        Map<String, Object> params) {
    super(facetName);
    this.fieldDataCache = context.fieldDataCache();
    this.size = size;
    this.comparatorType = comparatorType;
    this.numberOfShards = context.numberOfShards();

    MapperService.SmartNameFieldMappers smartMappers = context.smartFieldMappers(fieldName);
    if (smartMappers == null || !smartMappers.hasMapper()) {
        this.indexFieldName = fieldName;
        this.fieldDataType = FieldDataType.DefaultTypes.STRING;
    } else {//from   ww w  .j a  v a 2 s .co m
        // add type filter if there is exact doc mapper associated with it
        if (smartMappers.hasDocMapper()) {
            setFilter(context.filterCache().cache(smartMappers.docMapper().typeFilter()));
        }

        this.indexFieldName = smartMappers.mapper().names().indexName();
        this.fieldDataType = smartMappers.mapper().fieldDataType();
    }

    if (script != null) {
        this.script = context.scriptService().search(context.lookup(), scriptLang, script, params);
    } else {
        this.script = null;
    }

    if (excluded.isEmpty() && pattern == null && this.script == null) {
        aggregator = new StaticAggregatorValueProc(CacheRecycler.<BytesRef>popObjectIntMap());
    } else {
        aggregator = new AggregatorValueProc(CacheRecycler.<BytesRef>popObjectIntMap(), excluded, pattern,
                this.script);
    }

    if (allTerms) {
        try {
            for (AtomicReaderContext readerContext : context.searcher().getTopReaderContext().leaves()) {
                FieldData fieldData = fieldDataCache.cache(fieldDataType, readerContext.reader(),
                        indexFieldName);
                fieldData.forEachValue(aggregator);
            }
        } catch (Exception e) {
            throw new FacetPhaseExecutionException(facetName, "failed to load all terms", e);
        }
    }
}

From source file:org.elasticsearch.search.facet.terms.ints.TermsIntOrdinalsFacetCollector.java

public TermsIntOrdinalsFacetCollector(String facetName, String fieldName, int size,
        TermsFacet.ComparatorType comparatorType, boolean allTerms, SearchContext context,
        ImmutableSet<BytesRef> excluded) {
    super(facetName);
    this.fieldDataCache = context.fieldDataCache();
    this.size = size;
    this.comparatorType = comparatorType;
    this.numberOfShards = context.numberOfShards();

    MapperService.SmartNameFieldMappers smartMappers = context.smartFieldMappers(fieldName);
    if (smartMappers == null || !smartMappers.hasMapper()) {
        throw new ElasticSearchIllegalArgumentException(
                "Field [" + fieldName + "] doesn't have a type, can't run terms int facet collector on it");
    }/*from  w ww . j av  a  2  s  .c om*/
    // add type filter if there is exact doc mapper associated with it
    if (smartMappers.explicitTypeInNameWithDocMapper()) {
        setFilter(context.filterCache().cache(smartMappers.docMapper().typeFilter()));
    }

    if (smartMappers.mapper().fieldDataType() != FieldDataType.DefaultTypes.INT) {
        throw new ElasticSearchIllegalArgumentException(
                "Field [" + fieldName + "] is not of int type, can't run terms int facet collector on it");
    }

    this.indexFieldName = smartMappers.mapper().names().indexName();
    this.fieldDataType = smartMappers.mapper().fieldDataType();

    if (excluded == null || excluded.isEmpty()) {
        this.excluded = null;
    } else {
        this.excluded = new TIntHashSet(excluded.size());
        for (BytesRef s : excluded) {
            this.excluded.add(Integer.parseInt(s.utf8ToString()));
        }
    }

    // minCount is offset by -1
    if (allTerms) {
        minCount = -1;
    } else {
        minCount = 0;
    }

    this.aggregators = new ArrayList<ReaderAggregator>(context.searcher().getIndexReader().leaves().size());
}