OfficeDev / ews-java-api

A java client library to access Exchange web services. The API works against Office 365 Exchange Online as well as on premises Exchange.
MIT License
867 stars 557 forks source link

StreamingSubscriptionConnection.getIsOpen() returns false after keep-alive #742

Open uklance opened 3 years ago

uklance commented 3 years ago

StreamingSubscriptionConnection.getIsOpen() returns true initially, but then starts returning false after the OnDisconnect handler fires (calling StreamingSubscriptionConnection.open())

The documentation here states:

After the time-out of the connection has elapsed, the OnDisconnect event is raised by the StreamingSubscriptionConnection instance. If your application still needs to monitor the subscription, you can just call the Open method of the StreamingSubscriptionConnection instance again to reconnect to the Exchange server. This behavior is expected and is not an error condition.

Please see my code below with comments showing when connection.getIsOpen() initially returns true, but starts returning false after the disconnect handler fires

public class EwsClient {
    private final ExchangeService exchangeService;
    private final Set<StreamingSubscriptionConnection> subscriptionConnections = ConcurrentHashMap.newKeySet();
    private final int subscriptionLifetimeMinutes = 2;

    // constructor

    public void subscribe(Collection<FolderId> folderIds, EventType[] eventTypes, INotificationEventDelegate eventHandler) throws Exception {
        StreamingSubscription subscription = exchangeService.subscribeToStreamingNotifications(folderIds, eventTypes);
        StreamingSubscriptionConnection connection = new StreamingSubscriptionConnection(exchangeService, subscriptionLifetimeMinutes), eventHandler);

        ISubscriptionErrorDelegate disconnectHandler = (sender, args) -> {
            try {
                connection.open(); // connection.getIsOpen() will start returning false now
            } catch (Exception e) {
                // I would expect connection.getIsOpen() will start returning false now
                log.error("Could not reconnect to the exchange server", e);
            }
        };
        connection.addSubscription(subscription);
        connection.addOnNotificationEvent(eventHandler);
        connection.addOnDisconnect(disconnectHandler);
        subscriptionConnections.add(connection);
        connection.open(); // connection.getIsOpen() will return true initially
    }

    // I use this method in a spring boot health check
    public boolean isSubscriptionsOpen() {
        return subscriptionConnections.stream().allMatch(connection -> {
            try {
                return connection.getIsOpen();
            } catch (Exception e) {
                log.error("Error validating subscription connection", e);
                return false;
            }
        });
    }
}