La fuente de evento de ejemplo, EventSource.java, es una fuente de evento sencilla que envía un único evento codificado internamente a los servicios web. Este ejemplo sirve para mostrar los pasos siguientes, que son los que debe seguir una fuente de eventos:
El código fuente de EventSource.java está disponible en el directorio
<dir_instal_sdk>/samples/wsnt-was/src/com/wtci/samples/was/source
del SDK.
Este ejemplo utiliza clases de registro cronológico Hyades, así como 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.waswsn10.emitter.NotificationConsumerService; import com.ibm.wtci.samples.waswsn10.emitter.NotificationConsumerServiceLocator; import com.ibm.wtci.samples.waswsn10.wsn.NotificationConsumer; import com.ibm.wtci.samples.waswsn10.wsn.NotificationMessageHolderType; import com.ibm.ws.webservices.engine.xmlsoap.SOAPElement; import com.ibm.ws.webservices.engine.xmlsoap.SOAPFactory; 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;
El método main
de EventSource.java crea una instancia nueva
de EventSource, 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 la 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(); } }
El método createEvent() de EventSource.java es un método helper 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 createEvent
ejecuta los pasos siguientes:
Las propiedades restantes establecidas por el ejemplo (version, severity y msg) son todas propiedades simples representadas por cadenas o enteros.
El siguiente método del ejemplo de fuente de eventos, createNotificationMessage(event), es un método helper 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 the name 'Topic' SOAPFactory soapFactory = new SOAPFactory(); SOAPElement topicSE = (SOAPElement) soapFactory.createElement("Topic"); SOAPElement topicSEChild = (SOAPElement) topicSE.addChildElement("Topic"); topicSEChild.setAttribute("dialect","none"); notificationArray[i].setTopic(topicSE); //Setting the event to be the message of the notification SOAPElement messageSE = (SOAPElement) soapFactory.createElement("Message"); messageSE.addNamespaceDeclaration("ns2", "http://www.ibm.com/AC/commonbaseevent1_0_1"); messageSE.addAttribute("http://www.w3.org/2001/XMLSchema-instance", "type", "ns2:CommonBaseEvent"); String cbeStr = EventFormatter.toCanonicalXMLString(events[i]); SOAPElement cbeSE = (SOAPElement) soapFactory.createElementFromXMLString(cbeStr); messageSE.addChildElement(cbeSE); notificationArray[i].setMessage(messageSE); //Setting information about the producer of the event in //the notification SOAPElement producerSE = (SOAPElement) soapFactory.createElement("ProducerReference"); SOAPElement producerSEChild = (SOAPElement) soapFactory.createElement("Address", "ns1", "http://schemas.xmlsoap.org/ws/2003/03/addressing"); producerSEChild.addTextNode("protocol://your.event.source.address"); producerSE.addChildElement(producerSEChild); notificationArray[i].setProducerReference(producerSE); } return notificationArray; }
createNotificationMessage(event) ejecuta los pasos siguientes:
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[] notification = createNotificationMessage(events); //Obtaining the address of the NotificationConsumerService webservice 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 9080 for was endpoint = "http://localhost:9080/wsnt-was/services/NotificationConsumer10Soap"; } //Creating an URL object for the address obtained java.net.URL serviceURL = new URL(endpoint); //Creating an instance of NotificationConsumerServiceLocator NotificationConsumerService notifierSvc = new NotificationConsumerServiceLocator(); NotificationConsumer notifier = notifierSvc.getNotificationConsumer10Soap(serviceURL); //Sending the notification notifier.notify(notification); }
El método sendEvent() ejecuta los pasos siguientes:
Temas relacionados
Creación de los ejemplos
Ejecución de los ejemplos
Conceptos relacionados
Conversión de un evento con el formato de
Common Base Event al formato de evento de Enterprise Console