use of com.arm.mbed.cloud.sdk.common.Callback in project mbed-cloud-sdk-java by ARMmbed.
the class ConnectExamples method subscribeToResourcesWithCallbacks.
/**
* Subscribes to a resource with callbacks.
*/
@SuppressWarnings({ "boxing", "null" })
@Example
public void subscribeToResourcesWithCallbacks() {
ConnectionOptions config = Configuration.get();
Connect api = new Connect(config);
try {
// Getting a connected device.
DeviceListOptions options = new DeviceListOptions();
options.setLimit(1);
Paginator<Device> deviceIterator = api.listAllConnectedDevices(options);
if (!deviceIterator.hasNext()) {
fail("No endpoints registered. Aborting.");
}
Device device = deviceIterator.next();
log("Device", device);
List<Resource> observableResources = api.listObservableResources(device);
if (observableResources == null) {
fail("There is no observable resources on this device");
}
for (final Resource resourceToSubscribeTo : observableResources) {
log("Resource suscribed", resourceToSubscribeTo);
// Creating a subscriber for each resource.
if (resourceToSubscribeTo != null) {
// Defining callbacks.
Callback<Object> onNotificationCallback = new Callback<Object>() {
@Override
public void execute(Object arg) {
log("Received notification value for " + resourceToSubscribeTo + " using callbacks", arg);
}
};
Callback<Throwable> onErrorCallback = new Callback<Throwable>() {
@Override
public void execute(Throwable t) {
log("Received following error for " + resourceToSubscribeTo, t);
}
};
api.addResourceSubscription(resourceToSubscribeTo, onNotificationCallback, onErrorCallback);
}
}
// Listening to notifications for 2 minutes.
api.startNotifications();
Thread.sleep(120000);
// Stopping notification pull channel.
api.stopNotifications();
Thread.sleep(100);
api.shutdownConnectService();
} catch (Exception e) {
e.printStackTrace();
logError("last API Metadata", api.getLastApiMetadata());
try {
api.stopNotifications();
Thread.sleep(100);
} catch (Exception e1) {
e1.printStackTrace();
}
api.shutdownConnectService();
fail(e.getMessage());
}
}
use of com.arm.mbed.cloud.sdk.common.Callback in project mbed-cloud-sdk-java by ARMmbed.
the class TestNotificationHandling method testDeviceState.
/**
* Tests subscriptions to device state changes
*/
@Test
public void testDeviceState() {
Future<?> handle = null;
ScheduledExecutorService executor = null;
try {
List<DeviceStateNotification> receivedNotifications = new LinkedList<>();
executor = Executors.newScheduledThreadPool(1);
NotificationHandlersStore store = new NotificationHandlersStore(null, null, executor, null);
DeviceStateObserver obs1 = store.getSubscriptionManager().deviceState(new DeviceStateFilterOptions().likeDevice("016%33e").equalDeviceState(DeviceState.REGISTRATION_UPDATE), BackpressureStrategy.BUFFER);
// Generating notifications
@SuppressWarnings("boxing") List<NotificationMessage> notifications = Stream.iterate(0, n -> n + 1).limit(32).map(i -> {
NotificationMessage message = new NotificationMessage();
EndpointData data = new EndpointData();
if (i % 5 == 0) {
data.setEp("0161661e9ce10000000000010010033e");
} else {
data.setEp("0161661edbab000000000001001002b7");
}
data.setEpt("random");
data.setQ(false);
data.setResources(Stream.iterate(0, n -> n + 1).limit(50).map(v -> {
final ResourcesData resource = new ResourcesData();
resource.setPath("/" + v);
resource.setObs(true);
return resource;
}).collect(Collectors.toList()));
if (i % 2 == 0) {
message.addRegUpdatesItem(data);
} else {
message.addRegistrationsItem(data);
}
return message;
}).collect(Collectors.toList());
obs1.addCallback(new NotificationCallback<>(new Callback<DeviceStateNotification>() {
@Override
public void execute(DeviceStateNotification arg) {
receivedNotifications.add(arg);
}
}, null));
int Interval = 300;
handle = executor.scheduleWithFixedDelay(new Runnable() {
private int i = 0;
@Override
public void run() {
if (i < notifications.size()) {
store.notify(notifications.get(i));
i++;
}
}
}, 0, Interval, TimeUnit.MILLISECONDS);
// Waiting for all notifications to be emitted
Thread.sleep((notifications.size() + 1) * Interval);
assertFalse(receivedNotifications.isEmpty());
// Only multiples of 10 between 0 and 32
assertEquals(4, receivedNotifications.size());
// Observer only cares about changes related to devices like 016%33e and REGISTRATION_UPDATE state
receivedNotifications.forEach(n -> {
assertEquals("0161661e9ce10000000000010010033e", n.getDeviceId());
assertEquals(DeviceState.REGISTRATION_UPDATE, n.getState());
});
if (handle != null) {
handle.cancel(true);
}
executor.shutdownNow();
} catch (Exception e) {
if (handle != null) {
handle.cancel(true);
}
if (executor != null) {
executor.shutdownNow();
}
e.printStackTrace();
fail(e.getMessage());
}
}
use of com.arm.mbed.cloud.sdk.common.Callback in project mbed-cloud-sdk-java by ARMmbed.
the class TestSubscriptionObserversStore method testDeviceState.
/**
* Tests subscriptions to device state changes
*/
@Test
public void testDeviceState() {
Future<?> handle = null;
ScheduledExecutorService executor = null;
try {
List<DeviceStateNotification> receivedNotifications = new LinkedList<>();
SubscriptionObserversStore store = new SubscriptionObserversStore(Schedulers.computation());
DeviceStateObserver obs1 = store.deviceState(new DeviceStateFilterOptions().likeDevice("016%33e").equalDeviceState(DeviceState.REGISTRATION_UPDATE), BackpressureStrategy.BUFFER);
// We are only interested in one value of obs1
Future<DeviceStateNotification> future = obs1.futureOne();
DeviceStateObserver obs2 = store.deviceState(DeviceStateFilterOptions.newFilter().likeDevice("016%2b7").equalDeviceState(DeviceState.REGISTRATION_UPDATE), BackpressureStrategy.BUFFER);
assertTrue(store.hasObservers());
assertTrue(store.hasObservers(SubscriptionType.DEVICE_STATE_CHANGE));
assertFalse(store.hasObservers(SubscriptionType.NOTIFICATION));
assertEquals(2, store.listAll().size());
assertEquals(2, store.listAll(SubscriptionType.DEVICE_STATE_CHANGE).size());
assertNull(store.listAll(SubscriptionType.NOTIFICATION));
// Generating notifications
@SuppressWarnings("boxing") List<DeviceStateNotification> notifications = Stream.iterate(0, n -> n + 1).limit(102).map(i -> {
return (i % 2 == 0) ? new DeviceStateNotification((i % 5 == 0) ? DeviceState.REGISTRATION_UPDATE : DeviceState.EXPIRED_REGISTRATION, "0161661e9ce10000000000010010033e") : new DeviceStateNotification((i % 5 == 0) ? DeviceState.REGISTRATION_UPDATE : DeviceState.REGISTRATION, "0161661edbab000000000001001002b7");
}).collect(Collectors.toList());
obs2.addCallback(new NotificationCallback<>(new Callback<DeviceStateNotification>() {
@Override
public void execute(DeviceStateNotification arg) {
receivedNotifications.add(arg);
}
}, null));
executor = Executors.newScheduledThreadPool(1);
int Interval = 300;
handle = executor.scheduleWithFixedDelay(new Runnable() {
private int i = 0;
@Override
public void run() {
if (i < notifications.size()) {
try {
store.notify(SubscriptionType.DEVICE_STATE_CHANGE, notifications.get(i));
} catch (MbedCloudException e) {
e.printStackTrace();
}
i++;
}
}
}, 0, Interval, TimeUnit.MILLISECONDS);
// Waiting for all notifications to be emitted
Thread.sleep((notifications.size() + 1) * Interval);
DeviceStateNotification receivedNotificationForObs1 = future.get(2, TimeUnit.SECONDS);
assertNotNull(receivedNotificationForObs1);
assertEquals("0161661e9ce10000000000010010033e", receivedNotificationForObs1.getDeviceId());
assertEquals(DeviceState.REGISTRATION_UPDATE, receivedNotificationForObs1.getState());
assertFalse(receivedNotifications.isEmpty());
// odd Multiples of 5 between 0 and 102: 10
assertEquals(10, receivedNotifications.size());
// Observer 2 only cares about changes related to devices like 016%2b7 and REGISTRATION_UPDATE state
receivedNotifications.forEach(n -> {
assertEquals("0161661edbab000000000001001002b7", n.getDeviceId());
assertEquals(DeviceState.REGISTRATION_UPDATE, n.getState());
});
assertTrue(store.hasObserver(obs1));
store.completeAll();
store.unsubscribeAll();
assertFalse(store.hasObservers());
assertFalse(store.hasObserver(obs1));
if (handle != null) {
handle.cancel(true);
}
executor.shutdownNow();
} catch (Exception e) {
if (handle != null) {
handle.cancel(true);
}
if (executor != null) {
executor.shutdownNow();
}
e.printStackTrace();
fail(e.getMessage());
}
}
use of com.arm.mbed.cloud.sdk.common.Callback in project mbed-cloud-sdk-java by ARMmbed.
the class TestAbstractObserver method testErrorNotification.
@Test
public void testErrorNotification() {
Future<?> handle = null;
ScheduledExecutorService executor = null;
try {
@SuppressWarnings("boxing") List<Integer> messages = Stream.iterate(0, n -> n + 1).limit(102).collect(Collectors.toList());
SubscriptionTestManagerModifiableInput manager = new SubscriptionTestManagerModifiableInput(false);
TestObserver obs = manager.createObserver(SubscriptionType.DEVICE_STATE_CHANGE, null, BackpressureStrategy.BUFFER);
// Only storing multiple of 10.
List<Integer> multiplesOfTenList = new LinkedList<>();
List<String> errorList = new LinkedList<>();
Callback<Throwable> onFailureCallback = new Callback<Throwable>() {
@Override
public void execute(Throwable arg) {
errorList.add(arg.getMessage());
}
};
obs.addCallback(new NotificationCallback<>(new Callback<NotificationTestMessageValue>() {
@Override
public void execute(NotificationTestMessageValue arg) {
if (((Integer) arg.getRawValue()).intValue() % 5 == 0) {
multiplesOfTenList.add(((Integer) arg.getRawValue()));
}
}
}, onFailureCallback));
executor = Executors.newScheduledThreadPool(1);
int Interval = 50;
handle = executor.scheduleWithFixedDelay(new Runnable() {
private int i = 0;
@Override
public void run() {
if (i < messages.size()) {
@SuppressWarnings({ "unchecked", "boxing", "rawtypes" }) NotificationMessage<NotificationTestMessageValue> notification = null;
if (i < 52) {
notification = new NotificationMessage(new NotificationTestMessageValue(messages.get(i)), null);
} else {
notification = new NotificationMessage(new NotificationTestMessageValue(messages.get(i)), new Exception("An error occurred"));
}
try {
obs.notify(notification);
} catch (MbedCloudException e) {
System.out.println(e.getMessage());
// e.printStackTrace();
}
i++;
}
}
}, 0, Interval, TimeUnit.MILLISECONDS);
Thread.sleep((messages.size() + 1) * Interval);
// the list should only contain multiples of 10 from 0 to 50 included.
assertEquals(6, multiplesOfTenList.size());
// the list should only contain multiples of 10.
for (int i = 0; i < multiplesOfTenList.size(); i++) {
assertEquals(i * 10, multiplesOfTenList.get(i).intValue());
}
// Errors should have been raised
assertFalse(errorList.isEmpty());
assertEquals(1, errorList.size());
assertEquals("An error occurred", errorList.get(0));
assertFalse(obs.isDisposed());
obs.unsubscribe();
assertTrue(obs.isDisposed());
if (handle != null) {
handle.cancel(true);
}
if (executor != null) {
executor.shutdownNow();
}
} catch (Exception e) {
if (handle != null) {
handle.cancel(true);
}
if (executor != null) {
executor.shutdownNow();
}
e.printStackTrace();
fail(e.getMessage());
}
}
Aggregations