Handles HTTP RPC put requests
@param tsdb The TSDB to which we belong
@param query The HTTP query from the user
@throws IOException if there is an error parsing the query or formatting
the output
@throws BadRequestException if the user supplied bad data
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);
  }
73441
public <T> T execute(final String query, Object connection) {
        try {
            org.apache.cassandra.thrift.Cassandra.Client conn =
                (org.apache.cassandra.thrift.Cassandra.Client) connection;
            conn.set_cql_version(CassandraConstants.CQL_VERSION_3_0);
            KunderaCoreUtils.printQuery(query, showQuery);
            return (T) conn.execute_cql3_query(ByteBuffer.wrap(query.getBytes(Constants.CHARSET_UTF8)),
                Compression.NONE, getConsistencyLevel());
        } catch (Exception e) {
            log.error("Error while executing query {}", query);
            throw new KunderaException(e);
        }
    }
645210
public void processFlushQuery(ControlAreYouFlushed flushQuery) throws SIResourceException
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.entry(tc, "processFlushQuery", new Object[] { flushQuery });

    SIBUuid12 streamID = flushQuery.getGuaranteedStreamUUID();

    try
    {
      //synchronize to give a consistent view of the flushed state
      synchronized(this)
      {
        SIBUuid8 requestor = flushQuery.getGuaranteedSourceMessagingEngineUUID();
        if(isFlushed(streamID))
        {
          // It's flushed.  Send a message saying as much.
          downControl.sendFlushedMessage(requestor, streamID);
        }
        else
        {
          // Not flushed.  Send a message saying as much.
          downControl.sendNotFlushedMessage(requestor, streamID, flushQuery.getRequestID());
        }
      }
    }
    catch (SIResourceException e)
    {
      // FFDC
      FFDCFilter.processException(
        e,
        "com.ibm.ws.sib.processor.gd.SourceStreamManager.processFlushQuery",
        "1:1333:1.102",
        this);

      SibTr.exception(tc, e);

      if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
        SibTr.exit(tc, "processFlushQuery", e);

      throw e;
    }

    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.exit(tc, "processFlushQuery");

  }
482621
public void handleQuery(ChaincodeMessage message) {
		// Query does not transition state. It can happen anytime after Ready
		Runnable task = () -> {
			ChaincodeMessage serialSendMessage = null;
			try {
				// Get the function and args from Payload
				ChaincodeInput input;
				try {
					input = ChaincodeInput.parseFrom(message.getPayload());
				} catch (Exception e) {
					// Send ERROR message to chaincode support and change state
					logger.debug(String.format("[%s]Incorrect payload format. Sending %s",
							shortID(message), QUERY_ERROR));
					serialSendMessage = ChaincodeMessage.newBuilder()
							.setType(QUERY_ERROR)
							.setPayload(ByteString.copyFromUtf8(e.getMessage()))
							.setTxid(message.getTxid())
							.build();
					return;
				}

				// Mark as a query (do not allow put/del state)
				markIsTransaction(message.getTxid(), false);

				// Call chaincode's Query
				// Create the ChaincodeStub which the chaincode can use to callback
				ChaincodeStub stub = new ChaincodeStub(message.getTxid(), this, message.getSecurityContext());
				ByteString response;
				try {
					response = chaincode.queryHelper(stub, getFunction(input.getArgsList()), getParameters(input.getArgsList()));
				} catch (Exception e) {
					// Send ERROR message to chaincode support and change state
					logger.debug(String.format("[%s]Query execution failed. Sending %s",
							shortID(message), QUERY_ERROR));
					serialSendMessage = ChaincodeMessage.newBuilder()
							.setType(QUERY_ERROR)
							.setPayload(ByteString.copyFromUtf8(e.getMessage()))
							.setTxid(message.getTxid())
							.build();
					return;
				} finally {
					deleteIsTransaction(message.getTxid());
				}

				// Send COMPLETED message to chaincode support
				logger.debug("["+ shortID(message)+"]Query completed. Sending "+ QUERY_COMPLETED);
				serialSendMessage = ChaincodeMessage.newBuilder()
						.setType(QUERY_COMPLETED)
						.setPayload(response)
						.setTxid(message.getTxid())
						.build();
			} finally {
				serialSend(serialSendMessage);
			}
		};

		new Thread(task).start();
	}
70057
public int executeUpdate(final String query) throws SQLException {
        startTimer();
        try {
            if (queryResult != null) {
                queryResult.close();
            }
            warningsCleared = false;
            if(inputStream == null)
                queryResult = protocol.executeQuery(queryFactory.createQuery(query));
            else 
                queryResult = protocol.executeQuery(queryFactory.createQuery(query), inputStream);
            return (int) ((ModifyQueryResult) queryResult).getUpdateCount();
        } catch (QueryException e) {
            throw SQLExceptionMapper.get(e);
        }
        finally
        {
            stopTimer();
            if(inputStream != null)
            {
                try
                {
                    inputStream.close();
                }
                catch (IOException e)
                {
                }
                inputStream = null;
            }
        }
    }
277688
function runQuery(query, connection) {
  const incomplete = false;

  return new Promise((resolve, reject) => {
    const client = hdb.createClient({
      host: connection.host,
      port: connection.hanaport,
      database: connection.hanadatabase,
      user: connection.username,
      password: connection.password,
      schema: connection.hanaSchema
    });

    client.on('error', err => {
      console.error('Network connection error', err);
      return reject(err);
    });

    client.connect(err => {
      if (err) {
        console.error('Connect error', err);
        return reject(err);
      }
      return client.execute(query, function(err, rs) {
        let rows = [];

        if (err) {
          client.disconnect();
          return reject(err);
        }

        if (!rs) {
          client.disconnect();
          return resolve({ rows, incomplete });
        }

        if (!rs.createObjectStream) {
          // Could be row count or something
          client.disconnect();
          return resolve({ rows: [{ result: rs }], incomplete });
        }

        const stream = rs.createObjectStream();

        stream.on('data', data => {
          if (rows.length < connection.maxRows) {
            return rows.push(data);
          }
          client.disconnect();
          return resolve({ rows, incomplete: true });
        });

        stream.on('error', error => {
          client.disconnect();
          return reject(error);
        });

        stream.on('finish', () => {
          client.disconnect();
          return resolve({ rows, incomplete });
        });
      });
    });
  });
}
659073
private void sendQuery(Query query, V3ParameterList parameters, int maxRows, int fetchSize,
      int flags, ResultHandler resultHandler,
      BatchResultHandler batchHandler) throws IOException, SQLException {
    // Now the query itself.
    Query[] subqueries = query.getSubqueries();
    SimpleParameterList[] subparams = parameters.getSubparams();

    // We know this is deprecated, but still respect it in case anyone's using it.
    // PgJDBC its self no longer does.
    @SuppressWarnings("deprecation")
    boolean disallowBatching = (flags & QueryExecutor.QUERY_DISALLOW_BATCHING) != 0;

    if (subqueries == null) {
      flushIfDeadlockRisk(query, disallowBatching, resultHandler, batchHandler, flags);

      // If we saw errors, don't send anything more.
      if (resultHandler.getException() == null) {
        sendOneQuery((SimpleQuery) query, (SimpleParameterList) parameters, maxRows, fetchSize,
            flags);
      }
    } else {
      for (int i = 0; i < subqueries.length; ++i) {
        final Query subquery = subqueries[i];
        flushIfDeadlockRisk(subquery, disallowBatching, resultHandler, batchHandler, flags);

        // If we saw errors, don't send anything more.
        if (resultHandler.getException() != null) {
          break;
        }

        // In the situation where parameters is already
        // NO_PARAMETERS it cannot know the correct
        // number of array elements to return in the
        // above call to getSubparams(), so it must
        // return null which we check for here.
        //
        SimpleParameterList subparam = SimpleQuery.NO_PARAMETERS;
        if (subparams != null) {
          subparam = subparams[i];
        }
        sendOneQuery((SimpleQuery) subquery, subparam, maxRows, fetchSize, flags);
      }
    }
  }
441147
public <T> T execute(final String query, final Object connection,
        final List<KunderaQuery.BindParameter> parameters) {
        throw new KunderaException("not implemented");
    }
902317
private <T extends IEntity> IntuitMessage prepareQuery(String query) throws FMSException {
        IntuitMessage intuitMessage = new IntuitMessage();
        RequestElements requestElements = intuitMessage.getRequestElements();

        //set the request params
        Map<String, String> requestParameters = requestElements.getRequestParameters();
        if (query.length() > LENGTH_200) {
            requestParameters.put(RequestElements.REQ_PARAM_METHOD_TYPE, MethodType.POST.toString());
            requestElements.setPostString(query);
        } else {
            requestParameters.put(RequestElements.REQ_PARAM_METHOD_TYPE, MethodType.GET.toString());
            requestParameters.put(RequestElements.REQ_PARAM_QUERY, query);
        }

        requestElements.setAction(OperationType.QUERY.toString());
        requestElements.setContext(context);

        return intuitMessage;
    }
1226285
private void handleQuery(final TSDB tsdb, final HttpQuery query, 
      final boolean allow_expressions) {
    final long start = DateTime.currentTimeMillis();
    final TSQuery data_query;
    final List<ExpressionTree> expressions;
    if (query.method() == HttpMethod.POST) {
      switch (query.apiVersion()) {
      case 0:
      case 1:
        data_query = query.serializer().parseQueryV1();
        break;
      default:
        query_invalid.incrementAndGet();
        throw new BadRequestException(HttpResponseStatus.NOT_IMPLEMENTED, 
            "Requested API version not implemented", "Version " + 
            query.apiVersion() + " is not implemented");
      }
      expressions = null;
    } else {
      expressions = new ArrayList<ExpressionTree>();
      data_query = parseQuery(tsdb, query, expressions);
    }
    
    if (query.getAPIMethod() == HttpMethod.DELETE &&
        tsdb.getConfig().getBoolean("tsd.http.query.allow_delete")) {
      data_query.setDelete(true);
    }
    
    // validate and then compile the queries
    try {
      LOG.debug(data_query.toString());
      data_query.validateAndSetQuery();
    } catch (Exception e) {
      throw new BadRequestException(HttpResponseStatus.BAD_REQUEST, 
          e.getMessage(), data_query.toString(), e);
    }

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

    // if the user tried this query multiple times from the same IP and src port
    // they'll be rejected on subsequent calls
    final QueryStats query_stats = 
        new QueryStats(query.getRemoteAddress(), data_query, 
            query.getPrintableHeaders());
    data_query.setQueryStats(query_stats);
    query.setStats(query_stats);
    
    final int nqueries = data_query.getQueries().size();
    final ArrayList<DataPoints[]> results = new ArrayList<DataPoints[]>(nqueries);
    final List<Annotation> globals = new ArrayList<Annotation>();
    
    /** This has to be attached to callbacks or we may never respond to clients */
    class ErrorCB implements Callback<Object, Exception> {
      public Object call(final Exception e) throws Exception {
        Throwable ex = e;
        try {
          LOG.error("Query exception: ", e);
          if (ex instanceof DeferredGroupException) {
            ex = e.getCause();
            while (ex != null && ex instanceof DeferredGroupException) {
              ex = ex.getCause();
            }
            if (ex == null) {
              LOG.error("The deferred group exception didn't have a cause???");
            }
          } 

          if (ex instanceof RpcTimedOutException) {
            query_stats.markSerialized(HttpResponseStatus.REQUEST_TIMEOUT, ex);
            query.badRequest(new BadRequestException(
                HttpResponseStatus.REQUEST_TIMEOUT, ex.getMessage()));
            query_exceptions.incrementAndGet();
          } else if (ex instanceof HBaseException) {
            query_stats.markSerialized(HttpResponseStatus.FAILED_DEPENDENCY, ex);
            query.badRequest(new BadRequestException(
                HttpResponseStatus.FAILED_DEPENDENCY, ex.getMessage()));
            query_exceptions.incrementAndGet();
          } else if (ex instanceof QueryException) {
            query_stats.markSerialized(((QueryException)ex).getStatus(), ex);
            query.badRequest(new BadRequestException(
                ((QueryException)ex).getStatus(), ex.getMessage()));
            query_exceptions.incrementAndGet();
          } else if (ex instanceof BadRequestException) {
            query_stats.markSerialized(((BadRequestException)ex).getStatus(), ex);
            query.badRequest((BadRequestException)ex);
            query_invalid.incrementAndGet();
          } else if (ex instanceof NoSuchUniqueName) {
            query_stats.markSerialized(HttpResponseStatus.BAD_REQUEST, ex);
            query.badRequest(new BadRequestException(ex));
            query_invalid.incrementAndGet();
          } else {
            query_stats.markSerialized(HttpResponseStatus.INTERNAL_SERVER_ERROR, ex);
            query.badRequest(new BadRequestException(ex));
            query_exceptions.incrementAndGet();
          }
          
        } catch (RuntimeException ex2) {
          LOG.error("Exception thrown during exception handling", ex2);
          query_stats.markSerialized(HttpResponseStatus.INTERNAL_SERVER_ERROR, ex2);
          query.sendReply(HttpResponseStatus.INTERNAL_SERVER_ERROR, 
              ex2.getMessage().getBytes());
          query_exceptions.incrementAndGet();
        }
        return null;
      }
    }
    
    /**
     * After all of the queries have run, we get the results in the order given
     * and add dump the results in an array
     */
    class QueriesCB implements Callback<Object, ArrayList<DataPoints[]>> {
      public Object call(final ArrayList<DataPoints[]> query_results) 
        throws Exception {
        if (allow_expressions) {
          // process each of the expressions into a new list, then merge it
          // with the original. This avoids possible recursion loops.
          final List<DataPoints[]> expression_results = 
              new ArrayList<DataPoints[]>(expressions.size());
          // let exceptions bubble up
          for (final ExpressionTree expression : expressions) {
            expression_results.add(expression.evaluate(query_results));
          }
          results.addAll(expression_results);
        } else {
          results.addAll(query_results);
        }
        
        /** Simply returns the buffer once serialization is complete and logs it */
        class SendIt implements Callback<Object, ChannelBuffer> {
          public Object call(final ChannelBuffer buffer) throws Exception {
            query.sendReply(buffer);
            query_success.incrementAndGet();
            return null;
          }
        }

        switch (query.apiVersion()) {
        case 0:
        case 1:
            query.serializer().formatQueryAsyncV1(data_query, results, 
               globals).addCallback(new SendIt()).addErrback(new ErrorCB());
          break;
        default: 
          query_invalid.incrementAndGet();
          throw new BadRequestException(HttpResponseStatus.NOT_IMPLEMENTED, 
              "Requested API version not implemented", "Version " + 
              query.apiVersion() + " is not implemented");
        }
        return null;
      }
    }
    
    /**
     * 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>, Query[]> {
      @Override
      public Deferred<Object> call(final Query[] queries) {
        final ArrayList<Deferred<DataPoints[]>> deferreds = 
            new ArrayList<Deferred<DataPoints[]>>(queries.length);
        for (final Query query : queries) {
          // call different interfaces basing on whether it is a percentile query
          if (!query.isHistogramQuery()) {
            deferreds.add(query.runAsync());
          } else {
            deferreds.add(query.runHistogramAsync());
          }
        }
        return Deferred.groupInOrder(deferreds).addCallback(new QueriesCB());
      }
    }
    
    /** Handles storing the global annotations after fetching them */
    class GlobalCB implements Callback<Object, List<Annotation>> {
      public Object call(final List<Annotation> annotations) throws Exception {
        globals.addAll(annotations);
        return data_query.buildQueriesAsync(tsdb).addCallback(new BuildCB());
      }
    }
 
    // if we the caller wants to search for global annotations, fire that off 
    // first then scan for the notes, then pass everything off to the formatter
    // when complete
    if (!data_query.getNoAnnotations() && data_query.getGlobalAnnotations()) {
      Annotation.getGlobalAnnotations(tsdb, 
        data_query.startTime() / 1000, data_query.endTime() / 1000)
          .addCallback(new GlobalCB()).addErrback(new ErrorCB());
    } else {
      data_query.buildQueriesAsync(tsdb).addCallback(new BuildCB())
        .addErrback(new ErrorCB());
    }
  }
6830
public SparqlResult runQuery(String endpoint, String query) {
    return SparqlClient.execute(endpoint, query, username, password);
  }
905491
@Override
    public final Query createQuery(String query)
    {
        checkClosed();
        checkTransactionNeeded();
        return getPersistenceDelegator().createQuery(query);
    }
952929
@Override
  public void execute(final TSDB tsdb, final HttpQuery query) 
    throws IOException {
    
    // only accept GET/POST/DELETE
    if (query.method() != HttpMethod.GET && query.method() != HttpMethod.POST &&
        query.method() != HttpMethod.DELETE) {
      throw new BadRequestException(HttpResponseStatus.METHOD_NOT_ALLOWED, 
          "Method not allowed", "The HTTP method [" + query.method().getName() +
          "] is not permitted for this endpoint");
    }
    if (query.method() == HttpMethod.DELETE && 
        !tsdb.getConfig().getBoolean("tsd.http.query.allow_delete")) {
      throw new BadRequestException(HttpResponseStatus.BAD_REQUEST,
               "Bad request",
               "Deleting data is not enabled (tsd.http.query.allow_delete=false)");
    }
    
    final String[] uri = query.explodeAPIPath();
    final String endpoint = uri.length > 1 ? uri[1] : ""; 
    
    if (endpoint.toLowerCase().equals("last")) {
      handleLastDataPointQuery(tsdb, query);
    } else if (endpoint.toLowerCase().equals("gexp")){
      handleQuery(tsdb, query, true);
    } else if (endpoint.toLowerCase().equals("exp")) {
      handleExpressionQuery(tsdb, query);
      return;
    } else {
      handleQuery(tsdb, query, false);
    }
  }
455868
@Override
    public MongodbQueryResult build(String query) throws IOException, ParserNotFoundException {
        DBObject result = (DBObject) super.parse(query);
        return new MongodbQueryResult(query, result);
    }
694467
public boolean execute(final String query) throws SQLException {
        startTimer();
        try {
            if (queryResult != null) {
                queryResult.close();
            }
            queryResult = protocol.executeQuery(queryFactory.createQuery(query));
            if (queryResult.getResultSetType() == ResultSetType.SELECT) {
                setResultSet(new DrizzleResultSet(queryResult, this, getProtocol()));
                return true;
            }
            setUpdateCount(((ModifyQueryResult) queryResult).getUpdateCount());
            return false;
        } catch (QueryException e) {
            throw SQLExceptionMapper.get(e);
        } finally {
            stopTimer();
        }
    }
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);
		}
	}
723109
public void configureIncidentQuery(IncidentQueryImpl query) {
    configureQuery(query);
    CompositePermissionCheck permissionCheck = new PermissionCheckBuilder()
            .disjunctive()
            .atomicCheck(PROCESS_INSTANCE, "RES.PROC_INST_ID_", READ)
            .atomicCheck(PROCESS_DEFINITION, "PROCDEF.KEY_", READ_INSTANCE)
            .build();
    addPermissionCheck(query.getAuthCheck(), permissionCheck);
  }