Routes the request to the proper handler
@param tsdb The TSDB to which we belong
@param query The HTTP query to use for parsing and responding
498901
@Override
  public void execute(TSDB tsdb, HttpQuery query) throws IOException {
    // the uri will be /api/vX/tree/? or /api/tree/?
    final String[] uri = query.explodeAPIPath();
    final String endpoint = uri.length > 1 ? uri[1] : ""; 
    
    try {
      if (endpoint.isEmpty()) {
        handleTree(tsdb, query);
      } else if (endpoint.toLowerCase().equals("branch")) {
        handleBranch(tsdb, query);
      } else if (endpoint.toLowerCase().equals("rule")) {
        handleRule(tsdb, query);
      } else if (endpoint.toLowerCase().equals("rules")) {
        handleRules(tsdb, query);
      } else if (endpoint.toLowerCase().equals("test")) {
        handleTest(tsdb, query);
      } else if (endpoint.toLowerCase().equals("collisions")) {
        handleCollisionNotMatched(tsdb, query, true);
      } else if (endpoint.toLowerCase().equals("notmatched")) {
        handleCollisionNotMatched(tsdb, query, false);
      } else {
        throw new BadRequestException(HttpResponseStatus.NOT_FOUND, 
            "This endpoint is not supported");
      }
    } catch (BadRequestException e) {
      throw e;
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
379037
@Override
    public void handlePress(CallbackQuery query) {
        value = !value;
        executeCallback();
        setText(callback.handleToggle(this, value));
    }
416692
public UrlBuilder withQuery(String query) {
        if (query == null || query.isEmpty()) {
            this.query.clear();
        } else {
            with(query, UrlTokenizerState.QUERY);
        }
        return this;
    }
620323
public function visit($query, NodeContract $node, string $context)
    {
        if ($node instanceof Nodes\AndNode) {
            $callback = function ($q) use ($node) {
                foreach ($node->getChildren() as $child) {
                    if ($child instanceof Nodes\KeyNode || $child instanceof Nodes\ValueNode) {
                        throw new \Railken\SQ\Exceptions\QuerySyntaxException();
                    }

                    $this->getBuilder()->build($q, $child, Nodes\AndNode::class);
                }
            };

            $context === Nodes\OrNode::class && $query->orWhere($callback);
            $context === Nodes\AndNode::class && $query->where($callback);
        }
    }
1335619
@Override
    public void search(final Query query) {
        getDispatcher().invokeLater(new AsyncTask(SEARCH, listeners) {
            @Override
            public void invoke(List<TwitterListener> listeners) throws TwitterException {
                QueryResult result = twitter.search(query);
                for (TwitterListener listener : listeners) {
                    try {
                        listener.searched(result);
                    } catch (Exception e) {
                        logger.warn("Exception at search", e);
                    }
                }
            }
        });
    }
1033228
private void doGraph(final TSDB tsdb, final HttpQuery query)
    throws IOException {
    final String basepath = getGnuplotBasePath(tsdb, query);
    long start_time = DateTime.parseDateTimeString(
      query.getRequiredQueryStringParam("start"),
      query.getQueryStringParam("tz"));
    final boolean nocache = query.hasQueryStringParam("nocache");
    if (start_time == -1) {
      throw BadRequestException.missingParameter("start");
    } else {
      // temp fixup to seconds from ms until the rest of TSDB supports ms
      // Note you can't append this to the DateTime.parseDateTimeString() call as
      // it clobbers -1 results
      start_time /= 1000;
    }
    long end_time = DateTime.parseDateTimeString(
        query.getQueryStringParam("end"),
        query.getQueryStringParam("tz"));
    final long now = System.currentTimeMillis() / 1000;
    if (end_time == -1) {
      end_time = now;
    } else {
      // temp fixup to seconds from ms until the rest of TSDB supports ms
      // Note you can't append this to the DateTime.parseDateTimeString() call as
      // it clobbers -1 results
      end_time /= 1000;
    }
    final int max_age = computeMaxAge(query, start_time, end_time, now);
    if (!nocache && isDiskCacheHit(query, end_time, max_age, basepath)) {
      return;
    }

    // Parse TSQuery from HTTP query
    final TSQuery tsquery = QueryRpc.parseQuery(tsdb, query);
    tsquery.validateAndSetQuery();

    // Build the queries for the parsed TSQuery
    Query[] tsdbqueries = tsquery.buildQueries(tsdb);

    List<String> options = query.getQueryStringParams("o");
    if (options == null) {
      options = new ArrayList<String>(tsdbqueries.length);
      for (int i = 0; i < tsdbqueries.length; i++) {
        options.add("");
      }
    } else if (options.size() != tsdbqueries.length) {
      throw new BadRequestException(options.size() + " `o' parameters, but "
        + tsdbqueries.length + " `m' parameters.");
    } else {
      for (final String option : options) {
        // TODO - far from perfect, should help a little.
        if (option.contains("`") || option.contains("%60") || 
            option.contains("&#96;")) {
          throw new BadRequestException("Option contained a back-tick. "
              + "That's a no-no.");
        }
      }
    }
    for (final Query tsdbquery : tsdbqueries) {
      try {
        tsdbquery.setStartTime(start_time);
      } catch (IllegalArgumentException e) {
        throw new BadRequestException("start time: " + e.getMessage());
      }
      try {
        tsdbquery.setEndTime(end_time);
      } catch (IllegalArgumentException e) {
        throw new BadRequestException("end time: " + e.getMessage());
      }
    }
    final Plot plot = new Plot(start_time, end_time,
          DateTime.timezones.get(query.getQueryStringParam("tz")));
    setPlotDimensions(query, plot);
    setPlotParams(query, plot);
    final int nqueries = tsdbqueries.length;
    @SuppressWarnings("unchecked")
    final HashSet<String>[] aggregated_tags = new HashSet[nqueries];
    int npoints = 0;
    for (int i = 0; i < nqueries; i++) {
      try {  // execute the TSDB query!
        // XXX This is slow and will block Netty.  TODO(tsuna): Don't block.
        // TODO(tsuna): Optimization: run each query in parallel.
        final DataPoints[] series = tsdbqueries[i].run();
        for (final DataPoints datapoints : series) {
          plot.add(datapoints, options.get(i));
          aggregated_tags[i] = new HashSet<String>();
          aggregated_tags[i].addAll(datapoints.getAggregatedTags());
          npoints += datapoints.aggregatedSize();
        }
      } catch (RuntimeException e) {
        logInfo(query, "Query failed (stack trace coming): "
                + tsdbqueries[i]);
        throw e;
      }
      tsdbqueries[i] = null;  // free()
    }
    tsdbqueries = null;  // free()

    if (query.hasQueryStringParam("ascii")) {
      respondAsciiQuery(query, max_age, basepath, plot);
      return;
    }

    final RunGnuplot rungnuplot = new RunGnuplot(query, max_age, plot, basepath,
            aggregated_tags, npoints);

    class ErrorCB implements Callback<Object, Exception> {
      public Object call(final Exception e) throws Exception {
        LOG.warn("Failed to retrieve global annotations: ", e);
        throw e;
      }
    }

    class GlobalCB implements Callback<Object, List<Annotation>> {
      public Object call(final List<Annotation> global_annotations) throws Exception {
        rungnuplot.plot.setGlobals(global_annotations);
        execGnuplot(rungnuplot, query);

        return null;
      }
    }

    // Fetch global annotations, if needed
    if (!tsquery.getNoAnnotations() && tsquery.getGlobalAnnotations()) {
      Annotation.getGlobalAnnotations(tsdb, start_time, end_time)
              .addCallback(new GlobalCB()).addErrback(new ErrorCB());
    } else {
      execGnuplot(rungnuplot, query);
    }
  }
812956
async function runQuery(query, connection) {
  // Connection here doesn't actually matter.
  // Someday this mock could get fancy and change output based on some connection value
  // For now validate that it is getting passed
  const { maxRows } = connection;

  // To determine the content of this mock query, inspect values from comments
  // Example format
  // -- dimensions = department 10, color 10, product 10, orderdate|orderdatetime 500
  // -- measures = cost, revenue, profit, <anythingyouwant>
  // -- orderby = department asc, product desc
  // -- limit = 100
  const dimensions = [];
  const measures = [];
  const orderByFields = [];
  const orderByDirections = [];
  let limit;

  query
    .split('\n')
    .map(line => line.trim())
    .filter(line => line.startsWith('--'))
    .map(line => line.replace('--', ''))
    .forEach(line => {
      const [fieldType, fieldData] = line
        .split('=')
        .map(p => p.trim().toLowerCase());

      if (!fieldData) {
        return;
      }

      // fieldData is something like <fieldname> <direction>, <field2> <direction>
      // or 100
      fieldData
        .split(',')
        .map(p => p.trim())
        .forEach(part => {
          if (fieldType === 'limit') {
            limit = parseInt(part);
          } else if (fieldType === 'dimensions') {
            const [fieldName, numString] = part.split(' ').map(p => p.trim());
            if (!fieldValues[fieldName]) {
              throw new Error(
                `Unknown ${fieldName}. must be one of: ${Object.keys(
                  fieldValues
                ).join(', ')}`
              );
            }
            dimensions.push({
              name: fieldName,
              values: fieldValues[fieldName].slice(0, parseInt(numString))
            });
          } else if (fieldType === 'measures') {
            measures.push(part);
          } else if (fieldType === 'orderby') {
            const [fieldName, direction] = part.split(' ').map(p => p.trim());
            if (!direction) {
              throw new Error('direction required. Must be asc or desc');
            }
            orderByFields.push(fieldName);
            orderByDirections.push(direction);
          } else {
            throw new Error(
              `Unknown ${fieldType}. Must be dimensions, measures, orderby, or limit`
            );
          }
        });
    });

  if (!dimensions.length) {
    throw new Error('dimensions required');
  }

  // Assemble dimensions and things
  let rows = [];
  dimensions.forEach(dimension => {
    rows = cartesianify(rows, dimension);
  });

  if (measures.length) {
    rows.forEach(row => {
      measures.forEach(measure => {
        const date = row.orderdate || row.orderdatetime;
        if (date) {
          const doy = moment.utc(date).dayOfYear();
          row[measure] = 10 + Math.round(doy * Math.random());
        } else {
          row[measure] = Math.round(Math.random() * 1000);
        }
      });
    });
  }

  if (orderByFields.length) {
    rows = _.orderBy(rows, orderByFields, orderByDirections);
  }

  if (limit) {
    rows = rows.slice(0, limit);
  }

  return { rows: rows.slice(0, maxRows), incomplete: rows.length > maxRows };
}
1211380
private void handleQueries(
      final HttpServletResponse response,
      final Map<String, List<String>> queries,
      final String version) throws IOException {

    LOG.log(Level.INFO, "HttpServerReefEventHandler handleQueries is called");

    for (final Map.Entry<String, List<String>> entry : queries.entrySet()) {
      final String queryTarget = entry.getKey().toLowerCase();

      switch (queryTarget) {
      case "id":
        if (version.equals(VER)) {
          writeEvaluatorInfoJsonOutput(response, entry.getValue());
        } else {
          writeEvaluatorInfoWebOutput(response, entry.getValue());
        }
        break;
      default:
        response.getWriter().println("Unsupported query : " + queryTarget);
        break;
      }
    }
  }
742282
public boolean handle(CallbackQuery query, int button) {
        if (button < 0 || button > buttons.size()) {
            return false;
        }

        buttonAt(button).handlePress(query);
        return true;
    }
880235
public <T> T find(Query query, RsHandler<T> rsh) throws SQLException {
		Connection conn = null;
		try {
			conn = this.getConnection();
			return runner.find(conn, query, rsh);
		} catch (SQLException e) {
			throw e;
		} finally {
			this.closeConnection(conn);
		}
	}
882880
public QueryRequestBuilder<T,ID> query(QueryExpression query)
    {
        return new QueryRequestBuilder<T, ID>(version,type,entityName,query.build());
    }
1349639
public AtlasSearchResult dslSearch(final String query) throws AtlasServiceException {
        MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
        queryParams.add(QUERY, query);

        return callAPI(DSL_SEARCH, AtlasSearchResult.class, queryParams);
    }
1225859
public void setQuery(String query) throws PageException {
	this.query = Caster.toQuery(pageContext.getVariable(query));
    }
441147
public <T> T execute(final String query, final Object connection,
        final List<KunderaQuery.BindParameter> parameters) {
        throw new KunderaException("not implemented");
    }
6830
public SparqlResult runQuery(String endpoint, String query) {
    return SparqlClient.execute(endpoint, query, username, password);
  }
183555
protected void prepareQuery(org.hibernate.query.Query query) {
        if (cacheQueries) {
            query.setCacheable(true);
        }
        if (shouldPassReadOnlyToHibernate()) {
            query.setReadOnly(true);
        }
        SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
        if (sessionHolder != null && sessionHolder.hasTimeout()) {
            query.setTimeout(sessionHolder.getTimeToLiveInSeconds());
        }
    }
42031
public static void checkQuery(Query<?> query, InjectionManager manager) {
        checkQuery(query, null, null, manager);
    }