List of usage examples for com.google.common.util.concurrent Futures immediateFailedFuture
@CheckReturnValue public static <V> ListenableFuture<V> immediateFailedFuture(Throwable throwable)
From source file:org.opendaylight.faas.fabric.general.FabricServiceAPIProvider.java
@Override public Future<RpcResult<Void>> rmGateway(RmGatewayInput input) { FabricId fabricId = input.getFabricId(); final NodeId routerId = input.getLogicalRouter(); IpAddress gwIp = input.getIpAddress(); final FabricInstance fabricObj = FabricInstanceCache.INSTANCE.retrieveFabric(fabricId); if (fabricObj == null) { return Futures.immediateFailedFuture( new IllegalArgumentException(String.format("fabric %s does not exist", fabricId))); }/*w ww . j a v a 2 s . c om*/ ReadWriteTransaction trans = dataBroker.newReadWriteTransaction(); TpId tpOnRouter = null; NodeId lswId = null; TpId tpOnSwitch = null; Link link = null; tpOnRouter = new TpId(String.valueOf(gwIp.getValue())); if (tpOnRouter != null) { link = findGWLink(trans, fabricId, tpOnRouter, routerId); trans.delete(LogicalDatastoreType.OPERATIONAL, MdSalUtils.createLinkIId(fabricId, link.getLinkId())); } if (link != null) { lswId = link.getDestination().getDestNode(); tpOnSwitch = link.getDestination().getDestTp(); trans.delete(LogicalDatastoreType.OPERATIONAL, MdSalUtils.createLogicPortIId(fabricId, lswId, tpOnSwitch)); } final NodeId flswid = lswId == null ? null : lswId; trans.delete(LogicalDatastoreType.OPERATIONAL, MdSalUtils.createLogicPortIId(fabricId, routerId, tpOnRouter)); return Futures.transform(trans.submit(), new AsyncFunction<Void, RpcResult<Void>>() { @Override public ListenableFuture<RpcResult<Void>> apply(Void submitResult) throws Exception { fabricObj.notifyGatewayRemoved(flswid, routerId); return Futures.immediateFuture(RpcResultBuilder.<Void>success().build()); } }, executor); }
From source file:com.microsoft.azure.keyvault.cryptography.SymmetricKey.java
@Override public ListenableFuture<Boolean> verifyAsync(final byte[] digest, final byte[] signature, final String algorithm) { return Futures.immediateFailedFuture(new NotImplementedException("verifyAsync is not currently supported")); }
From source file:com.google.gapid.views.GeometryView.java
private static ListenableFuture<Model> fetchModel(GfxAPI.Mesh mesh) { Vertex.Buffer vb = mesh.getVertexBuffer(); float[] positions = null; float[] normals = null; for (Vertex.Stream stream : vb.getStreamsList()) { switch (stream.getSemantic().getType()) { case Position: positions = byteStringToFloatArray(stream.getData()); break; case Normal: normals = byteStringToFloatArray(stream.getData()); break; default:/*w ww .java2 s. c o m*/ // Ignore. } } GfxAPI.DrawPrimitive primitive = mesh.getDrawPrimitive(); if (positions == null || (normals == null && isPolygon(primitive))) { return Futures.immediateFailedFuture(new DataUnavailableException(NO_MESH_ERR)); } int[] indices = mesh.getIndexBuffer().getIndicesList().stream().mapToInt(x -> x).toArray(); Model model = new Model(primitive, positions, normals, indices); return Futures.immediateFuture(model); }
From source file:com.spotify.asyncdatastoreclient.Datastore.java
/** * Execute a allocate ids statement.// www . j a va2s.co m * * @param statement the statement to execute. * @return the result of the allocate ids request. */ public ListenableFuture<AllocateIdsResult> executeAsync(final AllocateIds statement) { final ListenableFuture<Response> httpResponse; try { final DatastoreV1.AllocateIdsRequest.Builder request = DatastoreV1.AllocateIdsRequest.newBuilder() .addAllKey(statement.getPb(config.getNamespace())); final ProtoHttpContent payload = new ProtoHttpContent(request.build()); httpResponse = ListenableFutureAdapter.asGuavaFuture(prepareRequest("allocateIds", payload).execute()); } catch (final Exception e) { return Futures.immediateFailedFuture(new DatastoreException(e)); } return Futures.transform(httpResponse, (Response response) -> { if (!isSuccessful(response.getStatusCode())) { throw new DatastoreException(response.getStatusCode(), response.getResponseBody()); } final DatastoreV1.AllocateIdsResponse allocate = DatastoreV1.AllocateIdsResponse .parseFrom(streamResponse(response)); return Futures.immediateFuture(AllocateIdsResult.build(allocate)); }); }
From source file:org.caffinitas.ohc.linked.OHCacheLinkedImpl.java
public Future<V> getWithLoaderAsync(final K key, final CacheLoader<K, V> loader, final long expireAt) { if (key == null) throw new NullPointerException(); if (executorService == null || executorService.isShutdown() || closed) throw new IllegalStateException( "OHCache has no executor service - configure one via OHCacheBuilder.executorService()"); final KeyBuffer keySource = keySource(key); final OffHeapLinkedMap segment = segment(keySource.hash()); long hashEntryAdr = segment.getEntry(keySource, true, true); if (hashEntryAdr == 0L) { // this call is _likely_ the initial requestor for that key since there's no entry for the key final int keyLen = keySerializer.serializedSize(key); if (keyLen <= 0) throw new IllegalArgumentException("Illegal key length " + keyLen); long bytes = Util.allocLen(keyLen, 0L); if ((maxEntrySize > 0L && bytes > maxEntrySize) || (hashEntryAdr = Uns.allocate(bytes, throwOOME)) == 0L) { // entry too large to be inserted or OS is not able to provide enough memory putFailCount++;//from w w w. j av a 2 s . c om remove(key); return Futures .immediateFailedFuture(new RuntimeException("max entry size exceeded or malloc() failed")); } try { keySerializer.serialize(key, Uns.keyBuffer(hashEntryAdr, keyLen)); } catch (Throwable e) { freeAndThrow(e, hashEntryAdr); } final long hash = hasher.hash(hashEntryAdr, Util.ENTRY_OFF_DATA, keyLen); // initialize hash entry HashEntries.init(hash, keyLen, 0L, hashEntryAdr, Util.SENTINEL_LOADING, 0L); if (segment.putEntry(hashEntryAdr, hash, keyLen, bytes, true, 0L, 0L, 0L, 0L)) { // this request IS the initial requestor for the key final long sentinelHashEntryAdr = hashEntryAdr; return executorService.submit(new Callable<V>() { public V call() throws Exception { Exception failure = null; V value = null; boolean derefSentinel = false; try { value = loader.load(key); long entryExpireAt = expireAt; if (value == null || (entryExpireAt > 0L && entryExpireAt <= System.currentTimeMillis())) { // If the value is null, it means the loaded could not // already expired segment.removeEntry(sentinelHashEntryAdr); return null; } // not already expired long valueLen = valueSerializer.serializedSize(value); if (valueLen <= 0) throw new IllegalArgumentException("Illegal value length " + valueLen); long bytes = Util.allocLen(keyLen, valueLen); long hashEntryAdr; if ((maxEntrySize > 0L && bytes > maxEntrySize) || (hashEntryAdr = Uns.allocate(bytes, throwOOME)) == 0L) throw new RuntimeException("max entry size exceeded or malloc() failed"); long hash = serializeForPut(key, value, keyLen, valueLen, hashEntryAdr); if (entryExpireAt == USE_DEFAULT_EXPIRE_AT) entryExpireAt = defaultExpireAt(); // initialize hash entry HashEntries.init(hash, keyLen, valueLen, hashEntryAdr, Util.SENTINEL_NOT_PRESENT, entryExpireAt); if (!segment.replaceEntry(hash, sentinelHashEntryAdr, hashEntryAdr, bytes, entryExpireAt)) throw new RuntimeException("not enough free capacity"); derefSentinel = true; HashEntries.setSentinel(sentinelHashEntryAdr, Util.SENTINEL_SUCCESS); HashEntries.dereference(sentinelHashEntryAdr); } catch (PermanentLoadException e) { HashEntries.setSentinel(sentinelHashEntryAdr, Util.SENTINEL_PERMANENT_FAILURE); throw e; } catch (Throwable e) { failure = e instanceof Exception ? (Exception) e : new RuntimeException(e); HashEntries.setSentinel(sentinelHashEntryAdr, Util.SENTINEL_TEMPORARY_FAILURE); if (derefSentinel) HashEntries.dereference(sentinelHashEntryAdr); else segment.removeEntry(sentinelHashEntryAdr); } if (failure != null) throw failure; return value; } }); } else { // this request IS NOT the initial requestor for the key, so it must // free the unneeded but allocated sentinel Uns.free(hashEntryAdr); } // fall through } // this request IS NOT the initial requestor for the key // this request IS an adjacent requestor for the key // check if the value is already there (no sentinel) or has permanent failure status int sentinelStatus = HashEntries.getSentinel(hashEntryAdr); switch (sentinelStatus) { case Util.SENTINEL_NOT_PRESENT: try { return Futures.immediateFuture(valueSerializer.deserialize(Uns.valueBufferR(hashEntryAdr))); } finally { HashEntries.dereference(hashEntryAdr); } case Util.SENTINEL_PERMANENT_FAILURE: HashEntries.dereference(hashEntryAdr); return Futures.immediateFailedFuture(new PermanentLoadException()); } // handle sentinel final SettableFuture<V> future = SettableFuture.create(); final long sentinelHashEntryAdr = hashEntryAdr; // TODO / DOCUMENT: executorService shutdown with ongoing requests with referenced sentinel-entries --> off-heap memory leak // Reason: // The jobs started for adjacent getWithLoader*() calls are not running (and waiting) continuously. // Instead these are scheduled regularly and poll the referenced sentinel hash-entry. // The sentinel hash-entry is dereferenced within the following job for adjacent getWithLoader*() calls. // So - if the following job is no longer called, the sentinel hash-entry will never be dereferenced and // therefore never be deallocated. // Workaround is to close the OHCache instance, then wait some time and shutdown the scheduled executor service // when there are no more scheduled jobs. // The following job basically "spins" on the sentinel field of the sentinel hash-entry without // any lock on the segment. // It has two "exit" criterias: executorService.schedule(new Runnable() { public void run() { if (future.isCancelled() || closed) { HashEntries.dereference(sentinelHashEntryAdr); return; } int sentinelStatus = HashEntries.getSentinel(sentinelHashEntryAdr); switch (sentinelStatus) { // SENTINEL_NOT_PRESENT is an impossible status on the sentinel hash-entry case Util.SENTINEL_SUCCESS: break; case Util.SENTINEL_LOADING: reschedule(0L); return; case Util.SENTINEL_PERMANENT_FAILURE: failure(0L, new PermanentLoadException()); return; case Util.SENTINEL_TEMPORARY_FAILURE: failure(0L, new TemporaryLoadException()); return; default: failure(0L, new AssertionError("illegal sentinel value " + sentinelStatus)); return; } long hashEntryAdr = segment.getEntry(keySource, true, true); if (hashEntryAdr == 0L) { // two possibilities that the entry does not exist: // - entry has been evicted (very very unlikely, so ignore this option) // - loader indicated temporary failure (very very likely) future.setException(new TemporaryLoadException()); } if (hashEntryAdr == sentinelHashEntryAdr) { // oops, still the sentinel entry reschedule(0L); return; } sentinelStatus = HashEntries.getSentinel(hashEntryAdr); switch (sentinelStatus) { case Util.SENTINEL_NOT_PRESENT: try { future.set(valueSerializer.deserialize(Uns.valueBufferR(hashEntryAdr))); HashEntries.dereference(hashEntryAdr); HashEntries.dereference(sentinelHashEntryAdr); } catch (Throwable e) { failure(hashEntryAdr, e); } break; case Util.SENTINEL_SUCCESS: case Util.SENTINEL_LOADING: HashEntries.dereference(hashEntryAdr); reschedule(hashEntryAdr); break; case Util.SENTINEL_PERMANENT_FAILURE: failure(hashEntryAdr, new PermanentLoadException()); break; case Util.SENTINEL_TEMPORARY_FAILURE: failure(hashEntryAdr, new TemporaryLoadException()); break; default: failure(hashEntryAdr, new AssertionError("illegal sentinel value " + sentinelStatus)); break; } } private void failure(long hashEntryAdr, Throwable e) { if (hashEntryAdr != 0L) HashEntries.dereference(hashEntryAdr); HashEntries.dereference(sentinelHashEntryAdr); future.setException(e); } private void reschedule(long hashEntryAdr) { try { executorService.schedule(this, 10, TimeUnit.MILLISECONDS); } catch (Throwable t) { failure(hashEntryAdr, t); } } }, 10, TimeUnit.MILLISECONDS); return future; }
From source file:com.mypurecloud.sdk.v2.api.LicenseApiAsync.java
/** * Get license assignments for the organization. * // ww w . j a va2 s . co m * @param request the request object * @param callback the action to perform when the request is completed * @return the future indication when the request has completed */ public Future<ApiResponse<LicenseOrganization>> getLicenseOrganizationAsync(ApiRequest<Void> request, final AsyncApiCallback<ApiResponse<LicenseOrganization>> callback) { try { final SettableFuture<ApiResponse<LicenseOrganization>> future = SettableFuture.create(); final boolean shouldThrowErrors = pcapiClient.getShouldThrowErrors(); pcapiClient.invokeAsync(request, new TypeReference<LicenseOrganization>() { }, new AsyncApiCallback<ApiResponse<LicenseOrganization>>() { @Override public void onCompleted(ApiResponse<LicenseOrganization> response) { notifySuccess(future, callback, response); } @Override public void onFailed(Throwable exception) { if (exception instanceof ApiException) { @SuppressWarnings("unchecked") ApiResponse<LicenseOrganization> response = (ApiResponse<LicenseOrganization>) (ApiResponse<?>) exception; notifySuccess(future, callback, response); } if (shouldThrowErrors) { notifyFailure(future, callback, exception); } else { @SuppressWarnings("unchecked") ApiResponse<LicenseOrganization> response = (ApiResponse<LicenseOrganization>) (ApiResponse<?>) (new ApiException( exception)); notifySuccess(future, callback, response); } } }); return future; } catch (Throwable exception) { return Futures.immediateFailedFuture(exception); } }
From source file:org.opendaylight.faas.fabricmgr.VContainerNetNodeServiceProvider.java
@Override public Future<RpcResult<CreateLneLayer3Output>> createLneLayer3(CreateLneLayer3Input input) { String lrName = input.getName(); CreateLogicalRouterInputBuilder lrInputBuilder = new CreateLogicalRouterInputBuilder(); FabricId fabricId = new FabricId(input.getVfabricId()); lrInputBuilder.setFabricId(fabricId); //lrInputBuilder.setName(lrName); LOG.debug("FABMGR: createLneLayer3: lrName={}, fabricId={}", lrName, fabricId.getValue()); final RpcResultBuilder<CreateLneLayer3Output> resultBuilder = RpcResultBuilder .<CreateLneLayer3Output>success(); Future<RpcResult<CreateLogicalRouterOutput>> result = this.fabServiceService .createLogicalRouter(lrInputBuilder.build()); try {//from w w w. j av a 2 s . c om RpcResult<CreateLogicalRouterOutput> output = result.get(); if (output.isSuccessful()) { LOG.debug("FABMGR: createLneLayer3: createLogicRouter RPC success"); CreateLneLayer3OutputBuilder builder = new CreateLneLayer3OutputBuilder(); CreateLogicalRouterOutput createLrOutput = output.getResult(); NodeId nodeId = createLrOutput.getNodeId(); builder.setLneId(new VcLneId(nodeId)); return Futures.immediateFuture(resultBuilder.withResult(builder.build()).build()); } } catch (Exception e) { LOG.error("FABMGR: ERROR: createLneLayer3: createLogicRouter RPC failed.", e); } return Futures.immediateFailedFuture(new IllegalArgumentException("createLogicRouter RPC failed")); }
From source file:org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator.java
@Override public ListenableFuture<RpcResult<NetconfMessage>> sendRequest(final NetconfMessage message, final QName rpc) { sessionLock.lock();//from w w w.j a v a 2 s .co m if (semaphore != null && !semaphore.tryAcquire()) { LOG.warn("Limit of concurrent rpc messages was reached (limit :" + concurentRpcMsgs + "). Rpc reply message is needed. Discarding request of Netconf device with id" + id.getName()); sessionLock.unlock(); return Futures.immediateFailedFuture( new NetconfDocumentedException("Limit of rpc messages was reached (Limit :" + concurentRpcMsgs + ") waiting for emptying the queue of Netconf device with id" + id.getName())); } try { return sendRequestWithLock(message, rpc); } finally { sessionLock.unlock(); } }
From source file:com.google.cloud.bigtable.hbase.BigtableBufferedMutator.java
private ListenableFuture<? extends GeneratedMessageV3> issueRequestDetails(Mutation mutation, long operationId) { try {/*from w ww . j a v a2 s . c om*/ if (mutation == null) { return Futures.immediateFailedFuture( new IllegalArgumentException("Cannot perform a mutation on a null object.")); } if (mutation instanceof Put) { return asyncExecutor.mutateRowAsync(adapter.adapt((Put) mutation), operationId); } else if (mutation instanceof Delete) { return asyncExecutor.mutateRowAsync(adapter.adapt((Delete) mutation), operationId); } else if (mutation instanceof Increment) { return asyncExecutor.readModifyWriteRowAsync(adapter.adapt((Increment) mutation), operationId); } else if (mutation instanceof Append) { return asyncExecutor.readModifyWriteRowAsync(adapter.adapt((Append) mutation), operationId); } return Futures.immediateFailedFuture( new IllegalArgumentException("Encountered unknown mutation type: " + mutation.getClass())); } catch (Exception e) { // issueRequest(mutation) could throw an Exception for validation issues. Remove the heapsize // and inflight rpc count. return Futures.immediateFailedFuture(e); } }
From source file:org.apache.hadoop.hdfs.qjournal.client.IPCLoggerChannel.java
@Override public ListenableFuture<Void> sendEdits(final long segmentTxId, final long firstTxnId, final int numTxns, final byte[] data) { try {//from ww w. j a v a 2 s. c o m reserveQueueSpace(data.length); } catch (LoggerTooFarBehindException e) { return Futures.immediateFailedFuture(e); } // When this batch is acked, we use its submission time in order // to calculate how far we are lagging. final long submitNanos = System.nanoTime(); ListenableFuture<Void> ret = null; try { ret = singleThreadExecutor.submit(new Callable<Void>() { @Override public Void call() throws IOException { throwIfOutOfSync(); long rpcSendTimeNanos = System.nanoTime(); try { getProxy().journal(createReqInfo(), segmentTxId, firstTxnId, numTxns, data); } catch (IOException e) { QuorumJournalManager.LOG.warn("Remote journal " + IPCLoggerChannel.this + " failed to " + "write txns " + firstTxnId + "-" + (firstTxnId + numTxns - 1) + ". Will try to write to this JN again after the next " + "log roll.", e); synchronized (IPCLoggerChannel.this) { outOfSync = true; } throw e; } finally { long now = System.nanoTime(); long rpcTime = TimeUnit.MICROSECONDS.convert(now - rpcSendTimeNanos, TimeUnit.NANOSECONDS); long endToEndTime = TimeUnit.MICROSECONDS.convert(now - submitNanos, TimeUnit.NANOSECONDS); metrics.addWriteEndToEndLatency(endToEndTime); metrics.addWriteRpcLatency(rpcTime); if (rpcTime / 1000 > WARN_JOURNAL_MILLIS_THRESHOLD) { QuorumJournalManager.LOG.warn("Took " + (rpcTime / 1000) + "ms to send a batch of " + numTxns + " edits (" + data.length + " bytes) to " + "remote journal " + IPCLoggerChannel.this); } } synchronized (IPCLoggerChannel.this) { highestAckedTxId = firstTxnId + numTxns - 1; lastAckNanos = submitNanos; } return null; } }); } finally { if (ret == null) { // it didn't successfully get submitted, // so adjust the queue size back down. unreserveQueueSpace(data.length); } else { // It was submitted to the queue, so adjust the length // once the call completes, regardless of whether it // succeeds or fails. Futures.addCallback(ret, new FutureCallback<Void>() { @Override public void onFailure(Throwable t) { unreserveQueueSpace(data.length); } @Override public void onSuccess(Void t) { unreserveQueueSpace(data.length); } }); } } return ret; }