You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@beehive.apache.org by ek...@apache.org on 2005/05/09 22:18:03 UTC

svn commit: r169351 [9/12] - in /incubator/beehive/trunk/system-controls: ./ ant/ external/ external/commons/ external/ejb/ external/jms/ src/ src/ejb/ src/ejb/org/ src/ejb/org/apache/ src/ejb/org/apache/beehive/ src/ejb/org/apache/beehive/controls/ src/ejb/org/apache/beehive/controls/system/ src/ejb/org/apache/beehive/controls/system/ejb/ src/ejb/schema/ src/jdbc/ src/jdbc/org/ src/jdbc/org/apache/ src/jdbc/org/apache/beehive/ src/jdbc/org/apache/beehive/controls/ src/jdbc/org/apache/beehive/controls/system/ src/jdbc/org/apache/beehive/controls/system/jdbc/ src/jdbc/org/apache/beehive/controls/system/jdbc/parser/ src/jms/ src/jms/org/ src/jms/org/apache/ src/jms/org/apache/beehive/ src/jms/org/apache/beehive/controls/ src/jms/org/apache/beehive/controls/system/ src/jms/org/apache/beehive/controls/system/jms/ src/jms/org/apache/beehive/controls/system/jms/impl/ src/jms/org/apache/beehive/controls/system/jndi/ src/jms/org/apache/beehive/controls/system/jndi/impl/ src/webservice/ src/webservice/org/ src/webservice/org/apache/ src/webservice/org/apache/beehive/ src/webservice/org/apache/beehive/controls/ src/webservice/org/apache/beehive/controls/system/ src/webservice/org/apache/beehive/controls/system/webservice/ src/webservice/org/apache/beehive/controls/system/webservice/generator/ src/webservice/org/apache/beehive/controls/system/webservice/jaxrpc/ src/webservice/org/apache/beehive/controls/system/webservice/utils/ test/ test/ant/ test/conf/ test/src/ test/src/jdbc/ test/src/jdbc/controls/ test/src/jdbc/controls/org/ test/src/jdbc/controls/org/apache/ test/src/jdbc/controls/org/apache/beehive/ test/src/jdbc/controls/org/apache/beehive/controls/ test/src/jdbc/controls/org/apache/beehive/controls/system/ test/src/jdbc/controls/org/apache/beehive/controls/system/jdbc/ test/src/jdbc/controls/org/apache/beehive/controls/system/jdbc/test/ test/src/jdbc/controls/org/apache/beehive/controls/system/jdbc/test/dbconnection/ test/src/jdbc/controls/org/apache/beehive/controls/system/jdbc/test/errors/ test/src/jdbc/controls/org/apache/beehive/controls/system/jdbc/test/results/ test/src/jdbc/controls/schemas/ test/src/jdbc/controls/schemas/badusers/ test/src/jdbc/controls/schemas/users/ test/src/jdbc/jdbc-container/ test/src/jdbc/jdbc-container/application/ test/src/jdbc/jdbc-container/src/ test/src/jdbc/jdbc-container/src/org/ test/src/jdbc/jdbc-container/src/org/apache/ test/src/jdbc/jdbc-container/src/org/apache/beehive/ test/src/jdbc/jdbc-container/src/org/apache/beehive/controls/ test/src/jdbc/jdbc-container/src/org/apache/beehive/controls/system/ test/src/jdbc/jdbc-container/src/org/apache/beehive/controls/system/jdbc/ test/src/jdbc/jdbc-container/src/org/apache/beehive/controls/system/jdbc/containertest/ test/src/jdbc/jdbc-container/webapp/ test/src/jdbc/jdbc-container/webapp/WEB-INF/ test/src/jdbc/jdbc-container/webapp/conf/ test/src/jdbc/jdbc-container/webapp/conf/Catalina/ test/src/jdbc/jdbc-container/webapp/conf/Catalina/localhost/ test/src/jdbc/junitTests/ test/src/jdbc/junitTests/org/ test/src/jdbc/junitTests/org/apache/ test/src/jdbc/junitTests/org/apache/beehive/ test/src/jdbc/junitTests/org/apache/beehive/controls/ test/src/jdbc/junitTests/org/apache/beehive/controls/system/ test/src/jdbc/junitTests/org/apache/beehive/controls/system/jdbc/ test/src/jdbc/junitTests/org/apache/beehive/controls/system/jdbc/units/ test/src/jdbc/junitTests/org/apache/beehive/controls/system/jdbc/units/dbconnection/ test/src/jdbc/junitTests/org/apache/beehive/controls/system/jdbc/units/errors/ test/src/jdbc/junitTests/org/apache/beehive/controls/system/jdbc/units/results/ test/src/jdbc/junitTests/org/apache/beehive/controls/system/jdbc/units/sqlparser/ test/src/jdbc/junitTests/org/apache/beehive/controls/system/jdbc/units/utils/

Added: incubator/beehive/trunk/system-controls/src/jms/org/apache/beehive/controls/system/jms/impl/JMSControlImpl.jcs
URL: http://svn.apache.org/viewcvs/incubator/beehive/trunk/system-controls/src/jms/org/apache/beehive/controls/system/jms/impl/JMSControlImpl.jcs?rev=169351&view=auto
==============================================================================
--- incubator/beehive/trunk/system-controls/src/jms/org/apache/beehive/controls/system/jms/impl/JMSControlImpl.jcs (added)
+++ incubator/beehive/trunk/system-controls/src/jms/org/apache/beehive/controls/system/jms/impl/JMSControlImpl.jcs Mon May  9 13:17:58 2005
@@ -0,0 +1,1095 @@
+/*
+ * Copyright 2005 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * $Header:$
+ */
+package org.apache.beehive.controls.system.jms.impl;
+
+import java.io.Serializable;
+import java.lang.reflect.Method;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.HashMap;
+
+import javax.jms.JMSException;
+import javax.jms.MapMessage;
+import javax.jms.MessageProducer;
+import javax.jms.Queue;
+import javax.jms.QueueConnection;
+import javax.jms.QueueConnectionFactory;
+import javax.jms.ConnectionFactory;
+import javax.jms.QueueSender;
+import javax.jms.QueueSession;
+import javax.jms.Session;
+import javax.jms.BytesMessage;
+import javax.jms.TopicConnection;
+import javax.jms.TopicConnectionFactory;
+import javax.jms.Topic;
+import javax.jms.TopicPublisher;
+import javax.jms.TopicSession;
+
+import org.apache.beehive.controls.api.ControlException;
+import org.apache.beehive.controls.api.events.EventHandler;
+import org.apache.beehive.controls.api.context.ControlBeanContext;
+import org.apache.beehive.controls.api.context.Context;
+import org.apache.beehive.controls.api.context.ResourceContext;
+import org.apache.beehive.controls.api.bean.ControlImplementation;
+import org.apache.beehive.controls.api.bean.Extensible;
+import org.apache.beehive.controls.api.bean.Control;
+import org.apache.beehive.controls.system.jms.JMSControl;
+import org.apache.beehive.controls.system.jndi.JndiControlBean;
+import org.apache.xmlbeans.XmlObject;
+
+/**
+ * Implementation of the jms control.
+ */
+@ControlImplementation
+public class JMSControlImpl
+    implements JMSControl, Extensible, java.io.Serializable {
+
+    /**
+     * @see JMSControl.getSession() 
+     */
+    public Session getSession() throws ControlException
+    {
+        if (_session == null)
+        {
+            try
+            {	            
+	            switch(getDestinationType())
+	            {
+	            	case Auto:
+	            		determineDestination();
+	            		return getSession();
+	            	case Topic:
+	            		createTopicSession();
+	            		break;
+	            	case Queue:
+	            		createQueueSession();
+	            		break;
+	            }
+
+            }
+            catch(JMSException e)
+            {
+                throw new ControlException("Failure to get JMS connection or session",e);
+            }
+        }
+        return _session;
+    }
+    
+    /**
+     * Get the jms-destination.
+     * 
+     * @see org.apache.beehive.controls.system.jms.JMSControl#getDestination()
+     */
+    public javax.jms.Destination getDestination() throws ControlException
+    {
+        if (_destination == null)
+        {
+             _destination = (javax.jms.Destination) getJndiControl().getResource(
+                    getDestinationProperties().sendJndiName(), javax.jms.Destination.class);
+
+        }
+        return _destination;
+    }
+    
+    /**
+     * @see JMSControl#getConnection
+     */
+    public javax.jms.Connection getConnection() throws ControlException
+    {
+    	getSession();
+    	return _connection;
+   	}
+   	
+    /**
+     * @see JMSControl#setHeaders
+     */
+    public void setHeaders(Map headers) 
+    {
+    	Map map = new HashMap();
+        Iterator i = headers.keySet().iterator();
+        while (i.hasNext()) 
+        {
+            Object name = i.next();
+            Object value = headers.get(name);
+            HeaderType type = null;
+            /*
+             * Allow for string valued or HeaderType valued
+             * map entries.
+             */
+            if(name instanceof HeaderType)
+            {
+            	type = (HeaderType)type;
+            }
+            else
+            {
+                    if (name.equals(HeaderType.JMSCorrelationID.toString())) 
+        			{
+        				type = HeaderType.JMSCorrelationID;
+			        } 
+			        else if (name.equals(HeaderType.JMSDeliveryMode.toString())) 
+			        {
+        				type = HeaderType.JMSDeliveryMode;
+			        } 
+			        else if (name.equals(HeaderType.JMSExpiration.toString())) 
+			        {
+        				type = HeaderType.JMSExpiration;
+			        } 
+			        else if (name.equals(HeaderType.JMSMessageID.toString())) 
+			        {
+        				type = HeaderType.JMSMessageID;
+			        } 
+			        else if (name.equals(HeaderType.JMSPriority.toString())) 
+			        {
+        				type = HeaderType.JMSPriority;
+			        } 
+			        else if (name.equals(HeaderType.JMSRedelivered.toString())) 
+			        {
+        				type = HeaderType.JMSRedelivered;
+			        } 
+			        else if (name.equals(HeaderType.JMSTimestamp.toString())) 
+			        {
+        				type = HeaderType.JMSTimestamp;
+			        }
+			        else if (name.equals(HeaderType.JMSType.toString())) 
+			        {
+        				type = HeaderType.JMSType;
+			        }
+			        else
+			        {
+			        	throw new IllegalArgumentException("Invalid JMS header type '"+name+"'");
+			        }
+            }
+            map.put(type,value);
+        }
+        Iterator iter = map.keySet().iterator();
+        while(iter.hasNext())
+        {
+            Object key = iter.next();
+            headers.put(key,map.get(key));
+        }
+    }
+    
+    /**
+     * @see JMSControl#setHeader
+     */
+    public void setHeader(JMSControl.HeaderType type,Object value)
+    {
+    	if(_headers == null)
+    	{
+        	_headers = new HashMap<HeaderType,Object>();
+        }
+        _headers.put(type,value);
+    }
+    
+    
+    /**
+     * @see JMSControl#setProperties
+     */
+    public void setProperties(Map properties) 
+    {
+        Iterator<String> i = properties.keySet().iterator();
+        while (i.hasNext()) 
+        {
+            String name = i.next();
+            Object value = properties.get(name);
+            setProperty(name,value);
+		}
+    }
+    /**
+     * @see JMSControl#setProperty
+     */
+    public void setProperty(String name,Object value)
+    {
+    	if(_properties == null)
+    	{
+    		_properties = new HashMap<String,Object>();
+    	}
+    	_properties.put(name,value);
+    } 
+    
+    
+    /**
+     * @see com.bea.control.Extensible#invoke}. 
+     */
+    public Object invoke(Method method, Object[] args) throws ControlException 
+    {
+        assert (method != null && args != null);
+        javax.jms.Message m = null;
+    	boolean isBody = false;
+        try
+        {
+	        Destination props = getDestinationProperties();
+	        Session session = getSession();
+	        String jmsType = null;
+	        String correlationId = null;
+	        /*
+	         * Set the deliveryMode, priority and expiration.
+	         */
+	        int deliveryMode = getProducer().getDeliveryMode();
+		    int priority = getProducer().getPriority();
+		    long expiration = getProducer().getTimeToLive();
+		    Object mode = getHeader(HeaderType.JMSDeliveryMode);
+		    if(mode != null)
+	        {
+	        	deliveryMode = deliveryModeToJmsMode(mode);
+	        }
+	        Integer v = getHeaderAsInteger(HeaderType.JMSPriority);
+	        if(v != null)
+	        {
+	        	priority = v.intValue();
+	        }
+	        Long l = getHeaderAsLong(HeaderType.JMSExpiration);
+	        if(l != null)
+	        {
+	        	expiration = l.longValue();
+	        }
+	        /*
+	         * Get the body of the message.
+	         */
+	        Object body = null;
+	        // Check to see if any parameter has annotation. If it doesn't then don't bother
+	        // checking them.
+	        boolean hasAnnotation = method.getParameterAnnotations().length > 0;
+	        for (int i= 0; i< args.length; i++)
+	        {
+	        	if(hasAnnotation)
+	        	{
+		            if (_context.getParameterPropertySet(method, i, Priority.class) != null)
+		            {
+		            	continue;
+		            }
+		            if (_context.getParameterPropertySet(method, i, Property.class) != null)
+		            {
+		            	continue;
+		            }
+		            if (_context.getParameterPropertySet(method, i, Expiration.class) != null)
+		            {
+		            	continue;
+		            }
+		            if (_context.getParameterPropertySet(method, i, Delivery.class) != null)
+		            {
+		            	continue;
+		            }
+		            if (_context.getParameterPropertySet(method, i, Type.class) != null)
+		            {
+		            	continue;
+		            }
+		            if (_context.getParameterPropertySet(method, i, CorrelationId.class) != null)
+		            {
+		            	continue;
+		            }
+		        }
+	            if(isBody)
+	            {
+	            	throw new IllegalArgumentException("At most one parameter may be defined as the body of the JMS message");
+	            }
+	            body = args[i];
+	            isBody = true;
+	        }
+	        /*
+	         * Get the method level annotation properties.
+	         */
+	        Priority pri = _context.getMethodPropertySet(method,Priority.class);
+	        if(pri != null && pri.value() != -1)
+	        {
+	        	priority = pri.value();
+	        }
+	        Expiration exp = _context.getMethodPropertySet(method,Expiration.class);
+	        if(exp != null && exp.value() != -1L)
+	        {
+	        	expiration = exp.value();
+	        }
+	        Delivery del = _context.getMethodPropertySet(method,Delivery.class);
+	        if(del != null && del.value() != DeliveryMode.Auto)
+	        {
+	        	deliveryMode = deliveryModeToJmsMode(del.value());
+	        }
+	        Type t = _context.getMethodPropertySet(method,Type.class);
+	        if(t != null && t.value().length() != 0)
+	        {
+	        	jmsType = t.value();
+	        }
+	        CorrelationId id = _context.getMethodPropertySet(method,CorrelationId.class);
+	        if(id != null && id.value().length() != 0)
+	        {
+	        	correlationId = id.value();
+	        }
+	        /*
+	         * Create a message of the appropriate type and set the body.
+	         */
+	        JMSControl.Message mess = _context.getMethodPropertySet(method,JMSControl.Message.class);
+	        MessageType type = MessageType.Auto; 
+	        if(mess != null)
+	        {
+	        	type = mess.value();
+	        }
+	        if(type.equals(MessageType.Auto))
+	        {
+	        	if(body instanceof byte[])
+	        	{
+	        		type = MessageType.Bytes;
+	        	}
+	        	else if(body instanceof Map || !isBody)
+	        	{
+	        		type = MessageType.Map;
+	        	}
+	        	else if(body instanceof String || body instanceof XmlObject)
+	        	{
+	        		type = MessageType.Text;
+	        	}
+	        	else if(body instanceof javax.jms.Message)
+	        	{
+	        		type = MessageType.JMSMessage;
+	        	}
+	        	else if(body instanceof Serializable)
+	        	{
+	        		type = MessageType.Object;
+	        	}
+	        	else
+	        	{
+	        		throw new ControlException("Cannot determine message type from body");
+	        	}	
+	        }
+	        switch(type)
+	        {
+	        	case Object:
+	        	    checkBody(body,Serializable.class);
+	        	    m = session.createObjectMessage((Serializable)body);
+	        		break;
+	        	case Bytes:
+	        	    BytesMessage sm;
+	        	    checkBody(body,byte[].class);
+	        		m = sm = session.createBytesMessage();
+	        		sm.writeBytes((byte[])body);
+	        		break;
+	        	case Text:
+	        		if (body instanceof XmlObject) 
+	        		{
+	        			body = (((XmlObject)body)).xmlText();
+	        		}
+	        	    checkBody(body,String.class);
+	        	    m = session.createTextMessage((String)body);
+	        		break;
+	        	case Map:
+	        	    MapMessage mm;
+	        	    checkBody(body,Map.class);
+	        	    m = mm = session.createMapMessage();
+		            Map map =(Map)body;
+		            Iterator iter = map.keySet().iterator();
+		            while(iter.hasNext())
+		            {
+		        	String key = (String)iter.next();
+		       		mm.setObject(key,map.get(key));
+			    }
+	        	    break;
+	        	case JMSMessage:
+	        	    checkBody(body,javax.jms.Message.class);
+	        	    m = (javax.jms.Message)body;
+	        		break;
+	        }
+	        /*
+	         * Set the correlation id if given.
+	         */
+	        String correlationProp = props.sendCorrelationProperty();
+	        if(correlationProp != null && correlationProp.length() == 0)
+	        {
+	        	correlationProp = null;
+	        }
+			if(correlationId == null)
+			{
+				correlationId = getHeaderAsString(HeaderType.JMSCorrelationID);
+			}
+	        Properties jmsProps =
+	                (Properties)_context.getMethodPropertySet(method,Properties.class);
+			if(jmsProps != null && jmsProps.value() != null)
+			{
+				PropertyValue[] jprops = jmsProps.value();
+				for(int i = 0; i < jprops.length; i++)
+				{
+					PropertyValue jprop = jprops[i];
+					Class cls = jprop.type();
+					if(cls.equals(String.class))
+					{
+						m.setStringProperty(jprop.name(),jprop.value());
+					} 
+					else if(cls.equals(Integer.class))
+					{
+						m.setIntProperty(jprop.name(),valueAsInteger(jprop.value()));
+					}
+					else if(cls.equals(Long.class))
+					{
+						m.setLongProperty(jprop.name(),valueAsLong(jprop.value()));
+					}
+					else
+					{
+						throw new IllegalArgumentException("Invalid type for property-value");
+					}
+				}					
+			}
+	        /*
+	         * Set the properties/headers of the message from
+	         * the parameters to the invoke.
+	         */
+	        if(hasAnnotation)
+	        {
+		        for (int i= 0; i< args.length; i++)
+		        {
+		            Property jmsProp =
+		                (Property)_context.getParameterPropertySet(method,i, Property.class);
+		            if (jmsProp != null)
+		            {
+		                m.setObjectProperty(jmsProp.name(), args[i]);
+		            }
+		            Priority jmsPriority = 
+		                (Priority)_context.getParameterPropertySet(method,i, Priority.class);
+		            if (jmsPriority != null)
+		            {
+		            	Integer p = valueAsInteger(args[i]);
+		            	if(p != null)
+		            	{	            	
+		            		priority = p.intValue();
+		            	}
+		            }
+		            Expiration jmsExpiration = 
+		                (Expiration)_context.getParameterPropertySet(method,i, Expiration.class);
+		            if (jmsExpiration != null)
+		            {
+		            	Long e = valueAsLong(args[i]);
+		            	if(e != null)
+		            	{
+		            		expiration = e.longValue();
+		            	}
+		            }
+		            Delivery jmsDelivery = 
+		                (Delivery)_context.getParameterPropertySet(method,i, Delivery.class);
+		            if (jmsDelivery != null && args[i] != null)
+		            {
+		            	deliveryMode = deliveryModeToJmsMode(args[i]);
+		            }
+		            t = 
+		                (Type)_context.getParameterPropertySet(method,i, Type.class);
+		            if (t != null && args[i] != null)
+		            {
+		            	jmsType = (String)args[i];
+		            }
+		            CorrelationId jmsId = 
+		                (CorrelationId)_context.getParameterPropertySet(method,i, CorrelationId.class);
+		            if (jmsId != null && args[i] != null)
+		            {
+		            	correlationId = (String)args[i];
+		            }
+		        }
+		    }
+	        if(correlationProp != null)
+	        {
+	        	m.setStringProperty(correlationProp,correlationId);
+	        }
+	        else
+	        {
+	            m.setJMSCorrelationID(correlationId);
+	        }
+	        /*
+	         * Set the headers and properties from maps provided
+	         * by setProperties() and setHeaders()
+	         */
+	        m.setJMSExpiration(expiration);
+	        m.setJMSDeliveryMode(deliveryMode);
+	        m.setJMSPriority(priority);
+	        setMessageHeaders(m);
+	        setMessageProperties(m);
+	        expiration = m.getJMSExpiration();
+	        deliveryMode = m.getJMSDeliveryMode();
+	        priority = m.getJMSPriority();
+	        _headers = null;
+	        _properties = null;
+	        /*
+	         * Send the message.
+	         */
+	        switch(getDestinationType())
+	        {
+	        	case Topic:
+	            	((TopicPublisher)getProducer()).publish(m,deliveryMode,priority,expiration);
+	            	break;
+	            case Queue:
+	            	((QueueSender)getProducer()).send(m,deliveryMode,priority,expiration);
+	            	break;
+	        }
+        }
+
+        catch(JMSException e)
+        {
+            throw new ControlException("Error in sending message",e);
+        }
+        return m;
+    }  
+
+    
+    @EventHandler(field = "_resourceContext", eventSet = ResourceContext.ResourceEvents.class, eventName = "onAcquire")
+    public void onAcquire()
+    {
+    }
+    /*
+     * The onRelease event handler for the associated context This method will
+     * release all resource acquired by onAcquire.
+     */
+    @EventHandler(field = "_resourceContext", eventSet = ResourceContext.ResourceEvents.class, eventName = "onRelease") 
+    public void onRelease()
+    {
+    	close();
+    }
+    
+    /* Protected Method(s) */
+    
+    /**
+     * Close any resources.
+     */
+    protected void close()
+    {
+        try
+        {
+            if (_producer != null)
+            {
+                _producer.close();
+                _producer = null;
+            }
+            if (_session != null)
+            {
+                _session.close();
+                _session = null;
+            }
+            if (_connection != null)
+            {
+                _connection.close();
+                _connection = null;
+            }
+        } catch (JMSException jmse)
+        {
+            throw new ControlException("Unable to release JMS resource", jmse);
+        }
+    }
+    
+    /**
+     * Deterimine whether we are working with a queue or a topic.
+     */
+    protected void determineDestination()
+    {
+    	Destination props = getDestinationProperties();
+		String factory = props.jndiConnectionFactory();	            	
+		ConnectionFactory cfactory = (ConnectionFactory) getJndiControl().getResource(factory,ConnectionFactory.class);
+		if(cfactory instanceof QueueConnectionFactory && cfactory instanceof TopicConnectionFactory)
+		{
+   			javax.jms.Destination dest = getDestination();
+	    	if(dest instanceof Queue && dest instanceof Topic)
+			{
+				/* Try to create a topic producer...if fail then assume that it is a queue */
+				try
+				{
+				    createTopicSession();
+				    _producer = ((TopicSession)getSession()).createPublisher((Topic) getDestination());
+				}
+				catch(Exception e)
+				{
+					close();
+	    			_destinationType = DestinationType.Queue;
+	    			return;
+	    		}
+	    		_destinationType = DestinationType.Topic;
+			}
+			else
+			{
+	    		if(dest instanceof javax.jms.Queue)
+	    		{
+	    			_destinationType = DestinationType.Queue;
+	    		}
+	    		if(dest instanceof javax.jms.Topic)
+	    		{
+	    			_destinationType = DestinationType.Topic;
+	    		}
+	    	}
+		}
+		else
+		{
+    		if(cfactory instanceof QueueConnectionFactory)
+    		{
+    			_destinationType = DestinationType.Queue;
+    		}
+    		if(cfactory instanceof TopicConnectionFactory)
+    		{
+    			_destinationType = DestinationType.Topic;
+    		}
+    	}     	
+    }
+    
+    /**
+     * Get the queue/topic producer.
+     * @return the JMS producer.
+     */
+    protected MessageProducer getProducer()
+    {
+    	if(_producer == null)
+    	{
+	        //
+	        // Acquire the publisher/sender.
+	        //
+	        try
+	        {
+	        	javax.jms.Session sess = getSession();
+		        switch(getDestinationType())
+		        {
+		        	case Auto:
+		        		try
+		        		{
+		            		_producer = ((QueueSession)sess).createSender((Queue) getDestination());
+		        		}
+		        		catch(Exception e)
+		        		{
+		            		_producer = ((TopicSession)sess).createPublisher((Topic) getDestination());
+		        		}
+		        		break;
+		        	case Topic:
+		            	_producer = ((TopicSession)sess).createPublisher((Topic) getDestination());
+		        		break;
+		        	case Queue:
+		            	_producer = ((QueueSession)sess).createSender((Queue) getDestination());
+		            	break;
+		        }
+	        } catch (JMSException jmse)
+	        {
+	            throw new ControlException("Unable to acquire JMS resource", jmse);
+	        }
+	    }
+	    return _producer;
+    }
+
+    
+    /**
+     * Creates a topic session.
+     */
+	protected void createTopicSession() throws JMSException
+    {
+	    Destination props = getDestinationProperties();
+	    String factory = props.jndiConnectionFactory();
+	    boolean transacted = props.transacted();
+	    AcknowledgeMode ackMode = props.acknowledgeMode();
+        TopicConnectionFactory connFactory = (TopicConnectionFactory) getJndiControl()
+                .getResource(factory,
+                        TopicConnectionFactory.class);
+        _connection = connFactory.createTopicConnection();
+        _session = ((TopicConnection) _connection).createTopicSession(
+                transacted, modeToJmsMode(ackMode));
+
+    }
+        
+        
+    /**
+     * Creates a queue session.
+     */
+	protected void createQueueSession() throws JMSException
+    {
+    	Destination props = getDestinationProperties();
+	    String factory = props.jndiConnectionFactory();
+	    boolean transacted = props.transacted();
+	    AcknowledgeMode ackMode = props.acknowledgeMode();
+        QueueConnectionFactory connFactory = (QueueConnectionFactory) getJndiControl()
+                .getResource(factory,
+                        QueueConnectionFactory.class);
+        _connection = connFactory.createQueueConnection();
+        _session = ((QueueConnection) _connection).createQueueSession(
+                transacted, modeToJmsMode(ackMode));
+
+    }
+    /**
+     * Convert the enum to the JMS ack mode.
+     * @param mode the enum mode.
+     * @return the JMS mode.
+     */
+    protected int modeToJmsMode(AcknowledgeMode mode)
+    {
+        if (mode == AcknowledgeMode.Auto)
+        {
+            return Session.AUTO_ACKNOWLEDGE;
+        } else if (mode == AcknowledgeMode.Client)
+        {
+            return Session.CLIENT_ACKNOWLEDGE;
+        } else
+        {
+            return Session.DUPS_OK_ACKNOWLEDGE;
+        }
+    }
+    /**
+     * Convert the object to the JMS delivery mode.
+     * @param value a integer valued string, integer or DeliveryMode.
+     * @return the JMS delivery mode.
+     */
+    protected int deliveryModeToJmsMode(Object value)
+    {
+    	if(value instanceof DeliveryMode)
+    	{
+    	    DeliveryMode mode = (DeliveryMode)value;
+    		switch(mode)
+    		{
+    			case Persistent:
+    				return javax.jms.DeliveryMode.PERSISTENT;
+    			case NonPersistent:
+    				return javax.jms.DeliveryMode.NON_PERSISTENT;
+    		}
+	    }
+        if (value instanceof Number) 
+        {
+            return ((Number)value).intValue();
+        } 
+        else if (value instanceof String) 
+        {
+            return Integer.parseInt((String)value);
+        }
+        throw new IllegalArgumentException("Invalid delivery mode value");
+    }
+    /**
+     * Check the given value to see if is appropriate for the given message value class.
+     * @param value the body.
+     * @param cls the expected class.
+     */
+    protected void checkBody(Object value,Class cls) throws ControlException
+    {
+        if(!cls.isInstance(value))
+        {
+            throw new ControlException("Message body is not of correct type expected "+cls.getName());
+        }
+    }
+    /**
+     * Get the destination annotation info for the message.
+     * @return the destination method annotation.
+     */
+    protected Destination getDestinationProperties()
+    {
+        return (Destination) _context.getControlPropertySet(Destination.class);
+    }
+
+    /**
+     * Get the topic/queue state.
+     * Determine what connection and session from the destination
+     * itself if sendType is Auto otherwise use the Destination
+     * annotation element.
+     * @return true if the destination is a topic.
+     */
+    protected DestinationType getDestinationType() throws ControlException
+    {
+    	if(_destinationType != DestinationType.Auto)
+    	{
+    		return _destinationType;
+    	}
+    	Destination d = getDestinationProperties();
+    	if(d.sendType() != DestinationType.Auto)
+    	{
+    		_destinationType = d.sendType();
+    	}
+    	return d.sendType();
+   }
+
+
+
+
+    /**
+     * Set the properties of the given message.
+     * @param msg the message.
+     */
+    protected void setMessageProperties(javax.jms.Message msg)
+            throws ControlException 
+    {
+    	if(_properties == null)
+    	{
+    		return;
+    	}
+        Iterator i = _properties.keySet().iterator();
+        while (i.hasNext()) 
+        {
+            String name = (String) i.next();
+            Object value = _properties.get(name);
+            try
+            {
+            	msg.setObjectProperty(name,value);
+            }
+            catch(JMSException e)
+            {
+            	throw new ControlException("Cannot set property '"+name+"' into JMS message");
+            }
+        }
+    }
+    
+    /**
+     * Set the headers. Accessing msg may throw exception.
+     * @param msg the message.
+     */
+    protected void setMessageHeaders(javax.jms.Message msg)
+            throws ControlException 
+    {
+    	if(_headers == null)
+    	{
+    		return;
+    	}
+        Iterator<HeaderType> i = _headers.keySet().iterator();
+        while (i.hasNext()) 
+        {
+            HeaderType name = i.next();
+            Object value = _headers.get(name);
+			setMessageHeader(msg,name,value);
+		}
+	}
+	/**
+     * Set the header value of the given message.
+     * @param msg the message.
+     * @param type the header type.
+     * @param value the value.
+     */
+	protected void setMessageHeader(javax.jms.Message msg,HeaderType type,Object value)
+	{
+		switch(type)
+		{
+
+	        case JMSCorrelationID:
+	            try 
+	            {
+	                if (value instanceof byte[]) 
+	                {
+	                    msg.setJMSCorrelationIDAsBytes((byte[])value);
+	                } 
+	                else if (value instanceof String) 
+	                {
+	                	msg.setJMSCorrelationID((String)value);
+	                }
+	            } 
+	            catch (javax.jms.JMSException e) 
+	            {
+	                throw new ControlException("Error setting JMSCorrelationID for message", e);
+	            }
+	            break;
+	        case JMSPriority:
+	            try 
+	            {
+	                if (value instanceof Integer) 
+	                {
+	                    msg.setJMSPriority(((Integer)value).intValue());
+	                } 
+	                else if (value instanceof String) 
+	                {
+	                    msg.setJMSPriority(Integer.getInteger((String)value));
+	                }
+	            } 
+	            catch (javax.jms.JMSException e) 
+	            {
+	                throw new ControlException("Error setting JMSPriority for message", e);
+	            }
+	            break;
+	        case JMSExpiration:
+	            try 
+	            {
+	                if (value instanceof Long) 
+	                {
+	                    msg.setJMSExpiration(((Long)value).longValue());
+	                } 
+	                else if (value instanceof String) 
+	                {
+	                    msg.setJMSExpiration(Long.parseLong((String)value));
+	                }
+	            } catch (javax.jms.JMSException e) 
+	            {
+	                throw new ControlException("Error setting JMSExpiration for message", e);
+	            }
+	            break;
+			case JMSType:
+	            try 
+	            {
+	                msg.setJMSType((String)value);
+	            } 
+	            catch (javax.jms.JMSException e) 
+	            {
+	                throw new ControlException("Error setting JMSType for message", e);
+	            }
+	            break;
+        }
+    }
+    
+    /**
+     * Get the header type value.
+     * @param name the header type.
+     * @return the value or null.
+     */
+    protected Object getHeader(HeaderType name)
+    {
+    	if(_headers == null)
+    	{
+    		return null;
+    	}
+    	return _headers.get(name.toString());
+    }
+    /**
+     * Get the header type value as a string.
+     * @param name the header type.
+     * @return the string value or null.
+     */
+    protected String getHeaderAsString(HeaderType name)
+    {
+        Object obj = getHeader(name);
+    	if(obj != null)
+    	{
+    		return obj.toString();
+    	}
+    	return null;
+    }
+    
+    /**
+     * Get the header type value as a int.
+     * @param name the header type.
+     * @return the int value or null.
+     */
+    protected Integer getHeaderAsInteger(HeaderType name)
+    {
+    	Object obj = getHeader(name);
+    	return valueAsInteger(getHeader(name));
+    }
+    /**
+     * Return the given value as an integer.
+     * @param obj a string or number object.
+     * @return the integer value or null.
+     */
+    protected Integer valueAsInteger(Object obj)
+    {
+    	if(obj instanceof String)
+    	{
+    		return Integer.parseInt((String)obj);
+    	}
+    	else if(obj instanceof Integer)
+    	{
+    		return (Integer)obj;
+    	}
+    	else if(obj instanceof Number)
+    	{
+    		return new Integer(((Number)obj).intValue());
+    	}
+    	return null;
+    }
+    /**
+     * Get the header type value as a long.
+     * @param name the header type.
+     * @return the long value or null.
+     */
+    protected Long getHeaderAsLong(HeaderType name)
+    {
+    	return valueAsLong(getHeader(name));
+    }
+    /**
+     * Return the given value as a long.
+     * @param obj a string or number object.
+     * @return the long value or null.
+     */
+    protected Long valueAsLong(Object obj)
+    {
+    	if(obj instanceof String)
+    	{
+    		return Long.parseLong((String)obj);
+    	}
+    	else if(obj instanceof Long)
+    	{
+    		return (Long)obj;
+    	}
+    	else if(obj instanceof Number)
+    	{
+    		return new Long(((Number)obj).longValue());
+    	}
+    	return null;
+    }
+    /**
+     * Get the JNDI control instance.
+     * @return the jndi-control.
+     */
+    protected JndiControlBean getJndiControl()
+    {
+    	if(!_jndiInitialized)
+    	{
+    		_jndiInitialized = true;
+	    	Destination dest = getDestinationProperties();
+	    	String contextFactory = nullIfEmpty(dest.jndiContextFactory());
+	    	if(contextFactory != null)
+	    	{
+	    		_jndiControl.setFactory(contextFactory);
+	    	}
+	    	String providerURL = nullIfEmpty(dest.jndiProviderURL());
+	    	if(providerURL != null)
+	    	{
+	    		_jndiControl.setUrl(providerURL);
+	    	}
+	    	String userName = nullIfEmpty(dest.jndiUsername());
+	    	if(userName != null)
+	    	{
+	    		_jndiControl.setJndiSecurityPrincipal(userName);
+	    	}
+	    	String password = nullIfEmpty(dest.jndiPassword());
+	    	if(password != null)
+	    	{
+	    		_jndiControl.setJndiSecurityCredentials(password);
+	    	}
+    	}
+    	return _jndiControl;
+    }
+    
+    /**
+     * Return null if the given string is null or an empty string.
+     * @param str a string.
+     * @return null or the string.
+     */
+    protected String nullIfEmpty(String str)
+    {
+    	if(str == null || str.trim().length() == 0)
+    	{
+    		return null;
+    	}
+    	return str;
+    }
+    @Context
+    private ResourceContext _resourceContext;
+    
+    @Context
+    private ControlBeanContext _context;
+    
+    @Control
+    private JndiControlBean _jndiControl;
+    
+    /** The destination */
+    private transient javax.jms.Destination _destination;
+    
+    private transient DestinationType _destinationType = DestinationType.Auto;
+    
+    /** The connection. */
+    private transient javax.jms.Connection _connection;
+    
+    /** The session */
+    private transient Session _session;
+    
+    /** The message producer. */
+    private transient MessageProducer _producer;
+    
+    /** The JNDI control has been initialized */
+    private boolean _jndiInitialized = false;
+    
+    /** The headers to set in the next message to be sent. */
+    private Map<HeaderType,Object> _headers;
+    
+    /** The properties to set in the next message to be sent. */
+    private Map<String,Object> _properties;
+
+}

Added: incubator/beehive/trunk/system-controls/src/jms/org/apache/beehive/controls/system/jndi/JndiControl.java
URL: http://svn.apache.org/viewcvs/incubator/beehive/trunk/system-controls/src/jms/org/apache/beehive/controls/system/jndi/JndiControl.java?rev=169351&view=auto
==============================================================================
--- incubator/beehive/trunk/system-controls/src/jms/org/apache/beehive/controls/system/jndi/JndiControl.java (added)
+++ incubator/beehive/trunk/system-controls/src/jms/org/apache/beehive/controls/system/jndi/JndiControl.java Mon May  9 13:17:58 2005
@@ -0,0 +1,90 @@
+/*
+ * Copyright 2005 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * $Header:$
+ */
+
+package org.apache.beehive.controls.system.jndi;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+import java.lang.annotation.ElementType;
+import javax.naming.InitialContext;
+
+import org.apache.beehive.controls.api.ControlException;
+import org.apache.beehive.controls.api.packaging.FeatureInfo;
+import org.apache.beehive.controls.api.properties.PropertySet;
+import org.apache.beehive.controls.api.bean.ControlInterface;
+import org.apache.beehive.controls.api.bean.AnnotationMemberTypes;
+
+/**
+ * The Jndi Control encapsulates access to the JNDI context. It
+ * provides annotation for setting the factory and provider URL.
+ */
+@ControlInterface (defaultBinding="org.apache.beehive.controls.system.jndi.impl.JndiControlImpl")
+public interface JndiControl
+{
+    /**
+     * Get a JNDI based resource.
+     * @param resource the resource name.
+     * @param resourceClass the resource class.
+     * @return the resource object.
+     * @throws ControlException
+     */
+    public Object getResource(String resource,Class resourceClass) throws ControlException;
+    /**
+     * Get the JNDI initial context.
+     * @return the initial context.
+     *
+     * @throws ControlException
+     */
+    public InitialContext getInitialContext() throws ControlException;
+
+    @PropertySet
+    @Retention(RetentionPolicy.RUNTIME)
+    @Target({ElementType.TYPE,ElementType.FIELD})
+    public @interface Properties
+    {
+        /**
+         * The JNDI context factory.
+         */
+        @FeatureInfo(shortDescription="JNDI context factory")
+        @AnnotationMemberTypes.Optional
+        String factory();
+        /**
+         * The JNDI provider URL.
+         */
+        @FeatureInfo(shortDescription="JNDI provider URL")      
+        @AnnotationMemberTypes.Optional
+        @AnnotationMemberTypes.URI
+        String url();
+        /**
+         * The JNDI security principal.
+         */
+        @FeatureInfo(shortDescription="JNDI security principal")      
+        @AnnotationMemberTypes.Optional
+    	public String jndiSecurityPrincipal() default "";
+        
+        
+        /**
+         * The JNDI security credentials.
+         */
+        @FeatureInfo(shortDescription="JNDI security credentials")      
+        @AnnotationMemberTypes.Optional
+    	public String jndiSecurityCredentials() default "";
+    }
+
+}

Added: incubator/beehive/trunk/system-controls/src/jms/org/apache/beehive/controls/system/jndi/impl/JndiControlImpl.jcs
URL: http://svn.apache.org/viewcvs/incubator/beehive/trunk/system-controls/src/jms/org/apache/beehive/controls/system/jndi/impl/JndiControlImpl.jcs?rev=169351&view=auto
==============================================================================
--- incubator/beehive/trunk/system-controls/src/jms/org/apache/beehive/controls/system/jndi/impl/JndiControlImpl.jcs (added)
+++ incubator/beehive/trunk/system-controls/src/jms/org/apache/beehive/controls/system/jndi/impl/JndiControlImpl.jcs Mon May  9 13:17:58 2005
@@ -0,0 +1,129 @@
+/*
+ * Copyright 2005 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * $Header:$
+ */
+package org.apache.beehive.controls.system.jndi.impl;
+
+import java.util.Hashtable;
+import javax.naming.InitialContext;
+import javax.naming.NamingException;
+
+import org.apache.beehive.controls.api.ControlException;
+import org.apache.beehive.controls.api.context.ControlBeanContext;
+import org.apache.beehive.controls.api.context.Context;
+import org.apache.beehive.controls.api.bean.ControlImplementation;
+import org.apache.beehive.controls.system.jndi.JndiControl;
+
+/**
+ * Implementation of the jndi control.
+ */
+@ControlImplementation
+public class JndiControlImpl
+    implements JndiControl, java.io.Serializable {
+
+    /**
+     * @see JndiControl#getResource(String, Class)
+     */
+    public Object getResource(String resource,Class resourceClass) throws ControlException
+    {
+        try
+        {
+        	InitialContext cntxt = getInitialContext();
+	        Object obj = cntxt.lookup(resource);
+	        if(resourceClass != null && !(resourceClass.isInstance(obj)))
+	        {
+	            throw new ControlException("JNDI resource '"+resource+"' is not an instance of '"+resourceClass.getName()+"'");
+	        }
+	        return obj;
+        }
+        catch(NamingException e)
+        {
+            throw new ControlException("Cannot load JNDI resource '"+resource+"'",e);
+        }
+    }
+    
+    /**
+     * Get the initial context.
+     * @return the initial context.
+     */
+    public InitialContext getInitialContext() throws ControlException
+    {
+    	if(_initialContext != null)
+    	{
+    		return _initialContext;
+    	}
+    	Properties props = (Properties) _context.getControlPropertySet(Properties.class);
+        String url = nullIfEmpty(props.url());
+        String factory = nullIfEmpty(props.factory());
+	    if(url == null && factory == null)
+	    {
+	        try
+	        {
+				return new InitialContext();
+	        }
+	        catch(NamingException e)
+	        {        	
+	        	throw new ControlException("Cannot get default JNDI initial context",e);
+	        }
+        
+		}
+        if(url == null || factory == null)
+        {
+            throw new ControlException("Both the provider-url and jndi factory need to be provided");
+           
+        }
+        Hashtable<String,String> env = new Hashtable<String,String>();
+        env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, factory);
+        env.put(javax.naming.Context.PROVIDER_URL,url);
+        String username = nullIfEmpty(props.jndiSecurityPrincipal());
+        if(username != null)
+        {
+        	env.put(javax.naming.Context.SECURITY_PRINCIPAL,username);
+        }
+        String password = nullIfEmpty(props.jndiSecurityCredentials());
+        if(password != null)
+        {
+        	env.put(javax.naming.Context.SECURITY_CREDENTIALS,password);
+        }
+        try
+        {
+        	return _initialContext = new InitialContext(env);
+        }
+        catch(NamingException e)
+        {        	
+        	throw new ControlException("Cannot get JNDI initial context at provider '"+url+"' with factory '"+factory+"'",e);
+        }
+    }
+    /**
+     * Return null if the given string is null or an empty string.
+     * @param str a string.
+     * @return null or the string.
+     */
+    protected String nullIfEmpty(String str)
+    {
+    	if(str == null || str.trim().length() == 0)
+    	{
+    		return null;
+    	}
+    	return str;
+    }
+    /* Control Managed Field(s) */
+    @Context ControlBeanContext _context;
+
+    /* Private Field(s) */
+    /** The initial context. */
+    private transient InitialContext _initialContext;
+}

Added: incubator/beehive/trunk/system-controls/src/webservice/build.xml
URL: http://svn.apache.org/viewcvs/incubator/beehive/trunk/system-controls/src/webservice/build.xml?rev=169351&view=auto
==============================================================================
--- incubator/beehive/trunk/system-controls/src/webservice/build.xml (added)
+++ incubator/beehive/trunk/system-controls/src/webservice/build.xml Mon May  9 13:17:58 2005
@@ -0,0 +1,64 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+
+<project name="Service Control Build" default="build" basedir=".">
+
+
+    <import file="../../systemcontrols-imports.xml"/>
+
+    <property name="module.name" value="webservice-control"/>
+    <property name="module.dir" location="${src.dir}/webservice"/>
+    <property name="wsc.version" value="svn-snapshot"/>
+
+    <path id="module.classpath">
+        <path refid="webservices.dependency.path"/>
+        <path refid="controls.dependency.path"/>
+        <path refid="velocity.dependency.path"/>
+        <path refid="log4j.dependency.path"/>
+        <path refid="xbean.dependency.path"/>
+        <path refid="tools.dependency.path"/>
+    </path>
+
+
+    <!-- ========================================= -->
+    <!-- build - build the webservice control      -->
+    <!-- ========================================= -->
+    <target name="build" description="Builds webservice control.">
+
+        <mkdir dir="${classes.dir}/${module.name}"/>
+        <mkdir dir="${gen.src.dir}/${module.name}"/>
+
+        <build-controls srcdir="${module.dir}" destdir="${classes.dir}/${module.name}"
+            tempdir="${gen.src.dir}/${module.name}" classpathref="module.classpath"/>
+
+        <copy todir="${classes.dir}/${module.name}">
+            <fileset dir="${module.dir}">
+                <include name="**/*properties"/>
+            </fileset>
+        </copy>
+
+        <jar destfile="${build.lib.dir}/${wsmcontrol.jar.name}">
+          <fileset dir="${classes.dir}/${module.name}"/>
+          <manifest>
+            <attribute name="Extension-Name" value="Web Service Control Library"/>
+            <attribute name="Specification-Title" value="Web Service Control Library"/>
+            <attribute name="Specification-Vendor" value="BEA Systems, Inc."/>
+            <attribute name="Specification-Version" value="${wsc.version}"/>
+            <attribute name="Implementation-Title" value="Web Service Control"/>
+            <attribute name="Implementation-Vendor" value="BEA Systems, Inc."/>
+            <attribute name="Implementation-Version" value="${wsc.version}"/>
+            <attribute name="Web-Service-Control-Version" value="${wsc.version}"/>
+          </manifest>
+        </jar>
+    </target>
+
+    <!-- ========================================= -->
+    <!-- clean - delete all binaries and artifacts -->
+    <!-- ========================================= -->
+
+    <target name="clean">
+        <delete dir="${classes.dir}/${module.name}"/>
+        <delete dir="${gen.src.dir}/${module.name}"/>
+        <delete file="${build.lib.dir}/${wsmcontrol.jar.name}"/>
+    </target>
+
+</project>

Added: incubator/beehive/trunk/system-controls/src/webservice/org/apache/beehive/controls/system/webservice/ServiceControl.java
URL: http://svn.apache.org/viewcvs/incubator/beehive/trunk/system-controls/src/webservice/org/apache/beehive/controls/system/webservice/ServiceControl.java?rev=169351&view=auto
==============================================================================
--- incubator/beehive/trunk/system-controls/src/webservice/org/apache/beehive/controls/system/webservice/ServiceControl.java (added)
+++ incubator/beehive/trunk/system-controls/src/webservice/org/apache/beehive/controls/system/webservice/ServiceControl.java Mon May  9 13:17:58 2005
@@ -0,0 +1,192 @@
+/*
+ * Copyright 2005 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * $Header:$
+ */
+
+package org.apache.beehive.controls.system.webservice;
+
+import org.apache.beehive.controls.api.bean.AnnotationMemberTypes;
+import org.apache.beehive.controls.api.bean.ControlInterface;
+import org.apache.beehive.controls.api.properties.PropertySet;
+import org.w3c.dom.Element;
+
+import javax.xml.namespace.QName;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+import java.net.URL;
+
+
+/**
+ * Provides simplified access to web services. A Service control provides an interface between your application and a
+ * web service, which allows your application to invoke the methods. Using a Web Service control, you can connect to any
+ * web service for which a WSDL file is available. <br/><br/> You typically use a Service control by creating the
+ * control from a WSDL file The target web service's operations are exposed as methods of the control. <br/><br/>
+ */
+@ControlInterface (defaultBinding = "org.apache.beehive.controls.system.webservice.jaxrpc.ServiceControlImpl")
+        public interface ServiceControl {
+
+    // ----------------------------------------------
+    // Class level annotations.
+    // ----------------------------------------------
+
+    /**
+     * Location URL for target service. Multiple URLs may be specified and first URL of the appropriate scheme will be
+     * used.
+     */
+    @PropertySet(
+            prefix = "Location",
+            externalConfig = true,
+            optional = true,
+            hasSetters = false
+            )
+            @Retention(RetentionPolicy.RUNTIME)
+            @Target({ElementType.TYPE, ElementType.FIELD})
+            // allowed on declaration
+            public @interface Location {
+        String[] urls();
+    }
+
+    /**
+     * OperationName is only used when the target WSDL defines operations with names that are invalid as Java Method
+     * names.
+     */
+    @PropertySet(
+            prefix = "OperationName",
+            externalConfig = false,
+            optional = true,
+            hasSetters = false
+            )
+            @Retention(RetentionPolicy.RUNTIME)
+            @Target({ElementType.METHOD})
+            public @interface OperationName {
+
+        String value();
+    }
+
+    /**
+     * Path to WSDL - mandatory annotation.
+     */
+    @PropertySet(
+            prefix = "WSDL",
+            externalConfig = false,
+            optional = false,
+            hasSetters = false
+            )
+            @Retention(RetentionPolicy.RUNTIME)
+            @Target({ElementType.TYPE})
+            public @interface WSDL {
+        @AnnotationMemberTypes.FilePath
+        String path();
+
+        String service() default "";
+    }
+
+    /**
+     * Manual control over URL of the target service.
+     *
+     * @param url The new destination for callbacks.
+     */
+    public void setEndPoint(URL url);
+
+    /**
+     * Gets the URL that the Service control instance will use as the base URL.
+     *
+     * @return The URL that will be used.
+     */
+    public URL getEndPoint();
+
+
+    /**
+     * Specifies the QName for the port within the WSDL which the Service Control should use.
+     *
+     * @param wsdlPortName The QName of the port to use.
+     */
+    public void setWsdlPort(QName wsdlPortName);
+
+    /**
+     * Returns the QName of the port that will be used by the Service Control to call the webservice.
+     *
+     * @return The QName of the port that will be used.
+     */
+    public QName getWsdlPort();
+
+
+    /**
+     * Sets the username that will be sent with the next outgoing Service control method invocation. Used if the Service
+     * control uses HTTP basic authentication.
+     *
+     * @param username The username to send for authentication.
+     */
+    public void setUsername(String username);
+
+    /**
+     * Sets the password that will be sent with the next outgoing Service control method invocation. Used if the Service
+     * control uses HTTP basic authentication.
+     *
+     * @param password The password to send for authentication.
+     */
+    public void setPassword(String password);
+
+    /**
+     * Retrieves the username string that was set by the most recent call to setUsername.
+     *
+     * @return The username set by the setUsername method.
+     */
+    public String getUsername();
+
+    /**
+     * Retrieves the password string that was set by the most recent call to the setPassword method.
+     *
+     * @return The password set by the setPassword method.
+     */
+    public String getPassword();
+
+    /**
+     * Retrieves the SOAP headers that were included in the most recent arriving callback from this Service control.
+     *
+     * @return An array of the SOAP input header elements for this control's most recently receive callback.
+     */
+    public Element[] getInputHeaders();
+
+    /**
+     * Sets the SOAP headers that will be included in the next outgoing method invocation message to the Service
+     * control.
+     *
+     * @param headers An array of the new SOAP output header elements.
+     */
+    public void setOutputHeaders(Element[] headers);
+
+    /**
+     * Sets the timeout for the underlying HttpURLConnection (in millisecs, default is 0 which means no timeout,
+     * negative values are converted to 0).
+     */
+    public void setTimeout(int timeout);
+
+    /**
+     * Gets the timeout that has been set by setTimeout() for the underlying HttpURLConnection (returned in millisecs, a
+     * value of 0 means no timeout).
+     */
+    public int getTimeout();
+
+    /**
+     * Clears all parameters that were set by previous calls to the setOutputHeaders, setPassword, or setUsername
+     * methods.
+     */
+    public void reset();
+
+}

Added: incubator/beehive/trunk/system-controls/src/webservice/org/apache/beehive/controls/system/webservice/generator/ExtensionMaker.java
URL: http://svn.apache.org/viewcvs/incubator/beehive/trunk/system-controls/src/webservice/org/apache/beehive/controls/system/webservice/generator/ExtensionMaker.java?rev=169351&view=auto
==============================================================================
--- incubator/beehive/trunk/system-controls/src/webservice/org/apache/beehive/controls/system/webservice/generator/ExtensionMaker.java (added)
+++ incubator/beehive/trunk/system-controls/src/webservice/org/apache/beehive/controls/system/webservice/generator/ExtensionMaker.java Mon May  9 13:17:58 2005
@@ -0,0 +1,363 @@
+/*
+ * Copyright 2005 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * $Header:$
+ */
+package org.apache.beehive.controls.system.webservice.generator;
+
+import java.io.*;
+import java.util.List;
+
+import javax.jws.WebParam;
+import javax.xml.namespace.QName;
+import javax.xml.rpc.Service;
+import javax.xml.rpc.ServiceFactory;
+import javax.xml.rpc.encoding.TypeMapping;
+
+import org.apache.axis.wsdl.toJava.Namespaces;
+import org.apache.axis.wsdl.toJava.Utils;
+import org.apache.beehive.wsm.axis.ant.WSDLFilter;
+
+import org.apache.beehive.wsm.axis.databinding.SystemTypeLookupService;
+import org.apache.beehive.wsm.model.BeehiveWsMethodMetadata;
+import org.apache.beehive.wsm.model.BeehiveWsParameterMetadata;
+import org.apache.beehive.wsm.model.BeehiveWsTypeMetadata;
+import org.apache.beehive.wsm.model.wsdl.XmlBeanWSDLProcessor;
+
+import org.apache.beehive.wsm.wsdl.WSDLParser;
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.CommandLineParser;
+import org.apache.commons.cli.GnuParser;
+import org.apache.commons.cli.Option;
+import org.apache.commons.cli.OptionBuilder;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.ParseException;
+import org.apache.commons.cli.PosixParser;
+import org.apache.xmlbeans.XmlException;
+
+
+/*******************************************************************************
+ * 
+ * 
+ * @author Jonathan Colwell
+ */
+public class ExtensionMaker {
+
+    private static final String[] standardImports = {
+            "org.apache.beehive.controls.api.bean.ControlExtension",
+            "org.controlhaus.webservice.ServiceControl",
+            "org.controlhaus.webservice.ServiceControl.Location",
+            "org.controlhaus.webservice.ServiceControl.WSDL", };
+
+    File mOutputDir;
+
+    String mWSDLPath = "<path to WSDL>";
+
+    String packageName = null;
+
+    private String serviceURL = null;
+
+    public ExtensionMaker(File outputDir) {
+        mOutputDir = outputDir;
+    }
+
+    public void setWSDLPath(String wsdlPath) {
+        mWSDLPath = wsdlPath.replace('\\', '/');
+    }
+
+    /**
+     * @param serviceURL
+     *            The serviceURL to set.
+     */
+    public void setServiceURL(String serviceURL) {
+        this.serviceURL = serviceURL;
+    }
+
+    public void writeJCX(BeehiveWsTypeMetadata wsm) throws Exception {
+        String serviceName = wsm.getWsServiceName();
+
+        // TODO: Should the class generation depend on Axis?
+        if (packageName == null) {
+            packageName = Utils.makePackageName(wsm.getWsTargetNamespace());
+        }
+        if (serviceName != null && packageName != null) {
+            File subDir = new File(mOutputDir, new Namespaces(null)
+                    .toDir(packageName));
+            subDir.mkdirs();
+            if (subDir.isDirectory()) {
+                File jcx = new File(subDir, serviceName + ".jcx");
+                PrintWriter jcxWriter = new PrintWriter(jcx, "UTF-8");
+
+                jcxWriter.print("package ");
+                jcxWriter.print(packageName);
+                jcxWriter.print(";\n\n");
+
+                for (String imp : standardImports) {
+                    jcxWriter.print("import ");
+                    jcxWriter.print(imp);
+                    jcxWriter.print(";\n");
+                }
+
+                jcxWriter.print("@ControlExtension\n");
+                jcxWriter.print("@Location(urls = {\"");
+                jcxWriter.print(serviceURL);
+                jcxWriter.print("\"})\n");
+                jcxWriter.print("@WSDL(path = \"");
+                jcxWriter.print(mWSDLPath);
+                jcxWriter.print("\",\n\tservice = \"");
+                jcxWriter.print(serviceName);
+                jcxWriter.print("\")\n");
+                jcxWriter.print("\n\npublic interface ");
+                jcxWriter.print(serviceName);
+                jcxWriter.print(" extends ServiceControl {\n\n");
+
+                for (BeehiveWsMethodMetadata method : wsm.getMethods()) {
+                    jcxWriter.print("public ");
+                    // String returnVal = "Object";
+                    // Class javaType = method.getJavaReturnType();
+                    // if (javaType != null) {
+                    // returnVal = getClassName(javaType);
+                    // }
+                    //
+                    // QName q = method.getXmlReturnType();
+                    // if (q != null) {
+                    // returnVal = Utils.makePackageName(q.getNamespaceURI())
+                    // + q.getLocalPart();
+                    // }
+                    //
+                    // jcxWriter.print(returnVal);
+                    jcxWriter.print(method.getJavaReturnTypeFullName());
+                    jcxWriter.write(' ');
+                    jcxWriter.print(method.getWmOperationName());
+                    jcxWriter.write('(');
+                    printParameters(method.getParams(), jcxWriter);
+                    jcxWriter.print(") throws Exception;\n\n");
+                }
+
+                jcxWriter.print("}\n");
+                jcxWriter.close();
+            }
+        }
+    }
+
+    private String getClassName(Class cls) {
+        if (cls.isArray()) {
+            return getClassName(cls.getComponentType()) + "[]";
+        } else {
+            return cls.getName().replace('$', '.');
+        }
+    }
+
+    // NOTE: For OUT and IN/OUT parameters this method can use the GenericHolder
+    // class...TBD
+    private void printParameters(
+           List< ? extends BeehiveWsParameterMetadata> params, PrintWriter pw) {
+        int paramPos = 0;
+        for (BeehiveWsParameterMetadata param : params) {
+            if (paramPos > 0) {
+                pw.print(", ");
+            }
+
+            // String paramType = "Object";
+            // Class javaType = param.getJavaType();
+            // if (javaType != null) {
+            // paramType = getClassName(javaType);
+            // }
+            //
+            // QName q = param.getXmlType();
+            // if (q != null) {
+            // paramType = Utils.makePackageName(q.getNamespaceURI())
+            // + q.getLocalPart();
+            // }
+            //
+            // pw.print(paramType);
+            if( param.getWpMode() == WebParam.Mode.INOUT || param.getWpMode() == WebParam.Mode.OUT)  {
+                pw.print(getHolderForType(param.getJavaType()));
+            } else {
+                pw.print(param.getJavaTypeFullName());
+            }
+            pw.write(' ');
+            String paramName = param.getWpName();
+            if (paramName == null) {
+                paramName = "param" + paramPos;
+            }
+            pw.print(paramName);
+            paramPos++;
+        }
+    }
+
+    private String getHolderForType(Class clazz) {
+       if( clazz == int.class) return "javax.xml.rpc.holders.IntHolder";
+       else if( clazz == boolean.class) return "javax.xml.rpc.holders.BooleanHolder";
+       else if (clazz == new byte[0].getClass()) return "javax.xml.rpc.holders.ByteArrayHolder";
+       else if (clazz == byte.class) return "javax.xml.rpc.holders.ByteHolder";
+       else if (clazz == double.class) return "javax.xml.rpc.holders.DoubleHolder";
+       else if (clazz == float.class) return "javax.xml.rpc.holders.FloatHolder";
+       else if (clazz == long.class) return "javax.xml.rpc.holders.FloatHolder";
+       else if (clazz == short.class) return "javax.xml.rpc.holders.ShortHolder";
+       else     
+       return  "org.apache.beehive.wsm.databinding.GenericHolder<" + clazz.getCanonicalName() + ">";
+    }
+    private static Options buildOptions() {
+        Options options = new Options();
+        OptionBuilder.hasArg();
+        OptionBuilder.withArgName("dir");
+        OptionBuilder.withDescription("Base directory of the wsdl file(s)");
+        OptionBuilder.isRequired(true);
+        Option option = OptionBuilder.create("wsdl");
+        options.addOption(option);
+
+        OptionBuilder.hasArg();
+        OptionBuilder.withArgName("dir");
+        OptionBuilder.withDescription("Root directory for the jcx file.");
+        OptionBuilder.isRequired(true);
+        option = OptionBuilder.create("gen_root");
+        options.addOption(option);
+
+//        OptionBuilder.hasArg();
+//        OptionBuilder.withArgName("URL");
+//        OptionBuilder.withDescription("URL to the web service.");
+//        option = OptionBuilder.create("serviceURL");
+//        OptionBuilder.isRequired(false); // if specified, it will overwrite
+//                                            // the one in WSDL
+//        options.addOption(option);
+
+        OptionBuilder.hasArg();
+        OptionBuilder.withArgName("dir");
+        OptionBuilder.isRequired(false);
+        OptionBuilder.withDescription("path annotation to use in the jcx");
+        option = OptionBuilder.create("wsdl_path_annotation");
+        options.addOption(option);
+
+        OptionBuilder.hasArg();
+        OptionBuilder.withArgName("package_name");
+        OptionBuilder.isRequired(false);
+        OptionBuilder.withDescription("Package name of the jcx");
+        option = OptionBuilder.create("pkg");
+        options.addOption(option);
+
+        return options;
+    }
+
+    public static void main(String[] args) throws Exception {
+
+        String outFileName = null;
+        String wsdlDirName = null;
+        String serviceURL = null;
+        String wsdlPathAnnotation = null;
+        String pkgName = null;
+
+        try {
+            Options options = buildOptions();
+            CommandLineParser parser = new GnuParser();
+            CommandLine line = parser.parse(options, args);
+
+            outFileName = line.getOptionValue("gen_root");
+            wsdlDirName = line.getOptionValue("wsdl");
+//            if (line.hasOption("serviceURL"))
+//                serviceURL = line.getOptionValue("serviceURL");
+            if (line.hasOption("wsdl_path_annotation"))
+                wsdlPathAnnotation = line
+                        .getOptionValue("wsdl_path_annotation");
+
+            if (line.hasOption("pkg"))
+                pkgName = line.getOptionValue("pkg");
+
+        } catch (ParseException exp) {
+            // oops, something went wrong
+            System.err.println("Parsing failed.  Reason: " + exp.getMessage());
+            System.exit(-1);
+        }
+
+        File out = new File(outFileName);
+        ExtensionMaker em = new ExtensionMaker(out);
+
+        em.genJCX(wsdlDirName, serviceURL, pkgName, wsdlPathAnnotation);
+
+    }
+
+    /**
+     * @param wsdlDirName
+     * @param serviceURL
+     * @param pkgName
+     * @param em
+     * @throws IOException
+     * @throws Exception
+     * @throws FileNotFoundException
+     * @throws XmlException
+     * @throws IllegalAccessException
+     * @throws NoSuchFieldException
+     */
+    private void genJCX(String wsdlDirName, String serviceURL, String pkgName,
+            String wsdlPathAnnotation) throws IOException, Exception,
+            FileNotFoundException, XmlException, IllegalAccessException,
+            NoSuchFieldException {
+        setServiceURL(serviceURL);
+        setPackageName(pkgName);
+        File wsdlDir = new File(wsdlDirName);
+        if (wsdlDir.isDirectory()) {
+            for (File wsdlFile : wsdlDir.listFiles(new WSDLFilter())) {
+                genJCXForWSDLFile( wsdlPathAnnotation, wsdlFile);
+            }
+        } else if (wsdlDir.isFile()) {
+            genJCXForWSDLFile(wsdlPathAnnotation, wsdlDir);
+            
+        } else {
+            throw new Exception("no WSDL location specified at: " + wsdlDir.getCanonicalPath());
+        }
+    }
+
+    /**
+     * @param serviceURL
+     * @param wsdlPathAnnotation
+     * @param wsdlFile
+     * @throws IOException
+     * @throws Exception
+     * @throws FileNotFoundException
+     * @throws XmlException
+     * @throws IllegalAccessException
+     * @throws NoSuchFieldException
+     */
+    private void genJCXForWSDLFile(String wsdlPathAnnotation, File wsdlFile) throws IOException, Exception, FileNotFoundException, XmlException, IllegalAccessException, NoSuchFieldException {
+        if (wsdlPathAnnotation != null) {
+            setWSDLPath(wsdlPathAnnotation + "/" + wsdlFile.getName());
+        } else {
+            setWSDLPath(wsdlFile.getCanonicalPath());
+
+        }
+        // get additional wsdl information
+        WSDLParser parser = new WSDLParser(
+                new FileInputStream(wsdlFile));
+//        if (null == serviceURL) { // none has been defined, get it
+//                                    // from wsdl
+//        }
+
+       serviceURL = parser.getSoapAddressLocation();
+	   
+	   
+	   XmlBeanWSDLProcessor wsdlProcessor =  new XmlBeanWSDLProcessor( new FileInputStream(wsdlFile));
+
+	   
+       writeJCX(wsdlProcessor.getObjectModel( new SystemTypeLookupService()));
+    }
+
+    /**
+     * @param packageName
+     *            The packageName to set.
+     */
+    public void setPackageName(String packageName) {
+        this.packageName = packageName;
+    }
+}

Added: incubator/beehive/trunk/system-controls/src/webservice/org/apache/beehive/controls/system/webservice/jaxrpc/HeaderHandler.java
URL: http://svn.apache.org/viewcvs/incubator/beehive/trunk/system-controls/src/webservice/org/apache/beehive/controls/system/webservice/jaxrpc/HeaderHandler.java?rev=169351&view=auto
==============================================================================
--- incubator/beehive/trunk/system-controls/src/webservice/org/apache/beehive/controls/system/webservice/jaxrpc/HeaderHandler.java (added)
+++ incubator/beehive/trunk/system-controls/src/webservice/org/apache/beehive/controls/system/webservice/jaxrpc/HeaderHandler.java Mon May  9 13:17:58 2005
@@ -0,0 +1,189 @@
+/*
+ * Copyright 2005 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * $Header:$
+ */
+package org.apache.beehive.controls.system.webservice.jaxrpc;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+
+import javax.xml.namespace.QName;
+import javax.xml.rpc.handler.Handler;
+import javax.xml.rpc.handler.HandlerInfo;
+import javax.xml.rpc.handler.MessageContext;
+import javax.xml.rpc.handler.soap.SOAPMessageContext;
+import javax.xml.soap.SOAPElement;
+import javax.xml.soap.SOAPEnvelope;
+import javax.xml.soap.SOAPException;
+import javax.xml.soap.SOAPHeader;
+import javax.xml.soap.SOAPHeaderElement;
+import javax.xml.soap.SOAPMessage;
+import javax.xml.soap.SOAPPart;
+
+import org.apache.log4j.Logger;
+import org.w3c.dom.Element;
+
+public class HeaderHandler implements Handler {
+
+    static Logger logger = Logger.getLogger(HeaderHandler.class);
+
+    static ThreadLocal localInHeaders = new ThreadLocal();
+
+    static ThreadLocal localOutHeaders = new ThreadLocal();
+
+    /**
+     * Sign outgoing request message.
+     * 
+     * @throws SOAPException
+     */
+    public boolean handleRequest(MessageContext mc) {
+        System.out.println("In HeaderHandler's handleRequest myOutHeaders: "
+                + localOutHeaders.get());
+
+        try {
+            SOAPMessageContext smc = (SOAPMessageContext) mc;
+            SOAPMessage msg = smc.getMessage();
+            logger.debug("Request message body: "
+                    + msg.getSOAPBody().toString() + "\n header: "
+                    + msg.getSOAPHeader().toString());
+           SOAPPart part = msg.getSOAPPart();
+            SOAPEnvelope envelope = part.getEnvelope();
+            SOAPHeader header = envelope.getHeader();
+
+            /**
+             * Create new header element. We don't specify a role on this header
+             * element, meaning the target role is the "ultimate destination".
+             */
+            Element[] elemsToAdd = (Element[]) localOutHeaders.get();
+
+            if (null == elemsToAdd) {
+                logger.debug("no header to send");
+                return true;
+            }
+            for (Element nxtElement : elemsToAdd) {
+                header
+                        .addChildElement(new org.apache.axis.message.SOAPHeaderElement(
+                                nxtElement)); // NOTE: Axis specific
+            }
+
+        } catch (SOAPException e) {
+            e.printStackTrace();
+            logger.error("Failed to add header.", e);
+        }
+
+        return true;
+    }
+
+    /**
+     * 
+     */
+    static public void reset() {
+        localInHeaders = new ThreadLocal();
+        localOutHeaders = new ThreadLocal();
+
+    }
+
+    /**
+     * Check incoming response message.
+     */
+    public boolean handleResponse(MessageContext mc) {
+        System.out.println("In HeaderHandler's handleResponse");
+
+        try {
+            SOAPMessageContext smc = (SOAPMessageContext) mc;
+            SOAPMessage msg = smc.getMessage();
+            logger.debug("Response message body: "
+                    + msg.getSOAPBody().toString() + "\n header: "
+                    + msg.getSOAPHeader().toString());
+            SOAPPart part = msg.getSOAPPart();
+            SOAPEnvelope envelope = part.getEnvelope();
+            SOAPHeader header = envelope.getHeader();
+            if (header == null)
+                return true;
+
+            Iterator it = header.extractAllHeaderElements();
+            ArrayList<Element> list = new ArrayList<Element>();
+            while (it.hasNext()) {
+                SOAPElement nxtSoapElement = (SOAPElement) it.next();
+                list.add((Element) nxtSoapElement.cloneNode(true));
+            }
+
+            Element[] elems = (Element[]) list
+                    .toArray(new Element[list.size()]); // Use generics
+            localInHeaders.set(elems);
+
+        } catch (SOAPException e) {
+            e.printStackTrace();
+            logger.error("Error extracting the header.", e);
+        }
+
+        logger.debug("myInHeaders: " + localInHeaders.get());
+        return true;
+    }
+
+    /**
+     * Check incoming response message.
+     */
+    public boolean handleFault(MessageContext mc) {
+        System.out.println("In HeaderHandler's handleFault");
+        return true;
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see javax.xml.rpc.handler.Handler#init(javax.xml.rpc.handler.HandlerInfo)
+     */
+    public void init(HandlerInfo arg0) {
+        System.out.println("In HeaderHandler's init");
+
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see javax.xml.rpc.handler.Handler#destroy()
+     */
+    public void destroy() {
+        logger.debug("In HeaderHandler's destroy");
+
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see javax.xml.rpc.handler.Handler#getHeaders()
+     */
+    public QName[] getHeaders() {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    /**
+     * @return Returns the inHeaders.
+     */
+    static public Element[] getInHeaders() {
+        return (Element[]) localInHeaders.get();
+    }
+
+    /**
+     * @param outHeaders
+     *            The outHeaders to set.
+     */
+    static public void setOutHeaders(Element[] outHeaders) {
+        localOutHeaders.set(outHeaders);
+    }
+}
\ No newline at end of file