List of usage examples for com.google.common.util.concurrent Futures immediateFailedFuture
@CheckReturnValue public static <V> ListenableFuture<V> immediateFailedFuture(Throwable throwable)
From source file:io.crate.executor.transport.task.UpsertByIdTask.java
private ListenableFuture<Long> executeUpsertRequest(final UpsertById.Item item) { ShardId shardId;//from w w w. j av a2 s .c o m try { shardId = clusterService.operationRouting().indexShards(clusterService.state(), item.index(), Constants.DEFAULT_MAPPING_TYPE, item.id(), item.routing()).shardId(); } catch (IndexNotFoundException e) { if (PartitionName.isPartition(item.index())) { return Futures.immediateFuture(0L); } else { return Futures.immediateFailedFuture(e); } } ShardUpsertRequest upsertRequest = new ShardUpsertRequest.Builder(false, false, upsertById.updateColumns(), upsertById.insertColumns(), jobId(), false).newRequest(shardId, item.routing()); ShardUpsertRequest.Item requestItem = new ShardUpsertRequest.Item(item.id(), item.updateAssignments(), item.insertValues(), item.version()); upsertRequest.add(0, requestItem); UpsertByIdContext upsertByIdContext = new UpsertByIdContext(upsertById.executionPhaseId(), upsertRequest, item, transportShardUpsertActionDelegate); try { createJobExecutionContext(upsertByIdContext); jobExecutionContext.start(); } catch (Throwable throwable) { return Futures.immediateFailedFuture(throwable); } return upsertByIdContext.resultFuture(); }
From source file:org.opendaylight.faas.fabrics.vxlan.adapters.ovs.providers.FabricDeviceManager.java
@Override public Future<RpcResult<Void>> addToVxlanFabric(final AddToVxlanFabricInput input) { Preconditions.checkNotNull(input);//from www .java 2 s. com Preconditions.checkNotNull(input.getNodeId()); Preconditions.checkNotNull(input.getFabricId()); final RpcResult<Void> result = RpcResultBuilder.<Void>success().build(); @SuppressWarnings("unchecked") final InstanceIdentifier<Node> deviceIId = (InstanceIdentifier<Node>) input.getNodeId(); final FabricId fabricId = new FabricId(input.getFabricId()); final Node bridgeNode = OvsSouthboundUtils.getOvsdbBridgeNode(deviceIId, databroker); Preconditions.checkNotNull(bridgeNode); if (!OvsSouthboundUtils.addVxlanTunnelPort(bridgeNode, databroker)) { LOG.error("can not create tunnel port!"); return Futures.immediateFailedFuture(new RuntimeException("can not create tunnel port")); } if (!OvsSouthboundUtils.addVxlanGpeTunnelPort(bridgeNode, databroker)) { LOG.error("can not create tunnel port!"); return Futures.immediateFailedFuture(new RuntimeException("can not create nsh tunnel port")); } FabricCapableDeviceBuilder deviceBuilder = new FabricCapableDeviceBuilder(); AttributesBuilder attributesBuilder = new AttributesBuilder(); attributesBuilder.setFabricId(input.getFabricId()); InstanceIdentifier<Node> fabricpath = Constants.DOM_FABRICS_PATH.child(Node.class, new NodeKey(input.getFabricId())); attributesBuilder.setFabricRef(new NodeRef(fabricpath)); deviceBuilder.setAttributes(attributesBuilder.build()); @SuppressWarnings("unchecked") final InstanceIdentifier<FabricCapableDevice> path = ((InstanceIdentifier<Node>) input.getNodeId()) .augmentation(FabricCapableDevice.class); WriteTransaction wt = databroker.newWriteOnlyTransaction(); wt.merge(LogicalDatastoreType.OPERATIONAL, path, deviceBuilder.build(), true); addTp2Fabric(wt, bridgeNode, deviceIId, fabricId); CheckedFuture<Void, TransactionCommitFailedException> future = wt.submit(); return Futures.transform(future, new AsyncFunction<Void, RpcResult<Void>>() { @Override public ListenableFuture<RpcResult<Void>> apply(Void input) throws Exception { renderers.put(deviceIId, new DeviceRenderer(executor, databroker, deviceIId, bridgeNode, fabricId)); return Futures.immediateFuture(result); } }, executor); }
From source file:com.google.appengine.tools.cloudstorage.dev.LocalRawGcsService.java
@Override public Future<GcsFileMetadata> readObjectAsync(ByteBuffer dst, GcsFilename filename, long offset, long timeoutMillis) { Preconditions.checkArgument(offset >= 0, "%s: offset must be non-negative: %s", this, offset); try {/*from ww w . jav a 2 s .c om*/ GcsFileMetadata meta = getObjectMetadata(filename, timeoutMillis); if (meta == null) { return Futures .immediateFailedFuture(new FileNotFoundException(this + ": No such file: " + filename)); } if (offset >= meta.getLength()) { return Futures.immediateFailedFuture( new BadRangeException("The requested range cannot be satisfied. bytes=" + Long.toString(offset) + "-" + Long.toString(offset + dst.remaining()) + " the file is only " + meta.getLength())); } AppEngineFile file = nameToAppEngineFile(filename); FileReadChannel readChannel = FILES.openReadChannel(file, false); readChannel.position(offset); int read = 0; while (read != -1 && dst.hasRemaining()) { read = readChannel.read(dst); } return Futures.immediateFuture(meta); } catch (IOException e) { return Futures.immediateFailedFuture(e); } }
From source file:com.microsoft.azure.keyvault.cryptography.RsaKey.java
@Override public ListenableFuture<Pair<byte[], String>> signAsync(final byte[] digest, final String algorithm) throws NoSuchAlgorithmException { if (digest == null) { throw new IllegalArgumentException("encryptedKey "); }//from ww w.j a va 2 s . c om // Interpret the requested algorithm if (Strings.isNullOrWhiteSpace(algorithm)) { throw new IllegalArgumentException("algorithm"); } // Interpret the requested algorithm Algorithm baseAlgorithm = AlgorithmResolver.Default.get(algorithm); if (baseAlgorithm == null || !(baseAlgorithm instanceof AsymmetricSignatureAlgorithm)) { throw new NoSuchAlgorithmException(algorithm); } Rs256 algo = (Rs256) baseAlgorithm; ISignatureTransform signer = algo.createSignatureTransform(_keyPair); try { return Futures.immediateFuture(Pair.of(signer.sign(digest), Rs256.ALGORITHM_NAME)); } catch (Exception e) { return Futures.immediateFailedFuture(e); } }
From source file:org.onosproject.store.flowext.impl.DefaultFlowRuleExtRouter.java
/** * apply the sub batch of flow extension rules. * * @param batchOperation batch of flow rules. * A batch can contain flow rules for a single device only. * @return Future response indicating success/failure of the batch operation * all the way down to the device.// w w w .j a v a 2 s. c o m */ @Override public Future<FlowExtCompletedOperation> applySubBatch(FlowRuleBatchRequest batchOperation) { // TODO Auto-generated method stub if (batchOperation.ops().isEmpty()) { return Futures.immediateFuture( new FlowExtCompletedOperation(batchOperation.batchId(), true, Collections.emptySet())); } // get the deviceId all the collection belongs to DeviceId deviceId = getBatchDeviceId(batchOperation.ops()); if (deviceId == null) { log.error("This Batch exists more than two deviceId"); return null; } ReplicaInfo replicaInfo = replicaInfoManager.getReplicaInfoFor(deviceId); if (replicaInfo.master().get().equals(clusterService.getLocalNode().id())) { return applyBatchInternal(batchOperation); } log.trace("Forwarding storeBatch to {}, which is the primary (master) for device {}", replicaInfo.master().orNull(), deviceId); ClusterMessage message = new ClusterMessage(clusterService.getLocalNode().id(), APPLY_EXTEND_FLOWS, SERIALIZER.encode(batchOperation)); try { ListenableFuture<byte[]> responseFuture = clusterCommunicator.sendAndReceive(message, replicaInfo.master().get()); // here should add another decode process return Futures.transform(responseFuture, new DecodeTo<FlowExtCompletedOperation>(SERIALIZER)); } catch (IOException e) { return Futures.immediateFailedFuture(e); } }
From source file:org.opendaylight.openflowplugin.impl.statistics.StatisticsContextImpl.java
/** * Method checks a device state. It returns null for be able continue. Otherwise it returns immediateFuture * which has to be returned from caller too * * @return// www . j a v a 2s. co m */ @VisibleForTesting ListenableFuture<Boolean> deviceConnectionCheck() { if (!ConnectionContext.CONNECTION_STATE.WORKING .equals(deviceContext.getPrimaryConnectionContext().getConnectionState())) { ListenableFuture<Boolean> resultingFuture = SettableFuture.create(); switch (deviceContext.getPrimaryConnectionContext().getConnectionState()) { case RIP: final String errMsg = String.format( "Device connection doesn't exist anymore. Primary connection status : %s", deviceContext.getPrimaryConnectionContext().getConnectionState()); resultingFuture = Futures.immediateFailedFuture(new Throwable(errMsg)); break; default: resultingFuture = Futures.immediateCheckedFuture(Boolean.TRUE); break; } return resultingFuture; } return null; }
From source file:zipkin.storage.cassandra3.CassandraSpanConsumer.java
ListenableFuture<?> storeTraceServiceSpanName(String serviceName, String spanName, long timestamp_micro, Long duration, TraceIdUDT traceId) { int bucket = durationIndexBucket(timestamp_micro); UUID ts = new UUID(UUIDs.startOf(timestamp_micro / 1000).getMostSignificantBits(), UUIDs.random().getLeastSignificantBits()); try {// w w w .ja va2 s . c om BoundStatement bound = bindWithName(insertTraceServiceSpanName, "insert-trace-service-span-name") .setString("service_name", serviceName).setString("span_name", spanName) .setInt("bucket", bucket).setUUID("ts", ts).set("trace_id", traceId, TraceIdUDT.class); if (null != duration) { bound = bound.setLong("duration", duration); } return session.executeAsync(bound); } catch (RuntimeException ex) { return Futures.immediateFailedFuture(ex); } }
From source file:com.microsoft.azure.keyvault.cryptography.SymmetricKey.java
@Override public ListenableFuture<Triple<byte[], byte[], String>> encryptAsync(final byte[] plaintext, final byte[] iv, final byte[] authenticationData, final String algorithm) throws NoSuchAlgorithmException { if (plaintext == null) { throw new IllegalArgumentException("plaintext"); }// www .j a v a 2 s .c o m if (iv == null) { throw new IllegalArgumentException("iv"); } // Interpret the algorithm String algorithmName = (Strings.isNullOrWhiteSpace(algorithm)) ? getDefaultEncryptionAlgorithm() : algorithm; Algorithm baseAlgorithm = AlgorithmResolver.Default.get(algorithmName); if (baseAlgorithm == null || !(baseAlgorithm instanceof SymmetricEncryptionAlgorithm)) { throw new NoSuchAlgorithmException(algorithm); } SymmetricEncryptionAlgorithm algo = (SymmetricEncryptionAlgorithm) baseAlgorithm; ICryptoTransform transform = null; try { transform = algo.CreateEncryptor(_key, iv, authenticationData, _provider); } catch (Exception e) { return Futures.immediateFailedFuture(e); } byte[] cipherText = null; try { cipherText = transform.doFinal(plaintext); } catch (Exception e) { return Futures.immediateFailedFuture(e); } byte[] authenticationTag = null; if (transform instanceof IAuthenticatedCryptoTransform) { IAuthenticatedCryptoTransform authenticatedTransform = (IAuthenticatedCryptoTransform) transform; authenticationTag = authenticatedTransform.getTag().clone(); } return Futures.immediateFuture(Triple.of(cipherText, authenticationTag, algorithm)); }
From source file:com.mypurecloud.sdk.v2.api.BillingApiAsync.java
/** * Get the billing overview for an organization that is managed by a partner. * Tax Disclaimer: Prices returned by this API do not include applicable taxes. It is the responsibility of the customer to pay all taxes that are appropriate in their jurisdiction. See the PureCloud API Documentation in the Developer Center for more information about this API: https://developer.mypurecloud.com/api/rest/v2/ * @param request the request object/*www.j a v a2 s. co m*/ * @param callback the action to perform when the request is completed * @return the future indication when the request has completed */ public Future<ApiResponse<TrusteeBillingOverview>> getBillingTrusteebillingoverviewTrustorOrgIdAsync( ApiRequest<Void> request, final AsyncApiCallback<ApiResponse<TrusteeBillingOverview>> callback) { try { final SettableFuture<ApiResponse<TrusteeBillingOverview>> future = SettableFuture.create(); final boolean shouldThrowErrors = pcapiClient.getShouldThrowErrors(); pcapiClient.invokeAsync(request, new TypeReference<TrusteeBillingOverview>() { }, new AsyncApiCallback<ApiResponse<TrusteeBillingOverview>>() { @Override public void onCompleted(ApiResponse<TrusteeBillingOverview> response) { notifySuccess(future, callback, response); } @Override public void onFailed(Throwable exception) { if (exception instanceof ApiException) { @SuppressWarnings("unchecked") ApiResponse<TrusteeBillingOverview> response = (ApiResponse<TrusteeBillingOverview>) (ApiResponse<?>) exception; notifySuccess(future, callback, response); } if (shouldThrowErrors) { notifyFailure(future, callback, exception); } else { @SuppressWarnings("unchecked") ApiResponse<TrusteeBillingOverview> response = (ApiResponse<TrusteeBillingOverview>) (ApiResponse<?>) (new ApiException( exception)); notifySuccess(future, callback, response); } } }); return future; } catch (Throwable exception) { return Futures.immediateFailedFuture(exception); } }
From source file:io.crate.executor.transport.AlterTableOperation.java
private ListenableFuture<Long> updateTemplate(Map<String, Object> newMappings, Settings newSettings, TableIdent tableIdent) {//from w ww.ja v a2 s. c om String templateName = PartitionName.templateName(tableIdent.schema(), tableIdent.name()); IndexTemplateMetaData indexTemplateMetaData = clusterService.state().metaData().templates() .get(templateName); if (indexTemplateMetaData == null) { return Futures.immediateFailedFuture(new RuntimeException("Template for partitioned table is missing")); } // merge mappings Map<String, Object> mapping = mergeTemplateMapping(indexTemplateMetaData, newMappings); // merge settings Settings.Builder settingsBuilder = Settings.builder(); settingsBuilder.put(indexTemplateMetaData.settings()); settingsBuilder.put(newSettings); PutIndexTemplateRequest request = new PutIndexTemplateRequest(templateName).create(false) .mapping(Constants.DEFAULT_MAPPING_TYPE, mapping).order(indexTemplateMetaData.order()) .settings(settingsBuilder.build()).template(indexTemplateMetaData.template()); for (ObjectObjectCursor<String, AliasMetaData> container : indexTemplateMetaData.aliases()) { Alias alias = new Alias(container.key); request.alias(alias); } FutureActionListener<PutIndexTemplateResponse, Long> listener = new FutureActionListener<>( LONG_NULL_FUNCTION); transportActionProvider.transportPutIndexTemplateAction().execute(request, listener); return listener; }