Java org.elasticsearch.action.ActionListener 代码实例

・14 分钟阅读

以下是展示如何使用org.elasticsearch.action.ActionListener的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1


public void execute(DeleteIndexRequest request, final ActionListener<DeleteIndexResponse> listener) {
    logger.debug("delete index request {}", request);
    try {
        String[] indices = DeleteIndexRequestAccessor.indices(request);
        if (indices.length == 0) {
            throw new IllegalArgumentException("missing indices");
        }
        RequestUriBuilder uriBuilder = new RequestUriBuilder(Strings.arrayToCommaDelimitedString(indices));
        uriBuilder.addQueryParameter("timeout", request.timeout().toString());
        uriBuilder.addQueryParameter("master_timeout", request.timeout().toString());
        uriBuilder.addIndicesOptions(request);
        indicesAdminClient.getHttpClient().submit(HttpClientRequest.createDelete(uriBuilder.toString()))
                .flatMap(HANDLES_404)
                .flatMap(new Func1<HttpClientResponse<ByteBuf>, Observable<DeleteIndexResponse>>() {
                    @Override
                    public Observable<DeleteIndexResponse> call(final HttpClientResponse<ByteBuf> response) {
                        return response.getContent().flatMap(new Func1<ByteBuf, Observable<DeleteIndexResponse>>() {
                            @Override
                            public Observable<DeleteIndexResponse> call(ByteBuf byteBuf) {
                                return DeleteIndexResponse.parse(byteBuf, response.getStatus().code());
                            }
                        });
                    }
                })
                .single()
                .subscribe(new ListenerCompleterObserver<>(listener));
    } catch (Exception e) {
        listener.onFailure(e);
    }
}
 

实例 2


public void execute(IndicesExistsRequest request, final ActionListener<IndicesExistsResponse> listener) {
    logger.debug("indices exists request {}", request);
    try {
        RequestUriBuilder uriBuilder = new RequestUriBuilder(Strings.arrayToCommaDelimitedString(request.indices()));
        uriBuilder.addQueryParameter("local", request.local());
        uriBuilder.addIndicesOptions(request);
        indicesAdminClient.getHttpClient().submit(HttpClientRequest.<ByteBuf>create(HttpMethod.HEAD, uriBuilder.toString()))
                .flatMap(HANDLES_404)
                .flatMap(new Func1<HttpClientResponse<ByteBuf>, Observable<IndicesExistsResponse>>() {
                    @Override
                    public Observable<IndicesExistsResponse> call(final HttpClientResponse<ByteBuf> response) {
                        return IndicesExistsResponse.parse(response.getStatus().code());
                    }
                })
                .single()
                .subscribe(new ListenerCompleterObserver<>(listener));
    } catch (Exception e) {
        listener.onFailure(e);
    }
}
 

实例 3


@Override
protected void doExecute(final KnapsackPullRequest request, ActionListener<KnapsackPullResponse> listener) {
    final KnapsackState state = new KnapsackState()
            .setMode("pull")
            .setNodeName(nodeService.nodeName());
    final KnapsackPullResponse response = new KnapsackPullResponse()
            .setState(state);
    try {
        final BulkTransportClient transportClient = new BulkTransportClient();
        transportClient.flushIngestInterval(TimeValue.timeValueSeconds(5))
                .maxActionsPerRequest(request.getMaxActionsPerBulkRequest())
                .maxConcurrentRequests(request.getMaxBulkConcurrency())
                .init(clientSettings(client, environment, request));
        final BulkNodeClient nodeClient = new BulkNodeClient();
        nodeClient.flushIngestInterval(TimeValue.timeValueSeconds(5))
                .maxActionsPerRequest(request.getMaxActionsPerBulkRequest())
                .maxConcurrentRequests(request.getMaxBulkConcurrency())
                .init(client);
        state.setTimestamp(new DateTime());
        response.setRunning(true);
        knapsack.submit(new Thread() {
            public void run() {
                performPull(request, state, transportClient, nodeClient);
            }
        });
        listener.onResponse(response);
    } catch (Throwable e) {
        logger.error(e.getMessage(), e);
        listener.onFailure(e);
    }
}
 

实例 4


@Override
protected void doExecute(final KnapsackImportRequest request, ActionListener<KnapsackImportResponse> listener) {
    final KnapsackState state = new KnapsackState()
            .setMode("import")
            .setNodeName(nodeService.nodeName());
    final KnapsackImportResponse response = new KnapsackImportResponse()
            .setState(state);
    try {
        Path path = request.getArchivePath();
        if (path == null) {
            String dataPath = settings.get(KnapsackParameter.KNAPSACK_PATH, settings.get(KnapsackParameter.KNAPSACK_DEFAULT_PATH, "."));
            path = new File(dataPath + File.separator + "_all.tar.gz").toPath();
        }
        ByteSizeValue bytesToTransfer = request.getBytesToTransfer();
        BytesProgressWatcher watcher = new BytesProgressWatcher(bytesToTransfer.bytes());
        final Session<StringPacket> session = ArchiveService.newSession(path, watcher);
        EnumSet<Session.Mode> mode = EnumSet.of(Session.Mode.READ);
        session.open(mode, path);
        if (session.isOpen()) {
            final BulkNodeClient bulkClient = new BulkNodeClient();
            bulkClient.flushIngestInterval(TimeValue.timeValueSeconds(5))
                    .maxActionsPerRequest(request.getMaxActionsPerBulkRequest())
                    .maxConcurrentRequests(request.getMaxBulkConcurrency())
                    .init(client);
            state.setTimestamp(new DateTime())
                    .setPath(path);
            response.setRunning(true);
            knapsack.submit(new Thread() {
                public void run() {
                    try {
                        performImport(request, state, session, bulkClient);
                    } catch (Throwable t) {
                        //
                    }
                }
            });
        } else {
            response.setRunning(false).setReason("session can not be opened: mode=" + mode + " path=" + path);
        }
        listener.onResponse(response);
    } catch (Throwable e) {
        logger.error(e.getMessage(), e);
        listener.onFailure(e);
    }
}
 

实例 5


public void sendFreeContext(DiscoveryNode node, long contextId, ClearScrollRequest request, final ActionListener<Boolean> actionListener) {
    if (clusterService.state().nodes().localNodeId().equals(node.id())) {
        final boolean freed = searchService.freeContext(contextId);
        actionListener.onResponse(freed);
    } else {
        if (node.getVersion().onOrAfter(Version.V_1_4_0_Beta1)) {
            //use the separate action for scroll when possible
            transportService.sendRequest(node, FREE_CONTEXT_SCROLL_ACTION_NAME, new ScrollFreeContextRequest(request, contextId), new FreeContextResponseHandler(actionListener));
        } else {
            //fallback to the previous action name if the new one is not supported by the node we are talking to.
            //Do use the same request since it has the same binary format as the previous SearchFreeContextRequest (without the OriginalIndices addition).
            transportService.sendRequest(node, FREE_CONTEXT_ACTION_NAME, new ScrollFreeContextRequest(request, contextId), new FreeContextResponseHandler(actionListener));
        }
    }
}
 

实例 6


public void sendClearAllScrollContexts(DiscoveryNode node, ClearScrollRequest request, final ActionListener<Boolean> actionListener) {
    if (clusterService.state().nodes().localNodeId().equals(node.id())) {
        searchService.freeAllScrollContexts();
        actionListener.onResponse(true);
    } else {
        transportService.sendRequest(node, CLEAR_SCROLL_CONTEXTS_ACTION_NAME, new ClearScrollContextsRequest(request), new TransportResponseHandler<TransportResponse>() {
            @Override
            public TransportResponse newInstance() {
                return TransportResponse.Empty.INSTANCE;
            }
            @Override
            public void handleResponse(TransportResponse response) {
                actionListener.onResponse(true);
            }
            @Override
            public void handleException(TransportException exp) {
                actionListener.onFailure(exp);
            }
            @Override
            public String executor() {
                return ThreadPool.Names.SAME;
            }
        });
    }
}
 

实例 7


@Override
protected void masterOperation(ConsistencyCheckRequest request, ClusterState state, ActionListener<ConsistencyCheckResponse> listener) throws ElasticsearchException {
    ClusterState.Builder builder = builder(state);
    List<File> files = new ArrayList();
    builder.metaData(Skywalker.loadState(files, nodeEnv));
    listener.onResponse(new ConsistencyCheckResponse(clusterName, builder.build(), files));
}
 

实例 8


@Test
public void testNumDocs() throws Exception {
    final AtomicInteger numRequests = new AtomicInteger(0);
    final TransportSQLAction transportSQLAction = new TransportSQLAction(
            mock(ClusterService.class),
            ImmutableSettings.EMPTY,
            threadPool,
            mock(Analyzer.class),
            mock(Planner.class),
            mock(Provider.class),
            mock(TransportService.class),
            mock(StatsTables.class),
            new ActionFilters(ImmutableSet.<ActionFilter>of()),
            mock(TransportKillJobsNodeAction.class)
    ) {
        @Override
        protected void doExecute(SQLRequest request, ActionListener<SQLResponse> listener) {
            Object[] row;
            if (numRequests.get() == 0) {
                row = new Object[] { 2L, "foo", "bar"};
            } else {
                row = new Object[] { 4L, "foo", "bar"};
            }
            listener.onResponse(new SQLResponse(
                    new String[] {"cast(sum(num_docs) as long)", "schema_name", "table_name"},
                    new Object[][] { row },
                    new DataType[] {DataTypes.LONG, DataTypes.STRING, DataTypes.STRING},
                    1L,
                    1L,
                    false
            ));
            numRequests.incrementAndGet();
        }
    };
    TableStatsService statsService = new TableStatsService(
            ImmutableSettings.EMPTY, threadPool, TimeValue.timeValueMillis(100), new Provider<TransportSQLAction>() {
        @Override
        public TransportSQLAction get() {
            return transportSQLAction;
        }
    });
    assertThat(statsService.numDocs(new TableIdent("foo", "bar")), is(2L)); // first call triggers request
    assertThat(statsService.numDocs(new TableIdent("foo", "bar")), is(2L)); // second call hits cache
    int slept = 0;
    while (numRequests.get() < 2 && slept < 1000) {
        Thread.sleep(50);
        slept += 50;
    }
    // periodic update happened
    assertThat(numRequests.get(), Matchers.greaterThanOrEqualTo(2));
    assertThat(statsService.numDocs(new TableIdent("foo", "bar")), is(4L));
    assertThat(statsService.numDocs(new TableIdent("unknown", "table")), is(-1L));
}
 
讨论
淘淘あ西西 profile image