Example usage for com.google.common.collect ImmutableList subList

List of usage examples for com.google.common.collect ImmutableList subList

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableList subList.

Prototype

@Override
    public ImmutableList<E> subList(int fromIndex, int toIndex) 

Source Link

Usage

From source file:com.github.kryptohash.kryptohashj.crypto.DeterministicHierarchy.java

/**
 * Returns a key for the given path, optionally creating it.
 *
 * @param path the path to the key//from w  w  w  .  j  a  va  2 s .  c o  m
 * @param relativePath whether the path is relative to the root path
 * @param create whether the key corresponding to path should be created (with any necessary ancestors) if it doesn't exist already
 * @return next newly created key using the child derivation function
 * @throws IllegalArgumentException if create is false and the path was not found.
 */
public DeterministicEd25519Key get(List<ChildNumber> path, boolean relativePath, boolean create) {
    ImmutableList<ChildNumber> absolutePath = relativePath
            ? ImmutableList.<ChildNumber>builder().addAll(rootPath).addAll(path).build()
            : ImmutableList.copyOf(path);
    if (!keys.containsKey(absolutePath)) {
        if (!create)
            throw new IllegalArgumentException(String.format("No key found for %s path %s.",
                    relativePath ? "relative" : "absolute", HDUtils.formatPath(path)));
        checkArgument(absolutePath.size() > 0, "Can't derive the master key: nothing to derive from.");
        DeterministicEd25519Key parent = get(absolutePath.subList(0, absolutePath.size() - 1), false, true);
        putKey(HDKeyDerivation.deriveChildKey(parent, absolutePath.get(absolutePath.size() - 1)));
    }
    return keys.get(absolutePath);
}

From source file:com.facebook.buck.js.JsBundleGenrule.java

@Override
public ImmutableList<Step> getBuildSteps(BuildContext context, BuildableContext buildableContext) {
    SourcePathResolver sourcePathResolver = context.getSourcePathResolver();
    ImmutableList<Step> buildSteps = super.getBuildSteps(context, buildableContext);
    OptionalInt lastRmStep = IntStream.range(0, buildSteps.size()).map(x -> buildSteps.size() - 1 - x)
            .filter(i -> buildSteps.get(i) instanceof RmStep).findFirst();

    Preconditions.checkState(lastRmStep.isPresent(), "Genrule is expected to have at least on RmDir step");

    ImmutableList.Builder<Step> builder = ImmutableList.<Step>builder()
            // First, all Genrule steps including the last RmDir step are added
            .addAll(buildSteps.subList(0, lastRmStep.getAsInt() + 1))
            // Our MkdirStep must run after all RmSteps created by Genrule to prevent immediate
            // deletion of the directory. It must, however, run before the genrule command itself
            // runs.
            .add(MkdirStep.of(BuildCellRelativePath.fromCellRelativePath(context.getBuildCellRootPath(),
                    getProjectFilesystem(), sourcePathResolver.getRelativePath(getSourcePathToOutput()))));

    if (rewriteSourcemap) {
        // If the genrule rewrites the source map, we have to create the parent dir, and record
        // the build artifact

        SourcePath sourcePathToSourceMap = getSourcePathToSourceMap();
        buildableContext.recordArtifact(sourcePathResolver.getRelativePath(sourcePathToSourceMap));
        builder.add(MkdirStep.of(BuildCellRelativePath.fromCellRelativePath(context.getBuildCellRootPath(),
                getProjectFilesystem(),// w  w  w . j av  a 2  s.  com
                sourcePathResolver.getRelativePath(sourcePathToSourceMap).getParent())));
    }

    if (rewriteMisc) {
        // If the genrule rewrites the misc folder, we have to create the corresponding dir, and
        // record its contents

        SourcePath miscDirPath = getSourcePathToMisc();
        buildableContext.recordArtifact(sourcePathResolver.getRelativePath(miscDirPath));
        builder.add(MkdirStep.of(BuildCellRelativePath.fromCellRelativePath(context.getBuildCellRootPath(),
                getProjectFilesystem(), sourcePathResolver.getRelativePath(miscDirPath))));
    }

    // Last, we add all remaining genrule commands after the last RmStep
    return builder.addAll(buildSteps.subList(lastRmStep.getAsInt() + 1, buildSteps.size())).build();
}

From source file:org.guldenj.crypto.DeterministicHierarchy.java

/**
 * Returns a key for the given path, optionally creating it.
 *
 * @param path the path to the key//  ww  w  . ja  va2  s  . c  o  m
 * @param relativePath whether the path is relative to the root path
 * @param create whether the key corresponding to path should be created (with any necessary ancestors) if it doesn't exist already
 * @return next newly created key using the child derivation function
 * @throws IllegalArgumentException if create is false and the path was not found.
 */
public DeterministicKey get(List<ChildNumber> path, boolean relativePath, boolean create) {
    ImmutableList<ChildNumber> absolutePath = relativePath
            ? ImmutableList.<ChildNumber>builder().addAll(rootPath).addAll(path).build()
            : ImmutableList.copyOf(path);
    if (!keys.containsKey(absolutePath)) {
        if (!create)
            throw new IllegalArgumentException(String.format(Locale.US, "No key found for %s path %s.",
                    relativePath ? "relative" : "absolute", HDUtils.formatPath(path)));
        checkArgument(absolutePath.size() > 0, "Can't derive the master key: nothing to derive from.");
        DeterministicKey parent = get(absolutePath.subList(0, absolutePath.size() - 1), false, true);
        putKey(HDKeyDerivation.deriveChildKey(parent, absolutePath.get(absolutePath.size() - 1)));
    }
    return keys.get(absolutePath);
}

From source file:com.facebook.buck.features.js.JsBundleGenrule.java

@Override
public ImmutableList<Step> getBuildSteps(BuildContext context, BuildableContext buildableContext) {
    SourcePathResolver sourcePathResolver = context.getSourcePathResolver();
    ImmutableList<Step> buildSteps = super.getBuildSteps(context, buildableContext);
    OptionalInt lastRmStep = IntStream.range(0, buildSteps.size()).map(x -> buildSteps.size() - 1 - x)
            .filter(i -> buildSteps.get(i) instanceof RmStep).findFirst();

    Preconditions.checkState(lastRmStep.isPresent(), "Genrule is expected to have at least on RmDir step");

    ImmutableList.Builder<Step> builder = ImmutableList.<Step>builder()
            // First, all Genrule steps including the last RmDir step are added
            .addAll(buildSteps.subList(0, lastRmStep.getAsInt() + 1))
            // Our MkdirStep must run after all RmSteps created by Genrule to prevent immediate
            // deletion of the directory. It must, however, run before the genrule command itself
            // runs.
            .add(MkdirStep.of(BuildCellRelativePath.fromCellRelativePath(context.getBuildCellRootPath(),
                    getProjectFilesystem(), sourcePathResolver.getRelativePath(getSourcePathToOutput()))));

    if (rewriteSourcemap) {
        // If the genrule rewrites the source map, we have to create the parent dir, and record
        // the build artifact

        SourcePath sourcePathToSourceMap = getSourcePathToSourceMap();
        buildableContext.recordArtifact(sourcePathResolver.getRelativePath(sourcePathToSourceMap));
        builder.add(MkdirStep.of(BuildCellRelativePath.fromCellRelativePath(context.getBuildCellRootPath(),
                getProjectFilesystem(),/*from  www  .  ja  va 2 s .  c  om*/
                sourcePathResolver.getRelativePath(sourcePathToSourceMap).getParent())));
    }

    if (rewriteMisc) {
        // If the genrule rewrites the misc folder, we have to create the corresponding dir, and
        // record its contents

        SourcePath miscDirPath = getSourcePathToMisc();
        buildableContext.recordArtifact(sourcePathResolver.getRelativePath(miscDirPath));
        builder.add(MkdirStep.of(BuildCellRelativePath.fromCellRelativePath(context.getBuildCellRootPath(),
                getProjectFilesystem(), sourcePathResolver.getRelativePath(miscDirPath))));
    }

    if (rewriteDepsFile) {
        // If the genrule rewrites the dependencies file, we have to record its contents

        SourcePath dependenciesFilePath = getSourcePathToDepsFile();
        buildableContext.recordArtifact(sourcePathResolver.getRelativePath(dependenciesFilePath));
    }

    // Last, we add all remaining genrule commands after the last RmStep
    return builder.addAll(buildSteps.subList(lastRmStep.getAsInt() + 1, buildSteps.size())).build();
}

From source file:com.facebook.buck.json.PythonDslProjectBuildFileParser.java

@SuppressWarnings("unchecked")
private BuildFileManifest toBuildFileManifest(ImmutableList<Map<String, Object>> values) {
    return BuildFileManifest.builder().setTargets(values.subList(0, values.size() - 3))
            .setIncludes(ImmutableSortedSet.copyOf(Preconditions
                    .checkNotNull((List<String>) values.get(values.size() - 3).get("__includes"))))
            .setConfigs(Preconditions//from w ww . ja  va 2 s . c  o m
                    .checkNotNull((Map<String, Object>) values.get(values.size() - 2).get("__configs")))
            .setEnv(ImmutableMap.copyOf(Maps.transformValues(
                    Preconditions
                            .checkNotNull((Map<String, String>) values.get(values.size() - 1).get("__env")),
                    Optional::ofNullable)))
            .build();
}

From source file:com.squareup.javapoet.CodeWriter.java

/**
 * Returns the best name to identify {@code className} with in the current context. This uses the
 * available imports and the current scope to find the shortest name available. It does not honor
 * names visible due to inheritance./*from www.ja v  a2s.c  om*/
 */
private String lookupName(ClassName className) {
    // Different package than current? Just look for an import.
    if (!className.packageName().equals(packageName)) {
        if (conflictsWithLocalName(className)) {
            return className.toString(); // A local name conflicts? Use the fully-qualified name.
        }

        String importedName = importedTypes.get(className);
        if (importedName != null) {
            if (!javadoc)
                importableTypes.add(className);
            return importedName;
        }

        // If the target class wasn't imported, perhaps its enclosing class was. Try that.
        ClassName enclosingClassName = className.enclosingClassName();
        if (enclosingClassName != null) {
            return lookupName(enclosingClassName) + "." + className.simpleName();
        }

        // Fall back to the fully-qualified name. Mark the type as importable for a future pass.
        if (!javadoc)
            importableTypes.add(className);
        return className.toString();
    }

    // Look for the longest common prefix, which we can omit.
    ImmutableList<String> classNames = className.simpleNames();
    int prefixLength = commonPrefixLength(classNames);
    if (prefixLength == classNames.size()) {
        return className.simpleName(); // Special case: a class referring to itself!
    }

    return Joiner.on('.').join(classNames.subList(prefixLength, classNames.size()));
}

From source file:com.facebook.buck.rust.RustCompileRule.java

@Override
public ImmutableList<Step> getBuildSteps(BuildContext context, BuildableContext buildableContext) {
    buildableContext.recordArtifact(getOutput());
    return ImmutableList.of(new MakeCleanDirectoryStep(getProjectFilesystem(), scratchDir),
            new SymlinkFilesIntoDirectoryStep(getProjectFilesystem(), getProjectFilesystem().getRootPath(),
                    srcs.stream().map(getResolver()::getRelativePath).collect(MoreCollectors.toImmutableList()),
                    scratchDir),/*from   w ww.ja v a  2s  .  com*/
            new MakeCleanDirectoryStep(getProjectFilesystem(),
                    getOutputDir(getBuildTarget(), getProjectFilesystem())),
            new ShellStep(getProjectFilesystem().getRootPath()) {

                @Override
                protected ImmutableList<String> getShellCommandInternal(ExecutionContext context) {
                    ImmutableList<String> linkerCmd = linker.getCommandPrefix(getResolver());
                    ImmutableList.Builder<String> cmd = ImmutableList.builder();

                    Path src = scratchDir.resolve(getResolver().getRelativePath(rootModule));

                    cmd.addAll(compiler.getCommandPrefix(getResolver()))
                            .addAll(context.getAnsi().isAnsiTerminal() ? ImmutableList.of("--color=always")
                                    : ImmutableList.of())
                            .add(String.format("-Clinker=%s", linkerCmd.get(0)))
                            .addAll(processLinkerArgs(linkerCmd.subList(1, linkerCmd.size())))
                            .addAll(processLinkerArgs(Arg.stringify(linkerArgs))).addAll(Arg.stringify(args))
                            .add("-o", getOutput().toString()).add(src.toString());

                    return cmd.build();
                }

                /*
                 * Make sure all stderr output from rustc is emitted, since its either a warning or an
                 * error. In general Rust code should have zero warnings, or all warnings as errors.
                 * Regardless, respect requests for silence.
                 */
                @Override
                protected boolean shouldPrintStderr(Verbosity verbosity) {
                    return !verbosity.isSilent();
                }

                @Override
                public ImmutableMap<String, String> getEnvironmentVariables(ExecutionContext context) {
                    return compiler.getEnvironment();
                }

                @Override
                public String getShortName() {
                    return "rust-build";
                }

            });
}

From source file:com.facebook.buck.parser.PythonDslProjectBuildFileParser.java

@SuppressWarnings("unchecked")
private BuildFileManifest toBuildFileManifest(ImmutableList<Map<String, Object>> values) {
    return BuildFileManifest.of(indexTargetsByName(values.subList(0, values.size() - 3).asList()),
            ImmutableSortedSet.copyOf(Objects
                    .requireNonNull((List<String>) values.get(values.size() - 3).get(MetaRules.INCLUDES))),
            Objects.requireNonNull((Map<String, Object>) values.get(values.size() - 2).get(MetaRules.CONFIGS)),
            Optional.of(ImmutableMap.copyOf(Maps.transformValues(
                    Objects.requireNonNull(
                            (Map<String, String>) values.get(values.size() - 1).get(MetaRules.ENV)),
                    Optional::ofNullable))),
            ImmutableList.of());// w  w  w . ja  va 2s. c  o m
}

From source file:com.google.jimfs.JimfsPath.java

@Override
public JimfsPath relativize(Path other) {
    JimfsPath otherPath = checkPath(other);
    if (otherPath == null) {
        throw new ProviderMismatchException(other.toString());
    }/*from  www.ja va  2 s.  c  o m*/

    checkArgument(Objects.equal(root, otherPath.root), "Paths have different roots: %s, %s", this, other);

    if (equals(other)) {
        return pathService.emptyPath();
    }

    if (isEmptyPath()) {
        return otherPath;
    }

    ImmutableList<Name> otherNames = otherPath.names;
    int sharedSubsequenceLength = 0;
    for (int i = 0; i < Math.min(getNameCount(), otherNames.size()); i++) {
        if (names.get(i).equals(otherNames.get(i))) {
            sharedSubsequenceLength++;
        } else {
            break;
        }
    }

    int extraNamesInThis = Math.max(0, getNameCount() - sharedSubsequenceLength);

    ImmutableList<Name> extraNamesInOther = (otherNames.size() <= sharedSubsequenceLength)
            ? ImmutableList.<Name>of()
            : otherNames.subList(sharedSubsequenceLength, otherNames.size());

    List<Name> parts = new ArrayList<>(extraNamesInThis + extraNamesInOther.size());

    // add .. for each extra name in this path
    parts.addAll(Collections.nCopies(extraNamesInThis, Name.PARENT));
    // add each extra name in the other path
    parts.addAll(extraNamesInOther);

    return pathService.createRelativePath(parts);
}

From source file:com.facebook.buck.event.listener.ChromeTraceBuildListener.java

@VisibleForTesting
void deleteOldTraces() {
    if (!projectFilesystem.exists(BuckConstant.BUCK_TRACE_DIR)) {
        return;//from   w ww .j a v  a  2  s  . c  om
    }

    ImmutableList<File> filesSortedByModified = FluentIterable
            .from(Arrays.asList(projectFilesystem.listFiles(BuckConstant.BUCK_TRACE_DIR)))
            .filter(new Predicate<File>() {
                @Override
                public boolean apply(File input) {
                    return input.getName().matches(TRACE_FILE_PATTERN);
                }
            }).toSortedList(new Comparator<File>() {
                @Override
                public int compare(File a, File b) {
                    return Long.signum(b.lastModified() - a.lastModified());
                }
            });

    if (filesSortedByModified.size() > tracesToKeep) {
        ImmutableList<File> filesToRemove = filesSortedByModified.subList(tracesToKeep,
                filesSortedByModified.size());
        for (File file : filesToRemove) {
            file.delete();
        }
    }
}