下面列出了怎么用com.google.common.util.concurrent.CheckedFuture的API类实例代码及写法,或者点击链接到github查看源代码。
public static <T extends DataObject> boolean writeData(DataBroker dataBroker, LogicalDatastoreType logicalDatastoreType,
InstanceIdentifier<T> iid, T dataObject, boolean isAdd) {
Preconditions.checkNotNull(dataBroker);
WriteTransaction modification = dataBroker.newWriteOnlyTransaction();
if (isAdd) {
if (dataObject == null) {
logger.warn("Invalid attempt to add a non-existent object to path {}", iid);
return false;
}
modification.merge(logicalDatastoreType, iid, dataObject, true /*createMissingParents*/);
}
else {
modification.delete(LogicalDatastoreType.CONFIGURATION, iid);
}
CheckedFuture<Void, TransactionCommitFailedException> commitFuture = modification.submit();
try {
commitFuture.checkedGet();
logger.debug("Transaction success for {} of object {}", (isAdd) ? "add" : "delete", dataObject);
return true;
} catch (Exception e) {
logger.error("Transaction failed with error {} for {} of object {}", e.getMessage(), (isAdd) ? "add" : "delete", dataObject);
modification.cancel();
return false;
}
}
@Override
public void onDataChanged(AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> change) {
Map<InstanceIdentifier<?>, DataObject> createdData = change.getCreatedData();
for (Map.Entry<InstanceIdentifier<?>, DataObject> entrySet : createdData.entrySet()) {
InstanceIdentifier<?> iiD = entrySet.getKey();
final DataObject dataObject = entrySet.getValue();
if (dataObject instanceof FlowCapableNode) {
final InstanceIdentifier<Node> path = iiD.firstIdentifierOf(Node.class);
ReadOnlyTransaction readOnlyTransaction = dataBroker.newReadOnlyTransaction();
final CheckedFuture<Optional<Node>, ReadFailedException> readFuture = readOnlyTransaction
.read(LogicalDatastoreType.OPERATIONAL, path);
Futures.addCallback(readFuture, new FutureCallback<Optional<Node>>() {
@Override
public void onSuccess(Optional<Node> result) {
if (result.isPresent()) {
bgpRouter.processNodeAdd(result.get().getId());
LOG.info("Node discovered and passed to processNodeAdd : " + result.get().getId());
} else {
LOG.info("Read succeeded, node doesn't exist: {}", path);
}
}
@Override
public void onFailure(Throwable t) {
LOG.info("Failed to read Node: {}", path, t);
}
});
}
}
}
/**
* Instantiates bgp router
*/
private void setupBgpRouter() throws InterruptedException, ExecutionException {
ReadOnlyTransaction readOnlyTransaction = mock(ReadOnlyTransaction.class);
Optional<Nodes> nodes = Optional.of(mock(Nodes.class));
CheckedFuture<Optional<Nodes>, ReadFailedException> checkedNodes = mock(CheckedFuture.class);
when(dataBroker.newReadOnlyTransaction()).thenReturn(readOnlyTransaction);
when(readOnlyTransaction.read(any(LogicalDatastoreType.class),
(InstanceIdentifier<Nodes>) any(InstanceIdentifier.class))).thenReturn(checkedNodes);
when(checkedNodes.get()).thenReturn(nodes);
bgpRouter = new Bgprouter(connectivityManager, dataBroker, routingConfigService, routingService, packetService,
flowObjectives);
}
public CheckedFuture<V, E> check(ListenableFuture<V> future) {
return Futures.makeChecked(future, new Function<Exception, E>() {
@Override public E apply(Exception e) {
Throwable cause = e.getCause();
if (!(cause instanceof HttpBadResponseException)) {
cause.printStackTrace(); // TODO
return null;
}
HttpBadResponseException hbre = (HttpBadResponseException) cause;
return AbstractFutureChecker.this.getException(hbre.response);
}
});
}
/**
* Retrieve a JWT from the api. When passed in a MixerUser use this as the result.
* @return
*/
public <T> CheckedFuture<T, MixerException> authorize(final T value) {
return new JWT.JWTFutureChecker<T>().check(Futures.transform(
this.post("authorize", null, new Object()),
new AsyncFunction<Object, T>() {
@Override
public ListenableFuture<T> apply(Object o) throws Exception {
return Futures.immediateCheckedFuture(value);
}
}
));
}
public CheckedFuture<ChannelStatusResponse, MixerException> findRelationship(MixerChannel channel, MixerUser user) {
return new Channels.StatusChecker(this.mixer.gson).check(this.get(
String.format("%d/relationship", channel.id),
ChannelStatusResponse.class,
MixerHttpClient.getArgumentsBuilder()
.put("user", String.valueOf(user.id))
.build()
));
}
/**
* Tests if the ipv4 packets received are transmitted to the switch
*/
@Test
public void testOnIpv4PacketReceived() throws InterruptedException, ExecutionException {
Ipv4PacketReceived packetReceived = mock(Ipv4PacketReceived.class);
List<PacketChain> packetChains = new ArrayList<PacketChain>();
PacketChain packetChain1 = mock(PacketChain.class);
PacketChain packetChain2 = mock(PacketChain.class);
PacketChain packetChain3 = mock(PacketChain.class);
RawPacket rawPacket = mock(RawPacket.class);
EthernetPacket ethernetPacket = mock(EthernetPacket.class);
Ipv4Packet ipv4Packet = mock(Ipv4Packet.class);
packetChains.add(packetChain1);
packetChains.add(packetChain2);
packetChains.add(packetChain3);
List<Header8021q> headers = mock(ArrayList.class);
byte[] payload = new byte[100];
for (byte index = 1; payload.length <= index; index++) {
payload[index] = index;
}
NodeConnectorRef ncRef = mock(NodeConnectorRef.class);
ReadOnlyTransaction readTx = mock(ReadOnlyTransaction.class);
CheckedFuture<Optional<NodeConnector>, ReadFailedException> checkedNodes = mock(CheckedFuture.class);
Optional<NodeConnector> nc = mock(Optional.class);
NodeConnector nodeConnector = mock(NodeConnector.class);
NodeConnectorId ncId = new NodeConnectorId("openflow:20:17");
Ipv4Address destIpAddress = new Ipv4Address("192.168.10.1");
BgpPeer bgpPeer = mock(BgpPeer.class);
Future<RpcResult<Void>> future = mock(Future.class);
when(packetReceived.getPacketChain()).thenReturn(packetChains);
when(packetChain1.getPacket()).thenReturn(rawPacket);
when(packetChain2.getPacket()).thenReturn(ethernetPacket);
when(packetChain3.getPacket()).thenReturn(ipv4Packet);
when(ipv4Packet.getProtocol()).thenReturn(KnownIpProtocols.Icmp);
when(ethernetPacket.getHeader8021q()).thenReturn(headers);
when(packetReceived.getPayload()).thenReturn(payload);
when(rawPacket.getIngress()).thenReturn(ncRef);
when(dataBroker.newReadOnlyTransaction()).thenReturn(readTx);
when(readTx.read(any(LogicalDatastoreType.class),
(InstanceIdentifier<NodeConnector>) any(InstanceIdentifier.class))).thenReturn(checkedNodes);
when(checkedNodes.get()).thenReturn(nc);
when(nc.isPresent()).thenReturn(Boolean.valueOf(true));
when(nc.get()).thenReturn(nodeConnector);
when(nodeConnector.getId()).thenReturn(ncId);
when(ipv4Packet.getDestinationIpv4()).thenReturn(destIpAddress);
when(routingConfigService.getBgpPeerByIpAddress(any(IpAddress.class))).thenReturn(bgpPeer);
when(bgpPeer.getPeerDpId()).thenReturn(NodeId.getDefaultInstance("21"));
when(bgpPeer.getPeerPort()).thenReturn(Long.valueOf(18));
when(packetService.transmitPacket(any(TransmitPacketInput.class))).thenReturn(future);
connectivityManager.onIpv4PacketReceived(packetReceived);
verify(packetService, times(1)).transmitPacket(any(TransmitPacketInput.class));
}
public CheckedFuture<RobotInfo, MixerException> getRobotCredentials(int channelId) {
MixerChannel channel = new MixerChannel();
channel.id = channelId;
return this.getRobotCredentials(channel);
}
public CheckedFuture<RobotInfo, MixerException> getRobotCredentials(MixerChannel channel) {
return new Interactive.UnsetGameChecker().check(
this.get(String.format("%d/robot", channel.id), RobotInfo.class)
);
}
@Override
public CheckedFuture<MixerUser, MixerException> apply(final MixerUser mixerUser) throws Exception {
return UsersService.this.mixer.use(JWTService.class).authorize(mixerUser);
}