Example usage for com.google.common.collect ImmutableSortedSet naturalOrder

List of usage examples for com.google.common.collect ImmutableSortedSet naturalOrder

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableSortedSet naturalOrder.

Prototype

public static <E extends Comparable<?>> Builder<E> naturalOrder() 

Source Link

Usage

From source file:net.navatwo.jfxproperties.PropertyObject.java

/**
 * Initialize a {@link PropertyObject}.// ww w. j  ava 2 s. c o  m
 * <br/>
 * <p>
 * This should only be called from {@link Builder}.
 *
 * @param fields  Fields found in the hierarchy
 * @param methods Methods found in the hierarchy
 */
@SuppressWarnings("unchecked")
PropertyObject(TypeToken<T> base, Collection<? extends PropertyObject<? super T>> supers,
        Set<String> ignoredProperties, Map<String, TypeToken<?>> types, Map<String, Field> fields,
        Map<String, EnumMap<MethodType, Invokable<T, ?>>> methods) {
    this.base = checkNotNull(base, "base == null");
    this.hashCode = base.hashCode();
    this.supers = checkNotNull(supers, "supers == null");

    // Collect all of the properties from the immediate super collectors, these will have been initialized with
    // their super ignored properties as well.
    ImmutableSortedSet.Builder<String> ignoredPropertiesBuilder = ImmutableSortedSet.naturalOrder();
    ignoredPropertiesBuilder.addAll(ignoredProperties);
    supers.stream().flatMap(s -> s.getIgnoredProperties().stream()).forEach(ignoredPropertiesBuilder::add);
    this.ignoredProperties = ignoredPropertiesBuilder.build();

    // now we need to go through and create a mapping of property names to the accessing methods/fields
    // do a union on the keys this gives us all the property names that have been found
    ImmutableMap.Builder<String, PropertyInfo<?>> propertyMapBuilder = ImmutableMap.builder();
    Sets.union(methods.keySet(), fields.keySet()).stream()
            .filter(propName -> !this.ignoredProperties.contains(propName)).forEach(propName -> {
                // Now build the appropriate PropertyInfo<> implementation dependant on the type of the Field.
                // We can use the primitive versions when it will be faster for them to execute later.

                TypeToken<?> propType = types.get(propName).unwrap();

                EnumMap<MethodType, Invokable<T, ?>> mmap = methods.getOrDefault(propName,
                        new EnumMap<>(MethodType.class));

                Field field = fields.get(propName);
                Invokable<T, ? extends ReadOnlyProperty<?>> accessor = (Invokable<T, ? extends ReadOnlyProperty<?>>) mmap
                        .get(MethodType.ACCESSOR);
                Invokable<T, ?> getter = mmap.get(MethodType.GETTER);
                Invokable<T, Void> setter = (Invokable<T, Void>) mmap.get(MethodType.SETTER);

                if (getter != null || setter != null || accessor != null) {

                    PropertyInfoExtractor piExtract = new PropertyInfoExtractor(propName, base, propType, field,
                            getter, setter, accessor);
                    TypeAcceptor.accept(propType, piExtract);

                    propertyMapBuilder.put(propName, piExtract.getPropertyInfo());
                }
            });

    this.localProperties = propertyMapBuilder.build();
    this.thisNames = ImmutableSortedSet.copyOf(localProperties.keySet());

    supers.stream().flatMap(s -> s.getProperties().entrySet().stream())
            .filter(e -> !this.thisNames.contains(e.getKey()))
            .filter(e -> !this.ignoredProperties.contains(e.getKey()))
            .forEach(e -> propertyMapBuilder.put(e.getKey(), e.getValue()));

    // Now create the immutable structures required and store them.
    allProperties = propertyMapBuilder.build();
    allNames = ImmutableSortedSet.copyOf(allProperties.keySet());
}

From source file:com.facebook.buck.rules.DescribedRuleBuilder.java

@Override
public DescribedRule build(BuildRuleResolver ruleResolver) {
    ImmutableSortedSet.Builder<BuildRule> declaredRules = ImmutableSortedSet.naturalOrder();
    for (BuildTarget dep : declaredDeps) {
        BuildRule rule = ruleResolver.get(dep);
        Preconditions.checkNotNull(rule, dep.toString());
        declaredRules.add(rule);//w ww .  java  2 s. c om
    }
    ImmutableSortedSet.Builder<BuildRule> paramRules = ImmutableSortedSet.naturalOrder();
    for (BuildTarget dep : extraDeps) {
        paramRules.add(ruleResolver.get(dep));
    }

    ConstructorArgMarshaller inspector = new ConstructorArgMarshaller(Paths.get(target.getBasePath()));
    T arg = description.createUnpopulatedConstructorArg();
    inspector.populate(ruleResolver, ruleFactoryParams.getProjectFilesystem(), ruleFactoryParams, arg);

    // The params used for the Buildable only contain the declared parameters. However, the deps of
    // the rule include not only those, but also any that were picked up through the deps declared
    // via a SourcePath.
    BuildRuleParams params = new BuildRuleParams(target, declaredRules.build(), getVisibilityPatterns(),
            ruleFactoryParams.getProjectFilesystem(), ruleFactoryParams.getRuleKeyBuilderFactory());
    Buildable buildable = description.createBuildable(params, arg);

    // Check for graph enhancement.
    ImmutableSortedSet<BuildRule> enhancedDeps = buildable.getEnhancedDeps(ruleResolver);
    if (enhancedDeps != null) {
        paramRules.addAll(enhancedDeps);
    } else {
        paramRules.addAll(declaredRules.build());
    }

    // These are the params used by the rule, but not the buildable. Confusion will be lessened once
    // we move to a dependency graph that's not the action graph.
    params = new BuildRuleParams(params.getBuildTarget(), paramRules.build(), params.getVisibilityPatterns(),
            params.getProjectFilesystem(), params.getRuleKeyBuilderFactory());
    return new DescribedRule(description.getBuildRuleType(), buildable, params);
}

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

@Override
public ImmutableList<Step> getBuildSteps(BuildContext context, BuildableContext buildableContext) {
    ImmutableList.Builder<Step> steps = ImmutableList.builder();
    ImmutableSortedSet.Builder<Path> objectFiles = ImmutableSortedSet.naturalOrder();
    Set<Path> createdDirectories = Sets.newHashSet();

    addMkdirStepIfNeeded(createdDirectories, steps, getPathToOutputFile().getParent());

    for (SourcePath src : srcs) {
        Path srcFile = getResolver().getPath(src);
        // We expect srcFile to be relative to the buck root
        Preconditions.checkState(!srcFile.isAbsolute());
        Path parent = srcFile.getParent();
        if (parent == null) {
            parent = Paths.get("");
        }/*from w ww.j  a v a 2  s  .c  om*/
        // To avoid collisions, objects files are created in directories that reflects the path to
        // source files rather than the (path-like) name of build targets
        Path targetDir = BuckConstant.GEN_PATH.resolve(parent);
        addMkdirStepIfNeeded(createdDirectories, steps, targetDir);

        Path objectFile = targetDir
                .resolve(Files.getNameWithoutExtension(srcFile.getFileName().toString()) + OBJECT_EXTENSION);
        steps.add(new CompilerStep(/* compiler */ getCompiler(), /* shouldLink */ false,
                /* srcs */ ImmutableSortedSet.of(srcFile), /* outputFile */ objectFile,
                /* shouldAddProjectRootToIncludePaths */ true, /* includePaths */ ImmutableSortedSet.<Path>of(),
                /* commandLineArgs */ commandLineArgsForFile(src, perSrcFileFlags)));
        objectFiles.add(objectFile);
    }

    for (BuildRule dep : getDeps()) {
        // Only c++ static libraries are supported for now.
        if (dep instanceof CxxLibrary) {
            objectFiles.add(Preconditions.checkNotNull(dep.getPathToOutputFile()));
        }
    }

    steps.addAll(getFinalBuildSteps(objectFiles.build(), getPathToOutputFile()));

    return steps.build();
}

From source file:com.facebook.buck.util.MorePaths.java

/**
 * Convert a set of input file paths as strings to {@link Path} objects.
 *//*w w  w. j av  a2s.c om*/
public static ImmutableSortedSet<Path> asPaths(Iterable<String> paths) {
    ImmutableSortedSet.Builder<Path> builder = ImmutableSortedSet.naturalOrder();
    for (String path : paths) {
        builder.add(Paths.get(path));
    }
    return builder.build();
}

From source file:com.facebook.buck.java.intellij.IjDependencyListBuilder.java

public IjDependencyListBuilder() {
    builder = ImmutableSortedSet.naturalOrder();

    builder.add(DependencyEntry.builder().setType(Type.SOURCE_FOLDER).setSortOrder(SortOrder.SOURCE_FOLDER)
            .build());
}

From source file:org.voltcore.utils.COWNavigableSet.java

@Override
public boolean remove(Object o) {
    while (true) {
        ImmutableSortedSet<E> snapshot = m_set.get();
        if (!snapshot.contains(o))
            return false;

        ImmutableSortedSet.Builder<E> builder = ImmutableSortedSet.naturalOrder();
        for (E e : snapshot) {
            if (e.equals(o))
                continue;
            builder.add(e);//from  w w  w .ja v a  2 s  .c om
        }
        if (m_set.compareAndSet(snapshot, builder.build())) {
            return true;
        }
    }
}

From source file:com.facebook.buck.util.autosparse.MmappedHgManifest.java

public MmappedHgManifest(Path rawManifestPath, int chunkSize) throws IOException {
    // Here is to hoping this is the correct codec on all platforms; Mercurial
    // doesn't care what the filesystem encoding is and just stores the raw bytes.
    String systemEncoding = System.getProperty("file.encoding");
    this.encoding = Charset.availableCharsets().getOrDefault(systemEncoding, StandardCharsets.UTF_8);

    try (FileChannel fileChannel = FileChannel.open(rawManifestPath);) {
        long longSize = fileChannel.size();

        if (longSize > MAX_FILE_SIZE) {
            // MappedByteBuffer can only handle int positions, so we can only address 2GB with a single
            // mmap. Reaching larger manifest sizes would require using multiple mmap objects and
            // added complexity.
            throw new IOException("Unable to load a manifest > 2GB");
        }//from  w  ww  .j  ava2s.  c o m
        mmap = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, longSize);
        size = (int) longSize;

        Pair<Integer, ImmutableSet<String>> sizeAndDeleted = loadDeleted(size);
        lastIndex = sizeAndDeleted.getFirst().intValue();
        deletedPaths = sizeAndDeleted.getSecond();

        // build an index on which to do in-memory bisection before bisecting the mmap itself
        ImmutableSortedSet.Builder<ChunkIndexEntry> indexBuilder = ImmutableSortedSet.naturalOrder();

        for (int pos = chunkSize; pos < size; pos += chunkSize) {
            int start = findEntryStart(pos);
            int end = find(NUL, start);
            indexBuilder.add(new ChunkIndexEntry(getString(start, end), start));
        }

        chunkIndex = indexBuilder.build();
        LOG.info("Manifest mmap loaded, %d chunks, %d deleted paths, %d size", chunkIndex.size(),
                deletedPaths.size(), size);
    }
}

From source file:com.ccheptea.auto.value.node.TypeSimplifier.java

/**
 * Returns the set of types to import. We import every type that is neither in java.lang nor in
 * the package containing the AutoValue class, provided that the result refers to the type
 * unambiguously. For example, if there is a property of type java.util.Map.Entry then we will
 * import java.util.Map.Entry and refer to the property as Entry. We could also import just
 * java.util.Map in this case and refer to Map.Entry, but currently we never do that.
 *///  w w  w .j  ava2s  . com
ImmutableSortedSet<String> typesToImport() {
    ImmutableSortedSet.Builder<String> typesToImport = ImmutableSortedSet.naturalOrder();
    for (Map.Entry<String, Spelling> entry : imports.entrySet()) {
        if (entry.getValue().importIt) {
            typesToImport.add(entry.getKey());
        }
    }
    return typesToImport.build();
}

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

@Override
public BuildRule createBuildRule(TargetGraph targetGraph, BuildRuleParams params, BuildRuleResolver resolver,
        ThriftConstructorArg args, ImmutableMap<String, ThriftSource> sources,
        ImmutableSortedSet<BuildRule> deps) throws NoSuchBuildTargetException {
    SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(resolver);

    if (params.getBuildTarget().getFlavors().contains(CalculateAbi.FLAVOR)) {
        BuildTarget libraryTarget = params.getBuildTarget().withoutFlavors(CalculateAbi.FLAVOR);
        resolver.requireRule(libraryTarget);
        return CalculateAbi.of(params.getBuildTarget(), ruleFinder, params,
                new BuildTargetSourcePath(libraryTarget));
    }//from  ww w.  j  a  v a  2 s  .  c  o  m

    // Pack all the generated sources into a single source zip that we'll pass to the
    // java rule below.
    ImmutableSortedSet.Builder<BuildRule> sourceZipsBuilder = ImmutableSortedSet.naturalOrder();
    UnflavoredBuildTarget unflavoredBuildTarget = params.getBuildTarget().getUnflavoredBuildTarget();
    for (ImmutableMap.Entry<String, ThriftSource> ent : sources.entrySet()) {
        String name = ent.getKey();
        BuildRule compilerRule = ent.getValue().getCompileRule();
        Path sourceDirectory = ent.getValue().getOutputDir().resolve("gen-java");

        BuildTarget sourceZipTarget = getSourceZipBuildTarget(unflavoredBuildTarget, name);
        Path sourceZip = getSourceZipOutputPath(params.getProjectFilesystem(), unflavoredBuildTarget, name);

        sourceZipsBuilder.add(new SrcZip(params.copyWithChanges(sourceZipTarget,
                Suppliers.ofInstance(ImmutableSortedSet.of(compilerRule)),
                Suppliers.ofInstance(ImmutableSortedSet.of())), sourceZip, sourceDirectory));
    }
    ImmutableSortedSet<BuildRule> sourceZips = sourceZipsBuilder.build();
    resolver.addAllToIndex(sourceZips);

    // Create to main compile rule.
    BuildRuleParams javaParams = params.copyWithChanges(
            BuildTargets.createFlavoredBuildTarget(unflavoredBuildTarget, getFlavor()),
            Suppliers.ofInstance(ImmutableSortedSet.<BuildRule>naturalOrder().addAll(sourceZips).addAll(deps)
                    .addAll(BuildRules.getExportedRules(deps))
                    .addAll(ruleFinder.filterBuildRuleInputs(templateOptions.getInputs(ruleFinder))).build()),
            Suppliers.ofInstance(ImmutableSortedSet.of()));

    BuildTarget abiJarTarget = params.getBuildTarget().withAppendedFlavors(CalculateAbi.FLAVOR);

    final SourcePathResolver pathResolver = new SourcePathResolver(ruleFinder);

    return new DefaultJavaLibrary(javaParams, pathResolver, ruleFinder,
            FluentIterable.from(sourceZips).transform(SourcePaths.getToBuildTargetSourcePath())
                    .toSortedSet(Ordering.natural()),
            /* resources */ ImmutableSet.of(), templateOptions.getGeneratedSourceFolderName(),
            /* proguardConfig */ Optional.empty(), /* postprocessClassesCommands */ ImmutableList.of(),
            /* exportedDeps */ ImmutableSortedSet.of(), /* providedDeps */ ImmutableSortedSet.of(),
            /* abiJar */ abiJarTarget, JavaLibraryRules.getAbiInputs(resolver, javaParams.getDeps()),
            templateOptions.trackClassUsage(), /* additionalClasspathEntries */ ImmutableSet.of(),
            new JavacToJarStepFactory(templateOptions, JavacOptionsAmender.IDENTITY),
            /* resourcesRoot */ Optional.empty(), /* manifest file */ Optional.empty(),
            /* mavenCoords */ Optional.empty(), /* tests */ ImmutableSortedSet.of(),
            /* classesToRemoveFromJar */ ImmutableSet.of());
}

From source file:com.facebook.buck.rules.AndroidResourceRule.java

@Override
protected Iterable<String> getInputsToCompareToOutput(BuildContext context) {
    ImmutableSortedSet.Builder<String> inputsToConsiderForCachingPurposes = ImmutableSortedSet.naturalOrder();

    // This should include the res/ and assets/ folders.
    addResContents(inputsToConsiderForCachingPurposes);
    addAssetsContents(inputsToConsiderForCachingPurposes);

    // manifest file is optional
    if (manifestFile != null) {
        inputsToConsiderForCachingPurposes.add(manifestFile);
    }//from  www  .j  a v  a2s .  c o  m

    return inputsToConsiderForCachingPurposes.build();
}