WS-Notification 샘플 훑어보기

이벤트 소스 예제 EventSource.java는 단일, 하드 코딩된 이벤트를 Web Services로 전송하는 단일 이벤트 소스입니다. 이벤트 소스가 따라야 할 다음 단계에 대해 설명합니다.

  1. 이벤트 팩토리 획득
  2. 이벤트 작성 및 필수 데이터로 채우기
  3. 이벤트를 전송하기 위해 생성된 Web Services 클라이언트 측면 스텁 사용

EventSource.java용 소스 코드는 SDK의 <sdk_install_dir>/samples/wsnt-was/src/com/wtci/samples/was/source 디렉토리에 있습니다.

이 예제에서는 Hyades 로깅 클래스 및 wsdl 파일에서 생성된 클래스도 사용합니다. 필수 패키지에 액세스하려면 다음 반입 명령문을 사용하십시오.

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;

EventSource.java의 기본 메소드는 기본 생성자를 사용하여 EventSource의 인스턴스를 작성합니다. 그런 다음, 기본 프로그램 로직이 있는 개인용 sendEvent 메소드를 호출합니다. sendEvent 메소드가 리턴된 후 main() 메소드로 "통지 전송" 메시지를 표준 출력에 인쇄합니다.

    /**
     * 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();
        }
    }

이벤트 작성 및 채우기

EventSource.java의 createEvent() 메소드는 이벤트를 작성하고 이벤트를 최소의 특성 데이터로 채우는 데 사용되는 도움말 메소드입니다. sendEvent 메소드에서 이 메소드를 호출하여 Web Services로 전송될 이벤트를 작성합니다.

    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;
    }

createEvent 메소드는 다음 단계를 수행합니다.

  1. 새 EventFactory 오브젝트를 작성하기 위해 EventFactoryFactory의 createEventFactory() 메소드를 사용합니다.
  2. 새 오브젝트(CommonBaseEvent의 인스턴스)를 작성하기 위해 이벤트 팩토리의 createCommonBaseEvent(String) 메소드를 사용합니다. 지정 문자열("EVENT")을 사용하여 이벤트의 extensionName 특성을 설정하고, 현재 시스템 시간을 사용하여 creationTime 특성을 설정합니다.
  3. 이벤트의 situation 특성 값을 설정합니다. situation이 복합 특성이기 때문에 특수 Java 클래스에 의해 표시됩니다. 따라서 situation 특성을 설정하려면 다음과 같은 여러 개별 단계가 필요합니다.
    1. 새 Situation 오브젝트 작성
    2. setter 메소드를 사용하여 필수 특성 데이터로 Situation 오브젝트 채우기
    3. 채워진 Situation 오브젝트를 지정하는 Event.setSituation() 메소드를 호출하여 이벤트의 situation 특성 설정
  4. 필수 또는 선택적인 여러 기타 이벤트 특성 값을 설정합니다. 이 특성에는 severity, msg, versionsourceComponentId가 있습니다.
    주: situation와 같이, sourceComponentId도 집합 특성입니다. 그러나 하위 특성은 모두 문자열로 표시된 단순 속성으로 특수 Java 오브젝트를 개별적으로 인스턴스화하는 대신 setSourceComponentId() 도움말 메소드를 사용할 수 있습니다.

    예제(version, severity, msg)에서 설정된 기타 특성은 모두 문자열 또는 정수로 표시되는 단순 특성입니다.

  5. 마지막으로 createEvent() 메소드는 특성 데이터로 현재 채워진 이벤트를 리턴합니다.

통지 메시지 작성

이벤트 소스 예제의 다음 메소드 createNotificationMessage(event)는 메소드에 매개변수로서 전달된 이벤트를 캡슐화하는 통지 메시지를 작성하는 데 사용되는 도움말 메소드입니다. sendEvent 메소드에서 이 메소드를 호출하여 Web Services로 전송될 통지 메시지를 작성합니다.

    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)는 다음 단계를 수행합니다.

  1. 전송할 통지의 정보가 포함된 NotificationMessageHolderType 오브젝트를 작성합니다.
  2. 통지의 주제 요소는 '주제' 이름으로 작성됩니다. 중첩된 하위 요소가 추가되어 통지가 수신되었을 때 전체 주제 요소가 표시됩니다.
  3. 통지 메시지는 메소드에 전달되는 이벤트로 설정됩니다.
  4. 이벤트의 제작자에 관한 정보는 통지에 설정됩니다.
  5. 통지 메시지는 이와 같이 작성되고 정보로 채워져서 호출자에게 리턴됩니다.

이벤트 전송

이벤트 소스의 마지막 메소드 예제인 sendEvent()에는 기본 프로그램 로직이 포함됩니다. 이 메소드는 이벤트 전송을 비롯한 NotificationConsumer 클라이언트와의 모든 상호 작용을 처리합니다.

    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);

    }

sendEvent() 메소드는 다음 단계를 수행합니다.

  1. 새 이벤트를 작성 및 채우기 위해 createEvent() 도움말 메소드를 호출합니다.
  2. 작성된 이벤트를 캡슐화하는 통지 메시지를 작성하기 위해 createNotificationMessage(event) 도움말 메소드를 호출합니다.
  3. 시스템 특성으로부터 통지 요청을 서비스하는 NotificationConsumer Web Services를 가져옵니다.
  4. NotificationConsumerServiceLocator를 인스턴스화한 다음 이를 사용하여 NotificationConsumer 오브젝트를 가져옵니다.
  5. NotificationConsumer의 notify() 메소드를 호출하여 이벤트를 전송합니다. 그러면 이벤트를 캡슐화하는 SOAP 메시지가 생성됩니다.


관련 항목
샘플 빌드
샘플 실행


관련 개념
Common Base Event 형식의 이벤트를 Enterprise Console 이벤트 형식으로 변환