Search in sources :

Example 1 with MbedCloudException

use of com.arm.mbed.cloud.sdk.common.MbedCloudException in project mbed-cloud-sdk-java by ARMmbed.

the class TestAbstractObserver method testNotifyOnObserver.

@Test
public void testNotifyOnObserver() {
    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<>();
        obs.flow().filter(new Predicate<NotificationTestMessageValue>() {

            @Override
            public boolean test(NotificationTestMessageValue t) throws Exception {
                return ((Integer) t.getRawValue()).intValue() % 10 == 0;
            }
        }).subscribe(new Consumer<NotificationTestMessageValue>() {

            @Override
            public void accept(NotificationTestMessageValue t) throws Exception {
                MultiplesOfTenList.add(((Integer) t.getRawValue()));
            }
        });
        executor = Executors.newScheduledThreadPool(1);
        int Interval = 300;
        handle = executor.scheduleWithFixedDelay(new Runnable() {

            private int i = 0;

            @Override
            public void run() {
                if (i < messages.size()) {
                    @SuppressWarnings({ "unchecked", "boxing", "rawtypes" }) NotificationMessage<NotificationTestMessageValue> notification = new NotificationMessage(new NotificationTestMessageValue(messages.get(i)), null);
                    try {
                        obs.notify(notification);
                    } catch (MbedCloudException e) {
                        e.printStackTrace();
                    }
                    i++;
                }
            }
        }, 0, Interval, TimeUnit.MILLISECONDS);
        Thread.sleep((messages.size() + 1) * Interval);
        // the list should only contain multiples of 10 from 0 to 100 included.
        assertEquals(11, 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());
        }
        assertFalse(obs.isDisposed());
        obs.unsubscribe();
        assertTrue(obs.isDisposed());
        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());
    }
}
Also used : ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) LinkedList(java.util.LinkedList) MbedCloudException(com.arm.mbed.cloud.sdk.common.MbedCloudException) Predicate(io.reactivex.functions.Predicate) MbedCloudException(com.arm.mbed.cloud.sdk.common.MbedCloudException) Test(org.junit.Test)

Example 2 with MbedCloudException

use of com.arm.mbed.cloud.sdk.common.MbedCloudException 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());
    }
}
Also used : DeviceState(com.arm.mbed.cloud.sdk.subscribe.model.DeviceState) SubscriptionType(com.arm.mbed.cloud.sdk.subscribe.SubscriptionType) Future(java.util.concurrent.Future) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Assert.fail(org.junit.Assert.fail) NotificationCallback(com.arm.mbed.cloud.sdk.subscribe.NotificationCallback) Schedulers(io.reactivex.schedulers.Schedulers) MbedCloudException(com.arm.mbed.cloud.sdk.common.MbedCloudException) LinkedList(java.util.LinkedList) DeviceStateObserver(com.arm.mbed.cloud.sdk.subscribe.model.DeviceStateObserver) BackpressureStrategy(io.reactivex.BackpressureStrategy) Assert.assertNotNull(org.junit.Assert.assertNotNull) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Callback(com.arm.mbed.cloud.sdk.common.Callback) Collectors(java.util.stream.Collectors) Executors(java.util.concurrent.Executors) TimeUnit(java.util.concurrent.TimeUnit) DeviceStateFilterOptions(com.arm.mbed.cloud.sdk.subscribe.model.DeviceStateFilterOptions) List(java.util.List) Assert.assertNull(org.junit.Assert.assertNull) Stream(java.util.stream.Stream) Assert.assertFalse(org.junit.Assert.assertFalse) DeviceStateNotification(com.arm.mbed.cloud.sdk.subscribe.model.DeviceStateNotification) Assert.assertEquals(org.junit.Assert.assertEquals) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) DeviceStateObserver(com.arm.mbed.cloud.sdk.subscribe.model.DeviceStateObserver) LinkedList(java.util.LinkedList) MbedCloudException(com.arm.mbed.cloud.sdk.common.MbedCloudException) DeviceStateNotification(com.arm.mbed.cloud.sdk.subscribe.model.DeviceStateNotification) DeviceStateFilterOptions(com.arm.mbed.cloud.sdk.subscribe.model.DeviceStateFilterOptions) NotificationCallback(com.arm.mbed.cloud.sdk.subscribe.NotificationCallback) Callback(com.arm.mbed.cloud.sdk.common.Callback) MbedCloudException(com.arm.mbed.cloud.sdk.common.MbedCloudException) Test(org.junit.Test)

Example 3 with MbedCloudException

use of com.arm.mbed.cloud.sdk.common.MbedCloudException in project mbed-cloud-sdk-java by ARMmbed.

the class Connect method startNotifications.

/**
 * Starts notification pull.
 * <p>
 * If an external callback is not set up (using `update_webhook`) then calling this function is mandatory to get or
 * set resources. Unless {@link ConnectionOptions#setAutostartDaemon(boolean)} has been set to true or left as
 * default.
 * <p>
 * Example:
 *
 * <pre>
 * {@code
 * connectApi.startNotifications();
 * }
 * </pre>
 *
 * @throws MbedCloudException
 *             if a problem occurred during the process.
 */
@API
@Daemon(task = "Notification pull", start = true)
public void startNotifications() throws MbedCloudException {
    Webhook webhook = null;
    try {
        if (isForceClear()) {
            deleteWebhook();
        }
    } catch (MbedCloudException exception) {
    // Nothing to do
    }
    try {
        webhook = getWebhook();
    } catch (MbedCloudException exception) {
    // Nothing to do
    }
    if (webhook != null) {
        logger.throwSdkException("A webhook is currently set up [" + webhook + "]. Notification pull cannot be used at the same time. Please remove the webhook if you want to use this mechanism instead.");
    }
    handlersStore.startNotificationPull();
}
Also used : MbedCloudException(com.arm.mbed.cloud.sdk.common.MbedCloudException) Webhook(com.arm.mbed.cloud.sdk.connect.model.Webhook) Daemon(com.arm.mbed.cloud.sdk.annotations.Daemon) API(com.arm.mbed.cloud.sdk.annotations.API)

Example 4 with MbedCloudException

use of com.arm.mbed.cloud.sdk.common.MbedCloudException in project mbed-cloud-sdk-java by ARMmbed.

the class Connect method getResourceSubscription.

/**
 * Gets the status of a resource's subscription.
 * <p>
 * Example:
 *
 * <pre>
 * {@code
 * try {
 *     String deviceId = "015f4ac587f500000000000100100249";
 *     String resourcePath = "/3200/0/5501";
 *     Resource buttonResource = new Resource(deviceId, resourcePath);
 *
 *     boolean subscribed = connectApi.getResourceSubscription(buttonResource);
 *     System.out.println("Is " + deviceId + " subscribed to: " + resourcePath + "? " + (subscribed ? "yes" : "no"));
 * } catch (MbedCloudException e) {
 *     e.printStackTrace();
 * }
 * }
 * </pre>
 *
 * @param resource
 *            resource
 * @return true if resource is subscribed. false otherwise.
 * @throws MbedCloudException
 *             if a parameter is incorrect
 */
@API
public boolean getResourceSubscription(@NonNull Resource resource) throws MbedCloudException {
    checkNotNull(resource, TAG_RESOURCE);
    checkModelValidity(resource, TAG_RESOURCE);
    final Resource finalResource = resource;
    try {
        CloudCaller.call(this, "getResourceSubscription()", null, new CloudCall<Void>() {

            @Override
            public Call<Void> call() {
                return endpoint.getSubscriptions().v2SubscriptionsDeviceIdResourcePathGet(finalResource.getDeviceId(), ApiUtils.normalisePath(finalResource.getPath()));
            }
        }, true);
        return true;
    } catch (MbedCloudException exception) {
        return false;
    }
}
Also used : Call(retrofit2.Call) CloudCall(com.arm.mbed.cloud.sdk.common.CloudCaller.CloudCall) MbedCloudException(com.arm.mbed.cloud.sdk.common.MbedCloudException) Resource(com.arm.mbed.cloud.sdk.connect.model.Resource) API(com.arm.mbed.cloud.sdk.annotations.API)

Example 5 with MbedCloudException

use of com.arm.mbed.cloud.sdk.common.MbedCloudException in project mbed-cloud-sdk-java by ARMmbed.

the class NotificationHandlersStore method createCachingSingleAction.

private Runnable createCachingSingleAction() {
    return new Runnable() {

        private final ExponentialBackoff backoffPolicy = new ExponentialBackoff(api.getLogger());

        @Override
        public void run() {
            try {
                final CallFeedback<NotificationMessage> feedback = CloudCaller.callWithFeedback(api, "NotificationPullGet()", getIdentityMapper(), new CloudCall<NotificationMessage>() {

                    @Override
                    public Call<NotificationMessage> call() {
                        return endpoint.getNotifications().v2NotificationPullGet();
                    }
                }, false, true);
                final NotificationMessage notificationMessage = feedback.getResult();
                if (notificationMessage == null) {
                    api.getLogger().logInfo("Notification pull did not receive any notification during last call. Call information: " + feedback.getMetadata());
                    return;
                }
                storeResponses(notificationMessage.getAsyncResponses());
                handleSubscriptions(notificationMessage.getNotifications());
                handleDeviceStateChanges(notificationMessage);
            } catch (MbedCloudException exception) {
                backoffPolicy.backoff();
                logPullError(exception);
            }
        }
    };
}
Also used : CloudCall(com.arm.mbed.cloud.sdk.common.CloudCaller.CloudCall) Call(retrofit2.Call) NotificationMessage(com.arm.mbed.cloud.sdk.internal.mds.model.NotificationMessage) MbedCloudException(com.arm.mbed.cloud.sdk.common.MbedCloudException)

Aggregations

MbedCloudException (com.arm.mbed.cloud.sdk.common.MbedCloudException)11 Test (org.junit.Test)5 LinkedList (java.util.LinkedList)4 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)4 TimePeriod (com.arm.mbed.cloud.sdk.common.TimePeriod)3 Resource (com.arm.mbed.cloud.sdk.connect.model.Resource)3 Connect (com.arm.mbed.cloud.sdk.Connect)2 API (com.arm.mbed.cloud.sdk.annotations.API)2 Callback (com.arm.mbed.cloud.sdk.common.Callback)2 CloudCall (com.arm.mbed.cloud.sdk.common.CloudCaller.CloudCall)2 ConnectionOptions (com.arm.mbed.cloud.sdk.common.ConnectionOptions)2 Device (com.arm.mbed.cloud.sdk.devicedirectory.model.Device)2 DeviceListOptions (com.arm.mbed.cloud.sdk.devicedirectory.model.DeviceListOptions)2 Predicate (io.reactivex.functions.Predicate)2 Call (retrofit2.Call)2 AbstractExample (utils.AbstractExample)2 Example (utils.Example)2 Daemon (com.arm.mbed.cloud.sdk.annotations.Daemon)1 Webhook (com.arm.mbed.cloud.sdk.connect.model.Webhook)1 NotificationMessage (com.arm.mbed.cloud.sdk.internal.mds.model.NotificationMessage)1