Used with verb overrides to parse out values from a query string
@param query The query to parse
@return An TSMeta object with configured values
@throws BadRequestException if a required value was missing or could not
be parsed
542296
private TSMeta parseTSMetaQS(final HttpQuery query) {
    final String tsuid = query.getQueryStringParam("tsuid");
    final TSMeta meta;
    if (tsuid != null && !tsuid.isEmpty()) {
      meta = new TSMeta(tsuid);
    } else {
      meta = new TSMeta();
    }
    
    final String display_name = query.getQueryStringParam("display_name");
    if (display_name != null) {
      meta.setDisplayName(display_name);
    }
  
    final String description = query.getQueryStringParam("description");
    if (description != null) {
      meta.setDescription(description);
    }
    
    final String notes = query.getQueryStringParam("notes");
    if (notes != null) {
      meta.setNotes(notes);
    }
    
    final String units = query.getQueryStringParam("units");
    if (units != null) {
      meta.setUnits(units);
    }
    
    final String data_type = query.getQueryStringParam("data_type");
    if (data_type != null) {
      meta.setDataType(data_type);
    }
    
    final String retention = query.getQueryStringParam("retention");
    if (retention != null && !retention.isEmpty()) {
      try {
        meta.setRetention(Integer.parseInt(retention));
      } catch (NumberFormatException nfe) {
        throw new BadRequestException("Unable to parse 'retention' value");
      }
    }
    
    final String max = query.getQueryStringParam("max");
    if (max != null && !max.isEmpty()) {
      try {
        meta.setMax(Float.parseFloat(max));
      } catch (NumberFormatException nfe) {
        throw new BadRequestException("Unable to parse 'max' value");
      }
    }
    
    final String min = query.getQueryStringParam("min");
    if (min != null && !min.isEmpty()) {
      try {
        meta.setMin(Float.parseFloat(min));
      } catch (NumberFormatException nfe) {
        throw new BadRequestException("Unable to parse 'min' value");
      }
    }
    
    return meta;
  }
85855
private void printQueryStats(final HttpQuery query) {
    switch (query.apiVersion()) {
    case 0:
    case 1:
      query.sendReply(query.serializer().formatQueryStatsV1(
          QueryStats.getRunningAndCompleteStats()));
      break;
    default: 
      throw new BadRequestException(HttpResponseStatus.NOT_IMPLEMENTED, 
          "Requested API version not implemented", "Version " + 
          query.apiVersion() + " is not implemented");
    }
  }
441356
public WaybackRequest parse(HttpServletRequest httpRequest, 
			AccessPoint wbContext) throws BadQueryException, BetterRequestException {

		WaybackRequest wbRequest = null;

		for(int i = 0; i < parsers.length; i++) {
			wbRequest = parsers[i].parse(httpRequest, wbContext);
			if(wbRequest != null) {
				break;
			}
		}
		return wbRequest;
	}
262865
public TSQuery parseQueryV1() {
    final String json = query.getContent();
    if (json == null || json.isEmpty()) {
      throw new BadRequestException(HttpResponseStatus.BAD_REQUEST,
          "Missing message content",
          "Supply valid JSON formatted data in the body of your request");
    }
    try {
      TSQuery data_query =  JSON.parseToObject(json, TSQuery.class);
      // Filter out duplicate queries
      Set<TSSubQuery> query_set = new LinkedHashSet<TSSubQuery>(data_query.getQueries());
      data_query.getQueries().clear();
      data_query.getQueries().addAll(query_set);
      return data_query;
    } catch (IllegalArgumentException iae) {
      throw new BadRequestException("Unable to parse the given JSON", iae);
    }
  }
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));
  }
1076410
private TreeRule parseRule(HttpQuery query) {
    final TreeRule rule = new TreeRule(parseTreeId(query, true));
    
    if (query.hasQueryStringParam("type")) {
      try {
        rule.setType(TreeRule.stringToType(query.getQueryStringParam("type")));
      } catch (IllegalArgumentException e) {
        throw new BadRequestException("Unable to parse the 'type' parameter", e);
      }
    }
    if (query.hasQueryStringParam("field")) {
      rule.setField(query.getQueryStringParam("field"));
    }
    if (query.hasQueryStringParam("custom_field")) {
      rule.setCustomField(query.getQueryStringParam("custom_field"));
    }
    if (query.hasQueryStringParam("regex")) {
      try {
        rule.setRegex(query.getQueryStringParam("regex"));
      } catch (PatternSyntaxException e) {
        throw new BadRequestException(
            "Unable to parse the 'regex' parameter", e);
      }
    }
    if (query.hasQueryStringParam("separator")) {
      rule.setSeparator(query.getQueryStringParam("separator"));
    }
    if (query.hasQueryStringParam("description")) {
      rule.setDescription(query.getQueryStringParam("description"));
    }
    if (query.hasQueryStringParam("notes")) {
      rule.setNotes(query.getQueryStringParam("notes"));
    }
    if (query.hasQueryStringParam("regex_group_idx")) {
      try {
        rule.setRegexGroupIdx(Integer.parseInt(
            query.getQueryStringParam("regex_group_idx")));
      } catch (NumberFormatException e) {
        throw new BadRequestException(
            "Unable to parse the 'regex_group_idx' parameter", e);
      }
    }
    if (query.hasQueryStringParam("display_format")) {
      rule.setDisplayFormat(query.getQueryStringParam("display_format"));
    }
    //if (query.hasQueryStringParam("level")) {
      try {
        rule.setLevel(Integer.parseInt(
            query.getRequiredQueryStringParam("level")));
      } catch (NumberFormatException e) {
        throw new BadRequestException(
            "Unable to parse the 'level' parameter", e);
      }
    //}
    //if (query.hasQueryStringParam("order")) {
      try {
        rule.setOrder(Integer.parseInt(
            query.getRequiredQueryStringParam("order")));
      } catch (NumberFormatException e) {
        throw new BadRequestException(
            "Unable to parse the 'order' parameter", e);
      }
    //}
    return rule;
  }
310512
public WaybackRequest parse(HttpServletRequest httpRequest,
			AccessPoint wbContext) throws BadQueryException {
		
		WaybackRequest wbRequest = null;
		String server = httpRequest.getServerName() + 
			":" + httpRequest.getServerPort();
		if(server.toLowerCase().endsWith(hostPort.toLowerCase())) {
			int length = server.length() - hostPort.length();
			if(server.length() > hostPort.length()) {
				String prefix = server.substring(0,length - 1);
				Matcher replayMatcher = REPLAY_REGEX.matcher(prefix);
				if (replayMatcher != null && replayMatcher.matches()) {
					wbRequest = new WaybackRequest();
					String dateStr = replayMatcher.group(1);
					String host = replayMatcher.group(2);

					String requestUrl = getRequestString(host,httpRequest);

					wbRequest.setReplayRequest();
					wbRequest.setReplayTimestamp(dateStr);
					wbRequest.setRequestUrl(requestUrl);

				} else {
					Matcher queryMatcher = QUERY_REGEX.matcher(prefix);
					if(queryMatcher != null && queryMatcher.matches()) {
						wbRequest = new WaybackRequest();
						String dateStr = queryMatcher.group(1);
						String host = queryMatcher.group(2);

						String requestUrl = getRequestString(host,httpRequest);

						String startDate;
						String endDate;
						if(dateStr.length() == 0) {
							startDate = getEarliestTimestamp();
							endDate = getLatestTimestamp();
						} else {
							startDate = Timestamp.parseBefore(dateStr).getDateStr();
							endDate = Timestamp.parseAfter(dateStr).getDateStr();
						}
						wbRequest.setCaptureQueryRequest();
						wbRequest.setStartTimestamp(startDate);
						wbRequest.setEndTimestamp(endDate);
						wbRequest.setRequestUrl(requestUrl);
					}
					// TODO: what if it doesn't match the QUERY_REGEX?
					//       throw a BadQueryException?
				}
			}
		}
		return wbRequest;
	}
682463
private final SearchQuery parseQueryString(final HttpQuery query, 
      final SearchType type) {
    final SearchQuery search_query = new SearchQuery();
    
    if (type == SearchType.LOOKUP) {
      final String query_string = query.getRequiredQueryStringParam("m");
      search_query.setTags(new ArrayList<Pair<String, String>>());
      
      try {
      search_query.setMetric(Tags.parseWithMetric(query_string, 
          search_query.getTags()));
      } catch (IllegalArgumentException e) {
        throw new BadRequestException("Unable to parse query", e);
      }
      if (query.hasQueryStringParam("limit")) {
        final String limit = query.getQueryStringParam("limit");
        try {
          search_query.setLimit(Integer.parseInt(limit));
        } catch (NumberFormatException e) {
          throw new BadRequestException(
                  "Unable to convert 'limit' to a valid number");
        }
      }
      return search_query;
    }
    
    // process a regular search query
    search_query.setQuery(query.getRequiredQueryStringParam("query"));
    
    if (query.hasQueryStringParam("limit")) {
      final String limit = query.getQueryStringParam("limit");
      try {
        search_query.setLimit(Integer.parseInt(limit));
      } catch (NumberFormatException e) {
        throw new BadRequestException(
            "Unable to convert 'limit' to a valid number");
      }
    }
    
    if (query.hasQueryStringParam("start_index")) {
      final String idx = query.getQueryStringParam("start_index");
      try {
        search_query.setStartIndex(Integer.parseInt(idx));
      } catch (NumberFormatException e) {
        throw new BadRequestException(
            "Unable to convert 'start_index' to a valid number");
      }
    }
    
    if (query.hasQueryStringParam("use_meta")) {
      search_query.setUseMeta(Boolean.parseBoolean(
          query.getQueryStringParam("use_meta")));
    }
    
    return search_query;
  }
507510
public static TSQuery parseQuery(final TSDB tsdb, final HttpQuery query) {
    return parseQuery(tsdb, query, null);
  }
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;
      }, {});
}
996403
private void handleUIDMeta(final TSDB tsdb, final HttpQuery query) {

    final HttpMethod method = query.getAPIMethod();
    // GET
    if (method == HttpMethod.GET) {
      
      final String uid = query.getRequiredQueryStringParam("uid");
      final UniqueIdType type = UniqueId.stringToUniqueIdType(
          query.getRequiredQueryStringParam("type"));
      try {
        final UIDMeta meta = UIDMeta.getUIDMeta(tsdb, type, uid)
        .joinUninterruptibly();
        query.sendReply(query.serializer().formatUidMetaV1(meta));
      } catch (NoSuchUniqueId e) {
        throw new BadRequestException(HttpResponseStatus.NOT_FOUND, 
            "Could not find the requested UID", e);
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    // POST
    } else if (method == HttpMethod.POST || method == HttpMethod.PUT) {
      
      final UIDMeta meta;
      if (query.hasContent()) {
        meta = query.serializer().parseUidMetaV1();
      } else {
        meta = this.parseUIDMetaQS(query);
      }
      
      /**
       * Storage callback used to determine if the storage call was successful
       * or not. Also returns the updated object from storage.
       */
      class SyncCB implements Callback<Deferred<UIDMeta>, Boolean> {
        
        @Override
        public Deferred<UIDMeta> call(Boolean success) throws Exception {
          if (!success) {
            throw new BadRequestException(
                HttpResponseStatus.INTERNAL_SERVER_ERROR,
                "Failed to save the UIDMeta to storage", 
                "This may be caused by another process modifying storage data");
          }
          
          return UIDMeta.getUIDMeta(tsdb, meta.getType(), meta.getUID());
        }
        
      }
      
      try {
        final Deferred<UIDMeta> process_meta = meta.syncToStorage(tsdb, 
            method == HttpMethod.PUT).addCallbackDeferring(new SyncCB());
        final UIDMeta updated_meta = process_meta.joinUninterruptibly();
        tsdb.indexUIDMeta(updated_meta);
        query.sendReply(query.serializer().formatUidMetaV1(updated_meta));
      } catch (IllegalStateException e) {
        query.sendStatusOnly(HttpResponseStatus.NOT_MODIFIED);
      } catch (IllegalArgumentException e) {
        throw new BadRequestException(e);
      } catch (NoSuchUniqueId e) {
        throw new BadRequestException(HttpResponseStatus.NOT_FOUND, 
            "Could not find the requested UID", e);
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    // DELETE    
    } else if (method == HttpMethod.DELETE) {
      
      final UIDMeta meta;
      if (query.hasContent()) {
        meta = query.serializer().parseUidMetaV1();
      } else {
        meta = this.parseUIDMetaQS(query);
      }
      try {        
        meta.delete(tsdb).joinUninterruptibly();
        tsdb.deleteUIDMeta(meta);
      } catch (IllegalArgumentException e) {
        throw new BadRequestException("Unable to delete UIDMeta information", e);
      } catch (NoSuchUniqueId e) {
        throw new BadRequestException(HttpResponseStatus.NOT_FOUND, 
            "Could not find the requested UID", e);
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
      query.sendStatusOnly(HttpResponseStatus.NO_CONTENT);
      
    } else {
      throw new BadRequestException(HttpResponseStatus.METHOD_NOT_ALLOWED, 
          "Method not allowed", "The HTTP method [" + method.getName() +
          "] is not permitted for this endpoint");
    }
  }
364834
@Override
  public void execute(TSDB tsdb, HttpQuery query) {
  
    final HttpMethod method = query.getAPIMethod();
    if (method != HttpMethod.GET && method != HttpMethod.POST) {
      throw new BadRequestException("Unsupported method: " + method.getName());
    }
    
    // the uri will be /api/vX/search/<type> or /api/search/<type>
    final String[] uri = query.explodeAPIPath();
    final String endpoint = uri.length > 1 ? uri[1] : "";
    final SearchType type;
    final SearchQuery search_query;
    
    try {
      type = SearchQuery.parseSearchType(endpoint);
    } catch (IllegalArgumentException e) {
      throw new BadRequestException("Invalid search query type supplied", e);
    }
    
    if (query.hasContent()) {
      search_query = query.serializer().parseSearchQueryV1();
    } else {
      search_query = parseQueryString(query, type);
    }
    
    search_query.setType(type);
    
    if (type == SearchType.LOOKUP) {
      processLookup(tsdb, query, search_query);
      return;
    }
    
    try {
      final SearchQuery results = 
        tsdb.executeSearch(search_query).joinUninterruptibly();
      query.sendReply(query.serializer().formatSearchResultsV1(results));
    } catch (IllegalStateException e) {
      throw new BadRequestException("Searching is not enabled", e);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
630650
@Override
    public Map<String, DbColumnType> getQueryMetadata(String query) throws DatabaseEngineException {
        final Map<String, DbColumnType> metaMap = new LinkedHashMap<>();
        ResultSet rs = null;
        Statement stmt = null;

        try {
            getConnection();
            stmt = conn.createStatement();
            long start = System.currentTimeMillis();
            rs = stmt.executeQuery(query);
            logger.trace("[{} ms] {}", (System.currentTimeMillis() - start), query);

            ResultSetMetaData meta = rs.getMetaData();
            for (int i = 1; i <= meta.getColumnCount(); i++) {
                metaMap.put(meta.getColumnName(i), toPdbType(meta.getColumnType(i), meta.getColumnTypeName(i)));
            }

            return metaMap;
        } catch (final Exception e) {
            throw new DatabaseEngineException("Error querying", e);
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
            } catch (final Exception e) {
                logger.trace("Error closing result set.", e);
            }

            try {
                if (stmt != null) {
                    stmt.close();
                }
            } catch (final Exception e) {
                logger.trace("Error closing statement.", e);
            }
        }
    }
1067941
public Map<String, List<String>> getQueryString() {
    if (querystring == null) {
      try {
        querystring = new QueryStringDecoder(request.getUri()).getParameters();
      } catch (IllegalArgumentException e) {
        throw new BadRequestException("Bad query string: " + e.getMessage());
      }
    }
    return querystring;
  }
1045005
public static Properties parseInstructions( final String query )
        throws MalformedURLException
    {
        final Properties instructions = new Properties();
        if( query != null )
        {
            try
            {
                // just ignore for the moment and try out if we have valid properties separated by "&"
                final String segments[] = query.split( "&" );
                for( String segment : segments )
                {
                    // do not parse empty strings
                    if( segment.trim().length() > 0 )
                    {
                        final Matcher matcher = INSTRUCTIONS_PATTERN.matcher( segment );
                        if( matcher.matches() )
                        {
                            String key = matcher.group( 1 );
                            String val = matcher.group( 2 );
                            instructions.setProperty(
                                verifyKey(key),
                                val != null ? URLDecoder.decode( val, "UTF-8" ) : ""
                            );
                        }
                        else
                        {
                            throw new MalformedURLException( "Invalid syntax for instruction [" + segment
                                                             + "]. Take a look at http://www.aqute.biz/Code/Bnd."
                            );
                        }
                    }
                }
            }
            catch( UnsupportedEncodingException e )
            {
                // thrown by URLDecoder but it should never happen
                throwAsMalformedURLException( "Could not retrieve the instructions from [" + query + "]", e );
            }
        }
        return instructions;
    }
1177847
public UIDMeta parseUidMetaV1() {
    final String json = query.getContent();
    if (json == null || json.isEmpty()) {
      throw new BadRequestException(HttpResponseStatus.BAD_REQUEST,
          "Missing message content",
          "Supply valid JSON formatted data in the body of your request");
    }
    try {
      return JSON.parseToObject(json, UIDMeta.class);
    } catch (IllegalArgumentException iae) {
      throw new BadRequestException("Unable to parse the given JSON", iae);
    }
  }
227380
@NonNull
    public Expression match(@NonNull String query) {
        if (query == null) {
            throw new IllegalArgumentException("query is null.");
        }
        return new FullTextMatchExpression(this.name, query);
    }