List of usage examples for com.google.common.util.concurrent Futures transform
public static <I, O> ListenableFuture<O> transform(ListenableFuture<I> input, Function<? super I, ? extends O> function)
From source file:org.opendaylight.groupbasedpolicy.ui.backend.UiBackendServiceImpl.java
@Override public Future<RpcResult<GetEndpointsFromEndpointGroupOutput>> getEndpointsFromEndpointGroup( GetEndpointsFromEndpointGroupInput input) { LOG.trace("getEndpointsFromEndpointGroup: {}", input); final TenantId tenantId = input.getTenantId(); if (tenantId == null) { throw new IllegalArgumentException("Missing tenant-Id in RPC input."); }/*from w ww. j ava2 s. c om*/ final EndpointGroupId epgId = input.getEndpointGroupId(); if (epgId == null) { throw new IllegalArgumentException("Missing endpoint-group-id in RPC input."); } ReadOnlyTransaction rTx = dataProvider.newReadOnlyTransaction(); CheckedFuture<Optional<Endpoints>, ReadFailedException> futureEndpoints = rTx .read(LogicalDatastoreType.OPERATIONAL, ENDPOINTS_IID); return Futures.transform(futureEndpoints, new Function<Optional<Endpoints>, RpcResult<GetEndpointsFromEndpointGroupOutput>>() { @Override public RpcResult<GetEndpointsFromEndpointGroupOutput> apply( Optional<Endpoints> potentialEndpoints) { GetEndpointsFromEndpointGroupOutputBuilder outputBuilder = new GetEndpointsFromEndpointGroupOutputBuilder(); if (!potentialEndpoints.isPresent() || potentialEndpoints.get().getEndpoint() == null) { LOG.trace("No endpoint in datastore."); return RpcResultBuilder.success(outputBuilder.build()).build(); } List<Endpoint> endpoints = potentialEndpoints.get().getEndpoint(); List<UiEndpoint> uiEndpoints = new ArrayList<>(); for (Endpoint ep : endpoints) { if (tenantId.equals(ep.getTenant()) && isEpInEpg(ep, epgId)) { uiEndpoints.add(new UiEndpointBuilder(ep).build()); } } outputBuilder.setUiEndpoint(uiEndpoints); return RpcResultBuilder.success(outputBuilder.build()).build(); } }); }
From source file:org.apache.druid.indexing.worker.executor.ExecutorLifecycle.java
@LifecycleStart public void start() throws InterruptedException { final File taskFile = Preconditions.checkNotNull(taskExecutorConfig.getTaskFile(), "taskFile"); final File statusFile = Preconditions.checkNotNull(taskExecutorConfig.getStatusFile(), "statusFile"); final InputStream parentStream = Preconditions.checkNotNull(taskExecutorConfig.getParentStream(), "parentStream"); try {/*from w w w .ja va 2 s.c o m*/ task = jsonMapper.readValue(taskFile, Task.class); log.info("Running with task: %s", jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(task)); } catch (IOException e) { throw Throwables.propagate(e); } // Avoid running the same task twice on the same machine by locking the task base directory. final File taskLockFile = taskConfig.getTaskLockFile(task.getId()); try { synchronized (this) { if (taskLockChannel == null && taskLockFileLock == null) { taskLockChannel = FileChannel.open(taskLockFile.toPath(), StandardOpenOption.CREATE, StandardOpenOption.WRITE); log.info("Attempting to lock file[%s].", taskLockFile); final long startLocking = System.currentTimeMillis(); final long timeout = DateTimes.utc(startLocking).plus(taskConfig.getDirectoryLockTimeout()) .getMillis(); while (taskLockFileLock == null && System.currentTimeMillis() < timeout) { taskLockFileLock = taskLockChannel.tryLock(); if (taskLockFileLock == null) { Thread.sleep(100); } } if (taskLockFileLock == null) { throw new ISE("Could not acquire lock file[%s] within %,dms.", taskLockFile, timeout - startLocking); } else { log.info("Acquired lock file[%s] in %,dms.", taskLockFile, System.currentTimeMillis() - startLocking); } } else { throw new ISE("Already started!"); } } } catch (IOException e) { throw Throwables.propagate(e); } if (taskExecutorConfig.isParentStreamDefined()) { // Spawn monitor thread to keep a watch on parent's stdin // If stdin reaches eof, the parent is gone, and we should shut down parentMonitorExec.submit(new Runnable() { @Override public void run() { try { while (parentStream.read() != -1) { // Toss the byte } } catch (Exception e) { log.error(e, "Failed to read from stdin"); } // Kind of gross, but best way to kill the JVM as far as I know log.info("Triggering JVM shutdown."); System.exit(2); } }); } // Won't hurt in remote mode, and is required for setting up locks in local mode: try { if (!task.isReady(taskActionClientFactory.create(task))) { throw new ISE("Task[%s] is not ready to run yet!", task.getId()); } } catch (Exception e) { throw new ISE(e, "Failed to run task[%s] isReady", task.getId()); } statusFuture = Futures.transform(taskRunner.run(task), new Function<TaskStatus, TaskStatus>() { @Override public TaskStatus apply(TaskStatus taskStatus) { try { log.info("Task completed with status: %s", jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(taskStatus)); final File statusFileParent = statusFile.getParentFile(); if (statusFileParent != null) { FileUtils.forceMkdir(statusFileParent); } jsonMapper.writeValue(statusFile, taskStatus); return taskStatus; } catch (Exception e) { throw Throwables.propagate(e); } } }); }
From source file:org.opendaylight.openflowplugin.openflow.md.util.RoleUtil.java
public static ControllerRole readRoleFromDevice(SessionContext sessionContext) { Future<ControllerRole> roleFuture = null; Future<RpcResult<RoleRequestOutput>> roleReply = sendRoleChangeRequest(sessionContext, OfpRole.NOCHANGE, BigInteger.ZERO);/*from w w w . j ava 2 s.c o m*/ roleFuture = Futures.transform(JdkFutureAdapters.listenInPoolThread(roleReply), new Function<RpcResult<RoleRequestOutput>, ControllerRole>() { @Override public ControllerRole apply(RpcResult<RoleRequestOutput> input) { return input.getResult().getRole(); } }); ControllerRole role = null; try { role = roleFuture.get(); } catch (ExecutionException | InterruptedException e) { LOG.error(e.getMessage()); } return role; }
From source file:org.opendaylight.netconf.sal.connect.netconf.schema.NetconfRemoteSchemaYangSourceProvider.java
@Override public CheckedFuture<YangTextSchemaSource, SchemaSourceException> getSource( final SourceIdentifier sourceIdentifier) { final String moduleName = sourceIdentifier.getName(); // If formatted revision is SourceIdentifier.NOT_PRESENT_FORMATTED_REVISION, we have to omit it from request final String formattedRevision = sourceIdentifier.getRevision() .equals(SourceIdentifier.NOT_PRESENT_FORMATTED_REVISION) ? null : sourceIdentifier.getRevision(); final Optional<String> revision = Optional.fromNullable(formattedRevision); final NormalizedNode<?, ?> getSchemaRequest = createGetSchemaRequest(moduleName, revision); LOG.trace("{}: Loading YANG schema source for {}:{}", id, moduleName, revision); final ListenableFuture<YangTextSchemaSource> transformed = Futures.transform( rpc.invokeRpc(SchemaPath.create(true, NetconfMessageTransformUtil.GET_SCHEMA_QNAME), getSchemaRequest),/*from w w w . j av a 2 s .co m*/ new ResultToYangSourceTransformer(id, sourceIdentifier, moduleName, revision)); final CheckedFuture<YangTextSchemaSource, SchemaSourceException> checked = Futures.makeChecked(transformed, MAPPER); return checked; }
From source file:com.microsoft.intellij.helpers.o365.Office365ManagerImpl.java
@Override @NotNull//from ww w .j a v a2s.com public ListenableFuture<List<ServicePermissionEntry>> getO365PermissionsForApp(@NotNull final String objectId) { return requestFutureWithToken(new RequestCallback<ListenableFuture<List<ServicePermissionEntry>>>() { @Override public ListenableFuture<List<ServicePermissionEntry>> execute() throws Throwable { return Futures.transform(getApplicationByObjectId(objectId), new AsyncFunction<Application, List<ServicePermissionEntry>>() { @Override public ListenableFuture<List<ServicePermissionEntry>> apply(Application application) throws Exception { final String[] filterAppIds = new String[] { ServiceAppIds.SHARE_POINT, ServiceAppIds.EXCHANGE, ServiceAppIds.AZURE_ACTIVE_DIRECTORY }; // build initial list of permission from the app's permissions final List<ServicePermissionEntry> servicePermissions = getO365PermissionsFromResourceAccess( application.getrequiredResourceAccess(), filterAppIds); // get permissions list from O365 service principals return Futures.transform(getServicePrincipalsForO365(), new AsyncFunction<List<ServicePrincipal>, List<ServicePermissionEntry>>() { @Override public ListenableFuture<List<ServicePermissionEntry>> apply( List<ServicePrincipal> servicePrincipals) throws Exception { for (final ServicePrincipal servicePrincipal : servicePrincipals) { // lookup this service principal in app's list of resources; if it's not found add an entry ServicePermissionEntry servicePermissionEntry = Iterables.find( servicePermissions, new Predicate<ServicePermissionEntry>() { @Override public boolean apply( ServicePermissionEntry servicePermissionEntry) { return servicePermissionEntry.getKey().getId() .equals(servicePrincipal.getappId()); } }, null); if (servicePermissionEntry == null) { servicePermissions.add( servicePermissionEntry = new ServicePermissionEntry( new Office365Service(), new Office365PermissionList())); } Office365Service service = servicePermissionEntry.getKey(); Office365PermissionList permissionList = servicePermissionEntry .getValue(); service.setId(servicePrincipal.getappId()); service.setName(servicePrincipal.getdisplayName()); List<OAuth2Permission> permissions = servicePrincipal .getoauth2Permissions(); for (final OAuth2Permission permission : permissions) { // lookup permission in permissionList Office365Permission office365Permission = Iterables.find( permissionList, new Predicate<Office365Permission>() { @Override public boolean apply( Office365Permission office365Permission) { return office365Permission.getId().equals( permission.getid().toString()); } }, null); if (office365Permission == null) { permissionList.add( office365Permission = new Office365Permission()); office365Permission.setEnabled(false); } office365Permission.setId(permission.getid().toString()); office365Permission.setName( getPermissionDisplayName(permission.getvalue())); office365Permission.setDescription( permission.getuserConsentDisplayName()); } } return Futures.immediateFuture(servicePermissions); } }); } }); } }); }
From source file:org.thingsboard.server.service.transport.LocalTransportApiService.java
private ListenableFuture<TransportApiResponseMsg> getDeviceInfo(DeviceId deviceId) { return Futures.transform(deviceService.findDeviceByIdAsync(TenantId.SYS_TENANT_ID, deviceId), device -> { if (device == null) { log.trace("[{}] Failed to lookup device by id", deviceId); return getEmptyTransportApiResponse(); }/*from ww w .j a va 2s.c om*/ try { return TransportApiResponseMsg.newBuilder() .setValidateTokenResponseMsg(ValidateDeviceCredentialsResponseMsg.newBuilder() .setDeviceInfo(getDeviceInfoProto(device)).build()) .build(); } catch (JsonProcessingException e) { log.warn("[{}] Failed to lookup device by id", deviceId, e); return getEmptyTransportApiResponse(); } }); }
From source file:io.v.v23.syncbase.DatabaseImpl.java
public ListenableFuture<BatchDatabase> beginBatch(VContext ctx, BatchOptions opts) { ListenableFuture<BatchHandle> batchFuture = client.beginBatch(ctx, opts); final String parentFullName = this.parentFullName; final Id id = this.id; final Schema schema = this.schema; return VFutures.withUserLandChecks(ctx, Futures.transform(batchFuture, new Function<BatchHandle, BatchDatabase>() { @Override/* w w w . ja v a 2 s . co m*/ public BatchDatabase apply(BatchHandle batchHandle) { return new DatabaseImpl(parentFullName, id, schema, batchHandle); } })); }
From source file:org.onos.yangtools.yang.parser.repo.SharedSchemaContextFactory.java
@Override public CheckedFuture<SchemaContext, SchemaResolutionException> createSchemaContext( final Collection<SourceIdentifier> requiredSources) { // Make sources unique final List<SourceIdentifier> uniqueSourceIdentifiers = deDuplicateSources(requiredSources); final SchemaContext existing = cache.getIfPresent(uniqueSourceIdentifiers); if (existing != null) { LOG.debug("Returning cached context {}", existing); return Futures.immediateCheckedFuture(existing); }/*from www. java 2 s.c om*/ // Request all sources be loaded ListenableFuture<List<ASTSchemaSource>> sf = Futures .allAsList(Collections2.transform(uniqueSourceIdentifiers, requestSources)); // Detect mismatch between requested Source IDs and IDs that are extracted from parsed source // Also remove duplicates if present // We are relying on preserved order of uniqueSourceIdentifiers as well as sf sf = Futures.transform(sf, new SourceIdMismatchDetector(uniqueSourceIdentifiers)); // Assemble sources into a schema context final ListenableFuture<SchemaContext> cf = Futures.transform(sf, assembleSources); // Populate cache when successful Futures.addCallback(cf, new FutureCallback<SchemaContext>() { @Override public void onSuccess(final SchemaContext result) { cache.put(uniqueSourceIdentifiers, result); } @Override public void onFailure(final Throwable t) { LOG.debug("Failed to assemble sources", t); } }); return Futures.makeChecked(cf, MAPPER); }
From source file:org.opendaylight.controller.features_service.impl.FeaturesServiceImpl.java
private void checkStatusAndInstallFeature(final InstallFeatureInput input, final SettableFuture<RpcResult<Void>> futureResult, final int tries) { final ReadWriteTransaction tx = dataProvider.newReadWriteTransaction(); ListenableFuture<Optional<Features>> readFuture = tx.read(LogicalDatastoreType.OPERATIONAL, FEATURE_SERVICE_IID);//from www. j a va 2 s. c o m final ListenableFuture<Void> commitFuture = Futures.transform(readFuture, new AsyncFunction<Optional<Features>, Void>() { @Override public ListenableFuture<Void> apply(final Optional<Features> featuresData) throws Exception { FeaturesServiceStatus featuresServiceStatus = FeaturesServiceStatus.Available; if (featuresData.isPresent()) { featuresServiceStatus = featuresData.get().getFeaturesServiceStatus(); } LOG.debug("Read featuresServiceStatus status: {}", featuresServiceStatus); if (featuresServiceStatus == FeaturesServiceStatus.Available) { LOG.debug("Setting features service to unavailable (in use)"); tx.put(LogicalDatastoreType.OPERATIONAL, FEATURE_SERVICE_IID, buildFeatures(FeaturesServiceStatus.Unavailable)); return tx.submit(); } LOG.debug("Something went wrong while installing feature: " + input.getName()); return Futures.immediateFailedCheckedFuture( new TransactionCommitFailedException("", makeFeaturesServiceInUseError())); } }); Futures.addCallback(commitFuture, new FutureCallback<Void>() { @Override public void onSuccess(final Void result) { // OK to install a feature currentInstallFeaturesTask.set(executor.submit(new InstallFeaturesTask(input, futureResult))); } @Override public void onFailure(final Throwable ex) { if (ex instanceof OptimisticLockFailedException) { // Another thread is likely trying to install a feature // simultaneously and updated the // status before us. Try reading the status again - if // another install is now in progress, we should // get FeaturesService.available and fail. if ((tries - 1) > 0) { LOG.debug("Got OptimisticLockFailedException - trying again"); checkStatusAndInstallFeature(input, futureResult, tries - 1); } else { futureResult.set(RpcResultBuilder.<Void>failed() .withError(ErrorType.APPLICATION, ex.getMessage()).build()); } } else { LOG.debug("Failed to commit FeaturesService status", ex); futureResult.set(RpcResultBuilder.<Void>failed() .withRpcErrors(((TransactionCommitFailedException) ex).getErrorList()).build()); } } }); }
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 ww . ja v a 2 s . co 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); } }