Example usage for com.google.common.collect Iterables cycle

List of usage examples for com.google.common.collect Iterables cycle

Introduction

In this page you can find the example usage for com.google.common.collect Iterables cycle.

Prototype

public static <T> Iterable<T> cycle(T... elements) 

Source Link

Document

Returns an iterable whose iterators cycle indefinitely over the provided elements.

Usage

From source file:com.facebook.buck.features.haskell.HaskellGhciRule.java

@Override
public ImmutableList<Step> getBuildSteps(BuildContext context, BuildableContext buildableContext) {

    SourcePathResolver resolver = context.getSourcePathResolver();

    String name = getBuildTarget().getShortName();
    Path dir = getOutputDir();//  w ww  . java  2  s . c om
    Path so = resolver.getRelativePath(omnibusSharedObject.getSourcePathToOutput());
    Path packagesDir = dir.resolve(name + ".packages");
    Path symlinkDir = dir.resolve(HaskellGhciDescription.getSoLibsRelDir(getBuildTarget()));
    Path symlinkPreloadDir = dir.resolve(name + ".preload-symlinks");

    ImmutableList.Builder<String> compilerFlagsBuilder = ImmutableList.builder();
    compilerFlagsBuilder.addAll(compilerFlags);

    ImmutableList.Builder<Step> steps = ImmutableList.builder();
    steps.addAll(MakeCleanDirectoryStep.of(BuildCellRelativePath
            .fromCellRelativePath(context.getBuildCellRootPath(), getProjectFilesystem(), dir)));
    steps.addAll(MakeCleanDirectoryStep.of(BuildCellRelativePath
            .fromCellRelativePath(context.getBuildCellRootPath(), getProjectFilesystem(), symlinkDir)));
    steps.addAll(MakeCleanDirectoryStep.of(BuildCellRelativePath
            .fromCellRelativePath(context.getBuildCellRootPath(), getProjectFilesystem(), symlinkPreloadDir)));
    steps.addAll(MakeCleanDirectoryStep.of(BuildCellRelativePath
            .fromCellRelativePath(context.getBuildCellRootPath(), getProjectFilesystem(), packagesDir)));

    steps.add(CopyStep.forFile(getProjectFilesystem(), so, dir.resolve(so.getFileName())));

    symlinkLibs(resolver, symlinkDir, steps, solibs);
    symlinkLibs(resolver, symlinkPreloadDir, steps, preloadLibs);

    ImmutableSet.Builder<String> pkgdirs = ImmutableSet.builder();
    for (HaskellPackage pkg : prebuiltHaskellPackages) {
        try {
            pkgdirs.add(resolver.getRelativePath(pkg.getPackageDb()).toRealPath().toString());
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }

    for (HaskellPackage pkg : haskellPackages) {
        String pkgname = pkg.getInfo().getName();
        Path pkgdir = packagesDir.resolve(pkgname);
        steps.addAll(MakeCleanDirectoryStep.of(BuildCellRelativePath
                .fromCellRelativePath(context.getBuildCellRootPath(), getProjectFilesystem(), pkgdir)));

        Path pkgDbSrc = resolver.getRelativePath(pkg.getPackageDb());
        steps.add(CopyStep.forDirectory(getProjectFilesystem(), pkgDbSrc, pkgdir,
                CopyStep.DirectoryMode.DIRECTORY_AND_CONTENTS));

        ImmutableSet.Builder<Path> artifacts = ImmutableSet.builder();
        for (SourcePath lib : pkg.getLibraries()) {
            artifacts.add(resolver.getRelativePath(lib).getParent());
        }

        // this is required because the .a files above are thin archives,
        // they merely point to the .o files via a relative path.
        for (SourcePath obj : pkg.getObjects()) {
            artifacts.add(resolver.getRelativePath(obj).getParent());
        }

        for (SourcePath iface : pkg.getInterfaces()) {
            artifacts.add(resolver.getRelativePath(iface).getParent());
        }

        for (Path artifact : artifacts.build()) {
            steps.add(CopyStep.forDirectory(getProjectFilesystem(), artifact, pkgdir,
                    CopyStep.DirectoryMode.DIRECTORY_AND_CONTENTS));
        }

        pkgdirs.add("${DIR}/" + dir.relativize(pkgdir.resolve(pkgDbSrc.getFileName())));
    }

    ImmutableSet.Builder<String> exposedPkgs = ImmutableSet.builder();
    for (HaskellPackage pkg : firstOrderHaskellPackages) {
        exposedPkgs.add(String.format("%s-%s", pkg.getInfo().getName(), pkg.getInfo().getVersion()));
    }

    // iserv script
    Optional<Path> iservScript = Optional.empty();

    if (!preloadLibs.isEmpty()) {
        iservScript = Optional.of(dir.resolve("iserv"));
        compilerFlagsBuilder.add("-fexternal-interpreter");
        steps.add(new AbstractExecutionStep("ghci_iserv_wrapper") {
            @Override
            public StepExecutionResult execute(ExecutionContext context)
                    throws IOException, InterruptedException {
                String template;
                template = new String(Files.readAllBytes(ghciIservScriptTemplate), Charsets.UTF_8);
                ST st = new ST(template);
                ImmutableSet.Builder<String> preloadLibrariesB = ImmutableSet.builder();
                for (Map.Entry<String, SourcePath> ent : preloadLibs.entrySet()) {
                    preloadLibrariesB.add("${DIR}/" + dir.relativize(symlinkPreloadDir.resolve(ent.getKey())));
                }
                ImmutableSet<String> preloadLibraries = preloadLibrariesB.build();
                st.add("name", name + "-iserv");
                st.add("preload_libs", Joiner.on(':').join(preloadLibraries));
                if (enableProfiling) {
                    st.add("ghci_iserv_path", ghciIServProf.toRealPath().toString());
                } else {
                    st.add("ghci_iserv_path", ghciIServ.toRealPath().toString());
                }
                Path actualIserv = dir.resolve("iserv");
                if (enableProfiling) {
                    actualIserv = dir.resolve("iserv-prof");
                }
                return new WriteFileStep(getProjectFilesystem(), Objects.requireNonNull(st.render()),
                        actualIserv, /* executable */
                        true).execute(context);
            }
        });
    }

    // .ghci file
    StringBuilder startGhciContents = new StringBuilder();
    if (iservScript.isPresent()) {
        // Need to unset preloaded deps for `iserv`
        startGhciContents.append("System.Environment.unsetEnv \"LD_PRELOAD\"\n");
    }
    startGhciContents.append(":set ");
    startGhciContents.append(Joiner.on(' ').join(ImmutableList.<String>builder()
            .addAll(MoreIterables.zipAndConcat(Iterables.cycle("-package"), exposedPkgs.build())).build()));

    if (ghciInit.isPresent()) {
        try {
            startGhciContents.append('\n');
            List<String> lines = Files.readAllLines(resolver.getRelativePath(ghciInit.get()),
                    StandardCharsets.UTF_8);
            startGhciContents.append(Joiner.on('\n').join(lines));
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }

    Path startGhci = dir.resolve("start.ghci");
    steps.add(new WriteFileStep(getProjectFilesystem(), startGhciContents.toString(), startGhci,
            /* executable */ false));

    // ghciBinDep
    ImmutableList.Builder<String> srcpaths = ImmutableList.builder();
    for (SourcePath sp : srcs.getSourcePaths()) {
        srcpaths.add(resolver.getRelativePath(sp).toString());
    }

    String ghcPath = null;
    try {
        if (ghciBinDep.isPresent()) {

            Path binDir = dir.resolve(name + ".bin");
            Path bin = binDir.resolve("ghci");
            SourcePath sp = ghciBinDep.get();

            steps.addAll(MakeCleanDirectoryStep.of(BuildCellRelativePath
                    .fromCellRelativePath(context.getBuildCellRootPath(), getProjectFilesystem(), binDir)));

            steps.add(CopyStep.forFile(getProjectFilesystem(), resolver.getRelativePath(sp), bin));

            ghcPath = "${DIR}/" + dir.relativize(bin) + " -B" + ghciLib.toRealPath();
        } else {
            ghcPath = ghciGhc.toRealPath().toString();
        }
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }

    String pkgdbs = Joiner.on(' ').join(ImmutableList.<String>builder()
            .addAll(MoreIterables.zipAndConcat(Iterables.cycle("-package-db"), pkgdirs.build())).build());
    String exposed = Joiner.on(' ')
            .join(ImmutableList.<String>builder()
                    .addAll(MoreIterables.zipAndConcat(Iterables.cycle("-expose-package"), exposedPkgs.build()))
                    .build());

    if (enableProfiling) {
        compilerFlagsBuilder.addAll(HaskellDescriptionUtils.PROF_FLAGS);
    }

    String ghc = ghcPath;
    ImmutableMap.Builder<String, String> templateArgs = ImmutableMap.builder();
    try {
        templateArgs.put("name", name);
        templateArgs.put("start_ghci", dir.relativize(startGhci).toString());
        templateArgs.put("exposed_packages", exposed);
        templateArgs.put("package_dbs", pkgdbs);
        templateArgs.put("compiler_flags", Joiner.on(' ').join(compilerFlagsBuilder.build()));
        templateArgs.put("srcs", Joiner.on(' ').join(srcpaths.build()));
        templateArgs.put("squashed_so", dir.relativize(dir.resolve(so.getFileName())).toString());
        templateArgs.put("binutils_path", ghciBinutils.toRealPath().toString());
        templateArgs.put("ghc_path", ghc);
        templateArgs.put("cxx_path", ghciCxx.toRealPath().toString());
        templateArgs.put("cc_path", ghciCc.toRealPath().toString());
        templateArgs.put("cpp_path", ghciCpp.toRealPath().toString());
        templateArgs.put("ghc_pkg_path", ghciPackager.toRealPath().toString());
        if (iservScript.isPresent()) {
            templateArgs.put("iserv_path", dir.relativize(iservScript.get()).toString());
        }
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }

    Path script = scriptPath();
    steps.add(new StringTemplateStep(ghciScriptTemplate, getProjectFilesystem(), script, templateArgs.build()));
    steps.add(new MakeExecutableStep(getProjectFilesystem(), script));

    for (SourcePath s : extraScriptTemplates) {
        Path templateAbsPath = resolver.getAbsolutePath(s);
        Path extraScript = dir.resolve(templateAbsPath.getFileName());
        steps.add(new StringTemplateStep(templateAbsPath, getProjectFilesystem(), extraScript,
                templateArgs.build()));
        steps.add(new MakeExecutableStep(getProjectFilesystem(), extraScript));
    }

    buildableContext.recordArtifact(dir);

    return steps.build();
}

From source file:models.Room.java

public User nextUserPlayableTrack(User startingUser) {
    if (startingUser == null) {
        return null;
    }//from  w w  w  . j av a2s.c  o  m
    List<User> usersInRoomAndOnlineAndPlayable = User
            .find("room = ?1 and isOnline = ?2 and noPlayableTrack = ?3  order by id asc", this, true, false)
            .fetch();

    if (usersInRoomAndOnlineAndPlayable.size() == 1) {
        return null;
    }
    Iterable<User> users = Iterables.cycle(usersInRoomAndOnlineAndPlayable);

    Iterator<User> iterator = users.iterator();

    while (!iterator.next().id.equals(startingUser.id)) {

    }
    return iterator.next();

}

From source file:models.Room.java

public User nextUser(User startingUser) {

    List<User> usersInRoomAndOnline = getUsersInRoom();

    if (usersInRoomAndOnline.size() == 1) {
        return startingUser;
    }/*w  w w  . ja v  a  2  s  . co m*/

    Iterable<User> users = Iterables.cycle(usersInRoomAndOnline);
    Iterator<User> iterator = users.iterator();

    while (!iterator.next().equals(startingUser))
        ;

    return (User) iterator.next();

}

From source file:io.prestosql.plugin.raptor.legacy.metadata.DatabaseShardManager.java

private static <T> Iterator<T> cyclingShuffledIterator(Collection<T> collection) {
    List<T> list = new ArrayList<>(collection);
    Collections.shuffle(list);//w  ww  . j a v  a 2  s  .  c o  m
    return Iterables.cycle(list).iterator();
}

From source file:models.Room.java

public RoomQueue calculateRoomQueue(Room room) {

    RoomQueue roomQueue = new RoomQueue();
    roomQueue.items = new ArrayList<>();

    List<User> usersOnline = getUsersInRoom();

    int numOfUsers = usersOnline.size();

    if (numOfUsers == 0) {
        Logger.error("Calculating room queue for empty room");
        return roomQueue;
    }/*from  w  ww . java2 s  .c om*/

    if (numOfUsers == 1) {
        Logger.info("One user" + usersOnline.get(0).nickname);
        Logger.info(usersOnline.get(0).queue.userQueueItems.toString());
        if (usersOnline.get(0).queue != null && usersOnline.get(0).queue.userQueueItems != null) {
            usersOnline.get(0).queue.userQueueItems.forEach(e -> Logger.info(e.libraryItem.title));
            usersOnline.get(0).queue.userQueueItems.forEach(e -> roomQueue.items.add(e.libraryItem));
        }
        return roomQueue;
    }

    User firstUser = room.currentPlayingLibrary != null ? room.currentPlayingLibrary.user : usersOnline.get(0);

    Iterator iterUsers = Iterables.cycle(usersOnline).iterator();
    User nextUser = (User) iterUsers.next();

    if (!nextUser.getId().equals(firstUser.getId())) {
        while (!nextUser.getId().equals(firstUser.getId())) {
            //Logger.info(nextUser.nickname);
            nextUser = (User) iterUsers.next();
        }
    }
    nextUser = (User) iterUsers.next();
    int queueIndex = 0;
    boolean addedAQueue = true;

    while (addedAQueue == true) {

        addedAQueue = false;

        for (int i = 0; i < numOfUsers; i++) {

            if (queueIndex < nextUser.queue.userQueueItems.size()) {
                Logger.info("ASDASD" + room.name + " / "
                        + nextUser.queue.userQueueItems.get(queueIndex).libraryItem.title);
                roomQueue.items.add(nextUser.queue.userQueueItems.get(queueIndex).libraryItem);
                addedAQueue = true;
            }
            nextUser = (User) iterUsers.next();
        }
        queueIndex++;
    }
    return roomQueue;
}

From source file:org.apache.gobblin.metastore.database.DatabaseJobHistoryStoreV101.java

private static String getInPredicate(int count) {
    return StringUtils.join(Iterables.limit(Iterables.cycle("?"), count).iterator(), ",");
}

From source file:com.facebook.buck.apple.ProjectGenerator.java

private void generateCombinedTestTarget(final String productName, AppleTestBundleParamsKey key,
        ImmutableCollection<TargetNode<AppleTestDescription.Arg>> tests) throws IOException {
    ImmutableSet.Builder<PBXFileReference> testLibs = ImmutableSet.builder();
    for (TargetNode<AppleTestDescription.Arg> test : tests) {
        testLibs.add(getOrCreateTestLibraryFileReference(test));
    }//  www. j  a  va  2  s  . c o m
    NewNativeTargetProjectMutator mutator = new NewNativeTargetProjectMutator(pathRelativizer,
            sourcePathResolver)
                    .setTargetName(productName)
                    .setProduct(dylibProductTypeByBundleExtension(key.getExtension().getLeft()).get(),
                            productName, Paths.get(productName + "." + getExtensionString(key.getExtension())))
                    .setSourcesWithFlags(ImmutableSet.of(SourceWithFlags
                            .of(new PathSourcePath(projectFilesystem, emptyFileWithExtension("c")))))
                    .setArchives(Sets.union(collectRecursiveLibraryDependencies(tests), testLibs.build()))
                    .setRecursiveResources(AppleResources.collectRecursiveResources(targetGraph, tests))
                    .setRecursiveAssetCatalogs(
                            AppleBuildRules.collectRecursiveAssetCatalogs(targetGraph, tests));

    ImmutableSet.Builder<FrameworkPath> frameworksBuilder = ImmutableSet.builder();
    frameworksBuilder.addAll(collectRecursiveFrameworkDependencies(tests));
    for (TargetNode<AppleTestDescription.Arg> test : tests) {
        frameworksBuilder.addAll(test.getConstructorArg().frameworks.get());
        frameworksBuilder.addAll(test.getConstructorArg().libraries.get());
    }
    mutator.setFrameworks(frameworksBuilder.build());

    NewNativeTargetProjectMutator.Result result;
    try {
        result = mutator.buildTargetAndAddToProject(project);
    } catch (NoSuchBuildTargetException e) {
        throw new HumanReadableException(e);
    }

    ImmutableMap.Builder<String, String> overrideBuildSettingsBuilder = ImmutableMap.<String, String>builder()
            .put("GCC_PREFIX_HEADER", "").put("USE_HEADERMAP", "NO");
    if (key.getInfoPlist().isPresent()) {
        overrideBuildSettingsBuilder.put("INFOPLIST_FILE", pathRelativizer
                .outputDirToRootRelative(sourcePathResolver.apply(key.getInfoPlist().get())).toString());
    }
    setTargetBuildConfigurations(new Function<String, Path>() {
        @Override
        public Path apply(String input) {
            return outputDirectory.resolve(String.format("xcconfigs/%s-%s.xcconfig", productName, input));
        }
    }, result.target, project.getMainGroup(), key.getConfigs().get(), overrideBuildSettingsBuilder.build(),
            ImmutableMap.of(PRODUCT_NAME, productName, "WRAPPER_EXTENSION",
                    getExtensionString(key.getExtension())),
            ImmutableMap.of("FRAMEWORK_SEARCH_PATHS",
                    Joiner.on(' ').join(collectRecursiveFrameworkSearchPaths(tests)), "LIBRARY_SEARCH_PATHS",
                    Joiner.on(' ').join(collectRecursiveLibrarySearchPaths(tests)), "OTHER_LDFLAGS",
                    Joiner.on(' ').join(MoreIterables.zipAndConcat(Iterables.cycle("-Xlinker"), Iterables
                            .concat(key.getLinkerFlags(), collectRecursiveExportedLinkerFlags(tests))))));
    buildableCombinedTestTargets.add(result.target);
}