Parses a query string legacy style query from the URI
@param tsdb The TSDB we belong to
@param query The HTTP Query for parsing
@return A TSQuery if parsing was successful
@throws BadRequestException if parsing was unsuccessful
@since 2.3
507510
public static TSQuery parseQuery(final TSDB tsdb, final HttpQuery query) {
    return parseQuery(tsdb, query, null);
  }
130613
@Deprecated
    public static Map<String, Deque<String>> parseQueryString(final String newQueryString) {
        return parseQueryString(newQueryString, null);
    }
1219519
public void execute(final TSDB tsdb, final HttpQuery query) {
    // only accept GET/POST
    if (query.method() != HttpMethod.GET && query.method() != HttpMethod.POST) {
      throw new BadRequestException(HttpResponseStatus.METHOD_NOT_ALLOWED, 
          "Method not allowed", "The HTTP method [" + query.method().getName() +
          "] is not permitted for this endpoint");
    }
    
    try {
      final String[] uri = query.explodeAPIPath();
      final String endpoint = uri.length > 1 ? uri[1].toLowerCase() : "";

      // Handle /threads and /regions.
      if ("threads".equals(endpoint)) {
        printThreadStats(query);
        return;
      } else if ("jvm".equals(endpoint)) {
        printJVMStats(tsdb, query);
        return;
      } else if ("query".equals(endpoint)) {
        printQueryStats(query);
        return;
      } else if ("region_clients".equals(endpoint)) {
        printRegionClientStats(tsdb, query);
        return;
      }
    } catch (IllegalArgumentException e) {
      // this is thrown if the url doesn't start with /api. To maintain backwards
      // compatibility with the /stats endpoint we can catch and continue here.
    }
    
    final boolean canonical = tsdb.getConfig().getBoolean("tsd.stats.canonical");
    
    // if we don't have an API request we need to respond with the 1.x version
    if (query.apiVersion() < 1) {
      final boolean json = query.hasQueryStringParam("json");
      final StringBuilder buf = json ? null : new StringBuilder(2048);
      final ArrayList<String> stats = json ? new ArrayList<String>(64) : null;
      final ASCIICollector collector = new ASCIICollector("tsd", buf, stats);
      doCollectStats(tsdb, collector, canonical);
      if (json) {
        query.sendReply(JSON.serializeToBytes(stats));
      } else {
        query.sendReply(buf);
      }
      return;
    }
    
    // we have an API version, so go newschool
    final List<IncomingDataPoint> dps = new ArrayList<IncomingDataPoint>(64);
    final SerializerCollector collector = new SerializerCollector("tsd", dps, 
        canonical);
    ConnectionManager.collectStats(collector);
    RpcHandler.collectStats(collector);
    RpcManager.collectStats(collector);
    tsdb.collectStats(collector);
    query.sendReply(query.serializer().formatStatsV1(dps));
  }
671824
public static ElDescriptor analyzeQuery(final GenericsContext genericsContext, final String query) {
        final List<String> vars = ElUtils.findVars(query);
        ElDescriptor descriptor = null;
        if (!vars.isEmpty()) {
            descriptor = new ElDescriptor(vars);
            checkGenericVars(descriptor, genericsContext);
        }
        return descriptor;
    }
1290479
public static Map<String, String> queryToParams(String query) throws UnsupportedEncodingException {
		Map<String, String> query_pairs = new HashMap<String, String>();
		String[] pairs = query.split("&");
		for (String pair : pairs) {
			int idx = pair.indexOf("=");
			query_pairs.put(URLDecoder.decode(pair.substring(0, idx), "UTF-8"),
					URLDecoder.decode(pair.substring(idx + 1), "UTF-8"));
		}
		return query_pairs;
	}
960222
@Override
  public void execute(final TSDB tsdb, final HttpQuery query)
          throws IOException {
    http_requests.incrementAndGet();
    
    // only accept POST
    if (query.method() != HttpMethod.POST) {
      throw new BadRequestException(HttpResponseStatus.METHOD_NOT_ALLOWED,
          "Method not allowed", "The HTTP method [" + query.method().getName() +
          "] is not permitted for this endpoint");
    }

    final List<RollUpDataPoint> dps = query.serializer()
        .parsePutV1(RollUpDataPoint.class, HttpJsonSerializer.TR_ROLLUP);
    processDataPoint(tsdb, query, dps);
  }
454786
def raw_query(self, query, query_parameters=None):
        
        self.assert_no_raw_query()

        if len(self._where_tokens) != 0 or len(self._select_tokens) != 0 or len(
                self._order_by_tokens) != 0 or len(self._group_by_tokens) != 0:
            raise InvalidOperationException(
                "You can only use raw_query on a new query, without applying any operations "
                "(such as where, select, order_by, group_by, etc)")

        if query_parameters:
            self.query_parameters = query_parameters
        self._query = query
        return self
230468
public R textQueryString(String query, TextQueryString options) {
    peekExprList().textQueryString(query, options);
    return root;
  }
259855
private QueryBuilderKraken parseMap(QueryBuilderKraken query)
  {
    boolean distinct = false;

    Token token = scanToken();

    if (token == Token.DISTINCT)
      distinct = true;
    else
      _token = token;

    ArrayList<ExprKraken> resultItems = new ArrayList<>();

    Token startToken = scanToken();
    String startLexeme = _lexeme;
    int startOffset = _parseIndex;

    while ((token = scanToken()) != null
        && token != Token.EOF 
        && token != Token.FROM) {
    }

    if (token != Token.FROM) { 
      throw error("expected FROM at '{0}'", token);
    }

    _query = query;

    String tableName = parseFrom();

    query.setTableName(tableName);
    
    token = scanToken();
    
    Token tailToken = token;
    int tailOffset = _parseIndex;

    _token = startToken;
    _parseIndex = startOffset;
    _lexeme = startLexeme;

    ExprKraken expr = parseSelectExpr();

    resultItems.add(expr);

    while ((token = scanToken()) == Token.COMMA) {
      expr = parseSelectExpr();

      resultItems.add(expr);
    }

    _token = tailToken;
    _parseIndex = tailOffset;

    token = scanToken();
    
    ExprKraken whereExpr = null;

    if (token == Token.WHERE) {
      // _andExpr.add(parseExpr());
      whereExpr = parseExpr();
    }
    else {
      _token = token;
    }

    ParamExpr []params = _params.toArray(new ParamExpr[_params.size()]);
    
    query.setWhereExpr(whereExpr);
    // query.setKelpExpr(whereKelp);
    query.setParams(params);

    for (int i = resultItems.size() - 1; i >= 0; i--) {
      ExprKraken subExpr = resultItems.get(i);
    }

    ExprKraken []resultArray
      = resultItems.toArray(new ExprKraken[resultItems.size()]);

    query.setResults(resultArray);
    
    token = scanToken();
    
    if (token != null 
        && token != Token.EOF
        && token != Token.LIMIT 
        && token != Token.OFFSET) {
      throw error("unexpected token at end '{0}'", token);
    }

    return query;
  }
372642
public WaybackRequest parse(HttpServletRequest httpRequest, 
		AccessPoint wbContext) throws BadQueryException {
		
		WaybackRequest wbRequest = null;
		@SuppressWarnings("unchecked")
		Map<String,String[]> queryMap = httpRequest.getParameterMap();
		String query = AccessPoint.getMapParam(queryMap, SEARCH_QUERY);
		if (query == null) {
			return null;
		}
		wbRequest = new WaybackRequest();
		
		String base = wbContext.translateRequestPath(httpRequest);
		if (base.startsWith(REPLAY_BASE)) {
			wbRequest.setReplayRequest();
		} else if(base.startsWith(QUERY_BASE)){
			wbRequest.setCaptureQueryRequest();
		} else if(base.startsWith(XQUERY_BASE)){
			wbRequest.setCaptureQueryRequest();
			wbRequest.setXMLMode(true);
			
		} else {
			return null;
		}
		
		String numResults = AccessPoint.getMapParam(queryMap, SEARCH_RESULTS);
		String startPage = AccessPoint.getMapParam(queryMap, START_PAGE);

		if (numResults != null) {
			int nr = Integer.parseInt(numResults);
			wbRequest.setResultsPerPage(nr);
		} else {
			wbRequest.setResultsPerPage(getMaxRecords());
		}
		if (startPage != null) {
			int sp = Integer.parseInt(startPage);
			wbRequest.setPageNum(sp);
		} else {
			wbRequest.setPageNum(1);
		}

		// first try the entire line_tokens:
		for (int i = 0; i < lineTokens.length; i++) {
			String token = lineTokens[i] + ":";
			int index = query.indexOf(token);
			if (index > -1) {
				// found it, take value as the remainder of the query
				String value = query.substring(index + token.length());
				// TODO: trim trailing whitespace?
				wbRequest.put(lineTokens[i], value);
				query = query.substring(0, index);
			}
		}

		// now split whatever is left on whitespace:
		String[] parts = WHITESPACE_PATTERN.split(query);
		for (int i = 0; i < parts.length; i++) {
			String token = parts[i];
			int colonIndex = token.indexOf(":");
			if (colonIndex == -1) {
				throw new BadQueryException("Bad search token(" + token + ")");
			}
			try {
				String key = URLDecoder.decode(token.substring(0, colonIndex),
						"UTF-8");
				String value = URLDecoder.decode(
						token.substring(colonIndex + 1), "UTF-8");
				// TODO: make sure key is in singleTokens?
				// let's just let em all thru for now:
				wbRequest.put(key, value);
			} catch (UnsupportedEncodingException e) {
				throw new BadQueryException("Unsupported encoding: UTF-8");
			}
		}
		if (wbRequest.getStartTimestamp() == null) {
			wbRequest.setStartTimestamp(getEarliestTimestamp());
		}
		if (wbRequest.getEndTimestamp() == null) {
			wbRequest.setEndTimestamp(getLatestTimestamp());
		}

		return wbRequest;
	}
221943
function querystring(query) {
  var parser = /([^=?&]+)=?([^&]*)/g
    , result = {}
    , part;

  while (part = parser.exec(query)) {
    var key = decode(part[1])
      , value = decode(part[2]);

    //
    // Prevent overriding of existing properties. This ensures that build-in
    // methods like `toString` or __proto__ are not overriden by malicious
    // querystrings.
    //
    if (key in result) continue;
    result[key] = value;
  }

  return result;
}
455868
@Override
    public MongodbQueryResult build(String query) throws IOException, ParserNotFoundException {
        DBObject result = (DBObject) super.parse(query);
        return new MongodbQueryResult(query, result);
    }
462545
private String getTSUIDForMetric(final String query_string, TSDB tsdb) {
    if (query_string == null || query_string.isEmpty()) {
      throw new BadRequestException("The query string was empty");
    }
    
    // m is of the following forms:
    // metric[{tag=value,...}]
    // where the parts in square brackets `[' .. `]' are optional.
    final HashMap<String, String> tags = new HashMap<String, String>();
    String metric = null;
    try {
      metric = Tags.parseWithMetric(query_string, tags);
    } catch (IllegalArgumentException e) {
      throw new BadRequestException(e);
    }
    
    // sort the UIDs on tagk values
    final ByteMap<byte[]> tag_uids = new ByteMap<byte[]>();
    for (final Entry<String, String> pair : tags.entrySet()) {
      tag_uids.put(tsdb.getUID(UniqueIdType.TAGK, pair.getKey()), 
          tsdb.getUID(UniqueIdType.TAGV, pair.getValue()));
    }
    
    // Byte Buffer to generate TSUID, pre allocated to the size of the TSUID
    final ByteArrayOutputStream buf = new ByteArrayOutputStream(
        TSDB.metrics_width() + tag_uids.size() * 
        (TSDB.tagk_width() + TSDB.tagv_width()));
    try {
      buf.write(tsdb.getUID(UniqueIdType.METRIC, metric));
      for (final Entry<byte[], byte[]> uids: tag_uids.entrySet()) {
        buf.write(uids.getKey());
        buf.write(uids.getValue());
      }
    } catch (IOException e) {
      throw new BadRequestException(e);
    }
    final String tsuid = UniqueId.uidToString(buf.toByteArray());
    
    return tsuid;
  }
874100
function parseQueryString(query) {
  if (!query) {
    return {};
  }
  return (/^[?#]/.test(query) ? query.slice(1) : query)
      .split('&')
      .reduce((params, param) => {
        const item = param.split('=');
        const key = decodeURIComponent(item[0] || '');
        const value = decodeURIComponent(item[1] || '');
        if (key) {
          params[key] = value;
        }
        return params;
      }, {});
}
641282
public String query(String query) {
        try {
            Connection conn = this.tx().getConnection();
            ObjectNode result = this.mapper.createObjectNode();
            ArrayNode dataNode = this.mapper.createArrayNode();
            ArrayNode metaNode = this.mapper.createArrayNode();
            Statement statement = conn.createStatement();
            if (logger.isDebugEnabled()) {
                logger.debug(query);
            }
            ResultSet rs = statement.executeQuery(query);
            ResultSetMetaData rsmd = rs.getMetaData();
            boolean first = true;
            while (rs.next()) {
                int numColumns = rsmd.getColumnCount();
                ObjectNode obj = this.mapper.createObjectNode();
                for (int i = 1; i < numColumns + 1; i++) {
                    String columnName = rsmd.getColumnLabel(i);
                    int type = rsmd.getColumnType(i);
                    //make sure to obtain array using getArray()
                    //At least in H2, this makes a difference...
                    Object o = type == Types.ARRAY ? rs.getArray(i) : rs.getObject(i);
                    this.sqlDialect.putJsonObject(obj, columnName, type, o);
                    if (first) {
                        this.sqlDialect.putJsonMetaObject(this.mapper, metaNode, columnName, type, o);
                    }
                }
                first = false;
                dataNode.add(obj);
            }
            result.set("data", dataNode);
            result.set("meta", metaNode);
            return result.toString();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            this.tx().rollback();
        }
    }
126114
private void handleExpressionQuery(final TSDB tsdb, final HttpQuery query) {
    final net.opentsdb.query.pojo.Query v2_query = 
        JSON.parseToObject(query.getContent(), net.opentsdb.query.pojo.Query.class);
    v2_query.validate();

    checkAuthorization(tsdb, query.channel(), v2_query);

    final QueryExecutor executor = new QueryExecutor(tsdb, v2_query);
    executor.execute(query);
  }
311600
public static QueryType getQueryType(String query) {

        final String trimmedQuery = removeCommentAndWhiteSpace(query);
        if (trimmedQuery == null || trimmedQuery.length() < 1) {
            return QueryType.OTHER;
        }

        final char firstChar = trimmedQuery.charAt(0);
        final QueryType type;
        switch (firstChar) {
            case 'S':
            case 's':
                type = QueryType.SELECT;
                break;
            case 'I':
            case 'i':
                type = QueryType.INSERT;
                break;
            case 'U':
            case 'u':
                type = QueryType.UPDATE;
                break;
            case 'D':
            case 'd':
                type = QueryType.DELETE;
                break;
            default:
                type = QueryType.OTHER;
        }
        return type;
    }