Search in sources :

Example 1 with Message

use of org.cometd.bayeux.Message in project camel by apache.

the class SubscriptionHelper method subscribe.

public void subscribe(final String topicName, final SalesforceConsumer consumer) {
    // create subscription for consumer
    final String channelName = getChannelName(topicName);
    setupReplay((SalesforceEndpoint) consumer.getEndpoint());
    // channel message listener
    LOG.info("Subscribing to channel {}...", channelName);
    final ClientSessionChannel.MessageListener listener = new ClientSessionChannel.MessageListener() {

        @Override
        public void onMessage(ClientSessionChannel channel, Message message) {
            LOG.debug("Received Message: {}", message);
            // convert CometD message to Camel Message
            consumer.processMessage(channel, message);
        }
    };
    final ClientSessionChannel clientChannel = client.getChannel(channelName);
    // listener for subscription
    final ClientSessionChannel.MessageListener subscriptionListener = new ClientSessionChannel.MessageListener() {

        public void onMessage(ClientSessionChannel channel, Message message) {
            LOG.debug("[CHANNEL:META_SUBSCRIBE]: {}", message);
            final String subscribedChannelName = message.get(SUBSCRIPTION_FIELD).toString();
            if (channelName.equals(subscribedChannelName)) {
                if (!message.isSuccessful()) {
                    String error = (String) message.get(ERROR_FIELD);
                    if (error == null) {
                        error = "Missing error message";
                    }
                    Exception failure = getFailure(message);
                    String msg = String.format("Error subscribing to %s: %s", topicName, failure != null ? failure.getMessage() : error);
                    consumer.handleException(msg, new SalesforceException(msg, failure));
                } else {
                    // remember subscription
                    LOG.info("Subscribed to channel {}", subscribedChannelName);
                    listenerMap.put(consumer, listener);
                }
                // remove this subscription listener
                client.getChannel(META_SUBSCRIBE).removeListener(this);
            }
        }
    };
    client.getChannel(META_SUBSCRIBE).addListener(subscriptionListener);
    // subscribe asynchronously
    clientChannel.subscribe(listener);
}
Also used : SalesforceException(org.apache.camel.component.salesforce.api.SalesforceException) Message(org.cometd.bayeux.Message) ClientSessionChannel(org.cometd.bayeux.client.ClientSessionChannel) CamelException(org.apache.camel.CamelException) SalesforceException(org.apache.camel.component.salesforce.api.SalesforceException)

Example 2 with Message

use of org.cometd.bayeux.Message in project ddf by codice.

the class NotificationControllerTest method verifyGetPersistedNotificationsWithMessageData.

private void verifyGetPersistedNotificationsWithMessageData(Map<String, Object> messageData, boolean notificationPublished) {
    Message message = new HashMapMessage();
    message.put(Message.DATA_FIELD, messageData);
    List<Map<String, Object>> notifications = new ArrayList<>();
    notifications.add(testEventProperties);
    NotificationController spyNotificationController = spy(notificationController);
    doReturn(notifications).when(spyNotificationController).getNotificationsForUser(anyString());
    // Don't want queuePersistedMessages to start up a new thread.
    doNothing().when(spyNotificationController).queuePersistedMessages(any(ServerSession.class), Matchers.<List<Map<String, Object>>>any(), anyString());
    spyNotificationController.getPersistedNotifications(mockServerSession, message);
    if (notificationPublished) {
        ArgumentCaptor<Event> eventArgumentCaptor = ArgumentCaptor.forClass(Event.class);
        verify(spyNotificationController.eventAdmin, times(1)).postEvent(eventArgumentCaptor.capture());
        Event event = eventArgumentCaptor.getValue();
        assertThat(event.getProperty(Notification.NOTIFICATION_KEY_APPLICATION), is(MOCK_APPLICATION));
        assertThat(event.getProperty(Notification.NOTIFICATION_KEY_MESSAGE), is(MOCK_MESSAGE));
        assertThat(event.getProperty(Notification.NOTIFICATION_KEY_TIMESTAMP), is(ISODateTimeFormat.dateTime().print(MOCK_TIMESTAMP)));
        assertThat(event.getProperty(Notification.NOTIFICATION_KEY_TITLE), is(MOCK_TITLE));
        assertThat(event.getProperty(Notification.NOTIFICATION_KEY_SESSION_ID), is(MOCK_SESSION_ID));
        assertThat(event.getProperty(Notification.NOTIFICATION_KEY_USER_ID), is(MOCK_SESSION_ID));
    } else {
        verify(spyNotificationController, times(1)).queuePersistedMessages(eq(mockServerSession), eq(notifications), startsWith(EXPECTED_COMETD_NOTIFICATIONS_CHANNEL_PREFIX));
    }
}
Also used : HashMapMessage(org.cometd.common.HashMapMessage) ServerSession(org.cometd.bayeux.server.ServerSession) ServerMessage(org.cometd.bayeux.server.ServerMessage) HashMapMessage(org.cometd.common.HashMapMessage) Message(org.cometd.bayeux.Message) ArrayList(java.util.ArrayList) Event(org.osgi.service.event.Event) HashMap(java.util.HashMap) Map(java.util.Map)

Example 3 with Message

use of org.cometd.bayeux.Message in project camel by apache.

the class SubscriptionHelper method unsubscribe.

public void unsubscribe(String topicName, SalesforceConsumer consumer) throws CamelException {
    // channel name
    final String channelName = getChannelName(topicName);
    // listen for unsubscribe error
    final CountDownLatch latch = new CountDownLatch(1);
    final String[] unsubscribeError = { null };
    final Exception[] unsubscribeFailure = { null };
    final ClientSessionChannel.MessageListener unsubscribeListener = new ClientSessionChannel.MessageListener() {

        public void onMessage(ClientSessionChannel channel, Message message) {
            LOG.debug("[CHANNEL:META_UNSUBSCRIBE]: {}", message);
            Object subscription = message.get(SUBSCRIPTION_FIELD);
            if (subscription != null) {
                String unsubscribedChannelName = subscription.toString();
                if (channelName.equals(unsubscribedChannelName)) {
                    if (!message.isSuccessful()) {
                        unsubscribeError[0] = (String) message.get(ERROR_FIELD);
                        unsubscribeFailure[0] = getFailure(message);
                    } else {
                        // forget subscription
                        LOG.info("Unsubscribed from channel {}", unsubscribedChannelName);
                    }
                    latch.countDown();
                }
            }
        }
    };
    client.getChannel(META_UNSUBSCRIBE).addListener(unsubscribeListener);
    try {
        // unsubscribe from channel
        final ClientSessionChannel.MessageListener listener = listenerMap.remove(consumer);
        if (listener != null) {
            LOG.info("Unsubscribing from channel {}...", channelName);
            final ClientSessionChannel clientChannel = client.getChannel(channelName);
            clientChannel.unsubscribe(listener);
            // confirm unsubscribe
            try {
                if (!latch.await(CHANNEL_TIMEOUT, SECONDS)) {
                    String message;
                    if (unsubscribeFailure[0] != null) {
                        message = String.format("Error unsubscribing from topic %s: %s", topicName, unsubscribeFailure[0].getMessage());
                    } else if (unsubscribeError[0] != null) {
                        message = String.format("Error unsubscribing from topic %s: %s", topicName, unsubscribeError[0]);
                    } else {
                        message = String.format("Timeout error unsubscribing from topic %s after %s seconds", topicName, CHANNEL_TIMEOUT);
                    }
                    throw new CamelException(message, unsubscribeFailure[0]);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            // probably shutting down, forget unsubscribe and return
            }
        }
    } finally {
        client.getChannel(META_UNSUBSCRIBE).removeListener(unsubscribeListener);
    }
}
Also used : Message(org.cometd.bayeux.Message) CamelException(org.apache.camel.CamelException) CountDownLatch(java.util.concurrent.CountDownLatch) ClientSessionChannel(org.cometd.bayeux.client.ClientSessionChannel) CamelException(org.apache.camel.CamelException) SalesforceException(org.apache.camel.component.salesforce.api.SalesforceException)

Example 4 with Message

use of org.cometd.bayeux.Message in project camel by apache.

the class SubscriptionHelper method doStart.

@Override
protected void doStart() throws Exception {
    // create CometD client
    this.client = createClient(component);
    // reset all error conditions
    handshakeError = null;
    handshakeException = null;
    connectError = null;
    connectException = null;
    // listener for handshake error or exception
    if (handshakeListener == null) {
        // first start
        handshakeListener = new ClientSessionChannel.MessageListener() {

            public void onMessage(ClientSessionChannel channel, Message message) {
                LOG.debug("[CHANNEL:META_HANDSHAKE]: {}", message);
                if (!message.isSuccessful()) {
                    LOG.warn("Handshake failure: {}", message);
                    handshakeError = (String) message.get(ERROR_FIELD);
                    handshakeException = getFailure(message);
                    if (handshakeError != null) {
                        // refresh oauth token, if it's a 401 error
                        if (handshakeError.startsWith("401::")) {
                            try {
                                LOG.info("Refreshing OAuth token...");
                                session.login(session.getAccessToken());
                                LOG.info("Refreshed OAuth token for re-handshake");
                            } catch (SalesforceException e) {
                                LOG.error("Error renewing OAuth token on 401 error: " + e.getMessage(), e);
                            }
                        }
                    }
                    // restart if handshake fails for any reason
                    restartClient();
                } else if (!listenerMap.isEmpty()) {
                    reconnecting = true;
                }
            }
        };
    }
    client.getChannel(META_HANDSHAKE).addListener(handshakeListener);
    // listener for connect error
    if (connectListener == null) {
        connectListener = new ClientSessionChannel.MessageListener() {

            public void onMessage(ClientSessionChannel channel, Message message) {
                LOG.debug("[CHANNEL:META_CONNECT]: {}", message);
                if (!message.isSuccessful()) {
                    LOG.warn("Connect failure: {}", message);
                    connectError = (String) message.get(ERROR_FIELD);
                    connectException = getFailure(message);
                } else if (reconnecting) {
                    reconnecting = false;
                    LOG.debug("Refreshing subscriptions to {} channels on reconnect", listenerMap.size());
                    // reconnected to Salesforce, subscribe to existing channels
                    final Map<SalesforceConsumer, ClientSessionChannel.MessageListener> map = new HashMap<SalesforceConsumer, ClientSessionChannel.MessageListener>();
                    map.putAll(listenerMap);
                    listenerMap.clear();
                    for (Map.Entry<SalesforceConsumer, ClientSessionChannel.MessageListener> entry : map.entrySet()) {
                        final SalesforceConsumer consumer = entry.getKey();
                        final String topicName = consumer.getTopicName();
                        subscribe(topicName, consumer);
                    }
                }
            }
        };
    }
    client.getChannel(META_CONNECT).addListener(connectListener);
    // handle fatal disconnects by reconnecting asynchronously
    if (disconnectListener == null) {
        disconnectListener = new ClientSessionChannel.MessageListener() {

            @Override
            public void onMessage(ClientSessionChannel clientSessionChannel, Message message) {
                restartClient();
            }
        };
    }
    client.getChannel(META_DISCONNECT).addListener(disconnectListener);
    // connect to Salesforce cometd endpoint
    client.handshake();
    final long waitMs = MILLISECONDS.convert(CONNECT_TIMEOUT, SECONDS);
    if (!client.waitFor(waitMs, BayeuxClient.State.CONNECTED)) {
        if (handshakeException != null) {
            throw new CamelException(String.format("Exception during HANDSHAKE: %s", handshakeException.getMessage()), handshakeException);
        } else if (handshakeError != null) {
            throw new CamelException(String.format("Error during HANDSHAKE: %s", handshakeError));
        } else if (connectException != null) {
            throw new CamelException(String.format("Exception during CONNECT: %s", connectException.getMessage()), connectException);
        } else if (connectError != null) {
            throw new CamelException(String.format("Error during CONNECT: %s", connectError));
        } else {
            throw new CamelException(String.format("Handshake request timeout after %s seconds", CONNECT_TIMEOUT));
        }
    }
}
Also used : Message(org.cometd.bayeux.Message) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) SalesforceException(org.apache.camel.component.salesforce.api.SalesforceException) SalesforceConsumer(org.apache.camel.component.salesforce.SalesforceConsumer) CamelException(org.apache.camel.CamelException) ClientSessionChannel(org.cometd.bayeux.client.ClientSessionChannel) HashMap(java.util.HashMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Example 5 with Message

use of org.cometd.bayeux.Message in project ddf by codice.

the class ActivityControllerTest method verifyGetPersistedActivitiesWithMessageData.

private void verifyGetPersistedActivitiesWithMessageData(Map<String, Object> messageData, boolean expectPublish) {
    Message message = new HashMapMessage();
    message.put(Message.DATA_FIELD, messageData);
    List<Map<String, Object>> activities = new ArrayList<>();
    activities.add(testEventProperties);
    ActivityController spyActivityController = spy(activityController);
    doReturn(activities).when(spyActivityController).getActivitiesForUser(anyString());
    // Don't want queuePersistedMessages to start up a new thread.
    doNothing().when(spyActivityController).queuePersistedMessages(any(ServerSession.class), Matchers.<List<Map<String, Object>>>any(), anyString());
    spyActivityController.getPersistedActivities(mockServerSession, message);
    if (expectPublish) {
        verify(spyActivityController, times(1)).queuePersistedMessages(eq(mockServerSession), eq(activities), startsWith(EXPECTED_COMETD_ACTIVITIES_CHANNEL_PREFIX));
    } else {
        verify(spyActivityController, never()).queuePersistedMessages(any(ServerSession.class), Matchers.<List<Map<String, Object>>>any(), anyString());
    }
}
Also used : HashMapMessage(org.cometd.common.HashMapMessage) ServerSession(org.cometd.bayeux.server.ServerSession) ServerMessage(org.cometd.bayeux.server.ServerMessage) HashMapMessage(org.cometd.common.HashMapMessage) Message(org.cometd.bayeux.Message) ArrayList(java.util.ArrayList) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

Message (org.cometd.bayeux.Message)5 HashMap (java.util.HashMap)3 Map (java.util.Map)3 CamelException (org.apache.camel.CamelException)3 SalesforceException (org.apache.camel.component.salesforce.api.SalesforceException)3 ClientSessionChannel (org.cometd.bayeux.client.ClientSessionChannel)3 ArrayList (java.util.ArrayList)2 ServerMessage (org.cometd.bayeux.server.ServerMessage)2 ServerSession (org.cometd.bayeux.server.ServerSession)2 HashMapMessage (org.cometd.common.HashMapMessage)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1 CountDownLatch (java.util.concurrent.CountDownLatch)1 SalesforceConsumer (org.apache.camel.component.salesforce.SalesforceConsumer)1 Event (org.osgi.service.event.Event)1