/*
 * $RCSfile: NotificationServiceUtil.java,v $
 * $Date: 2006/01/26 14:48:59 $
 * $Revision: 1.1.2.1 $
 * $Author: andreys $
 */
 
/*
 * Copyright (c) 2002-2003 IST-2004-2006-511731 ModelWare - ModelBus.
 * All rights reserved.
 *
 * This software is published under the terms of the ModelBus Software License
 * in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
 * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * A copy of ModelBus Software License is provided with this distribution in
 * doc/LICENSE.txt file.
 */
 
/*
 * NotificationServiceUtil.java 
 * 
 * @author Prawee Sriplakich (LIP6)
 * @version $Revision: 1.1.2.1 $ $Date: 2006/01/26 14:48:59 $
 */
package org.eclipse.mddi.modelbus.adapter.infrastructure.notification;

import java.net.URL;

import javax.xml.soap.SOAPBody;

import org.activemq.ws.xmlbeans.notification.base.NotifyDocument;
import org.apache.axis.message.MessageElement;
import org.apache.axis.message.Text;
import org.apache.axis.types.URI;
import org.oasis_open.docs.wsn._2004._06.wsn_WS_BaseNotification_1_2_draft_01_xsd.NotificationMessageHolderType;
import org.oasis_open.docs.wsn._2004._06.wsn_WS_BaseNotification_1_2_draft_01_xsd.Notify;
import org.oasis_open.docs.wsn._2004._06.wsn_WS_BaseNotification_1_2_draft_01_xsd.Subscribe;
import org.oasis_open.docs.wsn._2004._06.wsn_WS_BaseNotification_1_2_draft_01_xsd.SubscribeResponse;
import org.oasis_open.docs.wsn._2004._06.wsn_WS_BaseNotification_1_2_draft_01_xsd.TopicExpressionType;
import org.oasis_open.docs.wsn._2004._06.wsn_WS_BrokeredNotification_1_2_draft_01_wsdl.NotificationBroker;
import org.oasis_open.docs.wsn._2004._06.wsn_WS_BrokeredNotification_1_2_draft_01_wsdl.NotificationBrokerServiceLocator;
import org.xmlsoap.schemas.ws._2003._03.addressing.AttributedURI;
import org.xmlsoap.schemas.ws._2003._03.addressing.EndpointReferenceType;



/**
 * Provides the low-level mechanism for interacting with Notification Service
 * 
 * @author P. Sriplakich
 *
 *
 */
public class NotificationServiceUtil {
    private static void subscribeTopic(String notificationBrokerEndpoint, 
            String notificationConsumerEndpoint, 
            String topic)throws NotifServiceNotAvailableException {
            try {
                NotificationBroker broker = new NotificationBrokerServiceLocator().getWsbnwNotificationBroker(new URL(notificationBrokerEndpoint)) ;
            	EndpointReferenceType endpoint = new EndpointReferenceType() ;
            	endpoint.setAddress(new AttributedURI(notificationConsumerEndpoint)) ;
            	
            	Subscribe subscribeData = new Subscribe() ;
            	subscribeData.setConsumerReference(endpoint) ;
            	MessageElement[] elements = new MessageElement[1];
            	elements[0] = new MessageElement(new Text(topic));
            	
            	TopicExpressionType topicExpressionType = new TopicExpressionType(
            	        elements, 
            	        new URI("http://www.ibm.com/xmlns/stdwip/web-services/WSTopics/TopicExpression/simple")) ;
            	
            	subscribeData.setTopicExpression(topicExpressionType) ;
            	
            	SubscribeResponse r = broker.subscribe(subscribeData) ;        

              } catch(Exception e) {
                  throw new NotifServiceNotAvailableException(e.toString(), e);
              }		
            
        }

    public static void subscribe(String notificationBrokerEndpoint, 
            String notificationConsumerEndpoint, 
            String[] topics) throws NotifServiceNotAvailableException {
    	for(int i=0; i<topics.length; i++) {
    	    subscribeTopic(notificationBrokerEndpoint, 
    	            notificationConsumerEndpoint, topics[i]) ;
    	}
    }
    
    
    public static void unsubscribe() {
        //TODO what are the parameters of the unsubscribe operation??
    } 
    

    public static void publish(String notificationBrokerEndpoint, String topicExpression,  String message) {
        try {
          // create a notify element
    	  MessageElement element = new MessageElement(new Text(topicExpression)) ;
    	  TopicExpressionType topicExpressionType = new TopicExpressionType(new MessageElement[]{element}, new URI("http://www.ibm.com/xmlns/stdwip/web-services/WSTopics/TopicExpression/simple")) ;
    	  NotificationMessageHolderType notificationMessageHolderType = new NotificationMessageHolderType(topicExpressionType, null, message) ;
    	  Notify notify = new Notify(new NotificationMessageHolderType[] {notificationMessageHolderType}) ;
    
    	  // create the broker client and send the notify message
    	  NotificationBroker broker = new NotificationBrokerServiceLocator().getWsbnwNotificationBroker(new URL(notificationBrokerEndpoint)) ;
    	  broker.notify(notify) ;
        } catch(Exception e) {
            throw new RuntimeException(e);
        }
    }


        
        
        /**
         * Extracts notifications from a SOAP body
         * 
         * @param body the notifications encoded as SOAP body
         * @return
         * 
         */
        public static SerializedNotification[] extractNotifications(SOAPBody body) {
            
//         The notification looks like this.
//             <Notify xmlns="http://docs.oasis-open.org/wsn/2004/06/wsn-WS-BaseNotification-1.2-draft-01.xsd">
//             <NotificationMessage>
//             <Topic Dialect="http://www.ibm.com/xmlns/stdwip/web-services/WSTopics/TopicExpression/simple">mytopic</Topic>
//             <Message xsi:type="xsd:string">message!!</Message>
//             </NotificationMessage>
//             </Notify>
            
            String bodyString = body.getChildNodes().item(0).toString();
            NotifyDocument notifyDocument = null;
            try {
                notifyDocument = NotifyDocument.Factory.parse(bodyString); 
            } catch (Exception e) {
                // should not occur
                throw new RuntimeException(e);
            }

            org.activemq.ws.xmlbeans.notification.base.NotificationMessageHolderType[] notificationMessages = notifyDocument.getNotify().getNotificationMessageArray();
            SerializedNotification[] results = new SerializedNotification[notificationMessages.length];
            for(int i=0; i<notificationMessages.length; i++) {
               results[i] = new SerializedNotification();
               results[i].message = notificationMessages[i].getMessage().getDomNode().getFirstChild().getNodeValue();  
               results[i].topic = notificationMessages[i].getTopic().getDomNode().getFirstChild().getNodeValue();
            }
            return results;
        }
            

}
