{@inheritDoc}

@see org.modeshape.jcr.query.parse.BasicSqlQueryParser#parseQuery(org.modeshape.common.text.TokenStream,
org.modeshape.jcr.query.model.TypeSystem)
15762
@Override
    protected Query parseQuery( TokenStream tokens,
                                TypeSystem typeSystem ) {
        Query query = super.parseQuery(tokens, typeSystem);
        // See if we have to rewrite the JCR-SQL-style join ...
        if (query.source() instanceof JoinableSources) {
            JoinableSources joinableSources = (JoinableSources)query.source();
            // Rewrite the joins ...
            Source newSource = rewrite(joinableSources);
            query = new Query(newSource, query.constraint(), query.orderings(), query.columns(), query.getLimits(),
                              query.isDistinct());
        }
        return query;
    }
1039771
private static Object readQueryString(String queryName,
                                          Class<?> paramType,
                                          Type genericType,
                                          Annotation[] paramAnns,
                                          Message m,
                                          String defaultValue,
                                          boolean decode) {

        MultivaluedMap<String, String> queryMap = new UriInfoImpl(m, null).getQueryParameters(decode);

        if ("".equals(queryName)) {
            return InjectionUtils.handleBean(paramType, paramAnns, queryMap, ParameterType.QUERY, m, false);
        }
        return InjectionUtils.createParameterObject(queryMap.get(queryName),
                                                    paramType,
                                                    genericType,
                                                    paramAnns,
                                                    defaultValue,
                                                    false,
                                                    ParameterType.QUERY, m);
    }
1172098
@Override
  public Query parse() throws SyntaxError {
    if (id == null) {
      throw new SyntaxError("no " + MTAS_JOIN_QPARSER_COLLECTION);
    } else if (fields == null) {
      throw new SyntaxError("no " + MTAS_JOIN_QPARSER_FIELD);
    } else {

      BooleanQuery.Builder booleanQueryBuilder = new BooleanQuery.Builder();

      MtasSolrCollectionCache mtasSolrJoinCache = null;
      for (PluginHolder<SearchComponent> item : req.getCore()
          .getSearchComponents().getRegistry().values()) {
        if (item.get() instanceof MtasSolrSearchComponent) {
          mtasSolrJoinCache = ((MtasSolrSearchComponent) item.get())
              .getCollectionCache();
        }
      }
      if (mtasSolrJoinCache != null) {
        Automaton automaton;
        try {
          automaton = mtasSolrJoinCache.getAutomatonById(id);
          if (automaton != null) {
            for (String field : fields) {
              booleanQueryBuilder.add(
                  new AutomatonQuery(new Term(field), automaton), Occur.SHOULD);
            }
          } else {
            throw new IOException("no data for collection '" + id + "'");
          }
        } catch (IOException e) {
          throw new SyntaxError(
              "could not construct automaton: " + e.getMessage(), e);
        }
        return booleanQueryBuilder.build();
      } else {
        throw new SyntaxError("no MtasSolrSearchComponent found");
      }
    }
  }
443323
@Override
	public QueryRequest<ArrayNode> query(String fql) {
		return this.query(fql, mapper.getTypeFactory().constructType(ArrayNode.class));
	}
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;
  }
75025
@Override
    protected AstNode parseAlterTableStatement( DdlTokenStream tokens,
                                                AstNode parentNode ) throws ParsingException {
        assert tokens != null;
        assert parentNode != null;

        markStartOfStatement(tokens);

        // ALTER TABLE table-Name
        // {
        // ADD COLUMN column-definition |
        // ADD CONSTRAINT clause |
        // DROP [ COLUMN ] column-name [ CASCADE | RESTRICT ] |
        // DROP { PRIMARY KEY | FOREIGN KEY constraint-name | UNIQUE constraint-name | CHECK constraint-name | CONSTRAINT
        // constraint-name } |
        // ALTER [ COLUMN ] column-alteration |
        // LOCKSIZE { ROW | TABLE }
        // }

        tokens.consume(ALTER, TABLE); // consumes 'ALTER TABLE'
        String tableName = parseName(tokens);

        AstNode alterTableNode = nodeFactory().node(tableName, parentNode, TYPE_ALTER_TABLE_STATEMENT);

        // System.out.println("  >> PARSIN ALTER STATEMENT >>  TABLE Name = " + tableName);

        if (tokens.canConsume("ADD")) {
            if (isTableConstraint(tokens)) {
                parseTableConstraint(tokens, alterTableNode, true);
            } else {
                // This segment can also be enclosed in "()" brackets to handle multiple ColumnDefinition ADDs
                if (tokens.matches(L_PAREN)) {
                    parseColumns(tokens, alterTableNode, true);
                } else {
                    parseSingleTerminatedColumnDefinition(tokens, alterTableNode, true);
                }
            }

        } else if (tokens.canConsume("DROP")) {
            // DROP { PRIMARY KEY | FOREIGN KEY constraint-name | UNIQUE constraint-name | CHECK constraint-name | CONSTRAINT
            // constraint-name }
            if (tokens.canConsume("PRIMARY", "KEY")) {
                String name = parseName(tokens); // constraint name
                nodeFactory().node(name, alterTableNode, TYPE_DROP_TABLE_CONSTRAINT_DEFINITION);
            } else if (tokens.canConsume("FOREIGN", "KEY")) {
                String name = parseName(tokens); // constraint name
                nodeFactory().node(name, alterTableNode, TYPE_DROP_TABLE_CONSTRAINT_DEFINITION);
            } else if (tokens.canConsume("UNIQUE")) {
                String name = parseName(tokens); // constraint name
                nodeFactory().node(name, alterTableNode, TYPE_DROP_TABLE_CONSTRAINT_DEFINITION);
            } else if (tokens.canConsume("CHECK")) {
                String name = parseName(tokens); // constraint name
                nodeFactory().node(name, alterTableNode, TYPE_DROP_TABLE_CONSTRAINT_DEFINITION);
            } else if (tokens.canConsume("CONSTRAINT")) {
                String name = parseName(tokens); // constraint name
                nodeFactory().node(name, alterTableNode, TYPE_DROP_TABLE_CONSTRAINT_DEFINITION);
            } else {
                // DROP [ COLUMN ] column-name [ CASCADE | RESTRICT ]
                tokens.canConsume("COLUMN"); // "COLUMN" is optional

                String columnName = parseName(tokens);

                AstNode columnNode = nodeFactory().node(columnName, alterTableNode, TYPE_DROP_COLUMN_DEFINITION);

                if (tokens.canConsume(DropBehavior.CASCADE)) {
                    columnNode.setProperty(StandardDdlLexicon.DROP_BEHAVIOR, DropBehavior.CASCADE);
                } else if (tokens.canConsume(DropBehavior.RESTRICT)) {
                    columnNode.setProperty(StandardDdlLexicon.DROP_BEHAVIOR, DropBehavior.RESTRICT);
                }
            }
        } else if (tokens.canConsume("ALTER")) {
            // column-alteration
            //
            // ALTER [ COLUMN ] column-Name SET DATA TYPE VARCHAR(integer) |
            // ALTER [ COLUMN ] column-Name SET DATA TYPE VARCHAR FOR BIT DATA(integer) |
            // ALTER [ COLUMN ] column-name SET INCREMENT BY integer-constant |
            // ALTER [ COLUMN ] column-name RESTART WITH integer-constant |
            // ALTER [ COLUMN ] column-name [ NOT ] NULL |
            // ALTER [ COLUMN ] column-name [ WITH | SET ] DEFAULT default-value |
            // ALTER [ COLUMN ] column-name DROP DEFAULT

            tokens.canConsume("COLUMN");
            String alterColumnName = parseName(tokens);

            AstNode columnNode = nodeFactory().node(alterColumnName, alterTableNode, TYPE_ALTER_COLUMN_DEFINITION);

            if (tokens.matches("DEFAULT")) {
                parseDefaultClause(tokens, columnNode);
            } else if (tokens.canConsume("SET")) {
                if (tokens.canConsume("DATA", "TYPE")) {
                    DataType datatype = getDatatypeParser().parse(tokens);

                    columnNode.setProperty(StandardDdlLexicon.DATATYPE_NAME, datatype.getName());
                    if (datatype.getLength() >= 0) {
                        columnNode.setProperty(StandardDdlLexicon.DATATYPE_LENGTH, datatype.getLength());
                    }
                    if (datatype.getPrecision() >= 0) {
                        columnNode.setProperty(StandardDdlLexicon.DATATYPE_PRECISION, datatype.getPrecision());
                    }
                    if (datatype.getScale() >= 0) {
                        columnNode.setProperty(StandardDdlLexicon.DATATYPE_SCALE, datatype.getScale());
                    }

                } else if (tokens.canConsume("INCREMENT")) {
                    tokens.consume("BY", TokenStream.ANY_VALUE);
                }
                if (tokens.matches("DEFAULT")) {
                    parseDefaultClause(tokens, columnNode);
                }
            } else if (tokens.canConsume("WITH")) {
                parseDefaultClause(tokens, columnNode);
            } else {
                tokens.canConsume("RESTART", "WITH", TokenStream.ANY_VALUE);
                tokens.canConsume("DROP", "DEFAULT");

                if (tokens.canConsume("NOT", "NULL")) {
                    columnNode.setProperty(StandardDdlLexicon.NULLABLE, "NOT NULL");
                } else if (tokens.canConsume("NULL")) {
                    columnNode.setProperty(StandardDdlLexicon.NULLABLE, "NULL");
                }
            }

        } else if (tokens.canConsume("LOCKSIZE")) {
            tokens.canConsume("ROWS");
            tokens.canConsume("TABLE");
        }

        markEndOfStatement(tokens, alterTableNode);

        return alterTableNode;
    }
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;
  }
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;
    }
1238044
final public void selectQuery() throws ParseException {
    select();
    from();
    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
    case WHERE:
      where();
      break;
    default:
      jj_la1[0] = jj_gen;
      ;
    }
    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
    case ORDER_BY:
      sort();
      break;
    default:
      jj_la1[1] = jj_gen;
      ;
    }
    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
    case LIMIT:
      limit();
      break;
    default:
      jj_la1[2] = jj_gen;
      ;
    }
    jj_consume_token(0);
  }
212317
public static boolean parseWithKeyword(final char[] query, int offset) {
    if (query.length < (offset + 4)) {
      return false;
    }

    return (query[offset] | 32) == 'w'
        && (query[offset + 1] | 32) == 'i'
        && (query[offset + 2] | 32) == 't'
        && (query[offset + 3] | 32) == 'h';
  }
525728
@Override
    protected AstNode parseAlterStatement( DdlTokenStream tokens,
                                           AstNode parentNode ) throws ParsingException {
        assert tokens != null;
        assert parentNode != null;

        if (tokens.matches(STMT_ALTER_ALGORITHM)) {
            return parseStatement(tokens, STMT_ALTER_ALGORITHM, parentNode, TYPE_ALTER_ALGORITHM_STATEMENT);
        } else if (tokens.matches(STMT_ALTER_DATABASE)) {
            return parseStatement(tokens, STMT_ALTER_DATABASE, parentNode, TYPE_ALTER_DATABASE_STATEMENT);
        } else if (tokens.matches(STMT_ALTER_DEFINER)) {
            return parseStatement(tokens, STMT_ALTER_DEFINER, parentNode, TYPE_ALTER_DEFINER_STATEMENT);
        } else if (tokens.matches(STMT_ALTER_EVENT)) {
            return parseStatement(tokens, STMT_ALTER_EVENT, parentNode, TYPE_ALTER_EVENT_STATEMENT);
        } else if (tokens.matches(STMT_ALTER_FUNCTION)) {
            return parseStatement(tokens, STMT_ALTER_FUNCTION, parentNode, TYPE_ALTER_FUNCTION_STATEMENT);
        } else if (tokens.matches(STMT_ALTER_LOGFILE_GROUP)) {
            return parseStatement(tokens, STMT_ALTER_LOGFILE_GROUP, parentNode, TYPE_ALTER_LOGFILE_GROUP_STATEMENT);
        } else if (tokens.matches(STMT_ALTER_PROCEDURE)) {
            return parseStatement(tokens, STMT_ALTER_PROCEDURE, parentNode, TYPE_ALTER_PROCEDURE_STATEMENT);
        } else if (tokens.matches(STMT_ALTER_SCHEMA)) {
            return parseStatement(tokens, STMT_ALTER_SCHEMA, parentNode, TYPE_ALTER_SCHEMA_STATEMENT);
        } else if (tokens.matches(STMT_ALTER_SERVER)) {
            return parseStatement(tokens, STMT_ALTER_SERVER, parentNode, TYPE_ALTER_SERVER_STATEMENT);
        } else if (tokens.matches(STMT_ALTER_TABLESPACE)) {
            return parseStatement(tokens, STMT_ALTER_TABLESPACE, parentNode, TYPE_ALTER_TABLESPACE_STATEMENT);
        } else if (tokens.matches(STMT_ALTER_SQL_SECURITY)) {
            return parseStatement(tokens, STMT_ALTER_SQL_SECURITY, parentNode, TYPE_ALTER_VIEW_STATEMENT);
        } else if (tokens.matches(STMT_ALTER_IGNORE_TABLE) || tokens.matches(STMT_ALTER_ONLINE_TABLE)
                   || tokens.matches(STMT_ALTER_ONLINE_IGNORE_TABLE) || tokens.matches(STMT_ALTER_OFFLINE_TABLE)
                   || tokens.matches(STMT_ALTER_OFFLINE_IGNORE_TABLE)) {
            return parseAlterTableStatement(tokens, parentNode);
        }

        return super.parseAlterStatement(tokens, parentNode);
    }
18919
@Override
  public Query parse() throws SyntaxError {
    if (field == null) {
      throw new SyntaxError("no " + MTAS_CQL_QPARSER_FIELD);
    } else if (cql == null) {
      throw new SyntaxError("no " + MTAS_CQL_QPARSER_QUERY);
    } else {
      MtasSpanQuery q = null;
      MtasSpanQuery iq = null;
      if (ignoreQuery != null) {
        Reader ignoreReader = new BufferedReader(new StringReader(ignoreQuery));
        MtasCQLParser ignoreParser = new MtasCQLParser(ignoreReader);
        try {
          iq = ignoreParser.parse(field, null, null, null, null);
        } catch (mtas.parser.cql.TokenMgrError
            | mtas.parser.cql.ParseException e) {
          throw new SyntaxError(e);
        }
      }
      Reader queryReader = new BufferedReader(new StringReader(cql));
      MtasCQLParser queryParser = new MtasCQLParser(queryReader);
      try {
        q = queryParser.parse(field, defaultPrefix, variables, iq,
            maximumIgnoreLength);
      } catch (mtas.parser.cql.TokenMgrError
          | mtas.parser.cql.ParseException e) {
        throw new SyntaxError(e);
      }
      return q;
    }
  }
436348
@Override
	public ResultSet doQuery(final SqlContext sqlContext, final PreparedStatement preparedStatement,
			final ResultSet resultSet) {
		try {
			if (resultSet.getType() == ResultSet.TYPE_FORWARD_ONLY) {
				LOG.warn("ResultSet type is TYPE_FORWARD_ONLY. DumpResultSqlFilter use ResultSet#beforeFirst(). Please Set TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE.");
			}
			StringBuilder builder = displayResult(resultSet);
			LOG.info(builder.toString());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return resultSet;
	}
1014148
public MtasSpanQuery getQuery() throws ParseException {
    simplify();
    MtasSpanSequenceItem currentQuery = null;
    List<MtasSpanSequenceItem> currentQueryList = null;
    for (MtasCQLParserBasicSentencePartCondition part : partList) {
      // start list
      if (currentQuery != null) {
        currentQueryList = new ArrayList<MtasSpanSequenceItem>();
        currentQueryList.add(currentQuery);
        currentQuery = null;
      }
      if (part.getMaximumOccurence() > 1) {
        MtasSpanQuery q = new MtasSpanRecurrenceQuery(part.getQuery(),
            part.getMinimumOccurence(), part.getMaximumOccurence(),
            ignoreClause, maximumIgnoreLength);
        currentQuery = new MtasSpanSequenceItem(q, part.isOptional());
      } else {
        currentQuery = new MtasSpanSequenceItem(part.getQuery(),
            part.isOptional());
      }
      // add to list, if it exists
      if (currentQueryList != null) {
        currentQueryList.add(currentQuery);
        currentQuery = null;
      }
    }
    if (currentQueryList != null) {
      return new MtasSpanSequenceQuery(currentQueryList, ignoreClause,
          maximumIgnoreLength);
    } else if (currentQuery.isOptional()) {
      currentQueryList = new ArrayList<MtasSpanSequenceItem>();
      currentQueryList.add(currentQuery);
      currentQuery = null;
      return new MtasSpanSequenceQuery(currentQueryList, ignoreClause,
          maximumIgnoreLength);
    } else {
      return currentQuery.getQuery();
    }
  }
106302
public static Map<String, String> parseQuery(String query) {
		Map<String, String> result = new LinkedHashMap<String, String>();
		
		if (query != null) {
			for (String keyValue: query.split("&")) {
				String[] pair = keyValue.split("=");
				result.put(StringUtils.urlDecode(pair[0]), StringUtils.urlDecode(pair[1]));
			}
		}
		
		return result;
	}
1278554
private InputStream runSparqlQuery(String query) throws IOException {
		try {
			String queryString = "query=" + URLEncoder.encode(query, "UTF-8")
					+ "&format=json";
			URL url = new URL("https://query.wikidata.org/sparql?"
					+ queryString);
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.setRequestMethod("GET");

			return connection.getInputStream();
		} catch (UnsupportedEncodingException | MalformedURLException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}
1255819
@Override
    public <T> TypedQuery<T> createQuery(CriteriaQuery<T> paramCriteriaQuery)
    {
        checkClosed();

        return this.createQuery(CriteriaQueryTranslator.translate(paramCriteriaQuery),
                paramCriteriaQuery.getResultType());
    }