List of usage examples for com.google.common.util.concurrent AsyncFunction AsyncFunction
AsyncFunction
From source file:org.opendaylight.openflowplugin.impl.role.RoleManagerImpl.java
@Override public void onDeviceContextLevelUp(@CheckForNull final DeviceContext deviceContext) { LOG.debug("RoleManager called for device:{}", deviceContext.getPrimaryConnectionContext().getNodeId()); if (deviceContext.getDeviceState().getFeatures().getVersion() < OFConstants.OFP_VERSION_1_3) { // Roles are not supported before OF1.3, so move forward. deviceInitializationPhaseHandler.onDeviceContextLevelUp(deviceContext); return;/*from www . j a v a2s . c om*/ } final RoleContext roleContext = new RoleContextImpl(deviceContext, entityOwnershipService, makeEntity(deviceContext.getDeviceState().getNodeId())); // if the device context gets closed (mostly on connection close), we would need to cleanup deviceContext.addDeviceContextClosedHandler(this); Verify.verify(contexts.putIfAbsent(roleContext.getEntity(), roleContext) == null, "RoleCtx for master Node {} is still not close.", deviceContext.getDeviceState().getNodeId()); final ListenableFuture<OfpRole> roleChangeFuture = roleContext.initialization(); final ListenableFuture<Void> initDeviceFuture = Futures.transform(roleChangeFuture, new AsyncFunction<OfpRole, Void>() { @Override public ListenableFuture<Void> apply(final OfpRole input) throws Exception { final ListenableFuture<Void> nextFuture; if (OfpRole.BECOMEMASTER.equals(input)) { LOG.debug("Node {} was initialized", deviceContext.getDeviceState().getNodeId()); nextFuture = DeviceInitializationUtils.initializeNodeInformation(deviceContext, switchFeaturesMandatory); } else { LOG.debug("Node {} we are not Master so we are going to finish.", deviceContext.getDeviceState().getNodeId()); nextFuture = Futures.immediateFuture(null); } return nextFuture; } }); Futures.addCallback(initDeviceFuture, new FutureCallback<Void>() { @Override public void onSuccess(final Void result) { LOG.debug("Initialization Node {} is done.", deviceContext.getDeviceState().getNodeId()); getRoleContextLevelUp(deviceContext); } @Override public void onFailure(final Throwable t) { LOG.warn("Unexpected error for Node {} initialization", deviceContext.getDeviceState().getNodeId(), t); deviceContext.close(); } }); }
From source file:de.dfki.kiara.impl.ServiceMethodExecutorImpl.java
@Override public ListenableFuture<Message> performLocalCall(InvocationEnvironment env, final Message requestMessage) throws IOException, IllegalAccessException, IllegalArgumentException, ExecutionException, InterruptedException {/*w w w .ja v a2 s.c o m*/ if (requestMessage.getMessageKind() != Message.Kind.REQUEST) { throw new IllegalArgumentException("message is not a request"); } final String methodName = requestMessage.getMethodName(); final Protocol protocol = requestMessage.getProtocol(); final ServiceMethodBinder serviceMethodBinder = getServiceMethodBinder(methodName); Object result; boolean isException = false; if (serviceMethodBinder == null) { isException = true; result = new GenericRemoteException("unbound method '" + methodName + "'", GenericRemoteException.METHOD_NOT_FOUND); Message responseMessage = protocol.createResponseMessage(requestMessage, new Message.ResponseObject(result, isException)); return Futures.immediateFuture(responseMessage); } else { final MethodEntry methodEntry = serviceMethodBinder.getMethodEntry(); final List<Object> args = requestMessage.getRequestObject(methodEntry.serializationParamTypes).args; //methodEntry.hasFutureParams final int numArgs = args.size(); for (int i = 0; i < numArgs; ++i) { if (methodEntry.isFutureParam.get(i)) { final Function<Object, Object> f = ((Function<Object, Object>) methodEntry.serializationToParamConverters[i]); args.set(i, f.apply(args.get(i))); } else if (methodEntry.specialParamTypes[i] != null && env != null) { final TypeToken<?> ptype = methodEntry.specialParamTypes[i]; if (ptype.isAssignableFrom(de.dfki.kiara.ServerConnection.class)) { args.set(i, env.getServiceConnection()); } } } AsyncFunction<List<Object>, Message> ff = new AsyncFunction<List<Object>, Message>() { @Override public ListenableFuture<Message> apply(final List<Object> input) throws Exception { return Global.executor.submit(new Callable<Message>() { @Override public Message call() throws Exception { Object result; boolean isException = false; try { result = serviceMethodBinder.getBoundMethod() .invoke(serviceMethodBinder.getImplementedClass(), args.toArray()); if (methodEntry.futureParamOfReturnType != null) { ListenableFuture<?> futureResult = (ListenableFuture<?>) (methodEntry.returnTypeConverter != null ? ((Function<Object, Object>) (methodEntry.returnTypeConverter)) .apply(result) : result); result = futureResult.get(); } } catch (InvocationTargetException ex) { isException = true; result = ex.getTargetException(); } Message responseMessage = protocol.createResponseMessage(requestMessage, new Message.ResponseObject(result, isException)); return responseMessage; } }); } }; return Futures.transform(Futures.immediateFuture(args), ff); } }
From source file:zipkin.cassandra.CassandraSpanStore.java
@Override public ListenableFuture<List<List<Span>>> getTraces(QueryRequest request) { String spanName = request.spanName != null ? request.spanName : ""; final ListenableFuture<Map<Long, Long>> traceIdToTimestamp; if (request.minDuration != null || request.maxDuration != null) { traceIdToTimestamp = repository.getTraceIdsByDuration(request.serviceName, spanName, request.minDuration, request.maxDuration != null ? request.maxDuration : Long.MAX_VALUE, request.endTs * 1000, (request.endTs - request.lookback) * 1000, request.limit, indexTtl); } else if (!spanName.isEmpty()) { traceIdToTimestamp = repository.getTraceIdsBySpanName(request.serviceName, spanName, request.endTs * 1000, request.lookback * 1000, request.limit); } else {/*from ww w . j a v a2 s .c o m*/ traceIdToTimestamp = repository.getTraceIdsByServiceName(request.serviceName, request.endTs * 1000, request.lookback * 1000, request.limit); } List<ByteBuffer> annotationKeys = annotationKeys(request); ListenableFuture<Set<Long>> traceIds; if (annotationKeys.isEmpty()) { // Simplest case is when there is no annotation query. Limit is valid since there's no AND // query that could reduce the results returned to less than the limit. traceIds = transform(traceIdToTimestamp, keyset()); } else { // While a valid port of the scala cassandra span store (from zipkin 1.35), there is a fault. // each annotation key is an intersection, which means we are likely to return < limit. List<ListenableFuture<Map<Long, Long>>> futureKeySetsToIntersect = new ArrayList<>(); futureKeySetsToIntersect.add(traceIdToTimestamp); for (ByteBuffer annotationKey : annotationKeys) { futureKeySetsToIntersect.add(repository.getTraceIdsByAnnotation(annotationKey, request.endTs * 1000, request.lookback * 1000, request.limit)); } // We achieve the AND goal, by intersecting each of the key sets. traceIds = transform(allAsList(futureKeySetsToIntersect), intersectKeySets()); } return transformAsync(traceIds, new AsyncFunction<Set<Long>, List<List<Span>>>() { @Override public ListenableFuture<List<List<Span>>> apply(Set<Long> traceIds) { return transform( repository.getSpansByTraceIds(traceIds.toArray(new Long[traceIds.size()]), maxTraceCols), ConvertTracesResponse.INSTANCE); } @Override public String toString() { return "getSpansByTraceIds"; } }); }
From source file:io.vitess.client.VTGateConn.java
public SQLFuture<Cursor> execute(Context ctx, String query, @Nullable Map<String, ?> bindVars, TabletType tabletType, Query.ExecuteOptions.IncludedFields includedFields) throws SQLException { ExecuteRequest.Builder requestBuilder = ExecuteRequest.newBuilder() .setQuery(Proto.bindQuery(checkNotNull(query), bindVars)).setKeyspaceShard(keyspace) .setTabletType(checkNotNull(tabletType)) .setOptions(Query.ExecuteOptions.newBuilder().setIncludedFields(includedFields)); if (ctx.getCallerId() != null) { requestBuilder.setCallerId(ctx.getCallerId()); }//w ww.j a v a 2 s.c o m return new SQLFuture<Cursor>(transformAsync(client.execute(ctx, requestBuilder.build()), new AsyncFunction<ExecuteResponse, Cursor>() { @Override public ListenableFuture<Cursor> apply(ExecuteResponse response) throws Exception { Proto.checkError(response.getError()); return Futures.<Cursor>immediateFuture(new SimpleCursor(response.getResult())); } }, directExecutor())); }
From source file:com.spotify.netty4.handler.codec.zmtp.ZMTPSocket.java
/** * Bind this socket to an endpoint./* ww w . j av a 2 s . c om*/ */ public ListenableFuture<InetSocketAddress> bind(final String endpoint) { return transform(address(endpoint), new AsyncFunction<InetSocketAddress, InetSocketAddress>() { @Override public ListenableFuture<InetSocketAddress> apply( @SuppressWarnings("NullableProblems") final InetSocketAddress input) throws Exception { return bind(input); } }); }
From source file:io.v.v23.VFutures.java
/** * Returns a new {@link ListenableFuture} that runs on an {@link Executor} specified in the * given {@code context}. If the future completes but the given {@code context} has been * canceled, the returned future is canceled as well. */// www .j a va 2 s . com public static <T> ListenableFuture<T> withUserLandChecks(final VContext context, final ListenableFuture<T> future) { Executor executor = V.getExecutor(context); if (executor == null) { throw new RuntimeException("NULL executor in context: did you derive this context " + "from the context returned by V.init()?"); } return Futures.transform(future, new AsyncFunction<T, T>() { @Override public ListenableFuture<T> apply(T input) throws Exception { if (context.isCanceled()) { return Futures.immediateCancelledFuture(); } return Futures.immediateFuture(input); } }, executor); }
From source file:org.robotninjas.util.composition.FunctionComposition.java
public AsyncFunction<I, O> buildAsyncFunction() { return new AsyncFunction<I, O>() { @Override//from ww w . j av a 2 s.c om public ListenableFuture<O> apply(I input) throws Exception { final SettableFuture<I> start = SettableFuture.create(); ListenableFuture<O> end = buildChain(start); start.set(input); return end; } }; }
From source file:com.orangerhymelabs.helenus.cassandra.AbstractCassandraRepository.java
public ListenableFuture<List<T>> readAll(PreparedStatement statement, Object... parms) { ListenableFuture<ResultSet> future = submitStatement(statement, parms); return Futures.transformAsync(future, new AsyncFunction<ResultSet, List<T>>() { @Override//w w w.j av a 2 s .c om public ListenableFuture<List<T>> apply(ResultSet input) { return Futures.immediateFuture(marshalAll(input)); } }, MoreExecutors.directExecutor()); }
From source file:org.opendaylight.openflowplugin.openflow.md.core.sal.OFRpcTaskUtil.java
/** * @param task of rpc//from ww w .ja v a2 s . c o m * @param originalResult original result * @param <T> R * @param <I> I * @return chained result with barrier */ public static <T extends TransactionAware, I extends DataContainer> ListenableFuture<RpcResult<T>> chainFutureBarrier( final OFRpcTask<I, RpcResult<T>> task, final ListenableFuture<RpcResult<T>> originalResult) { ListenableFuture<RpcResult<T>> chainResult = originalResult; if (MoreObjects.firstNonNull(task.isBarrier(), Boolean.FALSE)) { chainResult = Futures.transform(originalResult, new AsyncFunction<RpcResult<T>, RpcResult<T>>() { @Override public ListenableFuture<RpcResult<T>> apply(final RpcResult<T> input) throws Exception { if (input.isSuccessful()) { RpcInputOutputTuple<BarrierInput, ListenableFuture<RpcResult<BarrierOutput>>> sendBarrierRpc = TaskUtil .sendBarrier(task.getSession(), task.getCookie(), task.getMessageService()); ListenableFuture<RpcResult<T>> barrierTxResult = Futures.transform( sendBarrierRpc.getOutput(), transformBarrierToTransactionAware(input, sendBarrierRpc.getInput())); return barrierTxResult; } else { return Futures.immediateFuture(input); } } }); } return chainResult; }
From source file:org.opendaylight.faas.fabric.general.EndPointRegister.java
@Override public Future<RpcResult<RegisterEndpointOutput>> registerEndpoint(RegisterEndpointInput input) { final RpcResultBuilder<RegisterEndpointOutput> resultBuilder = RpcResultBuilder .<RegisterEndpointOutput>success(); final RegisterEndpointOutputBuilder outputBuilder = new RegisterEndpointOutputBuilder(); final FabricId fabricid = input.getFabricId(); final FabricInstance fabricObj = FabricInstanceCache.INSTANCE.retrieveFabric(fabricid); if (fabricObj == null) { return Futures.immediateFailedFuture(new IllegalArgumentException("fabric is not exist!")); }/*from w ww . j a v a 2 s. c o m*/ Uuid epId = input.getEndpointUuid(); if (epId == null) { epId = new Uuid(UUID.randomUUID().toString()); } final Uuid newepId = epId; final InstanceIdentifier<Endpoint> eppath = Constants.DOM_ENDPOINTS_PATH.child(Endpoint.class, new EndpointKey(newepId)); EndpointBuilder epBuilder = new EndpointBuilder(); epBuilder.setEndpointUuid(newepId); epBuilder.setGateway(input.getGateway()); epBuilder.setIpAddress(input.getIpAddress()); epBuilder.setLocation(input.getLocation()); epBuilder.setLogicalLocation(input.getLogicalLocation()); epBuilder.setMacAddress(input.getMacAddress()); epBuilder.setPublicIp(input.getPublicIp()); epBuilder.setOwnFabric(fabricid); ReadWriteTransaction trans = dataBroker.newReadWriteTransaction(); trans.put(LogicalDatastoreType.OPERATIONAL, eppath, epBuilder.build(), true); CheckedFuture<Void, TransactionCommitFailedException> future = trans.submit(); return Futures.transform(future, new AsyncFunction<Void, RpcResult<RegisterEndpointOutput>>() { @Override public ListenableFuture<RpcResult<RegisterEndpointOutput>> apply(Void input) throws Exception { outputBuilder.setEndpointId(newepId); return Futures.immediateFuture(resultBuilder.withResult(outputBuilder.build()).build()); } }, executor); }