org.elasticsearch.action.ActionResponse Java Examples

The following examples show how to use org.elasticsearch.action.ActionResponse. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TransportAction.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
@Override @SuppressWarnings("unchecked")
public void proceed(String action, ActionResponse response, ActionListener listener) {
    int i = index.decrementAndGet();
    try {
        if (i >= 0) {
            filters[i].apply(action, response, listener, this);
        } else if (i == -1) {
            listener.onResponse(response);
        } else {
            listener.onFailure(new IllegalStateException("proceed was called too many times"));
        }
    } catch (Throwable t) {
        logger.trace("Error during transport action execution.", t);
        listener.onFailure(t);
    }
}
 
Example #2
Source File: RangerSecurityActionFilter.java    From ranger with Apache License 2.0 6 votes vote down vote up
@Override
public <Request extends ActionRequest, Response extends ActionResponse> void apply(Task task, String action,
		Request request, ActionListener<Response> listener, ActionFilterChain<Request, Response> chain) {
	String user = threadContext.getTransient(UsernamePasswordToken.USERNAME);
	// If user is not null, then should check permission of the outside caller.
	if (StringUtils.isNotEmpty(user)) {
		List<String> indexs = RequestUtils.getIndexFromRequest(request);
		String clientIPAddress = threadContext.getTransient(RequestUtils.CLIENT_IP_ADDRESS);
		for (String index : indexs) {
			boolean result = rangerElasticsearchAuthorizer.checkPermission(user, null, index, action,
					clientIPAddress);
			if (!result) {
				String errorMsg = "Error: User[{}] could not do action[{}] on index[{}]";
				throw new ElasticsearchStatusException(errorMsg, RestStatus.FORBIDDEN, user, action, index);
			}
		}
	} else {
		if (LOG.isDebugEnabled()) {
			LOG.debug("User is null, no check permission for elasticsearch do action[{}] with request[{}]", action,
					request);
		}
	}
	chain.proceed(task, action, request, listener);
}
 
Example #3
Source File: SearchActionFilter.java    From elasticsearch-dynarank with Apache License 2.0 5 votes vote down vote up
@Override
public <Request extends ActionRequest, Response extends ActionResponse> void apply(final Task task, final String action,
        final Request request, final ActionListener<Response> listener, final ActionFilterChain<Request, Response> chain) {
    if (!SearchAction.INSTANCE.name().equals(action)) {
        chain.proceed(task, action, request, listener);
        return;
    }

    final SearchRequest searchRequest = (SearchRequest) request;
    final ActionListener<Response> wrappedListener = DynamicRanker.getInstance().wrapActionListener(action, searchRequest, listener);
    chain.proceed(task, action, request, wrappedListener == null ? listener : wrappedListener);
}
 
Example #4
Source File: LtrQueryParserPlugin.java    From elasticsearch-learning-to-rank with Apache License 2.0 5 votes vote down vote up
@Override
public List<ActionHandler<? extends ActionRequest, ? extends ActionResponse>> getActions() {
    return unmodifiableList(asList(
            new ActionHandler<>(FeatureStoreAction.INSTANCE, TransportFeatureStoreAction.class),
            new ActionHandler<>(CachesStatsAction.INSTANCE, TransportCacheStatsAction.class),
            new ActionHandler<>(ClearCachesAction.INSTANCE, TransportClearCachesAction.class),
            new ActionHandler<>(AddFeaturesToSetAction.INSTANCE, TransportAddFeatureToSetAction.class),
            new ActionHandler<>(CreateModelFromSetAction.INSTANCE, TransportCreateModelFromSetAction.class),
            new ActionHandler<>(ListStoresAction.INSTANCE, TransportListStoresAction.class)));
}
 
Example #5
Source File: ElasticsearchClientImpl.java    From herd with Apache License 2.0 5 votes vote down vote up
@Override
public <RequestT extends ActionRequest, ResponseT extends ActionResponse,
    RequestBuilderT extends ActionRequestBuilder<RequestT, ResponseT, RequestBuilderT>> ActionFuture<ResponseT> execute(
    Action<RequestT, ResponseT, RequestBuilderT> action, RequestT request)
{
    return null;
}
 
Example #6
Source File: ElasticsearchClientImpl.java    From herd with Apache License 2.0 5 votes vote down vote up
@Override
public <RequestT extends ActionRequest, ResponseT extends ActionResponse,
    RequestBuilderT extends ActionRequestBuilder<RequestT, ResponseT, RequestBuilderT>> void execute(
    Action<RequestT, ResponseT, RequestBuilderT> action, RequestT request, ActionListener<ResponseT> actionListener)
{
  // stub method
}
 
Example #7
Source File: ElasticsearchClientImpl.java    From herd with Apache License 2.0 5 votes vote down vote up
@Override
public <RequestT extends ActionRequest, ResponseT extends ActionResponse,
    RequestBuilderT extends ActionRequestBuilder<RequestT, ResponseT, RequestBuilderT>> RequestBuilderT prepareExecute(
    Action<RequestT, ResponseT, RequestBuilderT> action)
{
    return null;
}
 
Example #8
Source File: AbstractElasticsearchBackend.java    From heroic with Apache License 2.0 5 votes vote down vote up
protected  <T extends ActionResponse> ActionListener<T> bind(ResolvableFuture<T> future) {
    return new ActionListener<>() {
        @Override
        public void onResponse(T response) {
            future.resolve(response);
        }

        @Override
        public void onFailure(Exception e) {
            future.fail(e);
        }
    };
}
 
Example #9
Source File: AdapterActionFutureActionGetMethodsInterceptor.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Override
public Object afterMethod(EnhancedInstance objInst, Method method, Object[] allArguments,
                          Class<?>[] argumentsTypes, Object ret) throws Throwable {

    if (!isTrace(objInst)) {
        return ret;
    }

    AbstractSpan span = ContextManager.activeSpan();
    parseResponseInfo((ActionResponse) ret, span);
    ContextManager.stopSpan();
    return ret;
}
 
Example #10
Source File: AdapterActionFutureActionGetMethodsInterceptor.java    From skywalking with Apache License 2.0 5 votes vote down vote up
private void parseResponseInfo(ActionResponse response, AbstractSpan span) {
    // search response
    if (response instanceof SearchResponse) {
        parseSearchResponse((SearchResponse) response, span);
        return;
    }
    // bulk response
    if (response instanceof BulkResponse) {
        parseBulkResponse((BulkResponse) response, span);
        return;
    }
    // get response
    if (response instanceof GetResponse) {
        parseGetResponse((GetResponse) response, span);
        return;
    }
    // index response
    if (response instanceof IndexResponse) {
        parseIndexResponse((IndexResponse) response, span);
        return;
    }
    // update response
    if (response instanceof UpdateResponse) {
        parseUpdateResponse((UpdateResponse) response, span);
        return;
    }
    // delete response
    if (response instanceof DeleteResponse) {
        parseDeleteResponse((DeleteResponse) response, span);
        return;
    }
}
 
Example #11
Source File: AnomalyDetectorPlugin.java    From anomaly-detection with Apache License 2.0 5 votes vote down vote up
@Override
public List<ActionHandler<? extends ActionRequest, ? extends ActionResponse>> getActions() {
    return Arrays
        .asList(
            new ActionHandler<>(DeleteModelAction.INSTANCE, DeleteModelTransportAction.class),
            new ActionHandler<>(StopDetectorAction.INSTANCE, StopDetectorTransportAction.class),
            new ActionHandler<>(RCFResultAction.INSTANCE, RCFResultTransportAction.class),
            new ActionHandler<>(ThresholdResultAction.INSTANCE, ThresholdResultTransportAction.class),
            new ActionHandler<>(AnomalyResultAction.INSTANCE, AnomalyResultTransportAction.class),
            new ActionHandler<>(CronAction.INSTANCE, CronTransportAction.class),
            new ActionHandler<>(ADStatsNodesAction.INSTANCE, ADStatsNodesTransportAction.class),
            new ActionHandler<>(ProfileAction.INSTANCE, ProfileTransportAction.class)
        );
}
 
Example #12
Source File: ElasticsearchClusterRunner.java    From elasticsearch-cluster-runner with Apache License 2.0 5 votes vote down vote up
private void onFailure(final String message, final ActionResponse response) {
    if (printOnFailure) {
        print(message);
    } else {
        throw new ClusterRunnerException(message, response);
    }
}
 
Example #13
Source File: BundlePlugin.java    From elasticsearch-plugin-bundle with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public List<ActionHandler<? extends ActionRequest, ? extends ActionResponse>> getActions() {
    List<ActionHandler<? extends ActionRequest, ? extends ActionResponse>> extra = new ArrayList<>();
    if (settings.getAsBoolean("plugins.xbib.isbnformat.enabled", true)) {
        extra.add(new ActionHandler<>(ISBNFormatAction.INSTANCE, TransportISBNFormatAction.class));
    }
    if (settings.getAsBoolean("plugins.xbib.langdetect.enabled", true)) {
        extra.add(new ActionHandler<>(LangdetectAction.INSTANCE, TransportLangdetectAction.class));
    }
    return extra;
}
 
Example #14
Source File: HttpInvoker.java    From elasticsearch-helper with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>>
        void doExecute(Action<Request, Response, RequestBuilder> action, Request request, ActionListener<Response> listener) {
    HttpElasticsearchClient.ActionEntry entry = actionMap.get(action.name());
    if (entry == null) {
        throw new IllegalStateException("no action entry for " + action.name());
    }
    HttpAction<Request, Response> httpAction = entry.httpAction;
    if (httpAction == null) {
        throw new IllegalStateException("failed to find action [" + action + "] to execute");
    }
    HttpInvocationContext<Request, Response> httpInvocationContext = new HttpInvocationContext(httpAction, listener, new LinkedList<>(), request);
    try {
        httpInvocationContext.httpRequest = httpAction.createHttpRequest(this.url, request);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(url.getHost(), url.getPort()));
    future.awaitUninterruptibly();
    if (!future.isSuccess()) {
        bootstrap.releaseExternalResources();
        logger.error("can't connect to {}", url);
    } else {
        Channel channel = future.getChannel();
        httpInvocationContext.setChannel(channel);
        contexts.put(channel, httpInvocationContext);
        channel.getConfig().setConnectTimeoutMillis(settings.getAsInt("http.client.timeout", 5000));
        httpAction.execute(httpInvocationContext, listener);
    }
}
 
Example #15
Source File: HttpInvoker.java    From elasticsearch-helper with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public <Request extends ActionRequest, Response extends ActionResponse> void registerAction(GenericAction<Request, Response> action, Class<? extends HttpAction<Request, Response>> httpAction) {
    try {
        HttpAction<Request, Response> instance = httpAction.getDeclaredConstructor(Settings.class).newInstance(settings);
        actionMap.put(action.name(), new HttpElasticsearchClient.ActionEntry<>(action, instance));
    } catch (NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException e ) {
        logger.error(e.getMessage(), e);
    }
}
 
Example #16
Source File: HttpElasticsearchClient.java    From elasticsearch-helper with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>> void doExecute(Action<Request, Response, RequestBuilder> action, Request request, ActionListener<Response> listener) {
    ActionEntry entry = actionMap.get(action.name());
    if (entry == null) {
        throw new IllegalStateException("no action entry for " + action.name());
    }
    HttpAction<Request, Response> httpAction = entry.httpAction;
    if (httpAction == null) {
        throw new IllegalStateException("failed to find action [" + action + "] to execute");
    }
    HttpInvocationContext<Request, Response> httpInvocationContext = new HttpInvocationContext(httpAction, listener, new LinkedList<>(), request);
    try {
        httpInvocationContext.httpRequest = httpAction.createHttpRequest(this.url, request);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(url.getHost(), url.getPort()));
    future.awaitUninterruptibly();
    if (!future.isSuccess()) {
        bootstrap.releaseExternalResources();
        logger.error("can't connect to {}", url);
    } else {
        Channel channel = future.getChannel();
        httpInvocationContext.setChannel(channel);
        contextMap.put(channel, httpInvocationContext);
        channel.getConfig().setConnectTimeoutMillis(settings.getAsInt("http.client.timeout", 5000));
        httpAction.execute(httpInvocationContext, listener);
    }
}
 
Example #17
Source File: HttpElasticsearchClient.java    From elasticsearch-helper with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public <Request extends ActionRequest, Response extends ActionResponse> void registerAction(GenericAction<Request, Response> action,
                                                                                            Class<? extends HttpAction<Request, Response>> httpAction) {
    try {
        HttpAction<Request, Response> instance = httpAction.getDeclaredConstructor(Settings.class).newInstance(settings);
        actionMap.put(action.name(), new ActionEntry<>(action, instance));
    } catch (NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException e ) {
        logger.error(e.getMessage(), e);
    }
}
 
Example #18
Source File: TransportReplicaShardIngestAction.java    From elasticsearch-helper with Apache License 2.0 5 votes vote down vote up
@Override
public void messageReceived(final ReplicaOperationRequest request, final TransportChannel channel) throws Exception {
    try {
        ActionResponse response = shardOperationOnReplica(request);
        channel.sendResponse(response);
    } catch (Throwable t) {
        logger.error(t.getMessage(), t);
        channel.sendResponse(t);
    }
}
 
Example #19
Source File: ClusteringPlugin.java    From elasticsearch-carrot2 with Apache License 2.0 5 votes vote down vote up
@Override
public List<ActionHandler<? extends ActionRequest, ? extends ActionResponse>> getActions() {
   if (pluginEnabled) {
      return Arrays.asList(
          new ActionHandler<>(ClusteringAction.INSTANCE, TransportClusteringAction.class),
          new ActionHandler<>(ListAlgorithmsAction.INSTANCE, ListAlgorithmsAction.TransportListAlgorithmsAction.class));
   }
   return Collections.emptyList();
}
 
Example #20
Source File: ElasticSearchHelper.java    From camunda-bpm-elasticsearch with Apache License 2.0 5 votes vote down vote up
public static String convertResponseToJson(ActionResponse response) throws IOException {
    BytesStreamOutput bytesStreamOutput = new BytesStreamOutput();
    response.writeTo(bytesStreamOutput);

    XContentBuilder builder = XContentFactory.jsonBuilder(bytesStreamOutput);
    builder.prettyPrint();

//    builder.startObject();
//    builder.endObject();
    return builder.bytes().toUtf8();
  }
 
Example #21
Source File: AnomalyResultResponse.java    From anomaly-detection with Apache License 2.0 5 votes vote down vote up
public static AnomalyResultResponse fromActionResponse(final ActionResponse actionResponse) {
    if (actionResponse instanceof AnomalyResultResponse) {
        return (AnomalyResultResponse) actionResponse;
    }

    try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); OutputStreamStreamOutput osso = new OutputStreamStreamOutput(baos)) {
        actionResponse.writeTo(osso);
        try (InputStreamStreamInput input = new InputStreamStreamInput(new ByteArrayInputStream(baos.toByteArray()))) {
            return new AnomalyResultResponse(input);
        }
    } catch (IOException e) {
        throw new IllegalArgumentException("failed to parse ActionResponse into AnomalyResultResponse", e);
    }
}
 
Example #22
Source File: StopDetectorResponse.java    From anomaly-detection with Apache License 2.0 5 votes vote down vote up
public static StopDetectorResponse fromActionResponse(final ActionResponse actionResponse) {
    if (actionResponse instanceof StopDetectorResponse) {
        return (StopDetectorResponse) actionResponse;
    }

    try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); OutputStreamStreamOutput osso = new OutputStreamStreamOutput(baos)) {
        actionResponse.writeTo(osso);
        try (InputStreamStreamInput input = new InputStreamStreamInput(new ByteArrayInputStream(baos.toByteArray()))) {
            return new StopDetectorResponse(input);
        }
    } catch (IOException e) {
        throw new IllegalArgumentException("failed to parse ActionResponse into StopDetectorResponse", e);
    }
}
 
Example #23
Source File: ClientUtil.java    From anomaly-detection with Apache License 2.0 5 votes vote down vote up
/**
 * Send a nonblocking request with a timeout and return response. Blocking is not allowed in a
 * transport call context. See BaseFuture.blockingAllowed
 * @param request request like index/search/get
 * @param LOG log
 * @param consumer functional interface to operate as a client request like client::get
 * @param <Request> ActionRequest
 * @param <Response> ActionResponse
 * @return the response
 * @throws ElasticsearchTimeoutException when we cannot get response within time.
 * @throws IllegalStateException when the waiting thread is interrupted
 */
public <Request extends ActionRequest, Response extends ActionResponse> Optional<Response> timedRequest(
    Request request,
    Logger LOG,
    BiConsumer<Request, ActionListener<Response>> consumer
) {
    try {
        AtomicReference<Response> respReference = new AtomicReference<>();
        final CountDownLatch latch = new CountDownLatch(1);

        consumer
            .accept(
                request,
                new LatchedActionListener<Response>(
                    ActionListener
                        .wrap(
                            response -> { respReference.set(response); },
                            exception -> { LOG.error("Cannot get response for request {}, error: {}", request, exception); }
                        ),
                    latch
                )
            );

        if (!latch.await(requestTimeout.getSeconds(), TimeUnit.SECONDS)) {
            throw new ElasticsearchTimeoutException("Cannot get response within time limit: " + request.toString());
        }
        return Optional.ofNullable(respReference.get());
    } catch (InterruptedException e1) {
        LOG.error(CommonErrorMessages.WAIT_ERR_MSG);
        throw new IllegalStateException(e1);
    }
}
 
Example #24
Source File: ClientUtil.java    From anomaly-detection with Apache License 2.0 5 votes vote down vote up
/**
 * Send an asynchronous request and handle response with the provided listener.
 * @param <Request> ActionRequest
 * @param <Response> ActionResponse
 * @param request request body
 * @param consumer request method, functional interface to operate as a client request like client::get
 * @param listener needed to handle response
 */
public <Request extends ActionRequest, Response extends ActionResponse> void asyncRequest(
    Request request,
    BiConsumer<Request, ActionListener<Response>> consumer,
    ActionListener<Response> listener
) {
    consumer
        .accept(
            request,
            ActionListener.wrap(response -> { listener.onResponse(response); }, exception -> { listener.onFailure(exception); })
        );
}
 
Example #25
Source File: ClientUtil.java    From anomaly-detection with Apache License 2.0 5 votes vote down vote up
/**
 * Execute a transport action and handle response with the provided listener.
 * @param <Request> ActionRequest
 * @param <Response> ActionResponse
 * @param action transport action
 * @param request request body
 * @param listener needed to handle response
 */
public <Request extends ActionRequest, Response extends ActionResponse> void execute(
    ActionType<Response> action,
    Request request,
    ActionListener<Response> listener
) {
    client
        .execute(
            action,
            request,
            ActionListener.wrap(response -> { listener.onResponse(response); }, exception -> { listener.onFailure(exception); })
        );
}
 
Example #26
Source File: ElasticsearchWebClient.java    From staccato with Apache License 2.0 5 votes vote down vote up
/**
 * Utility method to deserialize responses from Elasticsearch into the response objects provided by Elasticsearch's
 * Java library.
 *
 * @param bytes The byte array response from the Elasticsearch request
 * @param clazz Class class for the Elasticsearch response class that the method should attempt to deserialize to
 * @param <T> The Elasticsearch response class that the method should attempt to deserialize to
 * @return The deserialized response
 */
private <T extends ActionResponse> T deserializeResponse(byte[] bytes, Class<T> clazz) {
    try {

        Method fromXContent = clazz.getMethod("fromXContent", XContentParser.class);
        XContentParser parser = XContentFactory
                .xContent(XContentType.JSON)
                .createParser(NamedXContentRegistry.EMPTY, null, bytes);
        return (T)fromXContent.invoke(null, parser);
    } catch (Exception e) {
        log.error("Error deserializing Elasticsearch SearchResponse.", e);
        throw new ItemException("An error occurred processing the result from the database.  Please contact an administrator.");
    }
}
 
Example #27
Source File: ClientUtil.java    From anomaly-detection with Apache License 2.0 4 votes vote down vote up
/**
 * Send a nonblocking request with a timeout and return response.
 * If there is already a query running on given detector, it will try to
 * cancel the query. Otherwise it will add this query to the negative cache
 * and then attach the AnomalyDetection specific header to the request.
 * Once the request complete, it will be removed from the negative cache.
 * @param <Request> ActionRequest
 * @param <Response> ActionResponse
 * @param request request like index/search/get
 * @param LOG log
 * @param consumer functional interface to operate as a client request like client::get
 * @param detector Anomaly Detector
 * @return the response
 * @throws InternalFailure when there is already a query running
 * @throws ElasticsearchTimeoutException when we cannot get response within time.
 * @throws IllegalStateException when the waiting thread is interrupted
 */
public <Request extends ActionRequest, Response extends ActionResponse> Optional<Response> throttledTimedRequest(
    Request request,
    Logger LOG,
    BiConsumer<Request, ActionListener<Response>> consumer,
    AnomalyDetector detector
) {

    try {
        String detectorId = detector.getDetectorId();
        if (!throttler.insertFilteredQuery(detectorId, request)) {
            LOG.info("There is one query running for detectorId: {}. Trying to cancel the long running query", detectorId);
            cancelRunningQuery(client, detectorId, LOG);
            throw new InternalFailure(detector.getDetectorId(), "There is already a query running on AnomalyDetector");
        }
        AtomicReference<Response> respReference = new AtomicReference<>();
        final CountDownLatch latch = new CountDownLatch(1);

        try (ThreadContext.StoredContext context = threadPool.getThreadContext().stashContext()) {
            assert context != null;
            threadPool.getThreadContext().putHeader(Task.X_OPAQUE_ID, CommonName.ANOMALY_DETECTOR + ":" + detectorId);
            consumer.accept(request, new LatchedActionListener<Response>(ActionListener.wrap(response -> {
                // clear negative cache
                throttler.clearFilteredQuery(detectorId);
                respReference.set(response);
            }, exception -> {
                // clear negative cache
                throttler.clearFilteredQuery(detectorId);
                LOG.error("Cannot get response for request {}, error: {}", request, exception);
            }), latch));
        } catch (Exception e) {
            LOG.error("Failed to process the request for detectorId: {}.", detectorId);
            throttler.clearFilteredQuery(detectorId);
            throw e;
        }

        if (!latch.await(requestTimeout.getSeconds(), TimeUnit.SECONDS)) {
            throw new ElasticsearchTimeoutException("Cannot get response within time limit: " + request.toString());
        }
        return Optional.ofNullable(respReference.get());
    } catch (InterruptedException e1) {
        LOG.error(CommonErrorMessages.WAIT_ERR_MSG);
        throw new IllegalStateException(e1);
    }
}
 
Example #28
Source File: QueryActionElasticExecutor.java    From elasticsearch-sql with Apache License 2.0 4 votes vote down vote up
public static ActionResponse executeDeleteAction(DeleteQueryAction deleteQueryAction) throws SqlParseException {
    return deleteQueryAction.explain().get();
}
 
Example #29
Source File: ClientWithStats.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public <Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>> ActionFuture<Response> execute(
		Action<Request, Response, RequestBuilder> action, Request request) {
	return wrapped.execute(action, request);
}
 
Example #30
Source File: ShowQueryAction.java    From elasticsearch-sql with Apache License 2.0 4 votes vote down vote up
@Override
public SqlElasticRequestBuilder explain() throws SqlParseException {
    String sql = this.sql.replaceAll("\\s+"," ");
    //todo: support indices with space?
    String indexName = sql.split(" ")[1];
    final GetIndexRequestBuilder  indexRequestBuilder ;
    String type = null;
    if (indexName.startsWith("<")) {
        if (!indexName.endsWith(">")) {
            int index = indexName.lastIndexOf('/');
            if (-1 < index) {
                type = indexName.substring(index + 1);
                indexName = indexName.substring(0, index);
            }
        }
    } else if (indexName.contains("/")) {
        String[] indexAndType = indexName.split("\\/");
        indexName = indexAndType[0];
        type = indexAndType[1];
    }
    indexRequestBuilder = client.admin().indices().prepareGetIndex();

    if(!indexName.equals("*")){
        indexRequestBuilder.addIndices(indexName);
        if(type!=null && !type.equals("")){
            indexRequestBuilder.setTypes(type);
        }
    }
    indexRequestBuilder.addFeatures(GetIndexRequest.Feature.MAPPINGS);

    return new SqlElasticRequestBuilder() {
        @Override
        public ActionRequest request() {
            return indexRequestBuilder.request();
        }

        @Override
        public String explain() {
            return indexRequestBuilder.toString();
        }

        @Override
        public ActionResponse get() {
            return indexRequestBuilder.get();
        }

        @Override
        public ActionRequestBuilder getBuilder() {
            return indexRequestBuilder;
        }
    };
}