Collect the values for this query and store them as {@link QueryResult} in the {@linkplain Query#queryResults} queue
776512
@Override
    public void collectMetrics() {
        long nanosBefore = System.nanoTime();
        /*
         * Optimisation tip: no need to skip 'mbeanServer.queryNames()' if the ObjectName is not a pattern
         * (i.e. not '*' or '?' wildcard) because the mbeanserver internally performs the check.
         * Seen on com.sun.jmx.interceptor.DefaultMBeanServerInterceptor
         */
        Set<ObjectName> matchingObjectNames = embeddedJmxTrans.getMbeanServer().queryNames(this.objectName, null);
        logger.trace("Query {} returned {}", objectName, matchingObjectNames);

        for (ObjectName matchingObjectName : matchingObjectNames) {
            long epochInMillis = System.currentTimeMillis();
            try {
                AttributeList jmxAttributes = embeddedJmxTrans.getMbeanServer().getAttributes(matchingObjectName, this.attributeNames);
                logger.trace("Query {} returned {}", matchingObjectName, jmxAttributes);
                for (Attribute jmxAttribute : jmxAttributes.asList()) {
                    QueryAttribute queryAttribute = this.attributesByName.get(jmxAttribute.getName());
                    Object value = jmxAttribute.getValue();
                    int count = queryAttribute.collectMetrics(matchingObjectName, value, epochInMillis, this.queryResults);
                    collectedMetricsCount.addAndGet(count);
                }
            } catch (Exception e) {
                logger.warn("Exception processing query {}", this, e);
            }
        }
        collectionCount.incrementAndGet();
        long nanosAfter = System.nanoTime();
        collectionDurationInNanos.addAndGet(nanosAfter - nanosBefore);
    }
472890
private function setResultRows()
    {
        $this->query->select($this->columnsToSelect);
        $this->resultRows = $this->query->get();
    }
1086013
@Override
    public void evaluate(TupleQueryResultHandler resultHandler) throws QueryEvaluationException, TupleQueryResultHandlerException {
        try {
            sync();
        } catch (MarkLogicSesameException e) {
            logger.info(e.getLocalizedMessage());
            throw new QueryEvaluationException(e);
        }
        TupleQueryResult queryResult = evaluate();
        if(queryResult.hasNext()) {
            QueryResults.report(queryResult, resultHandler);
        }
        queryResult.close();
    }
612107
def _prepare_results(self, results):
        
        # if we want a result sorted by a score, and if we have a full result
        # (no slice), we can do it know, by creating keys for each values with
        # the sorted set score, and sort on them
        if self._sort_by_sortedset_after and (len(results) > 1 or self._values):
            conn = self.cls.get_connection()

            sort_params = {}
            base_tmp_key, tmp_keys = self._prepare_sort_by_score(results, sort_params)

            # compose the set to sort
            final_set = '%s_final_set' % base_tmp_key
            conn.sadd(final_set, *results)

            # apply the sort
            results = conn.sort(final_set, **sort_params)

            # finally delete all temporary keys
            conn.delete(*(tmp_keys + [final_set, base_tmp_key]))

        if self._store:
            # if store, redis doesn't return result, so don't return anything here
            return

        if self._values and self._values['mode'] != 'flat':
            results = self._to_values(results)

        return super(ExtendedCollectionManager, self)._prepare_results(results)
317048
function() {
			if (this._aQueryResultNames) {
				return this._aQueryResultNames;
			}

			this._aQueryResultNames = new Array(0);

			for ( var sName in this._oQueryResultSet) {
				this._aQueryResultNames.push(this._oQueryResultSet[sName].getName());
			}

			return this._aQueryResultNames;
		}
1133193
protected List<T> currentResults() {
        return results == null ? Collections.emptyList()
            : Collections.unmodifiableList(results);
    }
938471
private void returnResults() {
    final StringBuilder sb = new StringBuilder();
    for (final String result : this.results) {
      sb.append(result);
    }
    this.results.clear();
    LOG.log(Level.INFO, "Return results to the client:\n{0}", sb);
    httpCallbackHandler.onNext(CODEC.encode(sb.toString()));
  }
627087
public void setResults(java.util.Collection<String> results) {
        if (results == null) {
            this.results = null;
            return;
        }

        this.results = new com.amazonaws.internal.SdkInternalList<String>(results);
    }
996332
private void releaseResultset() {
		TableModel model = tblQueryResult.getModel();
		if (model == null)
			return;
		if (!(model instanceof IncrementalResultSetTableModel))
			return;
		IncrementalResultSetTableModel imodel = (IncrementalResultSetTableModel) model;
		imodel.close();
	}
391564
private void runQuery() {
		if(this.rowKeysList != null && this.rowKeysList.size() > 0) { // Check if there are rowkeys to query Cassandra
			if (threadCount > 1) { // When thread count greater than 1 enables parallelism, use threads to query Cassandra
				// multiple times
				
				ExecutorService executor = Executors
						.newFixedThreadPool(threadCount);
				List<Future<?>> futures = new LinkedList<Future<?>>();

				for (final List<K> param : this.rowKeysList) {
					Future<?> future = executor.submit(new Runnable() {
						public void run() {
							// Query Cassandra with the input keys provided
							runMultigetSliceQuery(param); 
							
						}
					});

					futures.add(future);
				}

				for (Future<?> f : futures) {// iterate through thread results
					try {
						f.get(); // wait for thread to complete

					} catch (InterruptedException e) {
						throw new HectorException("Failed to retrieve rows from Cassandra.",e);
					} 
					catch (ExecutionException e) {
						throw new HectorException("Failed to retrieve rows from Cassandra.",e);
					} 
				}
				// Safe to shutdown the threadpool and release the resources
				executor.shutdown(); 

				// set the rowKeysIndex to size of input keys so as no further calls
				// will be made to Cassandra.
				// This ensures iterator.hasNext() returns false when all keys are
				// queried
				rowKeysIndex = this.rowKeysList.size();

			}
			else {// When thread count less than or equal to 1 (0 or negative) disables
				// parallelism, set of(maxRowCountPerQuery) keys queries
				// Cassandra at a time
			
				runMultigetSliceQuery(this.rowKeysList.get(rowKeysIndex));
				// Increment the rowKeyIndex instead of setting it to  this.rowKeysList.size(); 
				rowKeysIndex++; 
				
			}
		}

		ArrayList<Row<K, N, V>> resultList = new ArrayList<Row<K, N, V>>(queryResult.size());

		synchronized (queryResult) {
			// Ensure that runMultigetSliceQuery() method call updates global
			// variable queryResult with query result (if exists)
			if (queryResult != null && queryResult.size() > 0)	{
				for (Rows<K, N, V> rows : queryResult) {
					if (rows != null && rows.getCount() > 0) {
						for (Row<K, N, V> row : rows) {
							// prepare List<Row<K, N, V>> to return
							// the iterator of <Row<K,N,V>> to the caller
							resultList.add(row);
						}
					}

				}
			}
		}

		// assign global iterator with the result of multigetSliceQuery
		iterator = resultList.iterator(); 
										

	}
832775
@Override
  public FacetResult[] getFacetResults() {
    if (facets == null || facets.isEmpty()) {
      return new FacetResult[0];
    }
    Collection<FacetResult> facetResults = facets.values();
    return facetResults.toArray(new FacetResult[facetResults.size()]);
  }
1143831
private void generatePermutationsQueryVariables(
      ArrayList<HashMap<String, String[]>> result, Set<String> keys,
      HashMap<String, String[]> queryVariables) {
    if (keys != null && !keys.isEmpty()) {
      Set<String> newKeys = new HashSet<>();
      Iterator<String> it = keys.iterator();
      String key = it.next();
      String[] value = queryVariables.get(key);
      if (result.isEmpty()) {
        HashMap<String, String[]> newItem;
        if (value == null || value.length == 0) {
          newItem = new HashMap<>();
          newItem.put(key, value);
          result.add(newItem);
        } else {
          for (int j = 0; j < value.length; j++) {
            newItem = new HashMap<>();
            newItem.put(key, new String[] { value[j] });
            result.add(newItem);
          }
        }
      } else {
        ArrayList<HashMap<String, String[]>> newResult = new ArrayList<>();
        for (int i = 0; i < result.size(); i++) {
          HashMap<String, String[]> newItem;
          if (value == null || value.length == 0) {
            newItem = (HashMap<String, String[]>) result.get(i).clone();
            newItem.put(key, value);
            newResult.add(newItem);
          } else {
            for (int j = 0; j < value.length; j++) {
              newItem = (HashMap<String, String[]>) result.get(i).clone();
              newItem.put(key, new String[] { value[j] });
              newResult.add(newItem);
            }
          }
        }
        result.clear();
        result.addAll(newResult);
      }
      while (it.hasNext()) {
        newKeys.add(it.next());
      }
      generatePermutationsQueryVariables(result, newKeys, queryVariables);
    }
  }
771531
public java.util.List<String> getResults() {
        if (results == null) {
            results = new com.amazonaws.internal.SdkInternalList<String>();
        }
        return results;
    }
295794
public void setSqlStatementResults(java.util.Collection<SqlStatementResult> sqlStatementResults) {
        if (sqlStatementResults == null) {
            this.sqlStatementResults = null;
            return;
        }

        this.sqlStatementResults = new java.util.ArrayList<SqlStatementResult>(sqlStatementResults);
    }
222053
@Override
	public void cacheResult(List<CommercePriceEntry> commercePriceEntries) {
		for (CommercePriceEntry commercePriceEntry : commercePriceEntries) {
			if (entityCache.getResult(
						CommercePriceEntryModelImpl.ENTITY_CACHE_ENABLED,
						CommercePriceEntryImpl.class,
						commercePriceEntry.getPrimaryKey()) == null) {
				cacheResult(commercePriceEntry);
			}
			else {
				commercePriceEntry.resetOriginalValues();
			}
		}
	}
618722
public void execute(final HttpQuery query) {
    http_query = query;
    final QueryStats query_stats = 
        new QueryStats(query.getRemoteAddress(), ts_query, query.getHeaders());
    ts_query.setQueryStats(query_stats);
    
    /**
     * Sends the serialized results to the caller. This should be the very
     * last callback executed.
     */
    class CompleteCB implements Callback<Object, ChannelBuffer> {
      @Override
      public Object call(final ChannelBuffer cb) throws Exception {
        query.sendReply(cb);
        return null;
      }
    }
    
    /**
     * After all of the queries have run and we have data (or not) then we
     * need to compile the iterators.
     * This class could probably be improved:
     * First we iterate over the results AND for each result, iterate over
     * the expressions, giving a time synced iterator to each expression that 
     * needs the result set.
     * THEN we iterate over the expressions again and build a DAG to determine
     * if any of the expressions require the output of an expression. If so
     * then we add the expressions to the proper parent and compile them in
     * order.
     * After all of that we're ready to start serializing and iterating
     * over the results.
     */
    class QueriesCB implements Callback<Object, ArrayList<DataPoints[]>> {
      public Object call(final ArrayList<DataPoints[]> query_results) 
        throws Exception {
        
        for (int i = 0; i < query_results.size(); i++) {
          final TSSubQuery sub = ts_query.getQueries().get(i);
          
          Iterator<Entry<String, TSSubQuery>> it = sub_queries.entrySet().iterator();
          while (it.hasNext()) {
            final Entry<String, TSSubQuery> entry = it.next();
            if (entry.getValue().equals(sub)) {
              sub_query_results.put(entry.getKey(), query_results.get(i));
              for (final ExpressionIterator ei : expressions.values()) {
                if (ei.getVariableNames().contains(entry.getKey())) {
                  final TimeSyncedIterator tsi = new TimeSyncedIterator(
                      entry.getKey(), sub.getFilterTagKs(), 
                      query_results.get(i));
                  final NumericFillPolicy fill = fills.get(entry.getKey());
                  if (fill != null) {
                    tsi.setFillPolicy(fill);
                  }
                  ei.addResults(entry.getKey(), tsi);
                  if (LOG.isDebugEnabled()) {
                    LOG.debug("Added results for " + entry.getKey() + 
                        " to " + ei.getId());
                  }
                }
              }
            }
          }
        }

        // handle nested expressions
        final DirectedAcyclicGraph<String, DefaultEdge> graph = 
            new DirectedAcyclicGraph<String, DefaultEdge>(DefaultEdge.class);

        for (final Entry<String, ExpressionIterator> eii : expressions.entrySet()) {
          if (LOG.isDebugEnabled()) {
            LOG.debug(String.format("Expression entry key is %s, value is %s", 
                eii.getKey(), eii.getValue().toString()));
            LOG.debug(String.format("Time to loop through the variable names "
                + "for %s", eii.getKey()));
          }

          if (!graph.containsVertex(eii.getKey())) {
            if (LOG.isDebugEnabled()) {
              LOG.debug("Adding vertex " + eii.getKey());
            }
            graph.addVertex(eii.getKey());
          }

          for (final String var : eii.getValue().getVariableNames()) {
            if (LOG.isDebugEnabled()) {
              LOG.debug(String.format("var is %s", var));
            }

            final ExpressionIterator ei = expressions.get(var);

            if (ei != null) {
              if (LOG.isDebugEnabled()) {
                LOG.debug(String.format("The expression iterator for %s is %s", 
                    var, ei.toString()));
              }

              // TODO - really ought to calculate this earlier
              if (eii.getKey().equals(var)) {
                throw new IllegalArgumentException(
                    "Self referencing expression found: " + eii.getKey());
              }

              if (LOG.isDebugEnabled()) {
                LOG.debug("Nested expression detected. " + eii.getKey() + 
                    " depends on " + var);
              }

              if (!graph.containsVertex(eii.getKey())) {
                if (LOG.isDebugEnabled()) {
                  LOG.debug("Added vertex " + eii.getKey());
                }
                graph.addVertex(eii.getKey());
              } else if (LOG.isDebugEnabled()) {
                LOG.debug("Already contains vertex " + eii.getKey());
              }

              if (!graph.containsVertex(var)) {
                if (LOG.isDebugEnabled()) {
                  LOG.debug("Added vertex " + var);
                }
                graph.addVertex(var);
              } else if (LOG.isDebugEnabled()) {
                LOG.debug("Already contains vertex " + var);
              }

              try {
                if (LOG.isDebugEnabled()) {
                  LOG.debug("Added Edge " + eii.getKey() + " - " + var);
                }
                graph.addDagEdge(eii.getKey(), var);
              } catch (CycleFoundException cfe) {
                throw new IllegalArgumentException("Circular reference found: " + 
                    eii.getKey(), cfe);
              }
            } else if (LOG.isDebugEnabled()) {
              LOG.debug(String.format("The expression iterator for %s is null", var));
            }
          }
        }

        // compile all of the expressions
        final long intersect_start = DateTime.currentTimeMillis();

        final Integer expressionLength = expressions.size();
        final ExpressionIterator[] compile_stack = 
            new ExpressionIterator[expressionLength];
        final TopologicalOrderIterator<String, DefaultEdge> it = 
            new TopologicalOrderIterator<String, DefaultEdge>(graph);

        if (LOG.isDebugEnabled()) {
          LOG.debug(String.format("Expressions Size is %d", expressionLength));
          LOG.debug(String.format("Topology Iterator %s", it.toString()));
        }

        int i = 0;
        while (it.hasNext()) {
          String next = it.next();
          if (LOG.isDebugEnabled()) {
            LOG.debug(String.format("Expression: %s", next));
          }
          ExpressionIterator ei = expressions.get(next);
          if (LOG.isDebugEnabled()) {
            LOG.debug(String.format("Expression Iterator: %s", ei.toString()));
          }
          if (ei == null) {
            LOG.error(String.format("The expression iterator for %s is null", next));
          }
          compile_stack[i] = ei;
          if (LOG.isDebugEnabled()) {
            LOG.debug(String.format("Added expression %s to compile_stack[%d]", 
                next, i));
          }
          i++;
        }

        if (i != expressionLength) {
          throw new IOException(String.format(" Internal Error: Fewer "
              + "expressions where added to the compile stack than "
              + "expressions.size (%d instead of %d)", i, expressionLength));
        }

        if (LOG.isDebugEnabled()) {
          LOG.debug(String.format("compile stack length: %d", compile_stack.length));
        }

        for (int x = compile_stack.length - 1; x >= 0; x--) {
          if (compile_stack[x] == null) {
            throw new NullPointerException(String.format("Item %d in "
                + "compile_stack[] is null", x));
          }
          // look for and add expressions
          for (final String var : compile_stack[x].getVariableNames()) {
            if (LOG.isDebugEnabled()) {
              LOG.debug(String.format("Looking for variable %s for %s", var, 
                  compile_stack[x].getId()));
            }
            ExpressionIterator source = expressions.get(var);
            if (source != null) {
              compile_stack[x].addResults(var, source.getCopy());
              if (LOG.isDebugEnabled()) {
                LOG.debug(String.format("Adding expression %s to %s", 
                    source.getId(), compile_stack[x].getId()));
              }
            }
          }
          compile_stack[x].compile();
          if (LOG.isDebugEnabled()) {
            LOG.debug(String.format("Successfully compiled %s", 
                compile_stack[x].getId()));
          }
        }

        if (LOG.isDebugEnabled()) {
          LOG.debug("Finished compilations in " +
              (DateTime.currentTimeMillis() - intersect_start) + " ms");
        }
        
        return serialize()
            .addCallback(new CompleteCB())
            .addErrback(new ErrorCB());
      }
    }
    
    /**
     * Callback executed after we have resolved the metric, tag names and tag
     * values to their respective UIDs. This callback then runs the actual 
     * queries and fetches their results.
     */
    class BuildCB implements Callback<Deferred<Object>, net.opentsdb.core.Query[]> {
      @Override
      public Deferred<Object> call(final net.opentsdb.core.Query[] queries) {
        final ArrayList<Deferred<DataPoints[]>> deferreds = 
            new ArrayList<Deferred<DataPoints[]>>(queries.length);
        
        for (final net.opentsdb.core.Query query : queries) {
          deferreds.add(query.runAsync());
        }
        return Deferred.groupInOrder(deferreds).addCallback(new QueriesCB())
            .addErrback(new ErrorCB());
      }
    }
    
    // TODO - only run the ones that will be involved in an output. Folks WILL
    // ask for stuff they don't need.... *sigh*
    ts_query.buildQueriesAsync(tsdb)
      .addCallback(new BuildCB())
      .addErrback(new ErrorCB());
  }
1114324
@Override
   public final ReportDataHolderImpl collect() {
      holder = new BlockingDataHolder(dataQueueSize, queueTimeout);
      Runnable r = new collectThread();
      Thread t = new Thread(r, DATA_COLLECTOR_THREAD);
      t.setUncaughtExceptionHandler(this);
      t.start();
      return holder;
   }