Example usage for com.google.common.collect Iterators get

List of usage examples for com.google.common.collect Iterators get

Introduction

In this page you can find the example usage for com.google.common.collect Iterators get.

Prototype

public static <T> T get(Iterator<T> iterator, int position) 

Source Link

Document

Advances iterator position + 1 times, returning the element at the position th position.

Usage

From source file:org.deri.iris.queryrewriting.SQLRewriter.java

public String getSQLRewriting(IRule query, final String sqlConstraint, final int nbNodes, final int startedFrom)
        throws SQLException {
    //LOGGER.debug("Translating " + query);
    final IBasicFactory bf = Factory.BASIC;

    final Map<String, String> aliasMap = new HashMap<String, String>();
    final Set<ITerm> processedTargetTerms = new HashSet<ITerm>();
    final List<String> targetList = new ArrayList<String>();
    final List<String> fromList = new ArrayList<String>();
    final List<String> whereList = new ArrayList<String>();

    // Disambiguate same predicates in the query body
    final Set<ILiteral> body = new LinkedHashSet<ILiteral>();
    int dis = 1;//from   w  w w .j a v  a  2  s .  c  om
    for (final ILiteral l : query.getBody()) {
        final String p = l.getAtom().getPredicate().toString();
        String p_alias;
        if (aliasMap.containsValue(p)) {
            p_alias = Joiner.on("").join(p, "_", dis++);
        } else {
            p_alias = p;
        }
        aliasMap.put(p_alias, p);
        body.add(bf.createLiteral(l.isPositive(),
                bf.createPredicate(p_alias, l.getAtom().getPredicate().getArity()), l.getAtom().getTuple()));
    }
    query = bf.createRule(query.getHead(), body);

    try {
        final StringBuffer out = new StringBuffer();

        // Translate the Query
        for (int i = 0; i < query.getBody().size(); i++) {
            final ILiteral l = Iterators.get(query.getBody().iterator(), i);
            final String p = l.getAtom().getPredicate().getPredicateSymbol();
            fromList.add(p);

            int pos = 0;
            for (final ITerm t : l.getAtom().getTuple()) {
                pos++;
                if (query.getHeadVariables().contains(t) && !processedTargetTerms.contains(t)) {
                    // This is a head variable
                    targetList.add(
                            Joiner.on("").join(p, ".", StorageManager.getFields(aliasMap.get(p)).get(pos - 1)));
                    processedTargetTerms.add(t);
                }
                if (t instanceof StringTerm) {
                    if (aliasMap.containsKey(p)) {
                        whereList.add(Joiner.on("").join(p, ".",
                                StorageManager.getFields(aliasMap.get(p)).get(pos - 1), "=", t, ""));
                    }
                }
                for (int j = i + 1; j < query.getBody().size(); j++) {
                    final ILiteral lj = Iterators.get(query.getBody().iterator(), j);
                    final String pj = lj.getAtom().getPredicate().toString();
                    int posj = 0;
                    for (final ITerm jt : lj.getAtom().getTuple()) {
                        posj++;
                        if (jt.equals(t)) {
                            if (p.equalsIgnoreCase("I_CLASS")) {
                                final String whereAtom = Joiner.on("").join(p, ".",
                                        StorageManager.getFields(aliasMap.get(p)).get(pos - 1), "=", pj, ".",
                                        StorageManager.getFields(aliasMap.get(pj)).get(posj - 1));
                                whereList.add(whereAtom);
                            } else {
                                final String whereAtom = Joiner.on("").join(pj, ".",
                                        StorageManager.getFields(aliasMap.get(pj)).get(posj - 1), "=", p, ".",
                                        StorageManager.getFields(aliasMap.get(p)).get(pos - 1));
                                whereList.add(whereAtom);
                            }
                        }
                    }
                }
            }
        }

        // Building the target list
        if (targetList.size() == 0) {
            out.append("SELECT DISTINCT 'true'");
        } else {
            out.append("SELECT DISTINCT ");
            for (int i = 0; i < (targetList.size() - 1); i++) {
                out.append(targetList.get(i)).append(", ");
            }
            out.append(targetList.get(targetList.size() - 1));
        }

        // Building the from list
        out.append(" FROM ");
        final String vendor = StorageManager.getVendor();
        for (int i = 0; i < (fromList.size() - 1); i++) {
            if (aliasMap.get(fromList.get(i)).compareTo(fromList.get(i)) != 0) {
                if (vendor.compareTo("_ORACLE") == 0) {
                    out.append(aliasMap.get(fromList.get(i))).append(" ").append(fromList.get(i)).append(", ");
                } else if (vendor.compareTo("_MYSQL") == 0) {
                    out.append(aliasMap.get(fromList.get(i))).append(" AS ").append(fromList.get(i))
                            .append(", ");
                } else if (vendor.compareTo("_POSTGRES") == 0) {
                    out.append(StorageManager.getSchemaName()).append(".").append(aliasMap.get(fromList.get(i)))
                            .append(" AS ").append(fromList.get(i)).append(", ");
                } else
                    throw new SQLException("Unsupported Vendor: " + vendor);
            } else {
                if (vendor.equals("_POSTGRES")) {
                    out.append(StorageManager.getSchemaName()).append(".").append(fromList.get(i)).append(", ");
                } else {
                    out.append(fromList.get(i)).append(", ");
                }
            }
        }
        if (aliasMap.get(fromList.get(fromList.size() - 1)).compareTo(fromList.get(fromList.size() - 1)) != 0) {
            if (vendor.equals("_ORACLE")) {
                out.append(aliasMap.get(fromList.get(fromList.size() - 1))).append(" ")
                        .append(fromList.get(fromList.size() - 1));
            } else if (vendor.compareTo("_MYSQL") == 0) {
                out.append(aliasMap.get(fromList.get(fromList.size() - 1))).append(" AS ")
                        .append(fromList.get(fromList.size() - 1));
            } else if (vendor.compareTo("_POSTGRES") == 0) {
                out.append(StorageManager.getSchemaName()).append(".")
                        .append(aliasMap.get(fromList.get(fromList.size() - 1))).append(" AS ")
                        .append(fromList.get(fromList.size() - 1));
            } else
                throw new SQLException("Unsupported Vendor: " + vendor);
        } else {
            if (vendor.equals("_POSTGRES")) {
                out.append(StorageManager.getSchemaName()).append(".")
                        .append(fromList.get(fromList.size() - 1));
                out.append(", preferences.place ");
            } else {
                out.append(fromList.get(fromList.size() - 1));
            }
        }

        // Building the where list
        if (whereList.size() > 0) {
            out.append(" WHERE ");
            for (int i = 0; i < (whereList.size() - 1); i++) {
                out.append(whereList.get(i)).append(" AND ");
            }
            out.append(whereList.get(whereList.size() - 1));
            out.append("and business_categories.bs_id = place.bs_id " + sqlConstraint);

        }
        out.append("  limit " + nbNodes + " offset " + startedFrom);
        //LOGGER.debug("Q " + out.toString());
        return (out.toString());

    } catch (final SQLException e) {
        e.printStackTrace();
    }
    return (null);
}

From source file:hudson.util.RunList.java

/**
 * @deprecated as of 1.485/*from w w  w  .  j av  a 2 s .  co m*/
 *      {@link RunList}, despite its name, should be really used as {@link Iterable}, not as {@link List}.
 */
@Override
@Deprecated
public R get(int index) {
    return Iterators.get(iterator(), index);
}

From source file:org.apache.cassandra.stress.util.SmartThriftClient.java

private Client get(ByteBuffer pk) {
    Set<Host> hosts = metadata.getReplicas(metadata.quote(keyspace), pk);
    InetAddress address = null;// w w  w.j av a  2s .c om
    if (hosts.size() > 0) {
        int pos = roundrobin.incrementAndGet() % hosts.size();
        for (int i = 0; address == null && i < hosts.size(); i++) {
            if (pos < 0)
                pos = -pos;
            Host host = Iterators.get(hosts.iterator(), (pos + i) % hosts.size());
            if (whiteset == null || whiteset.contains(host.getAddress()))
                address = host.getAddress();
        }
    }
    if (address == null)
        address = whitelist.get(ThreadLocalRandom.current().nextInt(whitelist.size()));
    ConcurrentLinkedQueue<Client> q = cache.get(address);
    if (q == null) {
        ConcurrentLinkedQueue<Client> newQ = new ConcurrentLinkedQueue<Client>();
        q = cache.putIfAbsent(address, newQ);
        if (q == null)
            q = newQ;
    }
    Client tclient = q.poll();
    if (tclient != null)
        return tclient;
    return new Client(settings.getRawThriftClient(address.getHostAddress()), address);
}

From source file:dagger.internal.codegen.ComponentTreeTraverser.java

/**
 * Called once for each component in a component hierarchy.
 *
 * <p>Subclasses can override this method to perform whatever logic is required per component.
 * They should call the {@code super} implementation if they want to continue the traversal in the
 * standard order./*from ww w  .j a  v  a2s .  c  om*/
 *
 * <p>This implementation does the following:
 *
 * <ol>
 *   <li>If this component is installed in its parent by a subcomponent factory method, calls
 *       {@link #visitSubcomponentFactoryMethod(BindingGraph, BindingGraph, ExecutableElement)}.
 *   <li>For each entry point in the component, calls {@link #visitEntryPoint(DependencyRequest,
 *       BindingGraph)}.
 *   <li>For each child component, calls {@link #visitComponent(BindingGraph)}, updating the
 *       traversal state.
 * </ol>
 *
 * @param graph the currently visited graph
 */
protected void visitComponent(BindingGraph graph) {
    if (bindingGraphPath.size() > 1) {
        BindingGraph parent = Iterators.get(bindingGraphPath.descendingIterator(), 1);
        ComponentMethodDescriptor childFactoryMethod = parent.componentDescriptor()
                .subcomponentsByFactoryMethod().inverse().get(graph.componentDescriptor());
        if (childFactoryMethod != null) {
            visitSubcomponentFactoryMethod(graph, parent, childFactoryMethod.methodElement());
        }
    }

    for (DependencyRequest entryPoint : graph.componentDescriptor().entryPoints()) {
        visitEntryPoint(entryPoint, graph);
    }

    for (BindingGraph child : graph.subgraphs()) {
        bindingGraphPath.addLast(child);
        try {
            visitComponent(child);
        } finally {
            verify(bindingGraphPath.removeLast().equals(child));
        }
    }
}

From source file:r.lang.ListExp.java

public <X extends SEXP> X get(int i) {
    return (X) Iterators.get(iterator(), i);
}

From source file:r.lang.ListExp.java

public ListExp getNode(int i) {
    return Iterators.get(nodeIterator(), i);
}

From source file:de.cosmocode.collections.tree.AbstractTreeNode.java

@Override
public TreeNode<E> getChildAt(int index) throws IndexOutOfBoundsException {
    if (index < 0) {
        throw new IndexOutOfBoundsException("index < 0");
    } else if (index >= getNumberOfChildren()) {
        throw new IndexOutOfBoundsException("index >= number of children (" + getNumberOfChildren() + ")");
    } else {//from   w  w w  . ja  v  a  2s .c o  m
        final Iterator<TreeNode<E>> iterator = getChildren().iterator();
        return Iterators.get(iterator, index);
    }
}

From source file:de.cosmocode.collections.tree.iterator.AbstractTreeIterator.java

/**
 * <p> This method goes to the parent node of the current node.
 * The level is reduced by one after a call to this method.
 * The data of the parent element is returned as by {@link #currentData()}.
 * </p>//  ww  w. j  av  a  2s .  c o  m
 * 
 * @return the parent element's data
 * @throws NoSuchElementException if this method is called on the root node
 */
protected E parent() {
    if (isRoot()) {
        throw new NoSuchElementException("can not go to parent of root");
    }

    this.currentNode = this.currentNode.getParent();
    --this.currentLevel;

    if (isRoot()) {
        this.siblingIterator = Iterators.emptyIterator();
    } else {
        this.siblingIterator = this.currentNode.getParent().getChildren().iterator();
        if (currentIndex() >= 0) {
            Iterators.get(this.siblingIterator, currentIndex());
        }
    }

    return currentData();
}

From source file:com.mind_era.knime_rapidminer.knime.nodes.util.KnimeExampleSet.java

@Override
public Example getExample(final int n) {
    return Iterators.get(iterator(), n);
}

From source file:de.cosmocode.collections.tree.iterator.AbstractTreeIterator.java

/**
 * <p> This method goes to the next child node of the current node.
 * This method is only useful in conjunction with {@link #parent()},
 * because the last visited child node is saved when going to the parent.
 * This means that <code>parent(); nextChild();</code> is equivalent to <code>nextSibling();</code>.
 * </p>/*from  ww w .  ja v a2  s. c o  m*/
 * <p> The level is increased by one after a call to this method.
 * The data of the child element is returned as by {@link #currentData()}.
 * </p>
 * 
 * @return the data of the next child
 * @throws NoSuchElementException if the current node has no more children
 * @see #hasNextChild()
 */
protected E nextChild() {
    if (currentLevel + 1 >= childIndexes.length)
        increaseIndexes();

    if (this.childIndexes[currentLevel + 1] + 1 >= this.currentNode.getNumberOfChildren()) {
        throw new NoSuchElementException();
    }

    ++this.currentLevel;
    this.childIndexes[currentLevel] += 1;
    this.siblingIterator = this.currentNode.getChildren().iterator();
    this.currentNode = Iterators.get(this.siblingIterator, currentIndex());

    return this.currentNode.getData();
}