Example usage for java.util LinkedList getLast

List of usage examples for java.util LinkedList getLast

Introduction

In this page you can find the example usage for java.util LinkedList getLast.

Prototype

public E getLast() 

Source Link

Document

Returns the last element in this list.

Usage

From source file:com.caricah.iotracah.datastore.ignitecache.internal.impl.SubscriptionFilterHandler.java

public Observable<IotSubscriptionFilter> createTree(String partitionId, List<String> topicFilterTreeRoute) {

    return Observable.create(observer -> {

        try {//from   w  w w. j a  v  a  2s. c  o m

            List<String> growingTitles = new ArrayList<>();
            LinkedList<Long> growingParentIds = new LinkedList<>();

            ListIterator<String> pathIterator = topicFilterTreeRoute.listIterator();

            while (pathIterator.hasNext()) {

                growingTitles.add(pathIterator.next());

                IotSubscriptionFilterKey iotSubscriptionFilterKey = keyFromList(partitionId, growingTitles);
                Observable<IotSubscriptionFilter> filterObservable = getByKeyWithDefault(
                        iotSubscriptionFilterKey, null);

                filterObservable.subscribe(internalSubscriptionFilter -> {

                    if (null == internalSubscriptionFilter) {
                        internalSubscriptionFilter = new IotSubscriptionFilter();
                        internalSubscriptionFilter.setPartitionId(partitionId);
                        internalSubscriptionFilter.setName(iotSubscriptionFilterKey.getName());
                        internalSubscriptionFilter.setId(getIdSequence().incrementAndGet());

                        if (growingParentIds.isEmpty()) {
                            internalSubscriptionFilter.setParentId(0l);
                        } else {
                            internalSubscriptionFilter.setParentId(growingParentIds.getLast());
                        }
                        save(iotSubscriptionFilterKey, internalSubscriptionFilter);
                    }

                    growingParentIds.add(internalSubscriptionFilter.getId());

                    if (growingTitles.size() == topicFilterTreeRoute.size())
                        observer.onNext(internalSubscriptionFilter);

                }, throwable -> {
                }, () -> {

                    if (!pathIterator.hasNext()) {

                        observer.onCompleted();

                    }

                });
            }

        } catch (Exception e) {
            observer.onError(e);
        }

    });
}

From source file:org.apache.fop.layoutmgr.list.ListItemLayoutManager.java

/**
 * Add the areas for the break points./*from  www. j a  v  a2 s.co m*/
 *
 * @param parentIter the position iterator
 * @param layoutContext the layout context for adding areas
 */
@Override
public void addAreas(PositionIterator parentIter, LayoutContext layoutContext) {
    getParentArea(null);

    addId();

    LayoutContext lc = new LayoutContext(0);
    Position firstPos = null;
    Position lastPos = null;

    // "unwrap" the NonLeafPositions stored in parentIter
    LinkedList<Position> positionList = new LinkedList<Position>();
    Position pos;
    while (parentIter.hasNext()) {
        pos = parentIter.next();
        if (pos.getIndex() >= 0) {
            if (firstPos == null) {
                firstPos = pos;
            }
            lastPos = pos;
        }
        if (pos instanceof NonLeafPosition && pos.getPosition() != null) {
            // pos contains a ListItemPosition created by this ListBlockLM
            positionList.add(pos.getPosition());
        }
    }

    addMarkersToPage(true, isFirst(firstPos), isLast(lastPos));

    // use the first and the last ListItemPosition to determine the
    // corresponding indexes in the original labelList and bodyList
    int labelFirstIndex = ((ListItemPosition) positionList.getFirst()).getLabelFirstIndex();
    int labelLastIndex = ((ListItemPosition) positionList.getLast()).getLabelLastIndex();
    int bodyFirstIndex = ((ListItemPosition) positionList.getFirst()).getBodyFirstIndex();
    int bodyLastIndex = ((ListItemPosition) positionList.getLast()).getBodyLastIndex();

    //Determine previous break if any (in item label list)
    int previousBreak = ElementListUtils.determinePreviousBreak(labelList, labelFirstIndex);
    SpaceResolver.performConditionalsNotification(labelList, labelFirstIndex, labelLastIndex, previousBreak);

    //Determine previous break if any (in item body list)
    previousBreak = ElementListUtils.determinePreviousBreak(bodyList, bodyFirstIndex);
    SpaceResolver.performConditionalsNotification(bodyList, bodyFirstIndex, bodyLastIndex, previousBreak);

    // add label areas
    if (labelFirstIndex <= labelLastIndex) {
        KnuthPossPosIter labelIter = new KnuthPossPosIter(labelList, labelFirstIndex, labelLastIndex + 1);
        lc.setFlags(LayoutContext.FIRST_AREA, layoutContext.isFirstArea());
        lc.setFlags(LayoutContext.LAST_AREA, layoutContext.isLastArea());
        // set the space adjustment ratio
        lc.setSpaceAdjust(layoutContext.getSpaceAdjust());
        // TO DO: use the right stack limit for the label
        lc.setStackLimitBP(layoutContext.getStackLimitBP());
        label.addAreas(labelIter, lc);
    }

    // add body areas
    if (bodyFirstIndex <= bodyLastIndex) {
        KnuthPossPosIter bodyIter = new KnuthPossPosIter(bodyList, bodyFirstIndex, bodyLastIndex + 1);
        lc.setFlags(LayoutContext.FIRST_AREA, layoutContext.isFirstArea());
        lc.setFlags(LayoutContext.LAST_AREA, layoutContext.isLastArea());
        // set the space adjustment ratio
        lc.setSpaceAdjust(layoutContext.getSpaceAdjust());
        // TO DO: use the right stack limit for the body
        lc.setStackLimitBP(layoutContext.getStackLimitBP());
        body.addAreas(bodyIter, lc);
    }

    // after adding body areas, set the maximum area bpd
    int childCount = curBlockArea.getChildAreas().size();
    assert childCount >= 1 && childCount <= 2;
    int itemBPD = ((Block) curBlockArea.getChildAreas().get(0)).getAllocBPD();
    if (childCount == 2) {
        itemBPD = Math.max(itemBPD, ((Block) curBlockArea.getChildAreas().get(1)).getAllocBPD());
    }
    curBlockArea.setBPD(itemBPD);

    addMarkersToPage(false, isFirst(firstPos), isLast(lastPos));

    // We are done with this area add the background
    TraitSetter.addBackground(curBlockArea, getListItemFO().getCommonBorderPaddingBackground(), this);
    TraitSetter.addSpaceBeforeAfter(curBlockArea, layoutContext.getSpaceAdjust(), effSpaceBefore,
            effSpaceAfter);

    flush();

    curBlockArea = null;
    resetSpaces();

    checkEndOfLayout(lastPos);
}

From source file:net.jenet.Host.java

Event dispatchIncomingCommands() {
    Event result = new Event();
    Peer currentPeer;/*from   w  w  w .ja v a  2 s  .  co  m*/

    LinkedList<Peer> peersList = new LinkedList<Peer>(peers.values());

    if (peers.size() == 0)
        return result;

    /* 
     * Simply calling containsKey( lastServicedPeer.getIncomingPeerId() ) will 
     * not be sufficient because the peerID of lastServicedPeer may have been 
     * reassigned.  The get operation is quicker than containsValue because 
     * it does not have to search through all the peers. 
     * 
     * lastServicedPeer.isDisconnected() may be sufficient, but this feels more robust.
     */
    if (lastServicedPeer == null || peers.get(lastServicedPeer.getIncomingPeerID()) != lastServicedPeer)
        lastServicedPeer = peersList.getFirst();
    else
        while (peersList.getLast() != lastServicedPeer)
            peersList.addLast(peersList.removeFirst());

    do {
        currentPeer = peersList.removeFirst();
        peersList.addLast(currentPeer);

        if (currentPeer.isZombie()) {
            recalculateBandwithLimits = true;
            currentPeer.reset();
            result.setType(Event.TYPE.DISCONNECTED);
            result.setPeer(currentPeer);
            lastServicedPeer = currentPeer;
            return result;
        }

        if (!currentPeer.isConnected())
            continue;

        for (byte channelID : currentPeer.getChannels().keySet()) {
            Channel channel = currentPeer.getChannels().get(channelID);
            if (channel.getIncomingReliableCommands().isEmpty()
                    && channel.getIncomingUnreliableCommands().isEmpty())
                continue;
            Packet packet = currentPeer.receive(channelID);
            result.setPacket(packet);
            if (packet == null)
                continue;
            result.setType(Event.TYPE.RECEIVED);
            result.setPeer(currentPeer);
            result.setChannelID(channelID);
            result.setPacket(packet);
            lastServicedPeer = currentPeer;

            return result;
        }
    } while (currentPeer != lastServicedPeer);

    return result;
}

From source file:net.relet.freimap.LinkInfo.java

public void setFlowProfile(LinkedList<FlowData> lp) {

    XYSeries packets = new XYSeries("packets");
    XYSeries bytes = new XYSeries("bytes");
    XYSeries icmp = new XYSeries("icmp");
    XYSeries tcp = new XYSeries("tcp");
    XYSeries udp = new XYSeries("udp");
    XYSeries other = new XYSeries("other");

    XYSeriesCollection data1 = new XYSeriesCollection(bytes);
    XYSeriesCollection data2 = new XYSeriesCollection(packets);
    XYSeriesCollection data3 = new XYSeriesCollection(icmp);
    data3.addSeries(tcp);//from   w ww. j a v  a  2  s .  co m
    data3.addSeries(udp);
    data3.addSeries(other);

    //linkChart = ChartFactory.createXYLineChart("packets, bytes\r\nicmp, tcp, udp other", "time", "count", data1, PlotOrientation.VERTICAL, false, false, false);
    ValueAxis domain = new DateAxis();
    ValueAxis range1 = new NumberAxis();
    ValueAxis range2 = new NumberAxis();
    ValueAxis range3 = new NumberAxis();
    CombinedDomainXYPlot plot = new CombinedDomainXYPlot(domain);
    plot.add(new XYPlot(data2, domain, range1, new XYLineAndShapeRenderer(true, false)));
    plot.add(new XYPlot(data1, domain, range2, new XYLineAndShapeRenderer(true, false)));
    plot.add(new XYPlot(data3, domain, range1, new XYLineAndShapeRenderer(true, false)));
    linkChart = new JFreeChart(plot);
    linkChart.setTitle("");
    sexupLayout(linkChart);

    long min = lp.getFirst().begin, max = lp.getLast().end;

    for (float i = 0.0f; i < 1000.0f; i += 1.0f) {
        long cur = min + (long) ((max - min) * (i / 1000.0));

        long cpackets = 0;
        long cbytes = 0;
        long cicmp = 0;
        long ctcp = 0;
        long cudp = 0;
        long cother = 0;

        Iterator<FlowData> li = lp.iterator();
        while (li.hasNext()) {
            FlowData data = li.next();
            if (data.begin > cur)
                break;
            if (data.end < cur)
                continue;
            cpackets += data.packets;
            cbytes += data.bytes;
            switch (data.protocol) {
            case 1: {
                cicmp += data.packets;
                break;
            }
            case 6: {
                ctcp += data.packets;
                break;
            }
            case 17: {
                cudp += data.packets;
                break;
            }
            default: {
                cother += data.packets;
                break;
            }
            }
        }

        packets.add(cur, cpackets);
        bytes.add(cur, cbytes);
        icmp.add(cur, cicmp);
        tcp.add(cur, ctcp);
        udp.add(cur, cudp);
        other.add(cur, cother);
    }

    status = STATUS_AVAILABLE;
}

From source file:com.mirth.connect.server.controllers.MuleEngineController.java

private void configureInboundRouter(UMODescriptor descriptor, Channel channel) throws Exception {
    logger.debug("configuring inbound router for channel: " + channel.getId() + " (" + channel.getName() + ")");
    InboundMessageRouter inboundRouter = new InboundMessageRouter();
    Exception exceptionRegisteringInboundRouter = null;

    MuleEndpoint endpoint = new MuleEndpoint();
    String connectorReference = getConnectorReferenceForInboundRouter(channel);

    // Check if the channel is synchronous
    if ((channel.getProperties().get("synchronous")) != null
            && ((String) channel.getProperties().get("synchronous")).equalsIgnoreCase("true")) {
        endpoint.setSynchronous(true);/*from   ww w.j  a  v  a  2  s .c om*/
    }

    // STEP 1. append the default transformers required by the transport
    // (ex. ByteArrayToString)
    ConnectorMetaData transport = transports.get(channel.getSourceConnector().getTransportName());
    LinkedList<UMOTransformer> transformerList = null;

    if (transport.getTransformers() != null) {
        transformerList = chainTransformers(transport.getTransformers());
    }

    // STEP 2. append the preprocessing transformer
    UMOTransformer preprocessorTransformer = createPreprocessor(channel, connectorReference + "_preprocessor");

    try {
        muleManager.registerTransformer(preprocessorTransformer);
    } catch (Exception e) {
        exceptionRegisteringInboundRouter = e;
    }

    if (!transformerList.isEmpty()) {
        transformerList.getLast().setTransformer(preprocessorTransformer);
    } else {
        // there were no default transformers, so make the preprocessor
        // the first transformer in the list
        transformerList.add(preprocessorTransformer);
    }

    // STEP 3. finally, append the JavaScriptTransformer that does the
    // mappings
    UMOTransformer javascriptTransformer = createTransformer(channel, channel.getSourceConnector(),
            connectorReference + "_transformer");

    try {
        muleManager.registerTransformer(javascriptTransformer);
    } catch (Exception e) {
        exceptionRegisteringInboundRouter = e;
    }

    preprocessorTransformer.setTransformer(javascriptTransformer);

    // STEP 4. add the transformer sequence as an attribute to the endpoint
    endpoint.setTransformer(transformerList.getFirst());

    SelectiveConsumer selectiveConsumerRouter = new SelectiveConsumer();
    selectiveConsumerRouter.setFilter(new ValidMessageFilter());
    inboundRouter.addRouter(selectiveConsumerRouter);

    String endpointUri = getEndpointUri(channel.getSourceConnector());

    /*
     * NOTE: Even though every channel already has a VM Connector, we still
     * need to add a Channel Reader connector because of its possible
     * additional properties like "respond from". If a channel reader is
     * being used, add the channel id to the endpointUri so the endpoint can
     * be deployed.
     * 
     * Set the endpoint name to the channelId so
     * InboundMessageRouter#route(UMOEvent event) gets the right channel id.
     */
    if (endpointUri.equals("vm://")) {
        endpointUri += channel.getId();
        endpoint.setName(channel.getId());
        endpoint.setCreateConnector(1);
    } else {
        // add source endpoints
        MuleEndpoint vmEndpoint = new MuleEndpoint();
        vmEndpoint.setEndpointURI(new MuleEndpointURI(new URI("vm://" + channel.getId()).toString()));
        vmEndpoint.setTransformer(preprocessorTransformer);

        /*
         * XXX: Set create connector to true so that channel readers will
         * not use an existing connector (one from a different channel). Not
         * entirely sure why this is required, but if this is set to 0 then
         * a VM EndpointService mbean is created, and when undeploying
         * channels a null pointer is sometimes thrown when calling
         * unregisterComponent(descriptor). The error occurs in
         * AbstractConnector.unregisterListener because receivers is null.
         */
        vmEndpoint.setCreateConnector(1);
        inboundRouter.addEndpoint(vmEndpoint);
    }

    endpoint.setEndpointURI(new MuleEndpointURI(endpointUri, channel.getId()));

    /*
     * MUST BE LAST STEP: Add the source connector last so that if an
     * exception occurs (like creating the URI) it wont register the JMX
     * service.
     * 
     * If there are any exceptions registering the connector, still add the
     * endpoint and inbound router so that the channel can be properly
     * unregistered.
     */
    try {
        endpoint.setConnector(registerConnector(channel.getSourceConnector(),
                getConnectorNameForRouter(connectorReference), channel.getId()));
    } catch (Exception e) {
        exceptionRegisteringInboundRouter = e;
    }

    inboundRouter.addEndpoint(endpoint);

    descriptor.setInboundRouter(inboundRouter);

    if (exceptionRegisteringInboundRouter != null) {
        throw exceptionRegisteringInboundRouter;
    }
}

From source file:org.talend.tql.bean.BeanPredicateVisitor.java

private Method[] getMethods(String field) {
    StringTokenizer tokenizer = new StringTokenizer(field, ".");
    List<String> methodNames = new ArrayList<>();
    while (tokenizer.hasMoreTokens()) {
        methodNames.add(tokenizer.nextToken());
    }/*from   w w w .  j av  a2s  . c o  m*/

    Class currentClass = targetClass;
    LinkedList<Method> methods = new LinkedList<>();
    for (String methodName : methodNames) {
        if ("_class".equals(methodName)) {
            try {
                methods.add(Class.class.getMethod("getClass"));
                methods.add(Class.class.getMethod("getName"));
            } catch (NoSuchMethodException e) {
                throw new IllegalArgumentException("Unable to get methods for class' name.", e);
            }
        } else {
            String[] getterCandidates = new String[] { "get" + WordUtils.capitalize(methodName), //
                    methodName, //
                    "is" + WordUtils.capitalize(methodName) };

            final int beforeFind = methods.size();
            for (String getterCandidate : getterCandidates) {
                try {
                    methods.add(currentClass.getMethod(getterCandidate));
                    break;
                } catch (Exception e) {
                    LOGGER.debug("Can't find getter '{}'.", field, e);
                }
            }
            if (beforeFind == methods.size()) {
                throw new UnsupportedOperationException("Can't find getter '" + field + "'.");
            } else {
                currentClass = methods.getLast().getReturnType();
            }
        }
    }
    return methods.toArray(new Method[0]);
}

From source file:ch.icclab.cyclops.services.iaas.openstack.resource.impl.TelemetryResource.java

/**
 * In this method, usage made is calculated on per resource basis in the cumulative meters
 * <p/>/*  www .  ja  v a2s . c o m*/
 * Pseudo Code<br/>
 * 1. Traverse through the linkedlist<br/>
 * 2. Treat the first point subtracting the last inserted value to the current point one.<br/>
 * 3. Treat the N points with the last volumes.<br/>
 * 4. Add the updates sample object into an arraylist
 *
 * @param cMeterArr  This is an arrayList of type CumulativeMeterData containing sample object with the usage information
 * @param linkedList This is a Linked List of type CumulativeMeterData containing elements from a particular resource
 * @return An arrayList of type CumulativeMeterData containing sample objects with the usage information
 */
private ArrayList<CumulativeMeterData> calculateCumulativeMeterUsage(ArrayList<CumulativeMeterData> cMeterArr,
        LinkedList<CumulativeMeterData> linkedList) {
    logger.trace(
            "BEGIN ArrayList<CumulativeMeterData> calculateCumulativeMeterUsage(ArrayList<CumulativeMeterData> cMeterArr, LinkedList<CumulativeMeterData> linkedList)");
    long diff;
    //BigInteger maxMeterValue ;

    long oldVolume = 0;
    long newVolume;
    long lastUsage = 0;
    TSDBResource dbResource = new TSDBResource();
    for (int i = 0; i < linkedList.size(); i++) {
        if (i == 0) {
            //First point Treatment
            oldVolume = dbResource.getLastVolume(linkedList.get(i).getMeter(),
                    linkedList.get(i).getResource_id(), linkedList.get(i).getUser_id());
        } else
            //N point Treatment
            oldVolume = lastUsage;
        newVolume = linkedList.get(i).getVolume();
        if (newVolume >= oldVolume) {
            //Normal use case where the new usage is greater or equals than the last inserted point.
            //TODO: what if the value is higher but it's coz the counter reset and get higher? (if we have message queues or event based and they advise before reset, that's solved
            lastUsage = newVolume - oldVolume;
        } else {
            //TODO: if the volume is lower than the lastInserted get the maximum for that meter and operate on it.
            lastUsage = newVolume;
        }
        linkedList.get(i).setUsage(lastUsage);
        cMeterArr.add(linkedList.get(i));
    }
    cMeterArr.add(linkedList.getLast());
    logger.trace(
            "END ArrayList<CumulativeMeterData> calculateCumulativeMeterUsage(ArrayList<CumulativeMeterData> cMeterArr, LinkedList<CumulativeMeterData> linkedList)");
    return cMeterArr;
}

From source file:org.alfresco.web.forms.xforms.Schema2XForms.java

public static void removePrototypeNodes(final Node instanceDocumentElement) {
    final Map<String, LinkedList<Element>> prototypes = new HashMap<String, LinkedList<Element>>();
    final NodeList children = instanceDocumentElement.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        if (!(children.item(i) instanceof Element)) {
            continue;
        }/*from   w  w  w .j  a v  a2 s  .  c  o  m*/
        final String nodeName = children.item(i).getNodeName();
        if (!prototypes.containsKey(nodeName)) {
            prototypes.put(nodeName, new LinkedList<Element>());
        }
        prototypes.get(nodeName).add((Element) children.item(i));
    }

    for (LinkedList<Element> l : prototypes.values()) {
        for (Element e : l) {
            if (e.hasAttributeNS(NamespaceService.ALFRESCO_URI, "prototype")) {
                assert "true".equals(e.getAttributeNS(NamespaceService.ALFRESCO_URI, "prototype"));
                e.removeAttributeNS(NamespaceService.ALFRESCO_URI, "prototype");

                if (l.getLast().equals(e)) {
                    e.getParentNode().removeChild(e);
                }
            }
            if (e.getParentNode() != null) {
                Schema2XForms.removePrototypeNodes(e);
            }
        }
    }
}

From source file:nl.strohalm.cyclos.controls.accounts.transfertypes.EditTransferTypeAction.java

private void processAuthorizationLevels(final HttpServletRequest request, final TransferType transferType) {
    if (transferType.isRequiresAuthorization()) {
        final Collection<AuthorizationLevel> rawAuthorizationLevels = transferType.getAuthorizationLevels();
        final LinkedList<AuthorizationLevel> authorizationLevels = new LinkedList<AuthorizationLevel>(
                rawAuthorizationLevels);
        request.setAttribute("authorizationLevels", authorizationLevels);
        boolean insertNewLevel = false;
        Collection<AuthorizationLevel.Authorizer> possibleAuthorizers = null;
        if (CollectionUtils.isEmpty(authorizationLevels)) {
            insertNewLevel = true;/*w  ww  .  ja  v  a 2 s.  c o m*/
            if (transferType.isFromSystem() && transferType.isToSystem()) {
                possibleAuthorizers = Arrays.asList(AuthorizationLevel.Authorizer.ADMIN);
            } else if (transferType.isFromSystem() && transferType.isToMember()) {
                possibleAuthorizers = Arrays.asList(AuthorizationLevel.Authorizer.ADMIN,
                        AuthorizationLevel.Authorizer.RECEIVER);
            } else if (transferType.isToSystem()) {
                possibleAuthorizers = Arrays.asList(AuthorizationLevel.Authorizer.BROKER,
                        AuthorizationLevel.Authorizer.ADMIN);
            } else {
                possibleAuthorizers = Arrays.asList(AuthorizationLevel.Authorizer.RECEIVER,
                        AuthorizationLevel.Authorizer.BROKER, AuthorizationLevel.Authorizer.ADMIN);
            }
        } else {
            RequestHelper.storeEnum(request, AuthorizationLevel.Authorizer.class, "authorizers");
            final AuthorizationLevel highestAuthorizationLevel = authorizationLevels.getLast();
            if ((highestAuthorizationLevel.getAuthorizer() == AuthorizationLevel.Authorizer.RECEIVER)) {
                if (transferType.isFromSystem()) {
                    possibleAuthorizers = Arrays.asList(AuthorizationLevel.Authorizer.ADMIN,
                            AuthorizationLevel.Authorizer.RECEIVER);
                } else {
                    possibleAuthorizers = Arrays.asList(AuthorizationLevel.Authorizer.PAYER,
                            AuthorizationLevel.Authorizer.BROKER, AuthorizationLevel.Authorizer.ADMIN);
                }
            } else {
                possibleAuthorizers = Arrays.asList(AuthorizationLevel.Authorizer.ADMIN);
            }
            final Integer highestLevel = highestAuthorizationLevel.getLevel();
            insertNewLevel = (highestLevel < AuthorizationLevel.MAX_LEVELS);
        }
        request.setAttribute("insertNewLevel", insertNewLevel);
        if (insertNewLevel) {
            request.setAttribute("possibleAuthorizers", possibleAuthorizers);
        }
    }
}

From source file:org.nuxeo.elasticsearch.query.NxqlQueryConverter.java

public static QueryBuilder toESQueryBuilder(final String nxql, final CoreSession session) {
    final LinkedList<ExpressionBuilder> builders = new LinkedList<>();
    SQLQuery nxqlQuery = getSqlQuery(nxql);
    if (session != null) {
        nxqlQuery = addSecurityPolicy(session, nxqlQuery);
    }/*from  w  ww  .  ja  v a 2s  .c o  m*/
    final ExpressionBuilder ret = new ExpressionBuilder(null);
    builders.add(ret);
    final ArrayList<String> fromList = new ArrayList<>();
    nxqlQuery.accept(new DefaultQueryVisitor() {

        private static final long serialVersionUID = 1L;

        @Override
        public void visitFromClause(FromClause node) {
            FromList elements = node.elements;
            SchemaManager schemaManager = Framework.getLocalService(SchemaManager.class);

            for (int i = 0; i < elements.size(); i++) {
                String type = elements.get(i);
                if (NXQLQueryMaker.TYPE_DOCUMENT.equalsIgnoreCase(type)) {
                    // From Document means all doc types
                    fromList.clear();
                    return;
                }
                Set<String> types = schemaManager.getDocumentTypeNamesExtending(type);
                if (types != null) {
                    fromList.addAll(types);
                }
            }
        }

        @Override
        public void visitMultiExpression(MultiExpression node) {
            for (Iterator<Operand> it = node.values.iterator(); it.hasNext();) {
                it.next().accept(this);
                if (it.hasNext()) {
                    node.operator.accept(this);
                }
            }
        }

        @Override
        public void visitSelectClause(SelectClause node) {
            // NOP
        }

        @Override
        public void visitExpression(Expression node) {
            Operator op = node.operator;
            if (op == Operator.AND || op == Operator.OR || op == Operator.NOT) {
                builders.add(new ExpressionBuilder(op.toString()));
                super.visitExpression(node);
                ExpressionBuilder expr = builders.removeLast();
                if (!builders.isEmpty()) {
                    builders.getLast().merge(expr);
                }
            } else {
                Reference ref = node.lvalue instanceof Reference ? (Reference) node.lvalue : null;
                String name = ref != null ? ref.name : node.lvalue.toString();
                String value = null;
                if (node.rvalue instanceof Literal) {
                    value = ((Literal) node.rvalue).asString();
                } else if (node.rvalue != null) {
                    value = node.rvalue.toString();
                }
                Object[] values = null;
                if (node.rvalue instanceof LiteralList) {
                    LiteralList items = (LiteralList) node.rvalue;
                    values = new Object[items.size()];
                    int i = 0;
                    for (Literal item : items) {
                        values[i++] = item.asString();
                    }
                }
                // add expression to the last builder
                EsHint hint = (ref != null) ? ref.esHint : null;
                builders.getLast()
                        .add(makeQueryFromSimpleExpression(op.toString(), name, value, values, hint, session));
            }
        }
    });
    QueryBuilder queryBuilder = ret.get();
    if (!fromList.isEmpty()) {
        return QueryBuilders.boolQuery().must(queryBuilder).filter(makeQueryFromSimpleExpression("IN",
                NXQL.ECM_PRIMARYTYPE, null, fromList.toArray(), null, null).filter);
    }
    return queryBuilder;
}