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.haskell.HaskellBinaryDescription.java

@Override
public <A extends Arg> BuildRule createBuildRule(TargetGraph targetGraph, BuildRuleParams params,
        BuildRuleResolver resolver, A args) throws NoSuchBuildTargetException {

    SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(resolver);
    SourcePathResolver pathResolver = new SourcePathResolver(ruleFinder);
    CxxPlatform cxxPlatform = cxxPlatforms.getValue(params.getBuildTarget()).orElse(defaultCxxPlatform);
    Linker.LinkableDepType depType = getLinkStyle(params.getBuildTarget(), args);

    // The target to use for the link rule.
    BuildTarget binaryTarget = params.getBuildTarget().withFlavors(cxxPlatform.getFlavor(),
            ImmutableFlavor.of("binary"));

    ImmutableList.Builder<String> linkFlagsBuilder = ImmutableList.builder();
    ImmutableList.Builder<com.facebook.buck.rules.args.Arg> linkArgsBuilder = ImmutableList.builder();

    CommandTool.Builder executableBuilder = new CommandTool.Builder();

    // Add the binary as the first argument.
    executableBuilder.addArg(new SourcePathArg(pathResolver, new BuildTargetSourcePath(binaryTarget)));

    // Special handling for dynamically linked binaries.
    if (depType == Linker.LinkableDepType.SHARED) {

        // Create a symlink tree with for all shared libraries needed by this binary.
        SymlinkTree sharedLibraries = resolver.addToIndex(CxxDescriptionEnhancer.createSharedLibrarySymlinkTree(
                params, pathResolver, cxxPlatform, params.getDeps(), NativeLinkable.class::isInstance));

        // Embed a origin-relative library path into the binary so it can find the shared libraries.
        // The shared libraries root is absolute. Also need an absolute path to the linkOutput
        Path absBinaryDir = params.getBuildTarget().getCellPath()
                .resolve(HaskellLinkRule.getOutputDir(binaryTarget, params.getProjectFilesystem()));
        linkFlagsBuilder.addAll(MoreIterables.zipAndConcat(Iterables.cycle("-optl"),
                Linkers.iXlinker("-rpath",
                        String.format("%s/%s", cxxPlatform.getLd().resolve(resolver).origin(),
                                absBinaryDir.relativize(sharedLibraries.getRoot()).toString()))));

        // Add all the shared libraries and the symlink tree as inputs to the tool that represents
        // this binary, so that users can attach the proper deps.
        executableBuilder.addDep(sharedLibraries);
        executableBuilder.addInputs(sharedLibraries.getLinks().values());
    }//  w  w w . jav  a  2s .c  o  m

    // Generate the compile rule and add its objects to the link.
    HaskellCompileRule compileRule = resolver.addToIndex(HaskellDescriptionUtils.requireCompileRule(params,
            resolver, pathResolver, ruleFinder, cxxPlatform, haskellConfig, depType, args.main,
            Optional.empty(), args.compilerFlags, HaskellSources.from(params.getBuildTarget(), resolver,
                    pathResolver, ruleFinder, cxxPlatform, "srcs", args.srcs)));
    linkArgsBuilder.addAll(SourcePathArg.from(pathResolver, compileRule.getObjects()));

    ImmutableList<String> linkFlags = linkFlagsBuilder.build();
    ImmutableList<com.facebook.buck.rules.args.Arg> linkArgs = linkArgsBuilder.build();

    final CommandTool executable = executableBuilder.build();
    final HaskellLinkRule linkRule = HaskellDescriptionUtils.createLinkRule(binaryTarget, params, resolver,
            pathResolver, ruleFinder, cxxPlatform, haskellConfig, Linker.LinkType.EXECUTABLE, linkFlags,
            linkArgs, FluentIterable.from(params.getDeps()).filter(NativeLinkable.class), depType);

    return new BinaryWrapperRule(params.appendExtraDeps(linkRule), pathResolver, ruleFinder) {

        @Override
        public Tool getExecutableCommand() {
            return executable;
        }

        @Override
        public Path getPathToOutput() {
            return linkRule.getPathToOutput();
        }

    };
}

From source file:de.Keyle.MyPet.skill.skills.Behavior.java

public void upgrade(SkillInfo upgrade, boolean quiet) {
    if (upgrade instanceof BehaviorInfo) {
        active = true;//from w ww .j  a v a  2s. co  m
        boolean valuesEdit = false;
        String activeModes = "";
        if (upgrade.getProperties().getCompoundData().containsKey("friend")) {
            if (upgrade.getProperties().getAs("friend", TagByte.class).getBooleanData()) {
                activeBehaviors.add(Friendly);
                activeModes = ChatColor.GOLD
                        + Translation.getString("Name.Friendly", myPet.getOwner().getLanguage())
                        + ChatColor.RESET;
            } else {
                activeBehaviors.remove(Friendly);
            }
            valuesEdit = true;
        }
        if (upgrade.getProperties().getCompoundData().containsKey("aggro")) {
            if (upgrade.getProperties().getAs("aggro", TagByte.class).getBooleanData()) {
                activeBehaviors.add(Aggressive);
                if (!activeModes.equalsIgnoreCase("")) {
                    activeModes += ", ";
                }
                activeModes += ChatColor.GOLD
                        + Translation.getString("Name.Aggressive", myPet.getOwner().getLanguage())
                        + ChatColor.RESET;
            } else {
                activeBehaviors.remove(Aggressive);
            }
            valuesEdit = true;
        }
        if (upgrade.getProperties().getCompoundData().containsKey("farm")) {
            if (upgrade.getProperties().getAs("farm", TagByte.class).getBooleanData()) {
                activeBehaviors.add(Farm);
                if (!activeModes.equalsIgnoreCase("")) {
                    activeModes += ", ";
                }
                activeModes += ChatColor.GOLD
                        + Translation.getString("Name.Farm", myPet.getOwner().getLanguage()) + ChatColor.RESET;
            } else {
                activeBehaviors.remove(Farm);
            }
            valuesEdit = true;
        }
        if (upgrade.getProperties().getCompoundData().containsKey("raid")) {
            if (upgrade.getProperties().getAs("raid", TagByte.class).getBooleanData()) {
                activeBehaviors.add(Raid);
                if (!activeModes.equalsIgnoreCase("")) {
                    activeModes += ", ";
                }
                activeModes += ChatColor.GOLD
                        + Translation.getString("Name.Raid", myPet.getOwner().getLanguage()) + ChatColor.RESET;
            } else {
                activeBehaviors.remove(Raid);
            }
            valuesEdit = true;
        }
        if (upgrade.getProperties().getCompoundData().containsKey("duel")) {
            if (upgrade.getProperties().getAs("duel", TagByte.class).getBooleanData()) {
                activeBehaviors.add(Duel);
                if (!activeModes.equalsIgnoreCase("")) {
                    activeModes += ", ";
                }
                activeModes += ChatColor.GOLD
                        + Translation.getString("Name.Duel", myPet.getOwner().getLanguage()) + ChatColor.RESET;
            } else {
                activeBehaviors.remove(Duel);
            }
            valuesEdit = true;
        }
        if (valuesEdit) {
            behaviorCycler = Iterables.cycle(activeBehaviors).iterator();
            if (!activeBehaviors.contains(behavior)) {
                behavior = behaviorCycler.next();
            } else {
                while (behaviorCycler.next() != behavior) {
                    if (!behaviorCycler.hasNext()) {
                        break;
                    }
                }
            }
            if (!quiet) {
                myPet.getOwner().sendMessage(Util.formatText(
                        Translation.getString("Message.Skill.Behavior.Upgrade", myPet.getOwner().getLanguage()),
                        myPet.getPetName()));
                myPet.getOwner().sendMessage("  " + activeModes);
            }
        }
    }
}

From source file:com.facebook.buck.swift.SwiftCompile.java

private SwiftCompileStep makeCompileStep(SourcePathResolver resolver) {
    ImmutableList.Builder<String> compilerCommand = ImmutableList.builder();
    compilerCommand.addAll(swiftCompiler.getCommandPrefix(resolver));

    if (bridgingHeader.isPresent()) {
        compilerCommand.add("-import-objc-header", resolver.getRelativePath(bridgingHeader.get()).toString());
    }//from w w  w  .  j a v  a2 s  .  c om

    final Function<FrameworkPath, Path> frameworkPathToSearchPath = CxxDescriptionEnhancer
            .frameworkPathToSearchPath(cxxPlatform, resolver);

    compilerCommand.addAll(frameworks.stream().map(frameworkPathToSearchPath::apply)
            .flatMap(searchPath -> ImmutableSet.of("-F", searchPath.toString()).stream()).iterator());

    compilerCommand.addAll(MoreIterables.zipAndConcat(Iterables.cycle("-Xcc"), getSwiftIncludeArgs(resolver)));
    compilerCommand.addAll(MoreIterables.zipAndConcat(Iterables.cycle(INCLUDE_FLAG),
            FluentIterable.from(getDeps()).filter(SwiftCompile.class)
                    .transform(SourcePaths.getToBuildTargetSourcePath())
                    .transform(input -> resolver.getAbsolutePath(input).toString())));

    Optional<Iterable<String>> configFlags = swiftBuckConfig.getFlags();
    if (configFlags.isPresent()) {
        compilerCommand.addAll(configFlags.get());
    }
    boolean hasMainEntry = FluentIterable.from(srcs).firstMatch(input -> SWIFT_MAIN_FILENAME
            .equalsIgnoreCase(resolver.getAbsolutePath(input).getFileName().toString())).isPresent();

    compilerCommand.add("-enable-testing", "-c", enableObjcInterop ? "-enable-objc-interop" : "",
            hasMainEntry ? "" : "-parse-as-library", "-module-name", moduleName, "-emit-module",
            "-emit-module-path", modulePath.toString(), "-o", objectPath.toString(), "-emit-objc-header-path",
            headerPath.toString());
    compilerCommand.addAll(compilerFlags);
    for (SourcePath sourcePath : srcs) {
        compilerCommand.add(resolver.getRelativePath(sourcePath).toString());
    }

    ProjectFilesystem projectFilesystem = getProjectFilesystem();
    return new SwiftCompileStep(projectFilesystem.getRootPath(), ImmutableMap.of(), compilerCommand.build());
}

From source file:com.eucalyptus.cluster.callback.reporting.AbsoluteMetricQueue.java

private static void callPutMetricData(final List<PutMetricDataType> putMetricDataList) throws Exception {
    final List<ServiceConfiguration> serviceConfigurations = Lists
            .newArrayList(Topology.lookupMany(CloudWatch.class));
    final Map<ServiceConfiguration, Semaphore> semaphoreMap = Maps.newHashMap();
    for (final ServiceConfiguration serviceConfiguration : serviceConfigurations) {
        semaphoreMap.put(serviceConfiguration, new Semaphore(8));
    }/*from  ww w .ja va2s .c o  m*/
    final Iterator<ServiceConfiguration> putToServiceConfiguration = Iterables.cycle(serviceConfigurations)
            .iterator();
    for (final PutMetricDataType putMetricData : putMetricDataList) {
        final ServiceConfiguration serviceConfiguration = putToServiceConfiguration.next();
        final Semaphore activePuts = semaphoreMap.get(serviceConfiguration);
        activePuts.acquire();
        try {
            final CheckedListenableFuture<BaseMessage> replyFuture = AsyncRequests
                    .dispatch(serviceConfiguration, putMetricData);
            replyFuture.addListener(new Runnable() {
                @Override
                public void run() {
                    try {
                        final BaseMessage reply = replyFuture.get();
                        if (!(reply instanceof PutMetricDataResponseType)) {
                            LOG.error("Error putting compute system metric data");
                        }
                    } catch (ExecutionException | InterruptedException e) {
                        LOG.error("Error putting compute system metric data", e);
                    } finally {
                        activePuts.release();
                    }
                }
            });
        } catch (Throwable t) {
            activePuts.release();
            LOG.error("Error putting compute system metric data", t);
        }
    }
}

From source file:org.immutables.sequence.Sequence.java

/**
 * Returns a fluent iterable whose {@code Iterator} cycles indefinitely over the elements of
 * this fluent iterable./*from  w w  w  . j a  va2 s .  com*/
 * <p>
 * That iterator supports {@code remove()} if {@code iterable.iterator()} does. After
 * {@code remove()} is called, subsequent cycles omit the removed element, which is no longer in
 * this fluent iterable. The iterator's {@code hasNext()} method returns {@code true} until this
 * fluent iterable is empty.
 * <p>
 * <b>Warning:</b> Typical uses of the resulting iterator may produce an infinite loop. You should
 * use an explicit {@code break} or be certain that you will eventually remove all the elements.
 * @return the sequence
 */
@CheckReturnValue
public final Sequence<E> cycle() {
    return from(Iterables.cycle(iterable));
}

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

private String renderFullFrame(ImmutableList<String> logLines, ImmutableList<String> lines,
        int previousNumLinesPrinted) {
    int currentNumLines = lines.size();

    Iterable<String> renderedLines = Iterables.concat(
            MoreIterables.zipAndConcat(Iterables.cycle(ansi.clearLine()), logLines,
                    Iterables.cycle(ansi.clearToTheEndOfLine() + System.lineSeparator())),
            ansi.asNoWrap(MoreIterables.zipAndConcat(Iterables.cycle(ansi.clearLine()), lines,
                    Iterables.cycle(ansi.clearToTheEndOfLine() + System.lineSeparator()))));

    // Number of lines remaining to clear because of old output once we displayed
    // the new output.
    int remainingLinesToClear = previousNumLinesPrinted > currentNumLines
            ? previousNumLinesPrinted - currentNumLines
            : 0;/* w ww.  ja  v a  2s  .  c  om*/

    StringBuilder fullFrame = new StringBuilder();
    // We move the cursor back to the top.
    for (int i = 0; i < previousNumLinesPrinted; i++) {
        fullFrame.append(ansi.cursorPreviousLine(1));
    }
    // We display the new output.
    for (String part : renderedLines) {
        fullFrame.append(part);
    }
    // We clear the remaining lines of the old output.
    for (int i = 0; i < remainingLinesToClear; i++) {
        fullFrame.append(ansi.clearLine());
        fullFrame.append(System.lineSeparator());
    }
    // We move the cursor at the end of the new output.
    for (int i = 0; i < remainingLinesToClear; i++) {
        fullFrame.append(ansi.cursorPreviousLine(1));
    }
    return fullFrame.toString();
}

From source file:com.facebook.buck.ocaml.OCamlBuildContext.java

public ImmutableList<String> getIncludeFlags(boolean isBytecode, boolean excludeDeps) {
    Preconditions.checkNotNull(mlInput);
    return ImmutableList.copyOf(MoreIterables.zipAndConcat(Iterables.cycle(OCamlCompilables.OCAML_INCLUDE_FLAG),
            getIncludeDirectories(isBytecode, excludeDeps)));
}

From source file:com.facebook.buck.ocaml.OCamlBuildContext.java

public ImmutableList<String> getBytecodeIncludeFlags() {
    return ImmutableList.copyOf(MoreIterables.zipAndConcat(Iterables.cycle(OCamlCompilables.OCAML_INCLUDE_FLAG),
            getBytecodeIncludeDirectories()));
}

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

private Iterable<String> getPreprocessorFlags(SourcePathResolver resolver) {
    CxxToolFlags cxxToolFlags = ppFlags.toToolFlags(resolver, PathShortener.identity(),
            CxxDescriptionEnhancer.frameworkPathToSearchPath(platform.getCxxPlatform(), resolver), preprocessor,
            /* pch */ Optional.empty());
    return MoreIterables.zipAndConcat(Iterables.cycle("-optP"),
            Arg.stringify(cxxToolFlags.getAllFlags(), resolver));
}

From source file:com.facebook.buck.haskell.HaskellDescriptionUtils.java

/**
 * Create a Haskell link rule that links the given inputs to a executable or shared library and
 * pulls in transitive native linkable deps from the given dep roots.
 *///from   ww w  .ja  v a  2  s .  c  o  m
public static HaskellLinkRule createLinkRule(BuildTarget target, BuildRuleParams baseParams,
        BuildRuleResolver resolver, SourcePathResolver pathResolver, SourcePathRuleFinder ruleFinder,
        CxxPlatform cxxPlatform, HaskellConfig haskellConfig, Linker.LinkType linkType,
        ImmutableList<String> extraFlags, Iterable<Arg> linkerInputs, Iterable<? extends NativeLinkable> deps,
        Linker.LinkableDepType depType) throws NoSuchBuildTargetException {

    Tool linker = haskellConfig.getLinker().resolve(resolver);
    String name = target.getShortName();

    ImmutableList.Builder<Arg> linkerArgsBuilder = ImmutableList.builder();
    ImmutableList.Builder<Arg> argsBuilder = ImmutableList.builder();

    // Add the base flags from the `.buckconfig` first.
    argsBuilder.addAll(StringArg.from(haskellConfig.getLinkerFlags()));

    // Pass in the appropriate flags to link a shared library.
    if (linkType.equals(Linker.LinkType.SHARED)) {
        name = CxxDescriptionEnhancer.getSharedLibrarySoname(Optional.empty(), target.withFlavors(),
                cxxPlatform);
        argsBuilder.addAll(StringArg.from("-shared", "-dynamic"));
        argsBuilder.addAll(StringArg.from(MoreIterables.zipAndConcat(Iterables.cycle("-optl"),
                cxxPlatform.getLd().resolve(resolver).soname(name))));
    }

    // Add in extra flags passed into this function.
    argsBuilder.addAll(StringArg.from(extraFlags));

    // We pass in the linker inputs and all native linkable deps by prefixing with `-optl` so that
    // the args go straight to the linker, and preserve their order.
    linkerArgsBuilder.addAll(linkerInputs);
    for (NativeLinkable nativeLinkable : NativeLinkables.getNativeLinkables(cxxPlatform, deps, depType)
            .values()) {
        linkerArgsBuilder
                .addAll(NativeLinkables.getNativeLinkableInput(cxxPlatform, depType, nativeLinkable).getArgs());
    }

    // Since we use `-optl` to pass all linker inputs directly to the linker, the haskell linker
    // will complain about not having any input files.  So, create a dummy archive with an empty
    // module and pass that in normally to work around this.
    BuildTarget emptyModuleTarget = target.withAppendedFlavors(ImmutableFlavor.of("empty-module"));
    WriteFile emptyModule = resolver.addToIndex(new WriteFile(baseParams.copyWithBuildTarget(emptyModuleTarget),
            "module Unused where",
            BuildTargets.getGenPath(baseParams.getProjectFilesystem(), emptyModuleTarget, "%s/Unused.hs"),
            /* executable */ false));
    HaskellCompileRule emptyCompiledModule = resolver.addToIndex(createCompileRule(
            target.withAppendedFlavors(ImmutableFlavor.of("empty-compiled-module")), baseParams, resolver,
            ruleFinder, pathResolver, cxxPlatform, haskellConfig, depType, Optional.empty(), Optional.empty(),
            ImmutableList.of(), HaskellSources.builder()
                    .putModuleMap("Unused", new BuildTargetSourcePath(emptyModule.getBuildTarget())).build()));
    BuildTarget emptyArchiveTarget = target.withAppendedFlavors(ImmutableFlavor.of("empty-archive"));
    Archive emptyArchive = resolver.addToIndex(Archive.from(emptyArchiveTarget, baseParams, pathResolver,
            ruleFinder, cxxPlatform, Archive.Contents.NORMAL,
            BuildTargets.getGenPath(baseParams.getProjectFilesystem(), emptyArchiveTarget, "%s/libempty.a"),
            emptyCompiledModule.getObjects()));
    argsBuilder.add(new SourcePathArg(pathResolver, new BuildTargetSourcePath(emptyArchive.getBuildTarget())));

    ImmutableList<Arg> args = argsBuilder.build();
    ImmutableList<Arg> linkerArgs = linkerArgsBuilder.build();

    return resolver.addToIndex(new HaskellLinkRule(
            baseParams.copyWithChanges(target,
                    Suppliers.ofInstance(ImmutableSortedSet.<BuildRule>naturalOrder()
                            .addAll(linker.getDeps(ruleFinder))
                            .addAll(Stream.of(args, linkerArgs).flatMap(Collection::stream)
                                    .flatMap(arg -> arg.getDeps(ruleFinder).stream()).iterator())
                            .build()),
                    Suppliers.ofInstance(ImmutableSortedSet.of())),
            pathResolver, linker, name, args, linkerArgs, haskellConfig.shouldCacheLinks()));
}