下面列出了怎么用com.google.common.util.concurrent.JdkFutureAdapters的API类实例代码及写法,或者点击链接到github查看源代码。
@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);
}
@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);
}
/**
* 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());
}
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);
}
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);
}
/**
* 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 */
}
}
/**
* 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;
}
}
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);
}
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);
}
@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);
}
@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());
}
/**
* 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);
}
@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);
}
}));
}
@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);
}
}));
}
@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);
}
}
@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);
}
}));
}
@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);
}
}));
}
/**
* {@inheritDoc}
*/
@Override
public Object processResultFuture(final Future<?> future, final ExecutorService executor) {
return JdkFutureAdapters.listenInPoolThread(future, executor);
}
protected ScheduledTask<V> submittedScheduledTask(ScheduledFuture delegate) {
this.submissionDate = System.currentTimeMillis();
this.scheduledFuture = delegate;
this.future = JdkFutureAdapters.listenInPoolThread(delegate);
return this;
}