Executes the given {@link SearchQuery}.

@param query the query to execute
@param timeout the timeout for the query
@param timeUnit the timeunit for the timeout
@return an {@link Observable} eventually containing the {@link AsyncSearchQueryResult}.
487793
public Observable<AsyncSearchQueryResult> execute(final SearchQuery query, final long timeout,
        final TimeUnit timeUnit) {
        return deferAndWatch(new Func1<Subscriber, Observable<SearchQueryResponse>>() {
            @Override
            public Observable<SearchQueryResponse> call(Subscriber subscriber) {
                final SearchQueryRequest request = new SearchQueryRequest(
                        query.indexName(),
                        query.export().toString(),
                        bucket,
                        username,
                        password
                );
                Utils.addRequestSpan(environment, request, "search");
                request.subscriber(subscriber);
                return applyTimeout(core.<SearchQueryResponse>send(request), request, environment, timeout, timeUnit);
            }
        })
        .flatMap(new Func1<SearchQueryResponse, Observable<SearchQueryResponse>>() {
            @Override
            public Observable<SearchQueryResponse> call(final SearchQueryResponse r) {
                if (shouldRetry(r.statusCode())) {
                    return Observable.error(new RetryableException(r));
                }
                return Observable.just(r);
            }
        })
        .retryWhen(RetryBuilder
            .anyOf(RetryableException.class)
            .max(10)
            .delay(Delay.exponential(TimeUnit.MILLISECONDS, upperRetryLimit, lowerRetryLimit))
            .doOnRetry(new Action4<Integer, Throwable, Long, TimeUnit>() {
                @Override
                public void call(Integer attempt, Throwable error, Long delay, TimeUnit delayUnit) {
                    LOGGER.debug("Retrying {} because of {} (attempt {}, delay {} {})", query.export(),
                        error.getMessage(), attempt, delay, delayUnit);
            }
            })
            .build()
        )
        .map(new Func1<SearchQueryResponse, AsyncSearchQueryResult>() {
            @Override
            public AsyncSearchQueryResult call(final SearchQueryResponse response) {
                if (response.status().isSuccess()) {
                    JsonObject json = JsonObject.fromJson(response.payload());
                    return DefaultAsyncSearchQueryResult.fromJson(json);
                } else if (response.payload().contains("index not found")) {
                    return DefaultAsyncSearchQueryResult.fromIndexNotFound(query.indexName());
                } else if (response.status() == ResponseStatus.INVALID_ARGUMENTS) {
                    return DefaultAsyncSearchQueryResult.fromHttp400(response.payload());
                } else if (response.statusCode() == HTTP_PRECONDITION_FAILED) {
                    return DefaultAsyncSearchQueryResult.fromHttp412();
                } else {
                    throw new CouchbaseException("Could not query search index, "
                        + response.status() + ": " + response.payload());
                }
            }
        }).onErrorResumeNext(new Func1<Throwable, Observable<? extends AsyncSearchQueryResult>>() {
            @Override
            public Observable<? extends AsyncSearchQueryResult> call(Throwable throwable) {
                if (throwable instanceof CannotRetryException) {
                    if (throwable.getCause() != null && throwable.getCause() instanceof RetryableException) {
                        RetryableException x = (RetryableException) throwable.getCause();
                        if (x.response().statusCode() == HTTP_TOO_MANY_REQUESTS) {
                            return Observable.just(DefaultAsyncSearchQueryResult.fromHttp429(x.response().payload()));
                        } else {
                            return Observable.error(new CouchbaseException("Could not query search index, "
                                + x.response().status() + ": " + x.response().payload()));
                        }
                    }
                }
                return Observable.error(throwable);
            }
        });
    }
1253277
@Override
    public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
        if (this.m_coordinationLatch.await(timeout, unit) == false) {
            throw new TimeoutException();
        }

        if (m_pendingException != null) {
            throw m_pendingException;
        }

        return m_defaultFuture.get(timeout, unit);
    }
835548
@SuppressWarnings( "deprecation" )
    @Override
    public org.modeshape.jcr.api.query.QueryResult execute() throws RepositoryException {
        context.checkValid();
        final long start = System.nanoTime();
        // Create an executable query and set it on this object ...
        CancellableQuery newExecutable = context.createExecutableQuery(query, hints, variables);
        CancellableQuery executable = executingQuery.getAndSet(newExecutable);
        if (executable == null) {
            // We are the first to call 'execute()', so use our newly-created one ...
            executable = newExecutable;
        }
        // otherwise, some other thread called execute, so we can use it and just wait for the results ...
        final QueryResults result = executable.execute(); // may be cancelled

        // And reset the reference to null (if not already set to something else) ...
        executingQuery.compareAndSet(executable, null);

        checkForProblems(result.getProblems());
        context.recordDuration(Math.abs(System.nanoTime() - start), TimeUnit.NANOSECONDS, statement, language);
        if (Query.XPATH.equals(language)) {
            return new XPathQueryResult(context, statement, result, hints.restartable, hints.rowsKeptInMemory);
        } else if (Query.SQL.equals(language)) {
            return new JcrSqlQueryResult(context, statement, result, hints.restartable, hints.rowsKeptInMemory);
        }
        return new JcrQueryResult(context, statement, result, hints.restartable, hints.rowsKeptInMemory);
    }
157114
Query createQuery(String jpaQuery, final String persistenceUnit)
    {
        Client client = getClient(persistenceUnit);
        EntityMetadata metadata = null;
        try
        {
            metadata = KunderaMetadataManager.getMetamodel(kunderaMetadata, client.getPersistenceUnit())
                    .getEntityMetadataMap().values().iterator().next();
        }
        catch (Exception e)
        {
            log.info("Entity metadata is null. Proceeding as Scalar Query.");
        }

        Query query = new QueryResolver().getQueryImplementation(jpaQuery, getClient(persistenceUnit)
                .getQueryImplementor(), this, metadata, persistenceUnit);
        return query;
    }
773308
private void setQueryTimeout(final Statement statement, final int timeoutSec)
   {
      if (isQueryTimeoutSupported != FALSE) {
         try {
            statement.setQueryTimeout(timeoutSec);
            isQueryTimeoutSupported = TRUE;
         }
         catch (Exception e) {
            if (isQueryTimeoutSupported == UNINITIALIZED) {
               isQueryTimeoutSupported = FALSE;
               logger.info("{} - Failed to set query timeout for statement. ({})", poolName, e.getMessage());
            }
         }
      }
   }
1372061
public void waitForCompletion(final long timeout, final TimeUnit unit) 
			throws InterruptedException, ExecutionException, TimeoutException {
		doneLatch.await(timeout, unit);
	}
665645
private void executeSearch(CmsSearchController controller, CmsSolrQuery query) {

        CmsObject cms = A_CmsUI.getCmsObject();
        CmsSolrIndex index = OpenCms.getSearchManager().getIndexSolr(
            cms.getRequestContext().getCurrentProject().isOnlineProject()
            ? CmsSolrIndex.DEFAULT_INDEX_NAME_ONLINE
            : CmsSolrIndex.DEFAULT_INDEX_NAME_OFFLINE);
        try {
            CmsSolrResultList solrResultList = index.search(cms, query, true, CmsResourceFilter.IGNORE_EXPIRATION);
            displayResult(solrResultList);
            m_resultFacets.displayFacetResult(
                solrResultList,
                new CmsSearchResultWrapper(controller, solrResultList, query, cms, null));
        } catch (CmsSearchException e) {
            CmsErrorDialog.showErrorDialog(e);

            LOG.error("Error executing search.", e);
        }
    }
891174
@Override
    public synchronized Response get(long timeout, TimeUnit unit)
            throws InterruptedException, ExecutionException, TimeoutException {
        long now = System.currentTimeMillis();
        long mills = unit.toMillis(timeout);
        long toWait = mills;
        if (this.completed) {
            return this.getResult();
        } else if (toWait <= 0) {
            throw new TimeoutException("Timeout is smaller than 0.");
        } else {
            for (;;) {
                wait(toWait);
                if (this.completed) {
                    return this.getResult();
                }
                long gap = System.currentTimeMillis() - now;
                toWait = toWait - gap;
                if (toWait <= 0) {
                    throw new TimeoutException();
                }
            }
        }
    }
555653
public BoxRequestsSearch.Search getSearchRequest(String query) {
        BoxRequestsSearch.Search request = new BoxRequestsSearch.Search(query, getSearchUrl(), mSession);
        return request;
    }
1014180
public static HttpResult executeSearch(AsyncHttpClient client, HttpMethod method, String host,
                                     String path, String searchQuery) {
        RequestBuilder requestBuilder = new RequestBuilder(method.name());

        log.debug("Executing request against host {} with path {}",host,path);
        if(searchQuery!=null) {
            requestBuilder.setBody(searchQuery);
        }

        requestBuilder.setUrl(host + path);
        try {
            Response res = client.executeRequest(requestBuilder.build(),new AsyncCompletionHandlerBase()).get();
            return new HttpResult(HttpSearchExecutionStatus.OK,res.getResponseBody());
        } catch (Exception e) {
            Throwable cause = e.getCause();
            if(cause!=null) {
                if(cause instanceof ConnectException)
                {
                    log.error("Unable to connect to {}",host,e);
                    return HttpResult.CONNECTION_FAILURE;
                }
                else if (cause instanceof TimeoutException) {
                    log.error("Request timeout talking to {}",host,e);
                    return HttpResult.REQUEST_TIMEOUT_FAILURE;
                }
                else if (cause instanceof IOException && cause.getMessage().equalsIgnoreCase("closed")) {
                    log.warn("Unable to use client, client is closed");
                    return HttpResult.CLIENT_CLOSED;
                }
                else {
                    log.error("Exception talking to {}",host,e);
                    return new HttpResult(HttpSearchExecutionStatus.REQUEST_FAILURE,null);
                }
            }
            else {
                if (e instanceof IOException && e.getMessage().equalsIgnoreCase("closed")) {
                    log.warn("Unable to use client, client is closed");
                    return HttpResult.CLIENT_CLOSED;
                } else {
                    log.error("Exception talking to {}",host,e);
                    return new HttpResult(HttpSearchExecutionStatus.REQUEST_FAILURE,null);
                }
            }
        }
    }
586170
public Api getQueryResult(String query) throws Exception {
    Api result = this.getActionResult("query", query, null, null);
    return result;
  }
1325169
private static Observable<PingServiceHealth> pingQuery(
        final NetworkAddress hostname, final String bucket, final String password,
        final ClusterFacade core, final long timeout, final TimeUnit timeUnit) {
        final AtomicReference<CouchbaseRequest> request = new AtomicReference<CouchbaseRequest>();
        Observable<com.couchbase.client.core.message.query.PingResponse> response =
            Observable.defer(new Func0<Observable<com.couchbase.client.core.message.query.PingResponse>>() {
            @Override
            public Observable<com.couchbase.client.core.message.query.PingResponse> call() {
                CouchbaseRequest r;
                try {
                    r = new com.couchbase.client.core.message.query.PingRequest(
                        InetAddress.getByName(hostname.address()), bucket, password
                    );
                } catch (Exception e) {
                    return Observable.error(e);
                }
                request.set(r);
                return core.send(r);
            }
        }).timeout(timeout, timeUnit);
        return mapToServiceHealth(null, ServiceType.QUERY, response, request, timeout, timeUnit);
    }
882880
public QueryRequestBuilder<T,ID> query(QueryExpression query)
    {
        return new QueryRequestBuilder<T, ID>(version,type,entityName,query.build());
    }
1042003
@Override
    public QueryResult execute( String query,
                                String language ) throws RepositoryException {
        logger.trace("Executing query: {0}", query);

        // Create the query ...

        final Query jcrQuery = getLocalSession().getSession().getWorkspace().getQueryManager().createQuery(query, language);
        return jcrQuery.execute();
    }
1320164
@SafeVarargs
    public final ContinuableFuture<Boolean> asyncExists(final String query, final Object... parameters) {
        return asyncExecutor.execute(new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                return exists(query, parameters);
            }
        });
    }
1076300
public CompletableFuture<QueryResponse> query(QueryRequest request) {
    CompletableFuture<QueryResponse> future = new CompletableFuture<>();
    if (context.isCurrentContext()) {
      sendRequest(request, protocol::query, future);
    } else {
      context.execute(() -> sendRequest(request, protocol::query, future));
    }
    return future;
  }
1219766
static <T> Observable<T> execute(QuerySelect query, List<Parameter> parameters,
            ResultSetMapper<? extends T> function) {
        return Observable.create(new QuerySelectOnSubscribe<T>(query, parameters, function));
    }