com.google.common.util.concurrent.AsyncFunction Java Examples

The following examples show how to use com.google.common.util.concurrent.AsyncFunction. 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: NodeExecutionFallbackTest.java    From trickle with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldApplyFallbackToAnyException() throws Exception {
  AsyncFunction<Throwable, String> function = new AsyncFunction<Throwable, String>() {
    @Override
    public ListenableFuture<String> apply(Throwable input) throws Exception {
      return immediateFuture("all is well, nothing to see here");
    }
  };

  when(graphBuilder.getFallback()).thenReturn(Optional.of(function));

  Throwable expected = new GraphExecutionException(null, currentCallInfo, NO_CALLS);

  ListenableFuture<String> future = fallback.create(expected);

  assertThat(future.get(), equalTo("all is well, nothing to see here"));
}
 
Example #2
Source File: CassandraAlarmDao.java    From iotplatform with Apache License 2.0 6 votes vote down vote up
@Override
public ListenableFuture<List<AlarmInfo>> findAlarms(AlarmQuery query) {
    log.trace("Try to find alarms by entity [{}], searchStatus [{}], status [{}] and pageLink [{}]", query.getAffectedEntityId(), query.getSearchStatus(), query.getStatus(), query.getPageLink());
    EntityId affectedEntity = query.getAffectedEntityId();
    String searchStatusName;
    if (query.getSearchStatus() == null && query.getStatus() == null) {
        searchStatusName = AlarmSearchStatus.ANY.name();
    } else if (query.getSearchStatus() != null) {
        searchStatusName = query.getSearchStatus().name();
    } else {
        searchStatusName = query.getStatus().name();
    }
    String relationType = BaseAlarmService.ALARM_RELATION_PREFIX + searchStatusName;
    ListenableFuture<List<EntityRelation>> relations = relationDao.findRelations(affectedEntity, relationType, RelationTypeGroup.ALARM, ThingType.ALARM, query.getPageLink());
    return Futures.transform(relations, (AsyncFunction<List<EntityRelation>, List<AlarmInfo>>) input -> {
        List<ListenableFuture<AlarmInfo>> alarmFutures = new ArrayList<>(input.size());
        for (EntityRelation relation : input) {
            alarmFutures.add(Futures.transform(
                    findAlarmByIdAsync(relation.getTo().getId()),
                    (Function<Alarm, AlarmInfo>) AlarmInfo::new));
        }
        return Futures.successfulAsList(alarmFutures);
    });
}
 
Example #3
Source File: BaseAlarmService.java    From iotplatform with Apache License 2.0 6 votes vote down vote up
@Override
public ListenableFuture<AlarmInfo> findAlarmInfoByIdAsync(AlarmId alarmId) {
    log.trace("Executing findAlarmInfoByIdAsync [{}]", alarmId);
    validateId(alarmId, "Incorrect alarmId " + alarmId);
    return Futures.transform(alarmDao.findAlarmByIdAsync(alarmId.getId()),
            (AsyncFunction<Alarm, AlarmInfo>) alarm1 -> {
                AlarmInfo alarmInfo = new AlarmInfo(alarm1);
                return Futures.transform(
                        entityService.fetchEntityNameAsync(alarmInfo.getOriginator()), (Function<String, AlarmInfo>)
                                originatorName -> {
                                    alarmInfo.setOriginatorName(originatorName);
                                    return alarmInfo;
                                }
                );
            });
}
 
Example #4
Source File: DeviceServiceImpl.java    From iotplatform with Apache License 2.0 6 votes vote down vote up
@Override
public ListenableFuture<List<Device>> findDevicesByQuery(DeviceSearchQuery query) {
    ListenableFuture<List<EntityRelation>> relations = relationService.findByQuery(query.toEntitySearchQuery());
    ListenableFuture<List<Device>> devices = Futures.transform(relations, (AsyncFunction<List<EntityRelation>, List<Device>>) relations1 -> {
        EntitySearchDirection direction = query.toEntitySearchQuery().getParameters().getDirection();
        List<ListenableFuture<Device>> futures = new ArrayList<>();
        for (EntityRelation relation : relations1) {
            EntityId entityId = direction == EntitySearchDirection.FROM ? relation.getTo() : relation.getFrom();
            if (entityId.getEntityType() == ThingType.DEVICE) {
                futures.add(findDeviceByIdAsync(new DeviceId(entityId.getId())));
            }
        }
        return Futures.successfulAsList(futures);
    });

    devices = Futures.transform(devices, new Function<List<Device>, List<Device>>() {
        @Nullable
        @Override
        public List<Device> apply(@Nullable List<Device> deviceList) {
            return deviceList.stream().filter(device -> query.getDeviceTypes().contains(device.getType())).collect(Collectors.toList());
        }
    });

    return devices;
}
 
Example #5
Source File: BaseRelationService.java    From iotplatform with Apache License 2.0 6 votes vote down vote up
@Override
public ListenableFuture<List<EntityRelationInfo>> findInfoByQuery(EntityRelationsQuery query) {
    log.trace("Executing findInfoByQuery [{}]", query);
    ListenableFuture<List<EntityRelation>> relations = findByQuery(query);
    EntitySearchDirection direction = query.getParameters().getDirection();
    ListenableFuture<List<EntityRelationInfo>> relationsInfo = Futures.transform(relations,
            (AsyncFunction<List<EntityRelation>, List<EntityRelationInfo>>) relations1 -> {
                List<ListenableFuture<EntityRelationInfo>> futures = new ArrayList<>();
                relations1.stream().forEach(relation ->
                        futures.add(fetchRelationInfoAsync(relation,
                                relation2 -> direction == EntitySearchDirection.FROM ? relation2.getTo() : relation2.getFrom(),
                                (EntityRelationInfo relationInfo, String entityName) -> {
                                    if (direction == EntitySearchDirection.FROM) {
                                        relationInfo.setToName(entityName);
                                    } else {
                                        relationInfo.setFromName(entityName);
                                    }
                                }))
                );
                return Futures.successfulAsList(futures);
            });
    return relationsInfo;
}
 
Example #6
Source File: BaseRelationService.java    From iotplatform with Apache License 2.0 6 votes vote down vote up
@Override
public ListenableFuture<List<EntityRelationInfo>> findInfoByTo(EntityId to, RelationTypeGroup typeGroup) {
    log.trace("Executing findInfoByTo [{}][{}]", to, typeGroup);
    validate(to);
    validateTypeGroup(typeGroup);
    ListenableFuture<List<EntityRelation>> relations = relationDao.findAllByTo(to, typeGroup);
    ListenableFuture<List<EntityRelationInfo>> relationsInfo = Futures.transform(relations,
            (AsyncFunction<List<EntityRelation>, List<EntityRelationInfo>>) relations1 -> {
                List<ListenableFuture<EntityRelationInfo>> futures = new ArrayList<>();
                relations1.stream().forEach(relation ->
                    futures.add(fetchRelationInfoAsync(relation,
                            relation2 -> relation2.getFrom(),
                            (EntityRelationInfo relationInfo, String entityName) -> relationInfo.setFromName(entityName)))
                );
                return Futures.successfulAsList(futures);
            });
    return relationsInfo;
}
 
Example #7
Source File: BaseRelationService.java    From iotplatform with Apache License 2.0 6 votes vote down vote up
@Override
public ListenableFuture<List<EntityRelationInfo>> findInfoByFrom(EntityId from, RelationTypeGroup typeGroup) {
    log.trace("Executing findInfoByFrom [{}][{}]", from, typeGroup);
    validate(from);
    validateTypeGroup(typeGroup);
    ListenableFuture<List<EntityRelation>> relations = relationDao.findAllByFrom(from, typeGroup);
    ListenableFuture<List<EntityRelationInfo>> relationsInfo = Futures.transform(relations,
            (AsyncFunction<List<EntityRelation>, List<EntityRelationInfo>>) relations1 -> {
        List<ListenableFuture<EntityRelationInfo>> futures = new ArrayList<>();
                relations1.stream().forEach(relation ->
                        futures.add(fetchRelationInfoAsync(relation,
                                relation2 -> relation2.getTo(),
                                (EntityRelationInfo relationInfo, String entityName) -> relationInfo.setToName(entityName)))
                );
                return Futures.successfulAsList(futures);
    });
    return relationsInfo;
}
 
Example #8
Source File: BaseRelationService.java    From iotplatform with Apache License 2.0 6 votes vote down vote up
@Override
public ListenableFuture<Boolean> deleteEntityRelations(EntityId entity) {
    log.trace("Executing deleteEntityRelations [{}]", entity);
    validate(entity);
    List<ListenableFuture<List<EntityRelation>>> inboundRelationsList = new ArrayList<>();
    for (RelationTypeGroup typeGroup : RelationTypeGroup.values()) {
        inboundRelationsList.add(relationDao.findAllByTo(entity, typeGroup));
    }
    ListenableFuture<List<List<EntityRelation>>> inboundRelations = Futures.allAsList(inboundRelationsList);
    ListenableFuture<List<Boolean>> inboundDeletions = Futures.transform(inboundRelations, new AsyncFunction<List<List<EntityRelation>>, List<Boolean>>() {
        @Override
        public ListenableFuture<List<Boolean>> apply(List<List<EntityRelation>> relations) throws Exception {
            List<ListenableFuture<Boolean>> results = new ArrayList<>();
            for (List<EntityRelation> relationList : relations) {
                relationList.stream().forEach(relation -> results.add(relationDao.deleteRelation(relation)));
            }
            return Futures.allAsList(results);
        }
    });

    ListenableFuture<Boolean> inboundFuture = Futures.transform(inboundDeletions, getListToBooleanFunction());

    ListenableFuture<Boolean> outboundFuture = relationDao.deleteOutboundRelations(entity);

    return Futures.transform(Futures.allAsList(Arrays.asList(inboundFuture, outboundFuture)), getListToBooleanFunction());
}
 
Example #9
Source File: DeviceTypeServiceImpl.java    From iotplatform with Apache License 2.0 6 votes vote down vote up
@Override
public ListenableFuture<List<DeviceType>> findDevicesByQuery(DeviceTypeSearchQuery query) {
    ListenableFuture<List<EntityRelation>> relations = relationService.findByQuery(query.toEntitySearchQuery());
    ListenableFuture<List<DeviceType>> devices = Futures.transform(relations, (AsyncFunction<List<EntityRelation>, List<DeviceType>>) relations1 -> {
        EntitySearchDirection direction = query.toEntitySearchQuery().getParameters().getDirection();
        List<ListenableFuture<DeviceType>> futures = new ArrayList<>();
        for (EntityRelation relation : relations1) {
            EntityId entityId = direction == EntitySearchDirection.FROM ? relation.getTo() : relation.getFrom();
            if (entityId.getEntityType() == ThingType.DEVICE) {
                futures.add(findDeviceByIdAsync(new DeviceTypeId(entityId.getId())));
            }
        }
        return Futures.successfulAsList(futures);
    });

    devices = Futures.transform(devices, new Function<List<DeviceType>, List<DeviceType>>() {
        @Nullable
        @Override
        public List<DeviceType> apply(@Nullable List<DeviceType> deviceList) {
            return deviceList.stream().collect(Collectors.toList());
        }
    });

    return devices;
}
 
Example #10
Source File: NodeExecutionFallbackTest.java    From trickle with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  //noinspection unchecked
  graphBuilder = mock(GraphBuilder.class);
  when(graphBuilder.getFallback())
      .thenReturn(Optional.<AsyncFunction<Throwable, String>>absent());

  Map<Input<?>, Object> emptyMap = Collections.emptyMap();
  traverseState = new TraverseState(emptyMap, MoreExecutors.sameThreadExecutor(), true);

  List<? extends NodeInfo> currentNodeParameters = ImmutableList.of();

  currentNodeInfo = new FakeNodeInfo("the node", currentNodeParameters);
  List<ListenableFuture<?>> currentNodeValues = ImmutableList.of();

  currentCall = new TraverseState.FutureCallInformation(currentNodeInfo, currentNodeValues);
  currentCallInfo = new CallInfo(currentNodeInfo, NO_PARAMS);

  fallback = new NodeExecutionFallback<String>(graphBuilder, currentCall, traverseState);
}
 
Example #11
Source File: App.java    From graph-examples with Apache License 2.0 6 votes vote down vote up
/**
 * This handles the callback for processing the asynchronous results returned from a graph traversal
 *
 * @return
 */
private static AsyncFunction<GraphResultSet, GraphResultSet> processAsyncResults() {
    return new AsyncFunction<GraphResultSet, GraphResultSet>() {
        public ListenableFuture<GraphResultSet> apply(GraphResultSet rs) {
            // How far we can go without triggering the blocking fetch:
            int remainingInPage = rs.getAvailableWithoutFetching();

            while (--remainingInPage >= 0) {
                GraphNode node = rs.iterator().next();
                processNode(node);
            }
            if (rs.isFullyFetched()) {
                System.out.println("Finished Processing Asynchronously Paged Results");
                //Check to see if we have retrieved everything and if we have exit
                return Futures.immediateFuture(rs);
            } else {
                // If we have not then fetch the next set of results
                ListenableFuture<GraphResultSet> future = rs.fetchMoreResults();
                return Futures.transform(future, processAsyncResults());
            }
        }
    };
}
 
Example #12
Source File: CassandraBaseTimeseriesDao.java    From iotplatform with Apache License 2.0 6 votes vote down vote up
private AsyncFunction<List<Long>, List<ResultSet>> getFetchChunksAsyncFunction(EntityId entityId, String key, Aggregation aggregation, long startTs, long endTs) {
    return partitions -> {
        try {
            PreparedStatement proto = getFetchStmt(aggregation);
            List<ResultSetFuture> futures = new ArrayList<>(partitions.size());
            for (Long partition : partitions) {
                log.trace("Fetching data for partition [{}] for entityType {} and entityId {}", partition, entityId.getEntityType(), entityId.getId());
                BoundStatement stmt = proto.bind();
                stmt.setString(0, entityId.getEntityType().name());
                stmt.setUUID(1, entityId.getId());
                stmt.setString(2, key);
                stmt.setLong(3, partition);
                stmt.setLong(4, startTs);
                stmt.setLong(5, endTs);
                log.debug("Generated query [{}] for entityType {} and entityId {}", stmt, entityId.getEntityType(), entityId.getId());
                futures.add(executeAsyncRead(stmt));
            }
            return Futures.allAsList(futures);
        } catch (Throwable e) {
            log.error("Failed to fetch data", e);
            throw e;
        }
    };
}
 
Example #13
Source File: CongestionController.java    From azure-documentdb-java with MIT License 6 votes vote down vote up
public ListenableFuture<Void> executeAllAsync()  {

        Callable<ListenableFuture<Void>> c = new Callable<ListenableFuture<Void>>() {

            @Override
            public ListenableFuture<Void> call() throws Exception {
                return executeAll();
            }
        };

        ListenableFuture<ListenableFuture<Void>> f = executor.submit(c);
        AsyncFunction<ListenableFuture<Void>, Void> function = new AsyncFunction<ListenableFuture<Void>, Void>() {

            @Override
            public ListenableFuture<Void> apply(ListenableFuture<Void> input) throws Exception {
                return input;
            }
        };
        return Futures.transformAsync(f, function, executor);
    }
 
Example #14
Source File: MoreFutures.java    From glowroot with Apache License 2.0 6 votes vote down vote up
public static ListenableFuture<?> rollupAsync(Collection<ListenableFuture<ResultSet>> futures,
        Executor asyncExecutor, DoRollup function) {
    return transformAsync(Futures.allAsList(futures), asyncExecutor,
            new AsyncFunction<List<ResultSet>, /*@Nullable*/ Object>() {
                @Override
                @SuppressWarnings("unchecked")
                public ListenableFuture</*@Nullable*/ Object> apply(List<ResultSet> list)
                        throws Exception {
                    List<Row> rows = new ArrayList<>();
                    for (ResultSet results : list) {
                        rows.addAll(results.all());
                    }
                    if (rows.isEmpty()) {
                        return Futures.immediateFuture(null);
                    }
                    return (ListenableFuture</*@Nullable*/ Object>) function.execute(rows);
                }
            });
}
 
Example #15
Source File: JpaAlarmDao.java    From iotplatform with Apache License 2.0 6 votes vote down vote up
@Override
public ListenableFuture<List<AlarmInfo>> findAlarms(AlarmQuery query) {
  log.trace("Try to find alarms by entity [{}], status [{}] and pageLink [{}]", query.getAffectedEntityId(),
      query.getStatus(), query.getPageLink());
  EntityId affectedEntity = query.getAffectedEntityId();
  String searchStatusName;
  if (query.getSearchStatus() == null && query.getStatus() == null) {
    searchStatusName = AlarmSearchStatus.ANY.name();
  } else if (query.getSearchStatus() != null) {
    searchStatusName = query.getSearchStatus().name();
  } else {
    searchStatusName = query.getStatus().name();
  }
  String relationType = BaseAlarmService.ALARM_RELATION_PREFIX + searchStatusName;
  ListenableFuture<List<EntityRelation>> relations = relationDao.findRelations(affectedEntity, relationType,
      RelationTypeGroup.ALARM, ThingType.ALARM, query.getPageLink());
  return Futures.transform(relations, (AsyncFunction<List<EntityRelation>, List<AlarmInfo>>) input -> {
    List<ListenableFuture<AlarmInfo>> alarmFutures = new ArrayList<>(input.size());
    for (EntityRelation relation : input) {
      alarmFutures.add(Futures.transform(findAlarmByIdAsync(relation.getTo().getId()),
          (Function<Alarm, AlarmInfo>) AlarmInfo::new));
    }
    return Futures.successfulAsList(alarmFutures);
  });
}
 
Example #16
Source File: MoreFutures.java    From glowroot with Apache License 2.0 6 votes vote down vote up
private static <V, R> ListenableFuture<R> transformAsync(ListenableFuture<V> future,
        Executor asyncExecutor, AsyncFunction<V, R> function) {
    boolean inRollupThread = Session.isInRollupThread();
    return Futures.transformAsync(future,
            new AsyncFunction<V, R>() {
                @Override
                public ListenableFuture<R> apply(V input) throws Exception {
                    boolean priorInRollupThread = Session.isInRollupThread();
                    Session.setInRollupThread(inRollupThread);
                    try {
                        return function.apply(input);
                    } finally {
                        Session.setInRollupThread(priorInRollupThread);
                    }
                }
            },
            // calls to Session.readAsync() inside of the function could block due to the
            // per-thread concurrent limit, so this needs to be executed in its own thread, not
            // in the cassandra driver thread that completes the last future which will block
            // the cassandra driver thread pool
            asyncExecutor);
}
 
Example #17
Source File: CassandraVideoV2Dao.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
private ListenableFuture<Set<String>> removeFavoriteTags(UUID placeId, UUID recordingId, Set<String> tags) {
	VideoMetadata metadata = findByPlaceAndId(placeId, recordingId);
	if(metadata != null && metadata.getTags().contains(VideoConstants.TAG_FAVORITE)) {
		BatchStatement stmt = new BatchStatement(BatchStatement.Type.LOGGED);
		addStatementsForRemoveFromFavoriteTables(stmt, metadata);	
		return Futures.transformAsync(
				VideoV2Util.executeAsyncAndUpdateTimer(session, stmt, RemoveTagsTimer),
            (AsyncFunction<ResultSet, Set<String>>) input -> {
            	Set<String> expectedTags = new HashSet<>(metadata.getTags());
   				expectedTags.removeAll(tags);
               return Futures.immediateFuture(expectedTags);
            },
            MoreExecutors.directExecutor()
         );
	}else{
		logger.warn("Can not removeFavoriteTags.  Either recording id [{}] is invalid or video does not contain Favorite tag [{}]", recordingId, metadata.getTags());
		return Futures.immediateFuture(ImmutableSet.<String>of());
		
	}
}
 
Example #18
Source File: GraphBuilder.java    From trickle with Apache License 2.0 5 votes vote down vote up
GraphBuilder(String name,
             TrickleNode<R> node,
             ImmutableList<Dep<?>> inputs,
             ImmutableList<Graph<?>> predecessors,
             Optional<AsyncFunction<Throwable, R>> fallback,
             boolean debug) {
  this.name = checkNotNull(name, "name");
  this.node = checkNotNull(node, "node");
  this.inputs = checkNotNull(inputs, "inputs");
  this.predecessors = checkNotNull(predecessors, "predecessors");
  this.fallback = checkNotNull(fallback, "fallback");
  this.debug = debug;
}
 
Example #19
Source File: MoreFutures.java    From more-lambdas-java with Artistic License 2.0 5 votes vote down vote up
public static <I, O> ListenableFuture<O> transformAsync(ListenableFuture<I> input,
        AsyncFunction<? super I, ? extends O> function,
        Executor executor) {
    ListenableFuture<O> result = Futures.transformAsync(input, function, executor);
    if (input instanceof TimeoutListenableFuture) {
        TimeoutListenableFuture<O> newResult = new TimeoutListenableFuture<>(result);
        for (ThrowableConsumer<TimeoutException, Exception> timeoutListener : ((TimeoutListenableFuture<I>) input)
                .getTimeoutListeners()) {
            newResult.addTimeoutListener(timeoutListener);
        }
        return newResult;
    } else {
        return result;
    }
}
 
Example #20
Source File: MoreFutures.java    From glowroot with Apache License 2.0 5 votes vote down vote up
public static ListenableFuture<?> transformAsync(ListenableFuture<ResultSet> input,
        Executor asyncExecutor, DoWithResults function) {
    return transformAsync(input, asyncExecutor,
            new AsyncFunction<ResultSet, /*@Nullable*/ Object>() {
                @Override
                @SuppressWarnings("unchecked")
                public ListenableFuture</*@Nullable*/ Object> apply(ResultSet results)
                        throws Exception {
                    return (ListenableFuture</*@Nullable*/ Object>) function.execute(results);
                }
            });
}
 
Example #21
Source File: MoreFutures.java    From glowroot with Apache License 2.0 5 votes vote down vote up
public static ListenableFuture<?> rollupAsync(ListenableFuture<ResultSet> input,
        Executor asyncExecutor, DoRollup function) {
    return transformAsync(input, asyncExecutor,
            new AsyncFunction<ResultSet, /*@Nullable*/ Object>() {
                @Override
                @SuppressWarnings("unchecked")
                public ListenableFuture</*@Nullable*/ Object> apply(ResultSet results)
                        throws Exception {
                    if (results.isExhausted()) {
                        return Futures.immediateFuture(null);
                    }
                    return (ListenableFuture</*@Nullable*/ Object>) function.execute(results);
                }
            });
}
 
Example #22
Source File: Session.java    From glowroot with Apache License 2.0 5 votes vote down vote up
public ListenableFuture<ResultSet> readAsyncFailIfNoRows(Statement statement,
        String errorMessage) throws Exception {
    return Futures.transformAsync(readAsync(statement),
            new AsyncFunction<ResultSet, ResultSet>() {
                @Override
                public ListenableFuture<ResultSet> apply(ResultSet results) {
                    if (results.isExhausted()) {
                        return Futures.immediateFailedFuture(new Exception(errorMessage));
                    } else {
                        return Futures.immediateFuture(results);
                    }
                }
            },
            MoreExecutors.directExecutor());
}
 
Example #23
Source File: SmartHomeSkillV3Handler.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public ListenableFuture<AlexaMessage> handle(AlexaMessage message, UUID placeId) {
   long startTime = System.nanoTime();
   Txfm txfm = Txfm.transformerFor(message);
   PlatformMessage platformMessage = txfm.txfmRequest(message, placeId, populationCacheMgr.getPopulationByPlaceId(placeId), (int) config.getRequestTimeoutMs());
   logger.debug("[{}] transformed to platform message [{}]", message, platformMessage);
   return Futures.transformAsync(
      busClient.request(platformMessage),
      (AsyncFunction<PlatformMessage, AlexaMessage>) input -> {
         metrics.timeServiceSuccess(platformMessage.getMessageType(), startTime);
         return Futures.immediateFuture(txfm.transformResponse(input, message.getHeader().getCorrelationToken()));
      },
      executor
   );
}
 
Example #24
Source File: Fallbacks.java    From trickle with Apache License 2.0 5 votes vote down vote up
public static <T> AsyncFunction<Throwable, T> always(@Nullable final T value) {
  return new AsyncFunction<Throwable, T>() {
    @Nullable
    @Override
    public ListenableFuture<T> apply(@Nullable Throwable input) {
      return immediateFuture(value);
    }
  };
}
 
Example #25
Source File: TrickleTest.java    From trickle with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldPropagateExceptionsToResultFutureForFailedDefault() throws Exception {
  final RuntimeException unexpected = new RuntimeException("not me");
  final RuntimeException expected = new RuntimeException("expected");
  Func1<String, String> node1 = new Func1<String, String>() {
    @Override
    public ListenableFuture<String> run(String arg) {
      return immediateFailedFuture(unexpected);
    }
  };
  Func2<String, String, String> node2 = new Func2<String, String, String>() {
    @Override
    public ListenableFuture<String> run(String arg1, String arg2) {
      return immediateFuture(arg1 + ", " + arg2 + ", 2");
    }
  };

  Input<String> input = Input.named("in");

  Graph<String> g1 = call(node1).with(input).fallback(new AsyncFunction<Throwable, String>() {
    @Override
    public ListenableFuture<String> apply(@Nullable Throwable ignored) throws Exception {
      throw expected;
    }
  });
  Graph<String> g = call(node2).with(g1, input);

  thrown.expect(Exception.class);
  thrown.expectCause(hasAncestor(expected));

  g.bind(input, "hey").run().get();
}
 
Example #26
Source File: HeliosClient.java    From helios with Apache License 2.0 5 votes vote down vote up
public ListenableFuture<VersionResponse> version() {
  // Create a fallback in case we fail to connect to the master. Return null if this happens.
  // The transform below will handle this and return an appropriate error message to the caller.
  final ListenableFuture<Response> futureWithFallback = catching(
      request(uri("/version/"), "GET"),
      Exception.class,
      new Function<Exception, Response>() {
        @Override
        public Response apply(final Exception ex) {
          return null;
        }
      }, MoreExecutors.directExecutor());

  return transformAsync(
      futureWithFallback,
      new AsyncFunction<Response, VersionResponse>() {
        @Override
        public ListenableFuture<VersionResponse> apply(@NotNull Response reply) throws Exception {
          final String masterVersion = reply == null
              ? "Unable to connect to master"
              : reply.status() == HTTP_OK
                  ? Json.read(reply.payload(), String.class)
                  : "Master replied with error code " + reply.status();

          return immediateFuture(new VersionResponse(Version.POM_VERSION, masterVersion));
        }
      }, MoreExecutors.directExecutor());
}
 
Example #27
Source File: SchemaSourceTransformer.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
public SchemaSourceTransformer(final SchemaRepository provider, final Class<S> srcClass,
        final SchemaSourceRegistry consumer, final Class<D> dstClass, final AsyncFunction<S, D> function) {
    this.provider = requireNonNull(provider);
    this.consumer = requireNonNull(consumer);
    this.function = requireNonNull(function);
    this.srcClass = requireNonNull(srcClass);
    this.dstClass = requireNonNull(dstClass);
}
 
Example #28
Source File: ZMTPSocket.java    From netty-zmtp with Apache License 2.0 5 votes vote down vote up
/**
 * Bind this socket to an endpoint.
 */
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);
    }
  });
}
 
Example #29
Source File: CachingBuildRuleBuilder.java    From buck with Apache License 2.0 5 votes vote down vote up
private <F, T> AsyncFunction<F, T> ruleAsyncFunction(AsyncFunction<F, T> delegate) {
  return input -> {
    try (Scope ignored = buildRuleScope()) {
      return delegate.apply(input);
    }
  };
}
 
Example #30
Source File: EtcdClient.java    From jetcd with Apache License 2.0 5 votes vote down vote up
protected ListenableFuture<JsonResponse> asyncExecuteJson(HttpUriRequest request, final int[] expectedHttpStatusCodes) throws EtcdClientException {
    ListenableFuture<HttpResponse> response = asyncExecuteHttp(request);

    return Futures.transform(response, new AsyncFunction<HttpResponse, JsonResponse>() {
        public ListenableFuture<JsonResponse> apply(HttpResponse httpResponse) throws Exception {
            JsonResponse json = extractJsonResponse(httpResponse, expectedHttpStatusCodes);
            return Futures.immediateFuture(json);
        }
    });
}