[jboss-svn-commits] JBL Code SVN: r10049 - in labs/jbossesb/workspace/rsheridan/trunk/product/core: rosetta/src/org/jboss/soa/esb/addressing/eprs and 2 other directories.

jboss-svn-commits at lists.jboss.org jboss-svn-commits at lists.jboss.org
Wed Mar 7 17:31:56 EST 2007


Author: rex.sheridan
Date: 2007-03-07 17:31:56 -0500 (Wed, 07 Mar 2007)
New Revision: 10049

Added:
   labs/jbossesb/workspace/rsheridan/trunk/product/core/listeners/src/org/jboss/soa/esb/listeners/message/ActionBeanConfigurator.java
   labs/jbossesb/workspace/rsheridan/trunk/product/core/rosetta/src/org/jboss/soa/esb/addressing/eprs/FTPEprEditor.java
   labs/jbossesb/workspace/rsheridan/trunk/product/core/rosetta/src/org/jboss/soa/esb/notification/NotifyFTP.java
   labs/jbossesb/workspace/rsheridan/trunk/product/core/rosetta/src/org/jboss/soa/esb/util/BeanConfigurator.java
Removed:
   labs/jbossesb/workspace/rsheridan/trunk/product/core/listeners/src/org/jboss/soa/esb/listeners/message/ActionProcessingPipeline.java
   labs/jbossesb/workspace/rsheridan/trunk/product/core/rosetta/src/org/jboss/soa/esb/notification/NotificationTarget.java
Log:
Commit of bean configuration capabilities

Added: labs/jbossesb/workspace/rsheridan/trunk/product/core/listeners/src/org/jboss/soa/esb/listeners/message/ActionBeanConfigurator.java
===================================================================
--- labs/jbossesb/workspace/rsheridan/trunk/product/core/listeners/src/org/jboss/soa/esb/listeners/message/ActionBeanConfigurator.java	                        (rev 0)
+++ labs/jbossesb/workspace/rsheridan/trunk/product/core/listeners/src/org/jboss/soa/esb/listeners/message/ActionBeanConfigurator.java	2007-03-07 22:31:56 UTC (rev 10049)
@@ -0,0 +1,50 @@
+/**
+ * 
+ */
+package org.jboss.soa.esb.listeners.message;
+
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.jboss.soa.esb.helpers.ConfigTree;
+import org.jboss.soa.esb.helpers.KeyValuePair;
+import org.jboss.soa.esb.listeners.ListenerTagNames;
+import org.jboss.soa.esb.util.BeanConfigurator;
+
+/**
+ * ActionBeanConfigurator was created because ActionMapper flattens the
+ * ConfigTree by promoting child "property" elements to attributes on the parent
+ * element.
+ * 
+ * @author <a href="mailto:rex.sheridan at sapience360.com">Rex Sheridan</a>
+ * 
+ */
+public class ActionBeanConfigurator extends BeanConfigurator {
+
+	/**
+	 * A list of key-value pairs to ignore because they don't actually
+	 * correspond to bean properties.
+	 */
+	private static final List<String> ignored = Arrays.asList("action",
+			ListenerTagNames.ACTION_ELEMENT_TAG,
+			ListenerTagNames.ACTION_CLASS_TAG,
+			ListenerTagNames.PROCESS_METHOD_TAG);
+
+	/**
+	 * @param config
+	 * @param bean
+	 */
+	ActionBeanConfigurator(ConfigTree config, Object bean) {
+		setBean(bean);
+		List<KeyValuePair> pairs = config.attributesAsList();
+		Map<String, String> properties = new HashMap<String, String>();
+		for (KeyValuePair kvp : pairs) {
+			if (!ignored.contains(kvp.getKey())) {
+				properties.put(kvp.getKey(), kvp.getValue());
+			}
+		}
+		setProperties(properties);
+	}
+}

Deleted: labs/jbossesb/workspace/rsheridan/trunk/product/core/listeners/src/org/jboss/soa/esb/listeners/message/ActionProcessingPipeline.java
===================================================================
--- labs/jbossesb/workspace/rsheridan/trunk/product/core/listeners/src/org/jboss/soa/esb/listeners/message/ActionProcessingPipeline.java	2007-03-07 22:13:33 UTC (rev 10048)
+++ labs/jbossesb/workspace/rsheridan/trunk/product/core/listeners/src/org/jboss/soa/esb/listeners/message/ActionProcessingPipeline.java	2007-03-07 22:31:56 UTC (rev 10049)
@@ -1,232 +0,0 @@
-package org.jboss.soa.esb.listeners.message;
-
-import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.util.Observable;
-
-import org.apache.log4j.Logger;
-import org.jboss.soa.esb.ConfigurationException;
-import org.jboss.soa.esb.helpers.ConfigTree;
-import org.jboss.soa.esb.listeners.ListenerTagNames;
-import org.jboss.soa.esb.message.Message;
-
-
-/**
- * Action Processing Pipeline.
- * <p/>
- * Runs a list of action classes on a message
- * 
- * @author <a href="mailto:schifest at heuristica.com.ar">schifest at heuristica.com.ar</a>
- * @since Version 4.0
- */
-public class ActionProcessingPipeline extends Observable implements Runnable 
-{    
-	private boolean processingComplete = false;
-         
-    /**
-     * public constructor
-     * @param message Message - The initial message to be run through the whole action 
-     * class chain
-     */
-    public ActionProcessingPipeline(Message message, ConfigTree config)
-    	throws ConfigurationException
-    {
-    	if (null==message)
-    		throw new IllegalArgumentException("Message must be not null");
-        _message	= message;
-        _config		= config;
-    	if (null==_config)
-    		throw new IllegalArgumentException("Configuration needed for action classes");
-    	_actionList = _config.getChildren(ListenerTagNames.ACTION_ELEMENT_TAG);
-    	if (null==_actionList || _actionList.length<1)
-    		throw new ConfigurationException("No actions in list");
-    }
-    
-    /**
-     * 
-     * @return Message - current Message of this action chain processor
-     */
-    public Message getMessage()     { return _message; }
-
-    /**
-     * Implement Runnable Interface
-     * <p/>Uses reflection to instantiate action classes that must have a public constructor
-     * that takes a single ConfigTree as argument
-     * <p/>Requires each action class to have a public method that takes a Message and returns a Message
-     * <br/>Default name for it is 'process'  but can optionally be defined in the 'process' attribute
-     * of the corresponding &lt;action&gt; element of the ConfigTree
-     * <p/>Each &lt;action&gt; element can optionally define a method (taking a Message argument) to be 
-     * called upon successful completion of the action class (that step of the chain)
-     * <br/>Default name for it is 'process'  but can optionally be defined in the 'process' attribute
-     * <p/>See actionClassException and actionClassFinishedOk
-     * */
-    public void run()
-    {
-        try
-        {
-            // Run the message through each ActionProcessor...
-        	_currentIndex = -1;
-            for(ConfigTree oCurr : _actionList) 
-            {
-            	_currentIndex++;
-            	String attrName = ListenerTagNames.ACTION_CLASS_TAG;
-            	_currentAction = oCurr.getAttribute(attrName);
-            	_currentClass = Class.forName(_currentAction);
-            	Constructor oConst = _currentClass.getConstructor(new Class[] {ConfigTree.class});
-            	_currentProcessor = oConst.newInstance(oCurr);
-
-            	attrName	= ListenerTagNames.PROCESS_METHOD_TAG;
-            	String[] saMethodList = obtainAttribute(oCurr,attrName,attrName).split(",");
-
-            	for (String currMethod : saMethodList)
-            	{
-//                	_logger.debug("Attempting to invoke "+_currentClass.getName()+" method "+currMethod);
-	            	Method method = _currentClass.getMethod(currMethod,new Class[] {Message.class});
-	            	
-	            	// The processing result of each action feeds into the processing of the next action...
-	                try 
-	                {
-	                	Message next = (Message)method.invoke(_currentProcessor,new Object[] {_message} );
-	                    if(next==null)
-	                    {
-	                    	_logger.debug(prematureTermination("returned <null> - Cannot continue"));
-	                    	return;
-	                    }
-	                    _message = next;
-	                }
-	                catch (ClassCastException eCast)
-	                {
-	                	// If action class returns non Message, log and abort chain
-	                	_logger.error(prematureTermination("returned a non Message Object)"));
-	                	return;
-	                }
-	                catch (InvocationTargetException e)
-	                {
-	                	// If action class threw exception, log and abort chain
-	                	_logger.error("Process method threw Exception",e);
-	                    actionClassException(oCurr,_message,e.getCause());
-	                    return;
-	                }
-            	}            	
-                actionClassFinishedOk(oCurr,_message);
-            }
-            // notification of action chain end can be done with a no-operation action class
-            // with a proper ListenerPropertyNames.ACTION_NORMAL_COMPLETION_CALLBACK method
-            // Same idea when some interaction needed with the 'esb unaware' world
-        } 
-        catch(ClassNotFoundException e)
-    	{	_logger.error(prematureTermination("action class is not in path"),e); } 
-        catch(NoSuchMethodException e)
-    	{	_logger.error(prematureTermination("method not found"),e); }
-        catch(InstantiationException e)
-    	{	_logger.error(prematureTermination("cannot instantiate action class"),e); } 
-        catch(InvocationTargetException e)
-    	{	_logger.error(prematureTermination("method not found"),e); } 
-        catch(IllegalAccessException e)
-    	{	_logger.error(prematureTermination("unable to access method"),e); } 
-        catch (IllegalArgumentException e) {
-        	_logger.error(prematureTermination(e.getMessage()),e);
-        } 
-        finally 
-        {
-        	processingComplete = true;
-        	setChanged();
-        	notifyObservers(new Integer(-1));
-        }
-    }
-    
-    protected String prematureTermination(String s)
-    {
-    	return new StringBuilder("Premature termination of action processing pipeline ")
-		.append(getActionNames())
-		.append("].  ActionProcessor [").append(_currentAction)
-		.append("] ").append(s)
-		.toString()
-		;
-    }
-    
-    /**
-     * If 'current' action step was configured with a 'exceptionMethod' attribute
-     * that method will be called with a single argument of type Exception 
-     * @param tree ConfigTree - where to look for the exceptionMetod attribute
-     * @param thrown Exception - to be used in invocation to method (if found)
-     */
-    protected void actionClassException(ConfigTree tree, Message msg,  Throwable thrown)
-    {
-//    	thrown.printStackTrace();
-    	String sMethod = obtainAttribute(tree,ListenerTagNames.EXCEPTION_METHOD_TAG,null);
-    	if (null!=sMethod)
-	    	try
-	    	{
-	    		Method method = _currentClass.getMethod(sMethod,new Class[] {Message.class, Throwable.class});
-	    		method.invoke(_currentProcessor,new Object[] {msg, thrown} );
-	    	}
-	    	catch (NoSuchMethodException e) 	{_logger.error(e); }
-	    	catch (InvocationTargetException e) {_logger.error(e); }
-	    	catch (IllegalAccessException e) 	{_logger.error(e); }
-    }
-
-    /**
-     * If 'current' action step was configured with an 'okMethod' attribute
-     * that method will be called with no arguments 
-     * @param tree ConfigTree - where to look for the okMetod attribute
-     */
-    protected void actionClassFinishedOk(ConfigTree tree,Message msg)
-    {
-    	String sMethod = obtainAttribute(tree,ListenerTagNames.NORMAL_COMPLETION_METHOD_TAG,null);
-    	if (null!=sMethod)
-	    	try
-	    	{
-	    		Method method = _currentClass.getMethod(sMethod,new Class[] {Message.class});
-	    		method.invoke(_currentProcessor,new Object[] {msg} );
-	    	}
-	    	catch (NoSuchMethodException e) 	{_logger.error(e); }
-	    	catch (InvocationTargetException e) {_logger.error(e); }
-	    	catch (IllegalAccessException e) 	{_logger.error(e); }
-    }
-
-    protected String[] getActionNames()
-    {
-    	String[] sa = new String[_actionList.length];
-    	int i1=0;
-    	for (ConfigTree oCurr : _actionList)
-    		sa[i1++]=obtainAttribute(oCurr,ListenerTagNames.ACTION_CLASS_TAG,"NO_CLASSNAME");
-    	return sa;
-    }
-    
-    private static String obtainAttribute(ConfigTree tree,String p_sAtt, String p_sDefault)
-	{
-		String sVal = tree.getAttribute(p_sAtt);
-		return (null != sVal) ? sVal : p_sDefault;
-	} // ________________________________
-	
-    protected ConfigTree[]	_actionList;
-    protected int			_currentIndex;
-    protected String		_currentAction;
-    protected Class 		_currentClass;
-    protected Object		_currentProcessor;
-	protected Message		_message;
-	protected ConfigTree	_config;
-	protected Logger		_logger = Logger.getLogger(this.getClass());
-
-	/**
-	 * @return Returns the processingComplete.
-	 */
-	public boolean isProcessingComplete() {
-		return processingComplete;
-	}
-	
-	/**
-	 * Wait until processing is complete.
-	 */
-	public void waitUntilComplete() {
-		while(!processingComplete) {
-			try {
-				Thread.sleep(50);
-			} catch (InterruptedException e) {
-				_logger.error("Thread Interrupted.", e);
-			}
-		}
-	}
-}

Added: labs/jbossesb/workspace/rsheridan/trunk/product/core/rosetta/src/org/jboss/soa/esb/addressing/eprs/FTPEprEditor.java
===================================================================
--- labs/jbossesb/workspace/rsheridan/trunk/product/core/rosetta/src/org/jboss/soa/esb/addressing/eprs/FTPEprEditor.java	                        (rev 0)
+++ labs/jbossesb/workspace/rsheridan/trunk/product/core/rosetta/src/org/jboss/soa/esb/addressing/eprs/FTPEprEditor.java	2007-03-07 22:31:56 UTC (rev 10049)
@@ -0,0 +1,29 @@
+/**
+ * 
+ */
+package org.jboss.soa.esb.addressing.eprs;
+
+import java.beans.PropertyEditorSupport;
+import java.net.URISyntaxException;
+
+/**
+ * @author <a href="mailto:rex.sheridan at sapience360.com">Rex Sheridan</a>
+ *
+ */
+public class FTPEprEditor extends PropertyEditorSupport {
+
+	/* (non-Javadoc)
+	 * @see java.beans.PropertyEditorSupport#setAsText(java.lang.String)
+	 */
+	@Override
+	public void setAsText(String text) throws IllegalArgumentException {
+		try {
+			setValue(new FTPEpr(text));
+		} catch (URISyntaxException e) {
+			throw new IllegalArgumentException("Invalid EPR specification", e);
+		}
+	}
+
+	
+
+}

Deleted: labs/jbossesb/workspace/rsheridan/trunk/product/core/rosetta/src/org/jboss/soa/esb/notification/NotificationTarget.java
===================================================================
--- labs/jbossesb/workspace/rsheridan/trunk/product/core/rosetta/src/org/jboss/soa/esb/notification/NotificationTarget.java	2007-03-07 22:13:33 UTC (rev 10048)
+++ labs/jbossesb/workspace/rsheridan/trunk/product/core/rosetta/src/org/jboss/soa/esb/notification/NotificationTarget.java	2007-03-07 22:31:56 UTC (rev 10049)
@@ -1,153 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- * Copyright 2006, JBoss Inc., and individual contributors as indicated
- * by the @authors tag. See the copyright.txt in the distribution for a
- * full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed 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. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-
-package org.jboss.soa.esb.notification;
-
-import java.lang.reflect.Constructor;
-
-import org.jboss.soa.esb.ConfigurationException;
-import org.jboss.soa.esb.helpers.ConfigTree;
-
-/**
- * Abstract class to define expected behaviour of all NotificationTargets and
- * provide some common functionality to all of them
- * <p>
- * Description:
- * </p>
- * <p>
- * Heuristica - Buenos Aires - Argentina
- * </p>
- * 
- * @version 1.0
- */
-public abstract class NotificationTarget
-{
-	/**
-	 * Derived classes must implement this method to do what has to be done to
-	 * trigger that specific type of notification event
-	 * 
-	 * @param p_o
-	 *            Object - The toString() method of this object will be the
-	 *            actual notification content
-	 * @throws NotificationException -
-	 *             invoke Exception.getMessage() at runtime for this object
-	 * @see ConfigTree
-	 */
-	public abstract void sendNotification (java.io.Serializable p_o)
-			throws NotificationException;
-
-	private static final String NOTIF_PFX = NotificationTarget.class
-			.getPackage().getName();
-
-	public static final String PRM_NOTIF_CLASS = "class";
-
-	/**
-	 * Common object to hold details of object's information - Each derived
-	 * class will hold it's own needs
-	 */
-	protected ConfigTree m_oParms;
-
-	/**
-	 * Instantiate an empty NotificationTarget object
-	 */
-	protected NotificationTarget ()
-	{
-	}
-
-	/**
-	 * Instantiate a NotificationTarget object with the information contained in
-	 * &lt;arg 1&gt;
-	 * 
-	 * @param p_oP
-	 *            ConfigTree - Holds details to instantiate this object
-	 */
-	protected NotificationTarget (ConfigTree p_oP)
-	{
-		m_oParms = p_oP;
-	} // __________________________________
-
-	/**
-	 * A typical Factory.getInstance() method
-	 * 
-	 * @param p_oP
-	 *            ConfigTree - Contents of this argument will determine the type
-	 *            (derived class) of NotificationTarget returned
-	 * @throws ConfigurationException -
-	 *             Arg 1 does not contain a valid structure for currently
-	 *             implemented NotificationTarget subclasses - invoke
-	 *             Exception.getMessage() at runtime for details
-	 * @return NotificationTarget - An object that instantiates the
-	 *         NotificationTarget abstract class
-	 */
-	public static NotificationTarget fromParams (ConfigTree p_oP)
-			throws ConfigurationException
-	{
-		String sClass = p_oP.getAttribute(PRM_NOTIF_CLASS);
-		if (null == sClass)
-			throw new IllegalArgumentException(
-					"Missing '" + PRM_NOTIF_CLASS + "' attribute in parameters");
-		Class oCls = null;
-		try
-		{
-			oCls = Class.forName(NOTIF_PFX + "." + sClass);
-		}
-		catch (Exception e)
-		{
-			try
-			{
-				oCls = Class.forName(sClass);
-			}
-			catch (Exception e1)
-			{/* oCls will be null */
-			}
-		}
-		if (null == oCls)
-			throw new ConfigurationException(
-					"Invalid class <" + sClass + ">, or missing library");
-
-		Constructor oCons = null;
-		try
-		{
-			oCons = oCls.getConstructor(new Class[] { ConfigTree.class });
-		}
-		catch (Exception e)
-		{
-		}
-		if (null == oCons)
-			throw new ConfigurationException(
-					"No valid constructor " + sClass + "(ConfigTree)");
-
-		Object oRet = null;
-		try
-		{
-			oRet = oCons.newInstance(new Object[] { p_oP });
-		}
-		catch (Exception e)
-		{
-			e.printStackTrace();
-		}
-		if (null == oRet || (!(oRet instanceof NotificationTarget)))
-			throw new ConfigurationException(sClass + "  does not extend NotificationTarget");
-
-		return (NotificationTarget) oRet;
-	} // __________________________________
-} // ____________________________________________________________________________

Added: labs/jbossesb/workspace/rsheridan/trunk/product/core/rosetta/src/org/jboss/soa/esb/notification/NotifyFTP.java
===================================================================
--- labs/jbossesb/workspace/rsheridan/trunk/product/core/rosetta/src/org/jboss/soa/esb/notification/NotifyFTP.java	                        (rev 0)
+++ labs/jbossesb/workspace/rsheridan/trunk/product/core/rosetta/src/org/jboss/soa/esb/notification/NotifyFTP.java	2007-03-07 22:31:56 UTC (rev 10049)
@@ -0,0 +1,144 @@
+/**
+ * 
+ */
+package org.jboss.soa.esb.notification;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.ObjectOutputStream;
+import java.io.OutputStream;
+import java.io.Serializable;
+
+import org.apache.log4j.Logger;
+import org.jboss.soa.esb.addressing.eprs.FTPEpr;
+import org.jboss.soa.esb.util.RemoteFileSystem;
+import org.jboss.soa.esb.util.RemoteFileSystemException;
+import org.jboss.soa.esb.util.RemoteFileSystemFactory;
+
+/**
+ * @author <a href="mailto:rex.sheridan at sapience360.com">Rex Sheridan</a>
+ * 
+ */
+public class NotifyFTP extends NotificationTarget {
+
+	private static final Logger logger = Logger.getLogger(NotifyFTP.class);
+
+	private FTPEpr epr;
+
+	private String fileName;
+
+	/*
+	 * (non-Javadoc)
+	 * 
+	 * @see org.jboss.soa.esb.notification.NotificationTarget#sendNotification(java.io.Serializable)
+	 */
+	@Override
+	public void sendNotification(Serializable value)
+			throws NotificationException {
+
+		OutputStream stream = null;
+		File tmpFile = null;
+		RemoteFileSystem rfs = null;
+		try {
+			rfs = RemoteFileSystemFactory.getRemoteFileSystem(epr, true);
+			tmpFile = File.createTempFile("jbossesb-NotifyFTP", null);
+
+			stream = new FileOutputStream(tmpFile);
+			writeValueToStream(value, stream);
+
+			rfs.uploadFile(tmpFile, fileName);
+
+		} catch (RemoteFileSystemException e) {
+			throw new NotificationException(
+					"Could not complete FTP notification", e);
+		} catch (IOException e) {
+			throw new NotificationException(
+					"Could not complete FTP notification", e);
+		} finally {
+			if (stream != null) {
+				try {
+					stream.close();
+				} catch (IOException e) {
+					logger.error("Unable to close stream", e);
+				}
+			}
+			if (tmpFile != null) {
+				tmpFile.delete();
+			}
+			if (rfs != null) {
+				rfs.quit();
+			}
+		}
+
+	}
+
+	/**
+	 * @param value
+	 * @param stream
+	 * @throws NotificationException
+	 * @throws IOException
+	 */
+	private void writeValueToStream(Serializable value, OutputStream stream)
+			throws NotificationException, IOException {
+		if (value instanceof String) {
+			stringNotification(stream, (String) value);
+		} else {
+			objectNotification(stream, value);
+		}
+		stream.flush();
+		stream.close();
+	}
+
+	private void stringNotification(OutputStream stream, String data)
+			throws NotificationException {
+		try {
+			stream.write(data.getBytes());
+		} catch (Exception e) {
+			throw new NotificationException(
+					"Could not write data to the output stream", e);
+		}
+	}
+
+	private void objectNotification(OutputStream stream, Object value)
+			throws NotificationException {
+		try {
+			ObjectOutputStream objectStream = new ObjectOutputStream(stream);
+			objectStream.writeObject(value);
+		} catch (Exception e) {
+			throw new NotificationException(
+					"Could not write object to the output stream", e);
+		}
+	}
+
+	/**
+	 * @return the epr
+	 */
+	public FTPEpr getEpr() {
+		return epr;
+	}
+
+	/**
+	 * @param epr
+	 *            the epr to set
+	 */
+	public void setEpr(FTPEpr epr) {
+		this.epr = epr;
+	}
+
+	/**
+	 * @return the fileName
+	 */
+	public String getFileName() {
+		return fileName;
+	}
+
+	/**
+	 * @param fileName
+	 *            the fileName to set
+	 */
+	public void setFileName(String fileName) {
+		this.fileName = fileName;
+	}
+
+}

Added: labs/jbossesb/workspace/rsheridan/trunk/product/core/rosetta/src/org/jboss/soa/esb/util/BeanConfigurator.java
===================================================================
--- labs/jbossesb/workspace/rsheridan/trunk/product/core/rosetta/src/org/jboss/soa/esb/util/BeanConfigurator.java	                        (rev 0)
+++ labs/jbossesb/workspace/rsheridan/trunk/product/core/rosetta/src/org/jboss/soa/esb/util/BeanConfigurator.java	2007-03-07 22:31:56 UTC (rev 10049)
@@ -0,0 +1,136 @@
+/**
+ * 
+ */
+package org.jboss.soa.esb.util;
+
+import java.beans.BeanInfo;
+import java.beans.IntrospectionException;
+import java.beans.Introspector;
+import java.beans.PropertyDescriptor;
+import java.beans.PropertyEditor;
+import java.beans.PropertyEditorManager;
+import java.lang.reflect.Method;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import org.jboss.soa.esb.helpers.ConfigTree;
+import org.jboss.soa.esb.helpers.KeyValuePair;
+
+/**
+ * The BeanConfigurator knows how to map a ConfigTree to JavaBean properties.
+ * 
+ * @author <a href="mailto:rex.sheridan at sapience360.com">Rex Sheridan</a>
+ * 
+ */
+public class BeanConfigurator {
+
+	private PropertyDescriptor[] descriptors;
+
+	private Object bean;
+
+	private Map<String, String> properties;
+
+	public BeanConfigurator() {
+		super();
+	}
+
+	public BeanConfigurator(ConfigTree config, Object bean) {
+		List<KeyValuePair> pairs = config.childPropertyList();
+		properties = new HashMap<String, String>();
+		for (KeyValuePair kvp : pairs) {
+			properties.put(kvp.getKey(), kvp.getValue());
+		}
+		this.bean = bean;
+	}
+
+	public BeanConfigurator(Map<String, String> properties, Object bean) {
+		this.properties = properties;
+		this.bean = bean;
+	}
+
+	public void configure() throws IntrospectionException {
+		Class<? extends Object> beanClass = bean.getClass();
+		BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);
+		descriptors = beanInfo.getPropertyDescriptors();
+
+		for (Entry<String, String> entry : properties.entrySet()) {
+			String key = entry.getKey();
+			key = Introspector.decapitalize(key);
+			PropertyDescriptor descriptor = getPropertyDescriptor(key);
+			if (descriptor == null) {
+				throw new IllegalArgumentException("'" + key
+						+ "' property not found on " + beanClass.getName());
+			}
+			setProperty(descriptor, key, entry.getValue());
+		}
+	}
+
+	protected void setProperty(PropertyDescriptor descriptor, String name,
+			String value) {
+		Method setter = descriptor.getWriteMethod();
+		if (setter == null) {
+			throw new IllegalArgumentException("No setter for property ["
+					+ name + "]");
+		}
+
+		Object arg;
+		Class<?> propertyType = descriptor.getPropertyType();
+		PropertyEditor editor = PropertyEditorManager.findEditor(propertyType);
+		if (editor == null) {
+			throw new IllegalArgumentException(
+					"Unable to find suitable property editor for property="
+							+ name + " type=" + propertyType.getName());
+		}
+		editor.setAsText(value);
+		arg = editor.getValue();
+
+		try {
+			setter.invoke(bean, new Object[] { arg });
+		} catch (Exception ex) {
+			throw new RuntimeException("Unable to set property named '+" + name
+					+ "'", ex);
+		}
+	}
+
+	protected PropertyDescriptor getPropertyDescriptor(String name) {
+		for (int i = 0; i < descriptors.length; i++) {
+			if (name.equals(descriptors[i].getName())) {
+				return descriptors[i];
+			}
+		}
+		return null;
+	}
+
+	/**
+	 * @return the bean
+	 */
+	public Object getBean() {
+		return bean;
+	}
+
+	/**
+	 * @param bean
+	 *            the bean to set
+	 */
+	public void setBean(Object bean) {
+		this.bean = bean;
+	}
+
+	/**
+	 * @return the properties
+	 */
+	public Map<String, String> getProperties() {
+		return properties;
+	}
+
+	/**
+	 * @param properties
+	 *            the properties to set
+	 */
+	public void setProperties(Map<String, String> properties) {
+		this.properties = properties;
+	}
+
+}




More information about the jboss-svn-commits mailing list