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

The following examples show how to use com.google.common.util.concurrent.JdkFutureAdapters. 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: RestartCommand.java    From Cleanstone with MIT License 6 votes vote down vote up
@Override
public void execute(CommandMessage message) {
    if (message.getCommandSender() instanceof Player) {
        if (!((Player) message.getCommandSender()).isOp()) {
            message.getCommandSender().sendRawMessage("No permission");
            return;
        }
    }

    Text reason = message.optionalTextMessage().orElse(
            Text.ofLocalized("game.command.cleanstone.default-restart-reason",
                    CleanstoneServer.getDefaultLocale()));

    List<ListenableFuture<Void>> listenableFutures = playerManager.getOnlinePlayers().stream()
            .map(player -> player.kick(reason))
            .map(future -> JdkFutureAdapters.listenInPoolThread(future, executor))
            .collect(Collectors.toList());
    Futures.whenAllComplete(listenableFutures).run(CleanstoneServer::restart, executor);
}
 
Example #2
Source File: ArpSender.java    From atrium-odl with Apache License 2.0 6 votes vote down vote up
public ListenableFuture<RpcResult<Void>> sendArpResponse(ArpMessageAddress senderAddress,
		ArpMessageAddress receiverAddress, InstanceIdentifier<NodeConnector> egressNc, Header8021q vlan) {
	checkNotNull(senderAddress);
	checkNotNull(receiverAddress);
	checkNotNull(egressNc);
	final Ethernet arpFrame = createArpFrame(senderAddress, receiverAddress, vlan);
	byte[] arpFrameAsBytes;
	try {
		arpFrameAsBytes = arpFrame.serialize();
	} catch (PacketException e) {
		LOG.warn("Serializition of ARP packet is not successful.", e);
		if (LOG.isDebugEnabled()) {
			LOG.debug("ARP packet: {}", ArpUtils.getArpFrameToStringFormat(arpFrame));
		}
		return Futures.immediateFailedFuture(e);
	}
	// Generate packet with destination switch and port
	LOG.debug("Egress for ARP packetOut: " + new NodeConnectorRef(egressNc).toString());
	TransmitPacketInput packet = new TransmitPacketInputBuilder().setEgress(new NodeConnectorRef(egressNc))
			.setNode(new NodeRef(egressNc.firstIdentifierOf(Node.class))).setPayload(arpFrameAsBytes).build();
	if (LOG.isTraceEnabled()) {
		LOG.trace("Sending ARP RESPONSE \n{}", ArpUtils.getArpFrameToStringFormat(arpFrame));
	}
	Future<RpcResult<Void>> futureTransmitPacketResult = packetProcessingService.transmitPacket(packet);
	return JdkFutureAdapters.listenInPoolThread(futureTransmitPacketResult);
}
 
Example #3
Source File: TunnellingConnectivityManager.java    From atrium-odl with Apache License 2.0 6 votes vote down vote up
private void sendPacketOut(byte[] payload, NodeConnectorRef egress) {
	if (egress == null) {
		LOG.info("Egress is null");
		return;
	}

	InstanceIdentifier<Node> egressNodePath = getNodePath(egress.getValue());

	TransmitPacketInput input = new TransmitPacketInputBuilder() //
			.setPayload(payload) //
			.setNode(new NodeRef(egressNodePath)) //
			.setEgress(egress) //
			.build();

	Future<RpcResult<Void>> future = packetService.transmitPacket(input);
	JdkFutureAdapters.listenInPoolThread(future);
}
 
Example #4
Source File: FuturesUtil.java    From intellij with Apache License 2.0 6 votes vote down vote up
/**
 * Iterates through the futures, returning the first future satisfying the predicate. Future
 * returns null if there are no results matching the predicate.
 *
 * <p>Prioritizes immediately available results.
 */
public static <T> ListenableFuture<T> getFirstFutureSatisfyingPredicate(
    Iterable<Future<T>> iterable, Predicate<T> predicate) {
  List<ListenableFuture<T>> futures = new ArrayList<>();
  for (Future<T> future : iterable) {
    if (future.isDone()) {
      T result = getIgnoringErrors(future);
      if (predicate.test(result)) {
        return Futures.immediateFuture(result);
      }
    } else {
      // we can't return ListenableFuture directly, because implementations are using different
      // versions of that class...
      futures.add(JdkFutureAdapters.listenInPoolThread(future));
    }
  }
  if (futures.isEmpty()) {
    return Futures.immediateFuture(null);
  }
  return Futures.transform(
      Futures.allAsList(futures),
      (Function<List<T>, T>)
          list -> list == null ? null : list.stream().filter(predicate).findFirst().orElse(null),
      directExecutor());
}
 
Example #5
Source File: StopCommand.java    From Cleanstone with MIT License 6 votes vote down vote up
@Override
public void execute(CommandMessage message) {
    if (message.getCommandSender() instanceof Player) {
        if (!((Player) message.getCommandSender()).isOp()) {
            message.getCommandSender().sendRawMessage("No permission");
            return;
        }
    }

    Text reason = message.optionalTextMessage().orElse(
            Text.ofLocalized("game.command.cleanstone.default-stop-reason",
                    CleanstoneServer.getDefaultLocale()));

    List<ListenableFuture<Void>> listenableFutures = playerManager.getOnlinePlayers().stream()
            .map(player -> player.kick(reason))
            .map(future -> JdkFutureAdapters.listenInPoolThread(future, executor))
            .collect(Collectors.toList());
    Futures.whenAllComplete(listenableFutures).run(() -> {
        CleanstoneServer.stop();
        System.exit(0);
    }, executor);
}
 
Example #6
Source File: AbstractFrameTransport.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
public ListenableFuture<Void> sendBytes(final byte[] bytes)
{
    Preconditions.checkState(_channel != null, "Not connected");
    ChannelPromise promise = _channel.newPromise();
    ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer();
    buffer.writeBytes(bytes);
    _channel.write(buffer, promise);
    return JdkFutureAdapters.listenInPoolThread(promise);
}
 
Example #7
Source File: AbstractFrameTransport.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
public ListenableFuture<Void> sendPerformative(final Object data) throws Exception
{
    Preconditions.checkState(_channel != null, "Not connected");
    ChannelPromise promise = _channel.newPromise();
    _channel.write(data, promise);
    return JdkFutureAdapters.listenInPoolThread(promise);
}
 
Example #8
Source File: AbstractVirtualHost.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Override
public ListenableFuture<Void> reallocateMessages()
{
    final ScheduledThreadPoolExecutor houseKeepingTaskExecutor = _houseKeepingTaskExecutor;
    if (houseKeepingTaskExecutor != null)
    {
        try
        {
            final Future<Void> future = houseKeepingTaskExecutor.submit(() ->
                                                                        {
                                                                            final Collection<Queue> queues =
                                                                                    getChildren(Queue.class);
                                                                            for (Queue q : queues)
                                                                            {
                                                                                if (q.getState() == State.ACTIVE)
                                                                                {
                                                                                    q.reallocateMessages();
                                                                                }
                                                                            }
                                                                            return null;
                                                                        });
            return JdkFutureAdapters.listenInPoolThread(future);
        }
        catch (RejectedExecutionException e)
        {
            if (!houseKeepingTaskExecutor.isShutdown())
            {
                LOGGER.warn("Failed to schedule reallocation of messages", e);
            }
        }
    }
    return Futures.immediateFuture(null);
}
 
Example #9
Source File: RestartRunnableTestRun.java    From twill with Apache License 2.0 5 votes vote down vote up
@SafeVarargs
private final <V> ListenableFuture<List<V>> allAsList(Future<? extends V>... futures) {
  ImmutableList.Builder<ListenableFuture<? extends V>> listBuilder = ImmutableList.builder();
  for (Future<? extends V> future : futures) {
    listBuilder.add(JdkFutureAdapters.listenInPoolThread(future));
  }
  return Futures.allAsList(listBuilder.build());
}
 
Example #10
Source File: ThreadPoolManager.java    From aion-germany with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Schedule at fixed rate
 * 
 * @param <T>
 * @param r
 * @param initial
 * @param delay
 * @return ScheduledFuture
 */
@SuppressWarnings("unchecked")
public <T extends Runnable> ListenableFuture<T> scheduleAtFixedRate(final T r, long initial, long delay) {
	try {
		if (delay < 0)
			delay = 0;
		if (initial < 0)
			initial = 0;
		return (ListenableFuture<T>) JdkFutureAdapters.listenInPoolThread(scheduledThreadPool.scheduleAtFixedRate(r, initial, delay, TimeUnit.MILLISECONDS));
	} catch (RejectedExecutionException e) {
		return null;
	}
}
 
Example #11
Source File: ThreadPoolManager.java    From aion-germany with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Schedule
 * 
 * @param <T>
 * @param r
 * @param delay
 * @return ScheduledFuture
 */

@SuppressWarnings("unchecked")
public <T extends Runnable> ListenableFuture<T> schedule(final T r, long delay) {
	try {
		if (delay < 0)
			delay = 0;
		return (ListenableFuture<T>) JdkFutureAdapters.listenInPoolThread(scheduledThreadPool.schedule(r, delay, TimeUnit.MILLISECONDS));
	} catch (RejectedExecutionException e) {
		return null; /* shutdown, ignore */
	}
}
 
Example #12
Source File: ArpSender.java    From atrium-odl with Apache License 2.0 5 votes vote down vote up
/**
 * Sends ARP Request as packet-out from the given port (node connector).
 *
 * @param senderAddress
 *            the addresses used in sender part of ARP packet
 * @param tpa
 *            the target protocol address, in this case IPv4 address for
 *            which MAC should be discovered
 * @param egressNc
 *            the path to node connector from where the ARP packet will be
 *            sent
 * @return future result about success of packet-out
 */
public ListenableFuture<RpcResult<Void>> sendArp(ArpMessageAddress senderAddress, Ipv4Address tpa,
		InstanceIdentifier<NodeConnector> egressNc) {
	checkNotNull(senderAddress);
	checkNotNull(tpa);
	checkNotNull(egressNc);
	final Ethernet arpFrame = createArpFrame(senderAddress, tpa);
	byte[] arpFrameAsBytes;
	try {
		arpFrameAsBytes = arpFrame.serialize();
	} catch (PacketException e) {
		LOG.warn("Serializition of ARP packet is not successful.", e);
		if (LOG.isDebugEnabled()) {
			LOG.debug("ARP packet: {}", ArpUtils.getArpFrameToStringFormat(arpFrame));
		}
		return Futures.immediateFailedFuture(e);
	}
	// Generate packet with destination switch and port

	TransmitPacketInput packet = new TransmitPacketInputBuilder().setEgress(new NodeConnectorRef(egressNc))
			.setNode(new NodeRef(egressNc.firstIdentifierOf(Node.class))).setPayload(arpFrameAsBytes).build();
	if (LOG.isTraceEnabled()) {
		LOG.trace("Sending ARP REQUEST \n{}", ArpUtils.getArpFrameToStringFormat(arpFrame));
	}
	Future<RpcResult<Void>> futureTransmitPacketResult = packetProcessingService.transmitPacket(packet);
	return JdkFutureAdapters.listenInPoolThread(futureTransmitPacketResult);
}
 
Example #13
Source File: HttpRobotConnection.java    From swellrt with Apache License 2.0 5 votes vote down vote up
@Override
public ListenableFuture<String> asyncGet(final String url) {
  return JdkFutureAdapters.listenInPoolThread(executor.submit(new Callable<String>() {
    @Override
    public String call() throws RobotConnectionException {
      return get(url);
    }
  }));
}
 
Example #14
Source File: HttpRobotConnection.java    From swellrt with Apache License 2.0 5 votes vote down vote up
@Override
public ListenableFuture<String> asyncPostJson(final String url, final String body) {
  return JdkFutureAdapters.listenInPoolThread(executor.submit(new Callable<String>() {
    @Override
    public String call() throws RobotConnectionException {
      return postJson(url, body);
    }
  }));
}
 
Example #15
Source File: GooglePubSubSender.java    From helios with Apache License 2.0 5 votes vote down vote up
@Override
public void send(final String topic, final byte[] message) {
  final String combinedTopic = topicPrefix + topic;

  if (!healthchecker.isHealthy()) {
    log.warn("will not publish message to pubsub topic={} as the pubsub client "
             + "appears to be unhealthy", combinedTopic);
    return;
  }

  try {
    Futures.addCallback(
        JdkFutureAdapters.listenInPoolThread(
            pubsub.publishAsync(combinedTopic, Message.of(ByteArray.copyFrom(message)))),
        new FutureCallback<String>() {
          @Override
          public void onSuccess(@Nullable final String ackId) {
            log.debug("Sent an event to Google PubSub, topic: {}, ack: {}", combinedTopic, ackId);
          }

          @Override
          public void onFailure(final Throwable th) {
            log.warn("Unable to send an event to Google PubSub, topic: {}", combinedTopic, th);
          }
        }, MoreExecutors.directExecutor());
  } catch (Exception e) {
    log.warn("Failed to publish Google PubSub message, topic: {}", combinedTopic, e);
  }
}
 
Example #16
Source File: HttpRobotConnection.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
@Override
public ListenableFuture<String> asyncGet(final String url) {
  return JdkFutureAdapters.listenInPoolThread(executor.submit(new Callable<String>() {
    @Override
    public String call() throws RobotConnectionException {
      return get(url);
    }
  }));
}
 
Example #17
Source File: HttpRobotConnection.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
@Override
public ListenableFuture<String> asyncPostJson(final String url, final String body) {
  return JdkFutureAdapters.listenInPoolThread(executor.submit(new Callable<String>() {
    @Override
    public String call() throws RobotConnectionException {
      return postJson(url, body);
    }
  }));
}
 
Example #18
Source File: ListenableFutureMethodRunner.java    From caesar with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Object processResultFuture(final Future<?> future, final ExecutorService executor) {
    return JdkFutureAdapters.listenInPoolThread(future, executor);
}
 
Example #19
Source File: ScheduledTask.java    From wisdom with Apache License 2.0 4 votes vote down vote up
protected ScheduledTask<V> submittedScheduledTask(ScheduledFuture delegate) {
    this.submissionDate = System.currentTimeMillis();
    this.scheduledFuture = delegate;
    this.future = JdkFutureAdapters.listenInPoolThread(delegate);
    return this;
}