Example usage for com.google.common.collect Queues newArrayDeque

List of usage examples for com.google.common.collect Queues newArrayDeque

Introduction

In this page you can find the example usage for com.google.common.collect Queues newArrayDeque.

Prototype

public static <E> ArrayDeque<E> newArrayDeque(Iterable<? extends E> elements) 

Source Link

Document

Creates an ArrayDeque containing the elements of the specified iterable, in the order they are returned by the iterable's iterator.

Usage

From source file:com.facebook.buck.core.util.graph.TopologicalSort.java

public static <T extends Comparable<?>> ImmutableList<T> sort(TraversableGraph<T> graph) {

    // AtomicInteger is used to decrement the integer value in-place.
    Map<T, AtomicInteger> effectiveOutDegreesOfExplorableNodes = new HashMap<>();
    Queue<T> nextLevel = Queues.newArrayDeque(graph.getNodesWithNoOutgoingEdges());
    Set<T> visitedNodes = new HashSet<>();
    ImmutableList.Builder<T> toReturn = ImmutableList.builder();

    while (!nextLevel.isEmpty()) {
        Queue<T> toExplore = nextLevel;
        nextLevel = Queues.newArrayDeque();

        Set<T> level = new TreeSet<>();

        while (!toExplore.isEmpty()) {
            T node = toExplore.remove();
            Preconditions.checkState(!visitedNodes.contains(node),
                    "The queue of nodes to explore should not contain a node that has already been"
                            + " visited.");

            level.add(node);/*from   ww w. j a v  a  2 s .  c  om*/
            visitedNodes.add(node);

            // Only add a node to the set of nodes to be explored if all the nodes it depends on have
            // been visited already. We achieve the same by keeping track of the out degrees of
            // explorable nodes. After visiting a node, decrement the out degree of each of its parent
            // node. When the out degree reaches zero, it is safe to add that node to the list of nodes
            // to explore next.
            for (T exploreCandidate : graph.getIncomingNodesFor(node)) {
                if (!effectiveOutDegreesOfExplorableNodes.containsKey(exploreCandidate)) {
                    effectiveOutDegreesOfExplorableNodes.put(exploreCandidate,
                            new AtomicInteger(Iterables.size(graph.getOutgoingNodesFor(exploreCandidate))));
                }
                if (effectiveOutDegreesOfExplorableNodes.get(exploreCandidate).decrementAndGet() == 0) {
                    nextLevel.add(exploreCandidate);
                }
            }
        }
        toReturn.addAll(level);
    }

    return toReturn.build();
}

From source file:com.palantir.common.io.ConcatenatedInputStream.java

public ConcatenatedInputStream(Iterable<InputStream> streams) {
    this.streams = Queues.newArrayDeque(streams);
}

From source file:com.groupon.deployment.fleet.Sequential.java

/**
 * Public constructor./*from   w  ww .  j a  va 2s  . co  m*/
 *
 * @param hostDeploymentFactory a factory to create a host deployment
 * @param dcf deployment client factory
 * @param sshFactory ssh session factory
 * @param deployment deployment to run
 */
@AssistedInject
public Sequential(final HostDeploymentFactory hostDeploymentFactory, final DeploymentClientFactory dcf,
        final SshSessionFactory sshFactory, @Assisted final Deployment deployment) {
    _hostDeploymentFactory = hostDeploymentFactory;
    _dcf = dcf;
    _sshFactory = sshFactory;
    _deployment = Deployment.getById(deployment.getId()); // Refresh the deployment

    final String myName;
    try {
        myName = InetAddress.getLocalHost().getCanonicalHostName();
    } catch (final UnknownHostException e) {
        throw Throwables.propagate(e);
    }
    // If this host no longer owns the deployment, die
    if (!myName.equals(_deployment.getDeploymentOwner())) {
        Logger.warn(String.format(
                "Current server does not own the deployment, aborting deploy on this server; owner=%s",
                _deployment.getDeploymentOwner()));
        self().tell(PoisonPill.getInstance(), self());
    }
    Logger.info("Sequential fleet deployment actor started up");

    final List<HostDeployment> hosts = Lists.newArrayList();
    deployment.getHostStates().forEach(host -> {
        final DeploymentState hostState = host.getState();
        if (host.getFinished() == null || hostState == null
                || (hostState != DeploymentState.FAILED && hostState != DeploymentState.SUCCEEDED)) {
            hosts.add(host);
        }
    });

    // Sort the hosts with the following rules:
    // TODO(barp): 1) hosts that are "down" should be deployed first [Artemis-?]
    // 2) if the current machine is in the list, it should be last
    hosts.sort((a, b) -> {
        if (a.getHost().getName().equals(myName)) {
            return 1;
        }
        if (b.getHost().getName().equals(myName)) {
            return -1;
        }
        return a.getHost().getName().compareTo(b.getHost().getName());
    });
    _hostQueue = Queues.newArrayDeque(hosts);
    self().tell("start", self());
}

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

/**
 * Returns the full set of modules transitively {@linkplain Module#includes included} from the
 * given seed modules.  If a module is malformed and a type listed in {@link Module#includes}
 * is not annotated with {@link Module}, it is ignored.
 *///  ww  w .  j av  a  2  s  . c om
static ImmutableSet<TypeElement> getTransitiveModules(Types types, Elements elements,
        Iterable<TypeElement> seedModules) {
    TypeMirror objectType = elements.getTypeElement(Object.class.getCanonicalName()).asType();
    Queue<TypeElement> moduleQueue = Queues.newArrayDeque(seedModules);
    Set<TypeElement> moduleElements = Sets.newLinkedHashSet();
    for (TypeElement moduleElement = moduleQueue.poll(); moduleElement != null; moduleElement = moduleQueue
            .poll()) {
        Optional<AnnotationMirror> moduleMirror = getAnnotationMirror(moduleElement, Module.class)
                .or(getAnnotationMirror(moduleElement, ProducerModule.class));
        if (moduleMirror.isPresent()) {
            ImmutableSet.Builder<TypeElement> moduleDependenciesBuilder = ImmutableSet.builder();
            moduleDependenciesBuilder.addAll(MoreTypes.asTypeElements(getModuleIncludes(moduleMirror.get())));
            // (note: we don't recurse on the parent class because we don't want the parent class as a
            // root that the component depends on, and also because we want the dependencies rooted
            // against this element, not the parent.)
            addIncludesFromSuperclasses(types, moduleElement, moduleDependenciesBuilder, objectType);
            ImmutableSet<TypeElement> moduleDependencies = moduleDependenciesBuilder.build();
            moduleElements.add(moduleElement);
            for (TypeElement dependencyType : moduleDependencies) {
                if (!moduleElements.contains(dependencyType)) {
                    moduleQueue.add(dependencyType);
                }
            }
        }
    }
    return ImmutableSet.copyOf(moduleElements);
}

From source file:org.terasology.engine.TerasologyEngine.java

public TerasologyEngine(Collection<EngineSubsystem> subsystems) {
    this.subsystems = Queues.newArrayDeque(subsystems);
}

From source file:dagger2.internal.codegen.writer.JavaWriter.java

public Appendable write(Appendable appendable) throws IOException {
    if (!packageName.isEmpty()) {
        appendable.append("package ").append(packageName).append(";\n\n");
    }//from w  ww .ja v a 2s.  c  o m

    // write imports
    ImmutableSet<ClassName> classNames = FluentIterable.from(typeWriters)
            .transformAndConcat(new Function<HasClassReferences, Set<ClassName>>() {
                @Override
                public Set<ClassName> apply(HasClassReferences input) {
                    return input.referencedClasses();
                }
            }).toSet();

    ImmutableSortedSet<ClassName> importCandidates = ImmutableSortedSet.<ClassName>naturalOrder()
            .addAll(explicitImports).addAll(classNames).build();
    ImmutableSet<ClassName> typeNames = FluentIterable.from(typeWriters)
            .transform(new Function<TypeWriter, ClassName>() {
                @Override
                public ClassName apply(TypeWriter input) {
                    return input.name;
                }
            }).toSet();

    ImmutableSet.Builder<String> declaredSimpleNamesBuilder = ImmutableSet.builder();
    Deque<TypeWriter> declaredTypes = Queues.newArrayDeque(typeWriters);
    while (!declaredTypes.isEmpty()) {
        TypeWriter currentType = declaredTypes.pop();
        declaredSimpleNamesBuilder.add(currentType.name().simpleName());
        declaredTypes.addAll(currentType.nestedTypeWriters);
    }

    ImmutableSet<String> declaredSimpleNames = declaredSimpleNamesBuilder.build();

    BiMap<String, ClassName> importedClassIndex = HashBiMap.create();
    for (ClassName className : importCandidates) {
        if (!(className.packageName().equals(packageName) && !className.enclosingClassName().isPresent())
                && !(className.packageName().equals("java.lang") && className.enclosingSimpleNames().isEmpty())
                && !typeNames.contains(className.topLevelClassName())) {
            Optional<ClassName> importCandidate = Optional.of(className);
            while (importCandidate.isPresent()
                    && (importedClassIndex.containsKey(importCandidate.get().simpleName())
                            || declaredSimpleNames.contains(importCandidate.get().simpleName()))) {
                importCandidate = importCandidate.get().enclosingClassName();
            }
            if (importCandidate.isPresent()) {
                appendable.append("import ").append(importCandidate.get().canonicalName()).append(";\n");
                importedClassIndex.put(importCandidate.get().simpleName(), importCandidate.get());
            }
        }
    }

    appendable.append('\n');

    CompilationUnitContext context = new CompilationUnitContext(packageName,
            ImmutableSet.copyOf(importedClassIndex.values()));

    // write types
    for (TypeWriter typeWriter : typeWriters) {
        typeWriter.write(appendable, context.createSubcontext(typeNames)).append('\n');
    }
    return appendable;
}

From source file:clocker.docker.location.strategy.affinity.AffinityRules.java

private Predicate<Entity> predicate(String rule) {
    Preconditions.checkNotNull(rule, "rule");
    Queue<String> tokens = Queues
            .newArrayDeque(Splitter.on(CharMatcher.WHITESPACE).omitEmptyStrings().splitToList(rule));

    boolean same = true;
    Predicate<Entity> predicate = Predicates.alwaysTrue();

    // Check first token for special values
    String first = tokens.peek();
    if (first.equalsIgnoreCase(NOT)) {
        same = false;//from  www  .j ava2  s  . c  o  m
        tokens.remove();
    }

    // Check verb
    String verb = tokens.peek();
    if (verb == null) {
        throw new IllegalStateException("Affinity rule verb not specified: " + rule);
    } else {
        if (Iterables.contains(VERBS, verb.toUpperCase(Locale.ENGLISH))) {
            tokens.remove();
        } else {
            throw new IllegalStateException("Affinity rule parser found unexpected verb token: " + verb);
        }
    }

    // Check paramater and instantiate if required
    final String parameter = tokens.peek();
    if (parameter == null) {
        if (verb.equalsIgnoreCase(EMPTY)) {
            allowEmpty = same;
            tokens.remove();
            if (tokens.isEmpty()) {
                return predicate;
            } else {
                throw new IllegalStateException("Affinity rule has extra tokens: " + rule);
            }
        } else if (verb.equalsIgnoreCase(TYPE)) {
            predicate = new Predicate<Entity>() {
                @Override
                public boolean apply(@Nullable Entity input) {
                    return input.getEntityType().getName().equalsIgnoreCase(entity.getEntityType().getName())
                            || input.getEntityType().getSimpleName()
                                    .equalsIgnoreCase(entity.getEntityType().getSimpleName());
                }
            };
        } else if (verb.equalsIgnoreCase(ID)) {
            predicate = EntityPredicates.idEqualTo(entity.getId());
        } else if (verb.equalsIgnoreCase(APPLICATION)) {
            predicate = EntityPredicates.applicationIdEqualTo(entity.getApplicationId());
        } else {
            throw new IllegalStateException("Affinity rule parameter not specified: " + rule);
        }
    } else {
        tokens.remove();
        if (verb.equalsIgnoreCase(TYPE)) {
            predicate = new Predicate<Entity>() {
                @Override
                public boolean apply(@Nullable Entity input) {
                    return input.getEntityType().getName().equalsIgnoreCase(parameter)
                            || input.getEntityType().getSimpleName().equalsIgnoreCase(parameter);
                }
            };
        } else if (verb.equalsIgnoreCase(NAME)) {
            predicate = new Predicate<Entity>() {
                @Override
                public boolean apply(@Nullable Entity input) {
                    return input.getDisplayName().toLowerCase(Locale.ENGLISH)
                            .contains(parameter.toLowerCase(Locale.ENGLISH));
                }
            };
        } else if (verb.equalsIgnoreCase(ID)) {
            predicate = EntityPredicates.idEqualTo(parameter);
        } else if (verb.equalsIgnoreCase(APPLICATION)) {
            predicate = EntityPredicates.applicationIdEqualTo(parameter);
        } else if (verb.equalsIgnoreCase(PREDICATE)) {
            try {
                Class<?> clazz = Class.forName(parameter);
                if (Reflections.hasNoArgConstructor(clazz)) {
                    predicate = (Predicate<Entity>) Reflections.invokeConstructorWithArgs(clazz);
                } else {
                    throw new IllegalStateException("Could not instantiate predicate: " + parameter);
                }
            } catch (ClassNotFoundException e) {
                throw new IllegalStateException("Could not find predicate: " + parameter);
            }
        }
    }

    // Check for left-over tokens
    if (tokens.peek() != null) {
        throw new IllegalStateException("Affinity rule has extra tokens: " + rule);
    }

    // Create predicate and return
    if (same) {
        return predicate;
    } else {
        return Predicates.not(predicate);
    }
}

From source file:com.facebook.hiveio.tailer.TailerCmd.java

@Override
public void execute() throws Exception {
    HadoopNative.requireHadoopNative();//w  w w . ja v  a2s. co m

    args.process();
    chooseRecordPrinter();

    HostPort metastoreHostPort = getMetastoreHostPort();
    if (metastoreHostPort == null) {
        return;
    }

    LOG.info("Creating Hive client for Metastore at {}", metastoreHostPort);
    ThriftHiveMetastore.Iface client = HiveMetastores.create(metastoreHostPort.host, metastoreHostPort.port);

    HiveInputDescription inputDesc = initInput(metastoreHostPort);

    HiveStats hiveStats = HiveUtils.statsOf(client, inputDesc);
    LOG.info("{}", hiveStats);

    HiveConf hiveConf = HiveUtils.newHiveConf(TailerCmd.class);
    args.inputTable.process(hiveConf);

    LOG.info("Setting up input using {}", inputDesc);
    HiveApiInputFormat.setProfileInputDesc(hiveConf, inputDesc, DEFAULT_PROFILE_ID);

    HiveApiInputFormat hapi = new HiveApiInputFormat();
    hapi.setMyProfileId(DEFAULT_PROFILE_ID);

    List<InputSplit> splits = hapi.getSplits(new JobContext(hiveConf, new JobID()));
    LOG.info("Have {} splits to read", splits.size());

    HiveTableDesc hiveTableDesc = new HiveTableDesc(args.inputTable.database, args.inputTable.table);
    HiveTableSchema schema = HiveTableSchemas.lookup(client, hiveConf, hiveTableDesc);
    chooseRowParser(schema);

    Stats stats = Stats.create(hiveStats);
    Context context = new Context(hapi, hiveConf, schema, hiveStats, stats);
    long startNanos = System.nanoTime();

    if (args.multiThread.isSingleThreaded()) {
        context.splitsQueue = Queues.newArrayDeque(splits);
        readSplits(context);
    } else {
        context.splitsQueue = Queues.newConcurrentLinkedQueue(splits);
        multiThreaded(context, args.multiThread.threads);
    }

    long timeNanos = System.nanoTime() - startNanos;
    if (args.appendStatsTo != null) {
        OutputStream out = new FileOutputStream(args.appendStatsTo, true);
        try {
            stats.printEndBenchmark(context, args, timeNanos, out);
        } finally {
            out.close();
        }
    }

    System.err.println("Finished.");
    if (args.metricsOpts.stderrEnabled()) {
        args.metricsOpts.dumpMetricsToStderr();
    }
}

From source file:edu.buaa.satla.analysis.core.predicate.PredicateStaticRefiner.java

private void buildDirectlyAffectingStatements() {
    if (directlyAffectingStatements != null) {
        return;/*  ww w . ja va 2  s. c  o  m*/
    }

    directlyAffectingStatements = LinkedHashMultimap.create();

    for (CFANode u : cfa.getAllNodes()) {
        Deque<CFAEdge> edgesToHandle = Queues.newArrayDeque(CFAUtils.leavingEdges(u));
        while (!edgesToHandle.isEmpty()) {
            CFAEdge e = edgesToHandle.pop();
            if (e instanceof MultiEdge) {
                edgesToHandle.addAll(((MultiEdge) e).getEdges());
            } else if (e instanceof CStatementEdge) {
                CStatementEdge stmtEdge = (CStatementEdge) e;
                if (stmtEdge.getStatement() instanceof CAssignment) {
                    CAssignment assign = (CAssignment) stmtEdge.getStatement();

                    if (assign.getLeftHandSide() instanceof CIdExpression) {
                        String variable = ((CIdExpression) assign.getLeftHandSide()).getDeclaration()
                                .getQualifiedName();
                        directlyAffectingStatements.put(variable, stmtEdge);
                    }
                }
            }
        }
    }
}

From source file:com.mgmtp.jfunk.common.util.Configuration.java

/**
 * If properties are present which start with {@link JFunkConstants#SYSTEM_PROPERTIES} the
 * corresponding values are taken as property files and loaded here.
 *//*from   w  w w.  j  av  a 2 s.c o  m*/
private void loadExtraFiles(final String filterPrefix, final boolean preserveExisting) {
    Map<String, String> view = Maps.filterKeys(this, Predicates.startsWith(filterPrefix));
    while (true) {
        if (view.isEmpty()) {
            break;
        }

        Queue<String> fileKeys = Queues.newArrayDeque(view.values());

        // we need to keep them separately in order to be able to reload them (see put method)
        extraFileProperties.addAll(fileKeys);

        // Remove original keys in order to prevent a stack overflow
        view.clear();

        for (String fileNameKey = null; (fileNameKey = fileKeys.poll()) != null;) {
            // Recursion
            String fileName = processPropertyValue(fileNameKey);
            if (PLACEHOLDER_PATTERN.matcher(fileName).find()) {
                // not all placeholders were resolved, so we enqueue it again to process another file first
                fileKeys.offer(fileName);
            } else {
                load(fileName, preserveExisting);
            }
        }
    }
}