Java Code Examples for org.elasticsearch.action.ActionListener#onFailure()
The following examples show how to use
org.elasticsearch.action.ActionListener#onFailure() .
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: TransportBulkCreateIndicesAction.java From Elasticsearch with Apache License 2.0 | 6 votes |
@Override protected void masterOperation(final BulkCreateIndicesRequest request, final ClusterState state, final ActionListener<BulkCreateIndicesResponse> listener) throws ElasticsearchException { if (request.indices().isEmpty()) { listener.onResponse(new BulkCreateIndicesResponse(true)); return; } final ActionListener<ClusterStateUpdateResponse> stateUpdateListener = new ActionListener<ClusterStateUpdateResponse>() { @Override public void onResponse(ClusterStateUpdateResponse clusterStateUpdateResponse) { listener.onResponse(new BulkCreateIndicesResponse(true)); } @Override public void onFailure(Throwable e) { listener.onFailure(e); } }; createIndices(request, stateUpdateListener); }
Example 2
Source File: RecoveryTarget.java From crate with Apache License 2.0 | 6 votes |
@Override public void writeFileChunk(StoreFileMetaData fileMetaData, long position, BytesReference content, boolean lastChunk, int totalTranslogOps, ActionListener<Void> listener) { try { state().getTranslog().totalOperations(totalTranslogOps); final FileChunkWriter writer = fileChunkWriters .computeIfAbsent(fileMetaData.name(), name -> new FileChunkWriter()); writer.writeChunk(new FileChunk(fileMetaData, content, position, lastChunk)); listener.onResponse(null); } catch (Exception e) { listener.onFailure(e); } }
Example 3
Source File: CustomCachingRealm.java From shield-custom-realm-example with Apache License 2.0 | 6 votes |
/** * Method that handles the actual authentication of the token. This method will only be called if the token is a * supported token. The method validates the credentials of the user and if they match, a {@link User} will be * returned as the argument to the {@code listener}'s {@link ActionListener#onResponse(Object)} method. Else * {@code null} is returned. * @param authenticationToken the token to authenticate * @param listener return authentication result by calling {@link ActionListener#onResponse(Object)} */ @Override public void authenticate(AuthenticationToken authenticationToken, ActionListener<AuthenticationResult> listener) { try { UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken; UserHolder userHolder = cache.get(token.principal()); // NOTE the null check for the password. This is done because a cache is shared between authentication and lookup // lookup will not store the password... if (userHolder == null || userHolder.password == null) { super.authenticate(token, ActionListener.wrap(authenticationResult -> { if (authenticationResult.isAuthenticated()) { cache.put(token.principal(), new UserHolder(token.credentials().clone().getChars(), authenticationResult.getUser())); } listener.onResponse(authenticationResult); }, listener::onFailure)); } else if (token.credentials().equals(new SecureString(userHolder.password))) { listener.onResponse(AuthenticationResult.success(userHolder.user)); } else { listener.onResponse(AuthenticationResult.notHandled()); } } catch (Exception e) { listener.onFailure(e); } }
Example 4
Source File: TransportReplicationAction.java From crate with Apache License 2.0 | 6 votes |
@Override public void performOn( final ShardRouting replica, final ReplicaRequest request, final long globalCheckpoint, final long maxSeqNoOfUpdatesOrDeletes, final ActionListener<ReplicationOperation.ReplicaResponse> listener) { String nodeId = replica.currentNodeId(); final DiscoveryNode node = clusterService.state().nodes().get(nodeId); if (node == null) { listener.onFailure(new NoNodeAvailableException("unknown node [" + nodeId + "]")); return; } final ConcreteReplicaRequest<ReplicaRequest> replicaRequest = new ConcreteReplicaRequest<>( request, replica.allocationId().getId(), primaryTerm, globalCheckpoint, maxSeqNoOfUpdatesOrDeletes); sendReplicaRequest(replicaRequest, node, listener); }
Example 5
Source File: Transports.java From crate with Apache License 2.0 | 6 votes |
public <TRequest extends TransportRequest, TResponse extends TransportResponse> void sendRequest( String action, String node, TRequest request, ActionListener<TResponse> listener, TransportResponseHandler<TResponse> handler, TransportRequestOptions options) { DiscoveryNode discoveryNode = clusterService.state().nodes().get(node); if (discoveryNode == null) { listener.onFailure(new NodeNotConnectedException(null, String.format(Locale.ENGLISH, "node \"%s\" not found in cluster state!", node))); return; } transportService.sendRequest(discoveryNode, action, request, options, handler); }
Example 6
Source File: ThresholdResultTransportAction.java From anomaly-detection with Apache License 2.0 | 6 votes |
@Override protected void doExecute(Task task, ThresholdResultRequest request, ActionListener<ThresholdResultResponse> listener) { try { LOG.info("Serve threshold request for {}", request.getModelID()); manager .getThresholdingResult( request.getAdID(), request.getModelID(), request.getRCFScore(), ActionListener .wrap( result -> listener.onResponse(new ThresholdResultResponse(result.getGrade(), result.getConfidence())), exception -> listener.onFailure(exception) ) ); } catch (Exception e) { LOG.error(e); listener.onFailure(e); } }
Example 7
Source File: Coordinator.java From crate with Apache License 2.0 | 6 votes |
private <T> ActionListener<T> wrapWithMutex(ActionListener<T> listener) { return new ActionListener<T>() { @Override public void onResponse(T t) { synchronized (mutex) { listener.onResponse(t); } } @Override public void onFailure(Exception e) { synchronized (mutex) { listener.onFailure(e); } } }; }
Example 8
Source File: BlobStoreRepository.java From crate with Apache License 2.0 | 6 votes |
@Override public void deleteSnapshot(SnapshotId snapshotId, long repositoryStateId, boolean writeShardGens, ActionListener<Void> listener) { if (isReadOnly()) { listener.onFailure(new RepositoryException(metadata.name(), "cannot delete snapshot from a readonly repository")); } else { try { final Map<String, BlobMetaData> rootBlobs = blobContainer().listBlobs(); final RepositoryData repositoryData = getRepositoryData(latestGeneration(rootBlobs.keySet())); // Cache the indices that were found before writing out the new index-N blob so that a stuck master will never // delete an index that was created by another master node after writing this index-N blob. final Map<String, BlobContainer> foundIndices = blobStore().blobContainer(indicesPath()).children(); doDeleteShardSnapshots(snapshotId, repositoryStateId, foundIndices, rootBlobs, repositoryData, writeShardGens, listener); } catch (Exception ex) { listener.onFailure(new RepositoryException(metadata.name(), "failed to delete snapshot [" + snapshotId + "]", ex)); } } }
Example 9
Source File: AnomalyResultTransportAction.java From anomaly-detection with Apache License 2.0 | 5 votes |
void handleExecuteException(Exception ex, ActionListener<AnomalyResultResponse> listener, String adID) { if (ex instanceof ClientException) { listener.onFailure(ex); } else if (ex instanceof AnomalyDetectionException) { listener.onFailure(new InternalFailure((AnomalyDetectionException) ex)); } else { Throwable cause = ExceptionsHelper.unwrapCause(ex); listener.onFailure(new InternalFailure(adID, cause)); } }
Example 10
Source File: IndexShardOperationPermits.java From crate with Apache License 2.0 | 5 votes |
private void acquire(final ActionListener<Releasable> onAcquired, final String executorOnDelay, final boolean forceExecution, final Object debugInfo, final StackTraceElement[] stackTrace) { if (closed) { onAcquired.onFailure(new IndexShardClosedException(shardId)); return; } final Releasable releasable; try { synchronized (this) { if (queuedBlockOperations > 0) { final ActionListener<Releasable> wrappedListener; if (executorOnDelay != null) { wrappedListener = new PermitAwareThreadedActionListener( threadPool, executorOnDelay, onAcquired, forceExecution ); } else { wrappedListener = onAcquired; } delayedOperations.add(new DelayedOperation(wrappedListener, debugInfo, stackTrace)); return; } else { releasable = acquire(debugInfo, stackTrace); } } } catch (final InterruptedException e) { onAcquired.onFailure(e); return; } // execute this outside the synchronized block! onAcquired.onResponse(releasable); }
Example 11
Source File: XlsContent.java From elasticsearch-dataformat with Apache License 2.0 | 5 votes |
@Override public void write(final File outputFile, final SearchResponse response, final RestChannel channel, final ActionListener<Void> listener) { try { final OnLoadListener onLoadListener = new OnLoadListener(outputFile, listener); onLoadListener.onResponse(response); } catch (final Exception e) { listener.onFailure(new ElasticsearchException("Failed to write data.", e)); } }
Example 12
Source File: TransportReplicationAction.java From crate with Apache License 2.0 | 5 votes |
public void respond(ActionListener<TransportResponse.Empty> listener) { if (finalFailure == null) { listener.onResponse(TransportResponse.Empty.INSTANCE); } else { listener.onFailure(finalFailure); } }
Example 13
Source File: CsvContent.java From elasticsearch-dataformat with Apache License 2.0 | 5 votes |
@Override public void write(final File outputFile, final SearchResponse response, final RestChannel channel, final ActionListener<Void> listener) { try { final OnLoadListener onLoadListener = new OnLoadListener( outputFile, listener); onLoadListener.onResponse(response); } catch (final Exception e) { listener.onFailure(new ElasticsearchException("Failed to write data.", e)); } }
Example 14
Source File: TransportRequestDeduplicator.java From crate with Apache License 2.0 | 5 votes |
CompositeListener addListener(ActionListener<Void> listener) { synchronized (this) { if (this.isNotified == false) { listeners.add(listener); return listeners.size() == 1 ? this : null; } } if (failure != null) { listener.onFailure(failure); } else { listener.onResponse(null); } return null; }
Example 15
Source File: PublicationTransportHandler.java From crate with Apache License 2.0 | 5 votes |
private void sendFullClusterState(ClusterState clusterState, Map<Version, BytesReference> serializedStates, DiscoveryNode node, ActionListener<PublishWithJoinResponse> responseActionListener) { BytesReference bytes = serializedStates.get(node.getVersion()); if (bytes == null) { try { bytes = serializeFullClusterState(clusterState, node.getVersion()); serializedStates.put(node.getVersion(), bytes); } catch (Exception e) { LOGGER.warn(() -> new ParameterizedMessage("failed to serialize cluster state before publishing it to node {}", node), e); responseActionListener.onFailure(e); return; } } sendClusterStateToNode(clusterState, bytes, node, responseActionListener, false, serializedStates); }
Example 16
Source File: AbstractListenableActionFuture.java From Elasticsearch with Apache License 2.0 | 5 votes |
private void executeListener(final ActionListener<T> listener) { try { // we use a timeout of 0 to by pass assertion forbidding to call actionGet() (blocking) on a network thread. // here we know we will never block listener.onResponse(actionGet(0)); } catch (Throwable e) { listener.onFailure(e); } }
Example 17
Source File: JsonContent.java From elasticsearch-dataformat with Apache License 2.0 | 5 votes |
@Override public void write(final File outputFile, final SearchResponse response, final RestChannel channel, final ActionListener<Void> listener) { try { final OnLoadListener onLoadListener = new OnLoadListener( outputFile, listener); onLoadListener.onResponse(response); } catch (final Exception e) { listener.onFailure(new ElasticsearchException("Failed to write data.", e)); } }
Example 18
Source File: TransportAction.java From crate with Apache License 2.0 | 5 votes |
/** * Use this method when the transport action should continue to run in the context of the current task */ public final void execute(Task task, Request request, ActionListener<Response> listener) { try { doExecute(task, request, listener); } catch (Exception e) { listener.onFailure(e); } }
Example 19
Source File: HttpAction.java From elasticsearch-helper with Apache License 2.0 | 5 votes |
public final void execute(HttpInvocationContext<Request,Response> httpInvocationContext, ActionListener<Response> listener) { ActionRequestValidationException validationException = httpInvocationContext.getRequest().validate(); if (validationException != null) { listener.onFailure(validationException); return; } httpInvocationContext.setListener(listener); httpInvocationContext.setMillis(System.currentTimeMillis()); try { doExecute(httpInvocationContext); } catch(Throwable t) { logger.error("exception during http action execution", t); listener.onFailure(t); } }
Example 20
Source File: AnomalyResultTransportAction.java From anomaly-detection with Apache License 2.0 | 3 votes |
/** * All the exceptions thrown by AD is a subclass of AnomalyDetectionException. * ClientException is a subclass of AnomalyDetectionException. All exception visible to * Client is under ClientVisible. Two classes directly extends ClientException: * - InternalFailure for "root cause unknown failure. Maybe transient." We can continue the * detector running. * - EndRunException for "failures that might impact the customer." The method endNow() is * added to indicate whether the client should immediately terminate running a detector. * + endNow() returns true for "unrecoverable issue". We want to terminate the detector run * immediately. * + endNow() returns false for "maybe unrecoverable issue but worth retrying a few more * times." We want to wait for a few more times on different requests before terminating * the detector run. * * AD may not be able to get an anomaly grade but can find a feature vector. Consider the * case when the shingle is not ready. In that case, AD just put NaN as anomaly grade and * return the feature vector. If AD cannot even find a feature vector, AD throws * EndRunException if there is an issue or returns empty response (all the numeric fields * are Double.NaN and feature array is empty. Do so so that customer can write painless * script.) otherwise. * * Also, AD is responsible for logging the stack trace. To avoid bloating our logs, alerting * should always just log the message of an AnomalyDetectionException exception by default. * * Known cause of EndRunException with endNow returning false: * + training data for cold start not available * + cold start cannot succeed * + unknown prediction error * + memory circuit breaker tripped * * Known cause of EndRunException with endNow returning true: * + a model's memory size reached limit * + models' total memory size reached limit * + Having trouble querying feature data due to * * index does not exist * * all features have been disabled * + anomaly detector is not available * + AD plugin is disabled * * Known cause of InternalFailure: * + threshold model node is not available * + cluster read/write is blocked * + cold start hasn't been finished * + fail to get all of rcf model nodes' responses * + fail to get threshold model node's response * + RCF/Threshold model node failing to get checkpoint to restore model before timeout * + Detection is throttle because previous detection query is running * */ @Override protected void doExecute(Task task, ActionRequest actionRequest, ActionListener<AnomalyResultResponse> listener) { AnomalyResultRequest request = AnomalyResultRequest.fromActionRequest(actionRequest); ActionListener<AnomalyResultResponse> original = listener; listener = ActionListener.wrap(original::onResponse, e -> { adStats.getStat(StatNames.AD_EXECUTE_FAIL_COUNT.getName()).increment(); original.onFailure(e); }); String adID = request.getAdID(); if (!EnabledSetting.isADPluginEnabled()) { throw new EndRunException(adID, CommonErrorMessages.DISABLED_ERR_MSG, true); } adStats.getStat(StatNames.AD_EXECUTE_REQUEST_COUNT.getName()).increment(); if (adCircuitBreakerService.isOpen()) { listener.onFailure(new LimitExceededException(adID, CommonErrorMessages.MEMORY_CIRCUIT_BROKEN_ERR_MSG, false)); return; } try { stateManager.getAnomalyDetector(adID, onGetDetector(listener, adID, request)); } catch (Exception ex) { handleExecuteException(ex, listener, adID); } }