Maps a raw {@link ViewQueryResponse} into a {@link AsyncViewResult}.

@param bucket reference to the bucket.
@param query the original query object.
@param response the response from the server.
@return a converted {@link AsyncViewResult}.
555103
public static Observable<AsyncViewResult> mapToViewResult(final AsyncBucket bucket, final ViewQuery query,
        final ViewQueryResponse response) {

        return response
            .info()
            .singleOrDefault(null)
            .map(new ByteBufToJsonObject())
            .map(new BuildViewResult(bucket, query, response));
    }
1061486
public QueryResult executeQuery(String query) throws FMSException {

        IntuitMessage intuitMessage = prepareQuery(query);

        // execute interceptors
        executeInterceptors(intuitMessage);

        QueryResult queryResult = null;

        // Iterate the IntuitObjects list in QueryResponse and convert to <T> entity
        IntuitResponse intuitResponse = (IntuitResponse) intuitMessage.getResponseElements().getResponse();
        if (intuitResponse != null) {
            QueryResponse queryResponse = intuitResponse.getQueryResponse();
            if (queryResponse != null) {
                queryResult = getQueryResult(queryResponse);
            }
        }
        return queryResult;
    }
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;
	}
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);
    }
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);
            }
        });
    }
215361
public SearchResults query(WaybackRequest wbRequest)
			throws ResourceIndexNotAvailableException,
			ResourceNotInArchiveException, BadQueryException,
			AccessControlException {
		SearchResults results = null; // return value placeholder

		if (wbRequest.isReplayRequest()) {

			results = doCaptureQuery(wbRequest, TYPE_REPLAY);
			results.putFilter(WaybackRequest.REQUEST_TYPE, 
					WaybackRequest.REQUEST_REPLAY_QUERY);

		} else if (wbRequest.isCaptureQueryRequest()) {

			results = doCaptureQuery(wbRequest, TYPE_CAPTURE);
			results.putFilter(WaybackRequest.REQUEST_TYPE, 
					WaybackRequest.REQUEST_CAPTURE_QUERY);

		} else if (wbRequest.isUrlQueryRequest()) {

			results = doUrlQuery(wbRequest);
			results.putFilter(WaybackRequest.REQUEST_TYPE, 
					WaybackRequest.REQUEST_URL_QUERY);

		} else {

			throw new BadQueryException("Unknown query type, must be " 
					+ WaybackRequest.REQUEST_REPLAY_QUERY
					+ ", " + WaybackRequest.REQUEST_CAPTURE_QUERY 
					+ ", or " + WaybackRequest.REQUEST_URL_QUERY);
		}
		return results;
	}
975059
public void runQueryOperation(Object operation, SimpleCompletableFuture resultFuture) {
        long commitIndex = state.commitIndex();
        Object result = raftIntegration.runOperation(operation, commitIndex);
        resultFuture.setResult(result);
    }
1136616
@Override
	public <T> Optional<T> queryForObject(String collection, Query query, Class<T> clazz, RequestMethod method) {

		Assert.notNull(collection, "Collection must not be null!");
		Assert.notNull(query, "Query must not be 'null'.");
		Assert.notNull(clazz, "Target class must not be 'null'.");

		query.setPageRequest(PageRequest.of(0, 1));
		QueryResponse response = querySolr(collection, query, clazz, method);

		if (response.getResults().size() > 0) {
			if (response.getResults().size() > 1) {
				LOGGER.warn("More than 1 result found for singe result query ('{}'), returning first entry in list", query);
			}
			return Optional.ofNullable(convertSolrDocumentListToBeans(response.getResults(), clazz).get(0));
		}
		return Optional.empty();
	}
470454
private List<?> getResultList(Query query) {
        // TODO : use lazy fetch here?
        if (projection != null) {
            List<?> results = query.getResultList();
            List<Object> rv = new ArrayList<Object>(results.size());
            for (Object o : results) {
                if (o != null) {
                    if (!o.getClass().isArray()) {
                        o = new Object[]{o};
                    }
                    rv.add(projection.newInstance((Object[]) o));
                } else {
                    rv.add(null);
                }
            }
            return rv;
        } else {
            return query.getResultList();
        }
    }
1232907
private QueryIterator forestQuery(QueryOptions options) throws ForestException {
        // NOTE: Geo & FullText queries are not supported yet
        if (options == null)
            options = new QueryOptions();
        long skip = options.getSkip();
        long limit = options.getLimit();
        boolean descending = options.isDescending();
        boolean inclusiveStart = options.isInclusiveStart();
        boolean inclusiveEnd = options.isInclusiveEnd();
        if (options.getKeys() != null && options.getKeys().size() > 0) {
            Object[] keys = options.getKeys().toArray();
            return _view.query(
                    skip,
                    limit,
                    descending,
                    inclusiveStart,
                    inclusiveEnd,
                    keys);
        } else {
            Object endKey = Misc.keyForPrefixMatch(options.getEndKey(),
                    options.getPrefixMatchLevel());
            Object startKey = options.getStartKey();
            String startKeyDocID = options.getStartKeyDocId();
            String endKeyDocID = options.getEndKeyDocId();
            return _view.query(
                    skip,
                    limit,
                    descending,
                    inclusiveStart,
                    inclusiveEnd,
                    startKey,
                    endKey,
                    startKeyDocID,
                    endKeyDocID);
        }
    }
203215
public SearchResult<WorkflowSummary> search(@Nonnull String query) {
        return search(null, null, null, null, query);
    }
927743
public Query getQueryImplementation(String jpaQuery, PersistenceDelegator persistenceDelegator, Class mappedClass,
            boolean isNative, final KunderaMetadata kunderaMetadata)
    {
        if (jpaQuery == null)
        {
            throw new QueryHandlerException("Query String should not be null ");
        }

        if (jpaQuery.trim().endsWith(Constants.SEMI_COLON))
        {
            throw new QueryHandlerException("unexpected char: ';' in query [ " + jpaQuery + " ]");
        }

        KunderaQuery kunderaQuery = null;
        ApplicationMetadata appMetadata = kunderaMetadata.getApplicationMetadata();
        String mappedQuery = appMetadata.getQuery(jpaQuery);

        isNative = mappedQuery != null ? appMetadata.isNative(jpaQuery) : isNative;

        EntityMetadata m = null;

        // In case of named native query
        if (!isNative)
        {
            kunderaQuery = new KunderaQuery(mappedQuery != null ? mappedQuery : jpaQuery, kunderaMetadata);
            KunderaQueryParser parser = new KunderaQueryParser(kunderaQuery);

            parser.parse();

            kunderaQuery.postParsingInit();
            m = kunderaQuery.getEntityMetadata();
        }
        else
        {
            // Means if it is a namedNativeQuery.
            if (appMetadata.isNative(jpaQuery))
            {
                mappedClass = appMetadata.getMappedClass(jpaQuery);
            }

            kunderaQuery = new KunderaQuery(jpaQuery, kunderaMetadata);

            kunderaQuery.isNativeQuery = true;

            m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, mappedClass);

            Field entityClazzField = null;
            try
            {
                entityClazzField = kunderaQuery.getClass().getDeclaredField("entityClass");
                if (entityClazzField != null && !entityClazzField.isAccessible())
                {
                    entityClazzField.setAccessible(true);
                }

                entityClazzField.set(kunderaQuery, mappedClass);
            }
            catch (Exception e)
            {
                log.error(e.getMessage());
                throw new QueryHandlerException(e);
            }
        }

        Query query = null;

        try
        {
            query = getQuery(jpaQuery, persistenceDelegator, m, kunderaQuery, kunderaMetadata);
        }
        catch (Exception e)
        {
            log.error(e.getMessage());
            throw new QueryHandlerException(e);
        }
        return query;
    }
667690
private void createResponse() {
        response = new GenericQueryResponse(
            queryErrorObservable.onBackpressureBuffer(),
            queryRowObservable.onBackpressureBuffer(),
            querySignatureObservable.onBackpressureBuffer(),
            queryStatusObservable.onBackpressureBuffer(),
            queryInfoObservable.onBackpressureBuffer(),
            queryProfileInfoObservable.onBackpressureBuffer(),
            currentRequest,
            status,
            requestID,
            clientContextID
        );
    }
839519
public JsonObject sendQuery(FutureAPIResponse response)
      throws ExecutionException, InterruptedException, IOException {
    int status = response.get().getStatus();
    String message = response.get().getMessage();

    if (status != HTTP_OK) {
      throw new IOException(status + " " + message);
    }
    return ((JsonObject) parser.parse(message));
  }
714181
public static Query toQuery(Object o) throws PageException {
	if (o instanceof Query) return (Query) o;
	if (o instanceof ObjectWrap) {
	    return toQuery(((ObjectWrap) o).getEmbededObject());
	}
	if (o instanceof ResultSet) return new QueryImpl((ResultSet) o, "query", ThreadLocalPageContext.getTimeZone());
	if (o instanceof Component) {
	    Member member = ((Component) o).getMember(Component.ACCESS_PRIVATE, KeyConstants.__toQuery, false, false);
	    if (member instanceof UDFPlus) {
		UDFPlus udf = (UDFPlus) member;
		if (udf.getReturnType() == CFTypes.TYPE_QUERY && udf.getFunctionArguments().length == 0) {
		    return Caster.toQuery(((Component) o).call(ThreadLocalPageContext.get(), KeyConstants.__toQuery, new Object[] {}));
		}
	    }
	}

	throw new CasterException(o, "query");
    }
117910
private void createView(Map<String, MapReduce> views, String columnName)
    {
        MapReduce mapr = new MapReduce();
        mapr.setMap("function(doc){if(doc." + columnName + "){emit(doc." + columnName + ", doc);}}");
        views.put(columnName, mapr);
    }
820931
@Override
	public Promise<QueryResult> query(CubeQuery cubeQuery) throws QueryException {
		DefiningClassLoader queryClassLoader = getQueryClassLoader(new CubeClassLoaderCache.Key(
				new LinkedHashSet<>(cubeQuery.getAttributes()),
				new LinkedHashSet<>(cubeQuery.getMeasures()),
				cubeQuery.getWhere().getDimensions()));
		long queryStarted = eventloop.currentTimeMillis();
		return new RequestContext<>().execute(queryClassLoader, cubeQuery)
				.whenComplete((queryResult, e) -> {
					if (e == null) {
						queryTimes.recordValue((int) (eventloop.currentTimeMillis() - queryStarted));
					} else {
						queryErrors++;
						queryLastError = e;

						if (e instanceof NoSuchFileException) {
							logger.warn("Query failed because of NoSuchFileException. " + cubeQuery.toString(), e);
						}
					}
				});
	}