Árvore de páginas

Versões comparadas

Chave

  • Esta linha foi adicionada.
  • Esta linha foi removida.
  • A formatação mudou.
Nota

Disponível a partir da versão 1.24.0 3 do Fluig

Índice

Índice

Objetivo

...

  1. Baixar o projeto: Clique aqui (projeto "alert-sender-sample").Criar uma nova fila no JBoss do Fluig com o nome "AlertSenderSampleQueue". Dentro da sessão "<jms-destinations>", adicionar o seguinte código:
    <jms-queue name="AlertSenderSampleQueue">
        <entry name="AlertSenderSampleQueue"/>
        <entry name="java:global/AlertSenderSampleQueue"/>
        <entry name="java:jboss/exported/AlertSenderSampleQueue"/>
        <durable>true</durable> </jms-queue>
  2. Compilar o projeto (é um projeto padrão maven, para compilar, executar "mvn clean install" na raíz do projeto)
  3. Fazer deploy do arquivo "/alert-sender-sample-server/target/alert-sender-sample-server.ear" em um servidor com o Fluig instalado
  4. Acessar o Fluig e gerar eventos que enviem notificações (ex. apoiar um post)

...

Bloco de código
languagejava
package com.fluig;
import java.util.HashMap;
import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.jms.JMSException;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * Registra o aplicatico como listener para os alertas.
 */
@Startup
@Singleton
public class StartupLoader {
	private transient Logger log = LoggerFactory.getLogger(StartupLoader.class);
	/*
	 * Nome da fila que será usada para receber os alertas.
	 */
	private static final String QUEUE = "AlertSenderSampleQueue";
	/**
	 * ID do tenante para o qual será registrado. Quando houver mais de um
	 * tenante, deverá fazer uma chamada para cada tenante.
	 */
	private static final Long TENANT_ID = 10097l;
	@PostConstruct
	private void startup() {
		log.info("Inicializando aplicativo");
		try {
			InitialContext ic = new InitialContext();
			Queue q = (Queue) ic
					.lookup("java:global/TOTVSTechAsyncQueue");
			QueueConnectionFactory factory = (QueueConnectionFactory) ic
					.lookup("java:global/FluigRemoteXAConnectionFactory");
			QueueConnection connection = factory.createQueueConnection();
			QueueSession session = null;
			QueueSender sender = null;
			try {
				session = connection.createQueueSession(false,
						javax.jms.Session.AUTO_ACKNOWLEDGE);
				sender = session.createSender(q);
				HashMap<String, Object> values = new HashMap<String, Object>();
				// Código do aplicativo.
				values.put("applicationKey", "alert.app.sender.sample");
				// Chave da descrição do aplicativo.
				values.put("descriptionKey",
						"alert.app.sender.sample.description");
				// Nome da fila criada no JBoss para receber os alertas.
				values.put("queueName", QUEUE);
				// ID do tenante.
				values.put("tenantId", TENANT_ID);
				ObjectMessage msg = session.createObjectMessage();
				msg.setObject(values);
				msg.setStringProperty("action", "registerAlertAppSender");
				sender.send(msg);
				log.info("Inicialização do aplicativo OK");
			} finally {
				if (sender != null) {
					sender.close();
				}
				if (session != null) {
					session.close();
				}
				if (connection != null) {
					connection.close();
				}
			}
		} catch (NamingException ex) {
			log.error("Nao foi possivel registrar o serviço de notificação via whatsapp");
			ex.printStackTrace();
		} catch (JMSException ex) {
			log.error("Nao foi possivel registrar o serviço de notificação via whatsapp");
			ex.printStackTrace();
		}
	}
}

...

  1. applicationKey: É uma string que será o identificador único para o aplicativo. Através desta string a Central de Notificações fará todo o gerenciamento do aplicativo.
  2. descriptionKey: É a descrição do aplicativo. Pode ser um texto plano ou uma chave para tradução (ex: app.my.application). Para que seja feita a tradução, a chave deve estar previamente cadastrada no módulo I18n, no bundle "foundation_alert". Caso seja inserido um texto plano, este será exibido sem tradução.
  3. queueName: É o nome da fila JMS que a Central de Notificações utilizará para fazer postar a notificação para envio. Deve ser criada uma fila para cada aplicativo.
  4. tenantId: O id do tenant onde o aplicativo será instalado.

...

Bloco de código
languagejava
package com.fluig;
import java.io.Serializable;
import java.util.Map;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.EJB;
import javax.ejb.MessageDriven;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * Esta é a classe que será chamada pela Central de Notificações para enviar
 * alertas por este aplicativo.
 */
@MessageDriven(name = "queuetopic/AlertSenderSampleQueueFluigNotificationTopic", mappedName = "AlertSenderSampleQueueFluigNotificationTopic", activationConfig = {
		@ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"),
		@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.QueueTopic"),
		@ActivationConfigProperty(propertyName = "destination", propertyValue = "AlertSenderSampleQueueFluigNotificationTopic")
})
public class AlertSampleMDBBean implements MessageListener {
	private static final Logger log = LoggerFactory
			.getLogger(AlertSampleMDBBean.class);
	@EJB(lookup = TxtSenderService.JNDI_REMOTE_NAME)
	private TxtSenderService service;
	@Override
	@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
	public void onMessage(final Message message) {
		if (message instanceof ObjectMessage) {
			final ObjectMessage msg = (ObjectMessage) message;
			try {
				final Serializable obj = msg.getObject();
				if (log.isDebugEnabled()) {
					log.debug("AlertSenderSampleQueue.onMessage - obj: " + obj);
				}
				service.sendAlert((Map<String, Object>) obj);
				if (log.isDebugEnabled()) {
					log.debug("AlertSenderSampleQueue.onMessage - FIM");
				}
			} catch (final JMSException ex) {
				log.error(ex.getMessage(), ex);
			}
		}
	}
}

...