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

The following examples show how to use com.google.common.util.concurrent.CheckedFuture. 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: GenericTransactionUtils.java    From SDNHub_Opendaylight_Tutorial with GNU General Public License v3.0 6 votes vote down vote up
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;
    }
}
 
Example #2
Source File: DeviceListener.java    From atrium-odl with Apache License 2.0 5 votes vote down vote up
@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);
				}
			});
		}
	}
}
 
Example #3
Source File: BgprouterTest.java    From atrium-odl with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #4
Source File: AbstractFutureChecker.java    From beam-client-java with MIT License 5 votes vote down vote up
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);
        }
    });
}
 
Example #5
Source File: JWTService.java    From beam-client-java with MIT License 5 votes vote down vote up
/**
 * 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);
            }
        }
    ));
}
 
Example #6
Source File: ChannelsService.java    From beam-client-java with MIT License 5 votes vote down vote up
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()
    ));
}
 
Example #7
Source File: TunnellingConnectivityManagerTest.java    From atrium-odl with Apache License 2.0 4 votes vote down vote up
/**
 * 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));
}
 
Example #8
Source File: InteractiveService.java    From beam-client-java with MIT License 4 votes vote down vote up
public CheckedFuture<RobotInfo, MixerException> getRobotCredentials(int channelId) {
    MixerChannel channel = new MixerChannel();
    channel.id = channelId;

    return this.getRobotCredentials(channel);
}
 
Example #9
Source File: InteractiveService.java    From beam-client-java with MIT License 4 votes vote down vote up
public CheckedFuture<RobotInfo, MixerException> getRobotCredentials(MixerChannel channel) {
    return new Interactive.UnsetGameChecker().check(
        this.get(String.format("%d/robot", channel.id), RobotInfo.class)
    );
}
 
Example #10
Source File: UsersService.java    From beam-client-java with MIT License 4 votes vote down vote up
@Override
public CheckedFuture<MixerUser, MixerException> apply(final MixerUser mixerUser) throws Exception {
    return UsersService.this.mixer.use(JWTService.class).authorize(mixerUser);
}