Ejemplo guiado de notificación WS

El ejemplo de fuente de eventos es un código de ejemplo de un productor de notificaciones WS 1.0. Utiliza las bibliotecas de los proyectos de fuente abierto de Apache Axis y Eclipse TPTP.

Este ejemplo sirve para mostrar los pasos siguientes, que son los que debe seguir una fuente de eventos:

  1. Obtención de una fábrica de eventos
  2. Creación y cumplimentación de un evento con los datos necesarios
  3. Utilización de los archivos apéndice de cliente de servicios web generados, para enviar un evento

El código fuente de EventSourceWsn10.java está disponible en el directorio <dir_instal_sdk>/samples/wsnt-axis/src/com/wtci/samples/axis/source.

Este ejemplo utiliza diversas clases de Apache Axis, clases de registro cronológico Hyades y las clases generadas a partir de los archivos wsdl. Utilice las siguientes sentencias de importación para acceder a los paquetes necesarios:

import com.ibm.wtci.samples.axiswsn10.wsa.AttributedURI; import
com.ibm.wtci.samples.axiswsn10.wsa.EndpointReferenceType; import
com.ibm.wtci.samples.axiswsn10.wsn.NotificationConsumer; import
com.ibm.wtci.samples.axiswsn10.wsn.NotificationConsumerService; import
com.ibm.wtci.samples.axiswsn10.wsn.NotificationConsumerServiceLocator; import
com.ibm.wtci.samples.axiswsn10.wsn.NotificationMessageHolderType; import
com.ibm.wtci.samples.axiswsn10.wsn.TopicExpressionType;
import org.apache.axis.encoding.TypeMapping;
import org.apache.axis.encoding.TypeMappingRegistry;
import org.apache.axis.message.MessageElement;
import org.apache.axis.types.URI;
import org.eclipse.hyades.logging.events.cbe.CommonBaseEvent;
import org.eclipse.hyades.logging.events.cbe.EventFactory;
import org.eclipse.hyades.logging.events.cbe.EventFactoryFactory;
import org.eclipse.hyades.logging.events.cbe.Situation;
import org.eclipse.hyades.logging.events.cbe.util.EventFormatter;

import java.net.URL;
import javax.xml.namespace.QName;

El método main de EventSourceWsn10.java crea una instancia nueva de EventSourceWsn10, mediante el constructor predeterminado. A continuación, llama al método sendEvent() privado, que contiene la lógica del programa principal. Cuando el método sendEvent() regresa, el método main() imprime el mensaje "Notification sent" en salida estándar.

    /**
     * Main method for the event source.
     * 
     * @param args
     *            arguments passed from the command line
     */
    public static void main(String args[]) {
        EventSourceWsn10 source = new EventSourceWsn10();
        try {
            source.sendEvent();
            System.out.println("Notification sent");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Creación y cumplimentación del evento

El método createEvents de EventSourceWsn10.java es un método de ayuda utilizado para crear un evento y cumplimentarlo con un conjunto mínimo de datos de propiedades. A este método lo llama el método sendEvent para crear el evento que se enviará a los servicios web.

    public static CommonBaseEvent[] createEvents() throws Exception {
        CommonBaseEvent[] events = null;

        String cbeFile = System.getProperty("cbe.file");
        if (cbeFile != null) {
            events = EventFormatter.eventsFromCanonicalXMLDoc(cbeFile);
        } else {
            // The first step is accessing the event factory
            EventFactory eventFactory = 
                EventFactoryFactory.createEventFactory();

            // Creating an event with an extension name.
            CommonBaseEvent event = 
                eventFactory.createCommonBaseEvent("EVENT");
            event.setCreationTimeAsLong(System.currentTimeMillis());

            // Setting the mandatory situation description for the event.
            Situation situation = eventFactory.createSituation();
            situation.setCategoryName(Situation.REPORT_SITUATION_CATEGORY);
            situation.setReportSituation("INTERNAL", "Succeeded");
            event.setSituation(situation);

            // Setting the mandatory component identification for the
            // event source
            event.setSourceComponentId("Event Source",
                "source.EventSource",
                "createEvent()",
                "http://www.ibm.com/namespaces/autonomic/Tivoli/Samples",
                "Sample",
                "unknown",
                "hostname");

            // Setting Common Base Event version
            event.setVersion("1.0.1");
            // Setting optional fields
            event.setSeverity((short) 10);
            event.setMsg("Common Event Infrastructure Tutorial");
            
            events = new CommonBaseEvent[] { event };
        }

        return events;
    }

El método createEvents ejecuta los pasos siguientes:

  1. Utiliza el método createEventFactory() de EventFactoryFactory para crear un objeto EventFactory nuevo.
  2. Utiliza el método createCommonBaseEvent(String) de la fábrica de eventos para crear un objeto de evento nuevo (una instancia de CommonBaseEvent). La cadena especificada ("EVENT") se utiliza para establecer la propiedad extensionName del evento y la hora actual del sistema se utiliza para establecer la propiedad creationTime.
  3. Establece el valor de la propiedad situation del evento. Dado que situation es una propiedad compleja, se representa mediante una clase Java especializada. Por consiguiente, para establecer la propiedad situation, es preciso ejecutar varios pasos diferentes:
    1. Crear un objeto de situación nuevo
    2. Utilizar métodos setter para cumplimentar el objeto de situación con los datos de propiedad necesarios
    3. Establecer la propiedad situation del evento llamando al método Event.setSituation() y especificando el objeto de situación cumplimentado
  4. Establece los valores de varias propiedades de eventos más, algunas de ellas necesarias y otras opcionales. Dichas propiedades son severity, msg, version y sourceComponentId.

    Nota:

    al igual que ocurre con situation, sourceComponentId es también una propiedad compleja. No obstante, sus propiedades secundarias son todas atributos simples representados por cadenas, por lo que puede utilizar el método de ayuda setSourceComponentId(), en vez de crear instancias por separado de un objeto Java especializado.

    Las propiedades restantes establecidas por el ejemplo (version, severity y msg) son todas propiedades simples representadas por cadenas o enteros.

  5. Por último, el método createEvents devuelve el evento, que ahora está cumplimentado con los datos de propiedades.

Creación del mensaje de notificación

El siguiente método del ejemplo de fuente de evento createNotificationMessage(event), es un método de ayuda utilizado para crear el mensaje de notificación que encapsula el evento que se ha pasado como un parámetro al método. A este método lo llama el método sendEvent para crear el mensaje de notificación que se enviará a los servicios web.

    public static NotificationMessageHolderType[] createNotificationMessage(
            CommonBaseEvent events[]) throws Exception {
        NotificationMessageHolderType[] notificationArray = 
            new NotificationMessageHolderType[events.length];
        for (int i = 0; i < events.length; i++) {

            //Creating an instance of NotificationMessageHolderType
            notificationArray[i] = new NotificationMessageHolderType();

            //Creating a Topic element with name 'Topic' and value of
            //dialect attribute as 'tec'
            MessageElement[] msgTopic = new MessageElement[1];
            msgTopic[0] = new MessageElement();
            msgTopic[0].setName("Topic");
            msgTopic[0].setAttribute("dialect", "none");
            TopicExpressionType topicExpType = new TopicExpressionType();
            topicExpType.set_any(msgTopic);

            //Setting the Topic of the notification
            notificationArray[i].setTopic(topicExpType);

            //Setting the event to be the message of the notification
            notificationArray[i].setMessage(events[i]);

            //Setting information about the producer of the event in
            //the notification
            EndpointReferenceType endPointRef = new EndpointReferenceType();
            AttributedURI au = new AttributedURI();
            URI value = new URI("protocol", "your.event.source.address");
            au.set_value(value);
            endPointRef.setAddress(au);
            notificationArray[i].setProducerReference(endPointRef);
        }

        return notificationArray;
    }

createNotificationMessage(event) ejecuta los pasos siguientes:

  1. Crea un objeto NotificationMessageHolderType que contiene la información de la notificación que se enviará.
  2. El elemento Topic de la notificación se crea con el nombre 'Topic' y el valor del atributo de dialecto 'tec'.
  3. Se establece que el mensaje de la notificación será el evento que se ha pasado al método.
  4. La información acerca del productor del evento se establece en la notificación.
  5. El mensaje de notificación creado y cumplimentado con la información de esta manera, se devuelve al interlocutor.

Envío de un evento

El último método del ejemplo de fuente de eventos, sendEvent(), contiene la lógica del programa principal. Este método se encarga de todas las interacciones con el cliente NotificationConsumer, incluido el envío del evento.

    private void sendEvent() throws Exception {
        //The first step is creating an event
        CommonBaseEvent[] events = createEvents();

        //Creating the Notification message encapsulating the event
        NotificationMessageHolderType[] notificationArray = 
            createNotificationMessage(events);

        // Obtaining the address of the NotificationConsumer10Service 
        // Web Services
        String endpoint = System.getProperty("service.address");
        if (endpoint == null) {
            //If no address was specified, the webservice is assumed to be
            // runnning in the localhost at port 8080 for axis
            endpoint = "http://localhost:8080/axis/services/NotificationConsumer10Soap";
        }

        //Creating an URL object for the address obtained
        URL serviceURL = new URL(endpoint);

        //Creating an instance of NotificationConsumerServiceLocator
        NotificationConsumerService notifierSvc = 
            new NotificationConsumerServiceLocator();

        //Using the NotificationConsumerService to obtain
        // NotificationConsumer object for the service
        NotificationConsumer notifier = 
            notifierSvc.getNotificationConsumer10Soap(serviceURL);

        //Registering an instance of CbeSerializer object for serializing
        // objects of
        //type CommonBaseEvent to be sent over the wire
        TypeMappingRegistry reg = (TypeMappingRegistry) 
            notifierSvc.getTypeMappingRegistry();
        TypeMapping tm = (TypeMapping) reg.getTypeMapping(endpoint);
        QName qn = new QName("http://www.ibm.com/AC/commonbaseevent1_0_1",
                "CommonBaseEvent");
        tm.register(CommonBaseEvent.class, qn, 
                    new CbeSerializerFactory(), null);

        //Sending the notification
        notifier.notify(notificationArray);
    }

El método sendEvent() ejecuta los pasos siguientes:

  1. Llama al método de ayuda createEvent() para crear y cumplimentar un evento nuevo.
  2. Llama al método de ayuda createNotificationMessage(event) para crear un mensaje de notificación que encapsule el evento creado.
  3. En la propiedad system, obtiene la dirección de los servicios web NotificationConsumer que se encargan de la petición de notificación.
  4. Crea una instancia de NotificationConsumerServiceLocator que, a continuación, se utiliza para obtener un objeto NotificationConsumer.
  5. La clase de fábrica CbeSerializer se registra como fábrica de serializadores que se utilizarán para serializar objetos de tipo CommonBaseEvent. CbeSerializerFactory devuelve una instancia del objeto CbeSerializer. Este objeto implementa el método de serialización que convierte los objetos CommonBaseEvent al formato xml para enviarse a través de la conexión.
  6. Envía el evento invocando el método notify() de NotificationConsumer. Esto genera un mensaje SOAP que encapsula el evento.


Temas relacionados
Creación de los ejemplos
Ejecución de ejemplos


Conceptos relacionados
Conversión de un evento con el formato de Common Base Event al formato de evento de Enterprise Console