[jboss-svn-commits] JBL Code SVN: r8933 - in labs/jbossesb/trunk/product/core: listeners/src/org/jboss/soa/esb/listeners/gateway and 6 other directories.
jboss-svn-commits at lists.jboss.org
jboss-svn-commits at lists.jboss.org
Sat Jan 20 04:33:17 EST 2007
Author: mark.little at jboss.com
Date: 2007-01-20 04:33:16 -0500 (Sat, 20 Jan 2007)
New Revision: 8933
Modified:
labs/jbossesb/trunk/product/core/listeners/src/org/jboss/soa/esb/listeners/ListenerManager.java
labs/jbossesb/trunk/product/core/listeners/src/org/jboss/soa/esb/listeners/ListenerManagerFactory.java
labs/jbossesb/trunk/product/core/listeners/src/org/jboss/soa/esb/listeners/ListenerUtil.java
labs/jbossesb/trunk/product/core/listeners/src/org/jboss/soa/esb/listeners/StandAloneBootStrapper.java
labs/jbossesb/trunk/product/core/listeners/src/org/jboss/soa/esb/listeners/gateway/GatewayListenerController.java
labs/jbossesb/trunk/product/core/listeners/src/org/jboss/soa/esb/listeners/gateway/JmsGatewayListener.java
labs/jbossesb/trunk/product/core/listeners/src/org/jboss/soa/esb/listeners/gateway/SqlTableGatewayListener.java
labs/jbossesb/trunk/product/core/listeners/src/org/jboss/soa/esb/listeners/message/MessageAwareListener.java
labs/jbossesb/trunk/product/core/rosetta/src/org/jboss/internal/soa/esb/command/JmsCommandQueue.java
labs/jbossesb/trunk/product/core/rosetta/src/org/jboss/internal/soa/esb/couriers/JmsCourier.java
labs/jbossesb/trunk/product/core/rosetta/src/org/jboss/internal/soa/esb/couriers/SqlTableCourier.java
labs/jbossesb/trunk/product/core/rosetta/src/org/jboss/internal/soa/esb/util/EdtFtpImpl.java
labs/jbossesb/trunk/product/core/rosetta/src/org/jboss/soa/esb/helpers/ConfigTree.java
labs/jbossesb/trunk/product/core/rosetta/src/org/jboss/soa/esb/helpers/persist/JdbcCleanConn.java
labs/jbossesb/trunk/product/core/rosetta/src/org/jboss/soa/esb/helpers/persist/SimpleDataSource.java
Log:
Method signature changes for finer granularity exceptions.
Modified: labs/jbossesb/trunk/product/core/listeners/src/org/jboss/soa/esb/listeners/ListenerManager.java
===================================================================
--- labs/jbossesb/trunk/product/core/listeners/src/org/jboss/soa/esb/listeners/ListenerManager.java 2007-01-20 09:09:48 UTC (rev 8932)
+++ labs/jbossesb/trunk/product/core/listeners/src/org/jboss/soa/esb/listeners/ListenerManager.java 2007-01-20 09:33:16 UTC (rev 8933)
@@ -45,9 +45,9 @@
public static final SimpleDateFormat s_oDateParse = new SimpleDateFormat("yyyyMMdd hh:mm:ss");
// Will return when all controlled processes are up and running (max 20 seconds)
- public void waitUntilReady() throws Exception;
+ public void waitUntilReady() throws InterruptedException;
// Will return when all controlled processes are up and running (max = arg0)
- public void waitUntilReady(long maxWaitMillis) throws Exception;
+ public void waitUntilReady(long maxWaitMillis) throws InterruptedException;
// Method to request an orderly shutdown of the managing process and it's children
public abstract void requestEnd();
// Child threads will invoke this method to continue or end their own process
Modified: labs/jbossesb/trunk/product/core/listeners/src/org/jboss/soa/esb/listeners/ListenerManagerFactory.java
===================================================================
--- labs/jbossesb/trunk/product/core/listeners/src/org/jboss/soa/esb/listeners/ListenerManagerFactory.java 2007-01-20 09:09:48 UTC (rev 8932)
+++ labs/jbossesb/trunk/product/core/listeners/src/org/jboss/soa/esb/listeners/ListenerManagerFactory.java 2007-01-20 09:33:16 UTC (rev 8933)
@@ -1,6 +1,8 @@
package org.jboss.soa.esb.listeners;
+import org.jboss.internal.soa.esb.command.CommandQueueException;
import org.jboss.internal.soa.esb.listeners.DefaultListenerManager;
+import org.jboss.soa.esb.ConfigurationException;
import org.jboss.soa.esb.helpers.ConfigTree;
public class ListenerManagerFactory
@@ -11,14 +13,28 @@
public static ListenerManagerFactory getInstance() {return _instance; }
public ListenerManager getListenerManager(String parametersName)
- throws Exception
+ throws ConfigurationException
{
- return new DefaultListenerManager(parametersName);
+ try
+ {
+ return new DefaultListenerManager(parametersName);
+ }
+ catch (CommandQueueException ex)
+ {
+ throw new ConfigurationException(ex);
+ }
}
public ListenerManager getListenerManager(ConfigTree tree)
- throws Exception
+ throws ConfigurationException
{
- return new DefaultListenerManager(tree);
+ try
+ {
+ return new DefaultListenerManager(tree);
+ }
+ catch (CommandQueueException ex)
+ {
+ throw new ConfigurationException(ex);
+ }
}
}
Modified: labs/jbossesb/trunk/product/core/listeners/src/org/jboss/soa/esb/listeners/ListenerUtil.java
===================================================================
--- labs/jbossesb/trunk/product/core/listeners/src/org/jboss/soa/esb/listeners/ListenerUtil.java 2007-01-20 09:09:48 UTC (rev 8932)
+++ labs/jbossesb/trunk/product/core/listeners/src/org/jboss/soa/esb/listeners/ListenerUtil.java 2007-01-20 09:33:16 UTC (rev 8933)
@@ -23,23 +23,28 @@
package org.jboss.soa.esb.listeners;
import java.io.File;
+import java.net.MalformedURLException;
+import java.net.URISyntaxException;
import java.net.URL;
import java.util.Collection;
import org.apache.log4j.Logger;
import org.jboss.soa.esb.ConfigurationException;
import org.jboss.soa.esb.addressing.EPR;
+import org.jboss.soa.esb.addressing.MalformedEPRException;
import org.jboss.soa.esb.addressing.eprs.FTPEpr;
import org.jboss.soa.esb.addressing.eprs.FileEpr;
import org.jboss.soa.esb.addressing.eprs.JDBCEpr;
import org.jboss.soa.esb.addressing.eprs.JMSEpr;
import org.jboss.soa.esb.couriers.Courier;
+import org.jboss.soa.esb.couriers.CourierException;
import org.jboss.soa.esb.couriers.CourierFactory;
import org.jboss.soa.esb.couriers.CourierUtil;
import org.jboss.soa.esb.helpers.ConfigTree;
import org.jboss.soa.esb.helpers.NamingContext;
import org.jboss.soa.esb.message.Message;
import org.jboss.soa.esb.services.registry.Registry;
+import org.jboss.soa.esb.services.registry.RegistryException;
import org.jboss.soa.esb.services.registry.RegistryFactory;
import org.jboss.soa.esb.util.Util;
@@ -63,10 +68,11 @@
* current thread - flow control will only return to invoker once
* the controller's run() method has finished
* @return ListenerManager
- * @throws Exception
+ * @throws ConfigurationException
*/
+
public static ListenerManager launchManager(String parametersName,
- boolean inNewThread) throws Exception
+ boolean inNewThread) throws ConfigurationException
{
ListenerManager manager = ListenerManagerFactory.getInstance()
.getListenerManager(parametersName);
@@ -86,10 +92,10 @@
* current thread - flow control will only return to invoker once
* the controller's run() method has finished
* @return ListenerManager
- * @throws Exception
+ * @throws ConfigurationException
*/
public static ListenerManager launchManager(ConfigTree tree,
- boolean inNewThread) throws Exception
+ boolean inNewThread) throws ConfigurationException
{
ListenerManager manager = ListenerManagerFactory.getInstance()
.getListenerManager(tree);
@@ -126,7 +132,7 @@
} // ________________________________
public static EPR tryToDeliver(Message message, String category, String name)
- throws Exception
+ throws CourierException, RegistryException, MalformedEPRException
{
Courier courier = null;
Registry reg = RegistryFactory.getRegistry();
@@ -150,7 +156,7 @@
String txt = (null == all || all.size() < 1) ? "No EPRs registered for "
+ service
: "Unable to deliver message to registered EPRs for " + service;
- throw new Exception(txt);
+ throw new CourierException(txt);
} // ________________________________
public static EPR assembleEpr(ConfigTree tree)
@@ -223,123 +229,141 @@
}
} // ________________________________
- public static FileEpr fileEprFromElement(ConfigTree tree) throws Exception
+ public static FileEpr fileEprFromElement(ConfigTree tree) throws ConfigurationException
{
- URL url = new URL(tree.getAttribute(ListenerTagNames.URL_TAG, null));
- String protocol = url.getProtocol();
-
- if ("file".equals(protocol))
+ try
{
- if (!new File(url.getFile()).isDirectory())
- throw new ConfigurationException("Attribute "
- + ListenerTagNames.URL_TAG
- + " must reference a directory");
+ URL url = new URL(tree.getAttribute(ListenerTagNames.URL_TAG, null));
+ String protocol = url.getProtocol();
+
+ if ("file".equals(protocol))
+ {
+ if (!new File(url.getFile()).isDirectory())
+ throw new ConfigurationException("Attribute "
+ + ListenerTagNames.URL_TAG
+ + " must reference a directory");
+ }
+
+ FileEpr epr = ("file".equals(protocol)) ? new FileEpr(url) : ("ftp"
+ .equals(protocol)) ? new FTPEpr(url) : null;
+ if (null == epr)
+ throw new ConfigurationException("Unsupported file protocol : "
+ + protocol);
+
+ String inputSuffix = tree.getAttribute(FileEpr.INPUT_SUFFIX_TAG);
+
+ if (!Util.isNullString(inputSuffix))
+ epr.setInputSuffix(inputSuffix);
+
+ boolean bErrorDel = Boolean.parseBoolean(getAttrAndWarn(tree,
+ FileEpr.ERROR_DEL_TAG, "true"));
+ String errorDir = tree.getAttribute(FileEpr.ERROR_DIR_TAG);
+ String errorSuffix = tree.getAttribute(FileEpr.ERROR_SUFFIX_TAG);
+
+ if (bErrorDel)
+ {
+ if (null != errorDir || null != errorSuffix)
+ _logger
+ .warn("If you don't specify "
+ + FileEpr.ERROR_DEL_TAG
+ + "'false' ,"
+ + FileEpr.ERROR_DIR_TAG
+ + " and "
+ + FileEpr.ERROR_SUFFIX_TAG
+ + " will have no effect because files in error will be deleted");
+ }
+ if (null == errorDir)
+ {
+ errorDir = url.getFile();
+ warnDefault(FileEpr.ERROR_DIR_TAG, errorDir);
+ }
+ if (null == errorSuffix)
+ {
+ errorSuffix = ".esbERROR";
+ warnDefault(FileEpr.ERROR_SUFFIX_TAG, errorSuffix);
+ }
+ epr.setErrorDelete(bErrorDel);
+ epr.setErrorDirectory(errorDir);
+ epr.setErrorSuffix(errorSuffix);
+
+ boolean bPostDel = Boolean.parseBoolean(getAttrAndWarn(tree,
+ FileEpr.POST_DEL_TAG, "true"));
+
+ String postDir = tree.getAttribute(FileEpr.POST_DIR_TAG);
+ String postSuffix = tree.getAttribute(FileEpr.POST_SUFFIX_TAG);
+ if (bPostDel)
+ {
+ if (null != postDir || null != postSuffix)
+ _logger
+ .warn("If you don't specify "
+ + FileEpr.POST_DEL_TAG
+ + "'false' ,"
+ + FileEpr.POST_DIR_TAG
+ + " and "
+ + FileEpr.POST_SUFFIX_TAG
+ + " will have no effect because processed input messages will be deleted");
+ }
+ if (null == postDir)
+ {
+ postDir = url.getFile();
+ warnDefault(FileEpr.POST_DIR_TAG, postDir);
+ }
+ if (null == postSuffix)
+ {
+ postSuffix = ".esbDONE";
+ warnDefault(FileEpr.POST_SUFFIX_TAG, postSuffix);
+ }
+ epr.setPostDelete(bPostDel);
+ epr.setPostDirectory(postDir);
+ epr.setPostSuffix(postSuffix);
+
+ if (epr instanceof FTPEpr)
+ {
+ FTPEpr ftp = (FTPEpr) epr;
+ ftp.setPassive(Boolean.valueOf(getAttrAndWarn(tree,
+ FTPEpr.PASSIVE_TAG, "false")));
+ }
+ return epr;
}
-
- FileEpr epr = ("file".equals(protocol)) ? new FileEpr(url) : ("ftp"
- .equals(protocol)) ? new FTPEpr(url) : null;
- if (null == epr)
- throw new ConfigurationException("Unsupported file protocol : "
- + protocol);
-
- String inputSuffix = tree.getAttribute(FileEpr.INPUT_SUFFIX_TAG);
-
- if (!Util.isNullString(inputSuffix))
- epr.setInputSuffix(inputSuffix);
-
- boolean bErrorDel = Boolean.parseBoolean(getAttrAndWarn(tree,
- FileEpr.ERROR_DEL_TAG, "true"));
- String errorDir = tree.getAttribute(FileEpr.ERROR_DIR_TAG);
- String errorSuffix = tree.getAttribute(FileEpr.ERROR_SUFFIX_TAG);
-
- if (bErrorDel)
+ catch (URISyntaxException ex)
{
- if (null != errorDir || null != errorSuffix)
- _logger
- .warn("If you don't specify "
- + FileEpr.ERROR_DEL_TAG
- + "'false' ,"
- + FileEpr.ERROR_DIR_TAG
- + " and "
- + FileEpr.ERROR_SUFFIX_TAG
- + " will have no effect because files in error will be deleted");
+ throw new ConfigurationException(ex);
}
- if (null == errorDir)
+ catch (MalformedURLException ex)
{
- errorDir = url.getFile();
- warnDefault(FileEpr.ERROR_DIR_TAG, errorDir);
+ throw new ConfigurationException(ex);
}
- if (null == errorSuffix)
- {
- errorSuffix = ".esbERROR";
- warnDefault(FileEpr.ERROR_SUFFIX_TAG, errorSuffix);
- }
- epr.setErrorDelete(bErrorDel);
- epr.setErrorDirectory(errorDir);
- epr.setErrorSuffix(errorSuffix);
-
- boolean bPostDel = Boolean.parseBoolean(getAttrAndWarn(tree,
- FileEpr.POST_DEL_TAG, "true"));
-
- String postDir = tree.getAttribute(FileEpr.POST_DIR_TAG);
- String postSuffix = tree.getAttribute(FileEpr.POST_SUFFIX_TAG);
- if (bPostDel)
- {
- if (null != postDir || null != postSuffix)
- _logger
- .warn("If you don't specify "
- + FileEpr.POST_DEL_TAG
- + "'false' ,"
- + FileEpr.POST_DIR_TAG
- + " and "
- + FileEpr.POST_SUFFIX_TAG
- + " will have no effect because processed input messages will be deleted");
- }
- if (null == postDir)
- {
- postDir = url.getFile();
- warnDefault(FileEpr.POST_DIR_TAG, postDir);
- }
- if (null == postSuffix)
- {
- postSuffix = ".esbDONE";
- warnDefault(FileEpr.POST_SUFFIX_TAG, postSuffix);
- }
- epr.setPostDelete(bPostDel);
- epr.setPostDirectory(postDir);
- epr.setPostSuffix(postSuffix);
-
- if (epr instanceof FTPEpr)
- {
- FTPEpr ftp = (FTPEpr) epr;
- ftp.setPassive(Boolean.valueOf(getAttrAndWarn(tree,
- FTPEpr.PASSIVE_TAG, "false")));
- }
- return epr;
} // ________________________________
- public static JDBCEpr jdbcEprFromElement(ConfigTree tree) throws Exception
+ public static JDBCEpr jdbcEprFromElement(ConfigTree tree) throws ConfigurationException
{
String url = tree.getAttribute(JDBCEpr.URL_TAG, null);
if (!url.toLowerCase().startsWith("jdbc"))
throw new ConfigurationException("URL in "
+ ListenerTagNames.URL_TAG + " must be a jdbc URL");
- boolean bPostDel = Boolean.valueOf(tree.getAttribute(
- JDBCEpr.POST_DEL_TAG, "true"));
- boolean bErrorDel = Boolean.valueOf(tree.getAttribute(
- JDBCEpr.ERROR_DEL_TAG, "true"));
- JDBCEpr epr = new JDBCEpr(url, bPostDel, bErrorDel);
- epr.setDriver(tree.getAttribute(JDBCEpr.DRIVER_TAG, null));
- epr.setUserName(getAttrAndWarn(tree, JDBCEpr.USERNAME_TAG, ""));
- epr.setPassword(getAttrAndWarn(tree, JDBCEpr.PASSWORD_TAG, ""));
- epr.setTableName(tree.getAttribute(JDBCEpr.TABLE_NAME_TAG, null));
- epr.setMessageIdColumn(getColName(tree, JDBCEpr.MESSAGE_ID_COLUMN_TAG));
- epr.setStatusColumn(getColName(tree, JDBCEpr.STATUS_COLUMN_TAG));
- epr.setDataColumn(getColName(tree, JDBCEpr.DATA_COLUMN_TAG));
- epr.setTimestampColumn(getColName(tree, JDBCEpr.TIMESTAMP_COLUMN_TAG));
-
- return epr;
+ try
+ {
+ boolean bPostDel = Boolean.valueOf(tree.getAttribute(
+ JDBCEpr.POST_DEL_TAG, "true"));
+ boolean bErrorDel = Boolean.valueOf(tree.getAttribute(
+ JDBCEpr.ERROR_DEL_TAG, "true"));
+ JDBCEpr epr = new JDBCEpr(url, bPostDel, bErrorDel);
+ epr.setDriver(tree.getAttribute(JDBCEpr.DRIVER_TAG, null));
+ epr.setUserName(getAttrAndWarn(tree, JDBCEpr.USERNAME_TAG, ""));
+ epr.setPassword(getAttrAndWarn(tree, JDBCEpr.PASSWORD_TAG, ""));
+ epr.setTableName(tree.getAttribute(JDBCEpr.TABLE_NAME_TAG, null));
+ epr.setMessageIdColumn(getColName(tree, JDBCEpr.MESSAGE_ID_COLUMN_TAG));
+ epr.setStatusColumn(getColName(tree, JDBCEpr.STATUS_COLUMN_TAG));
+ epr.setDataColumn(getColName(tree, JDBCEpr.DATA_COLUMN_TAG));
+ epr.setTimestampColumn(getColName(tree, JDBCEpr.TIMESTAMP_COLUMN_TAG));
+
+ return epr;
+ }
+ catch (URISyntaxException ex)
+ {
+ throw new ConfigurationException(ex);
+ }
} // ________________________________
private static final String s_Sfx = "_column";
Modified: labs/jbossesb/trunk/product/core/listeners/src/org/jboss/soa/esb/listeners/StandAloneBootStrapper.java
===================================================================
--- labs/jbossesb/trunk/product/core/listeners/src/org/jboss/soa/esb/listeners/StandAloneBootStrapper.java 2007-01-20 09:09:48 UTC (rev 8932)
+++ labs/jbossesb/trunk/product/core/listeners/src/org/jboss/soa/esb/listeners/StandAloneBootStrapper.java 2007-01-20 09:33:16 UTC (rev 8933)
@@ -25,34 +25,38 @@
import java.io.File;
import org.apache.log4j.Logger;
+import org.jboss.soa.esb.ConfigurationException;
import org.jboss.soa.esb.listeners.config.ConfigurationController;
import org.jboss.soa.esb.listeners.gateway.GatewayListenerController;
-
public class StandAloneBootStrapper
-{
- private ConfigurationController _confController;
- private ListenerManager _manager;
- private GatewayListenerController _gatewayController;
+{
+ private ConfigurationController _confController;
- private static Logger _logger = Logger.getLogger(StandAloneBootStrapper.class);
-
- public static void main(String[] args) throws Exception
+ private ListenerManager _manager;
+
+ private GatewayListenerController _gatewayController;
+
+ private static Logger _logger = Logger
+ .getLogger(StandAloneBootStrapper.class);
+
+ public static void main (String[] args) throws Exception
{
Exception eT = null;
if (args.length < 1)
{
- eT = new Exception ("No configuration file specified - Ending immediately");
+ eT = new Exception(
+ "No configuration file specified - Ending immediately");
_logger.fatal(eT);
throw eT;
}
StandAloneBootStrapper boot = null;
String configName = args[0];
- long lSecondsToRun = 365 * 24 * 3600; // run for 1 year (is it enough ?)
- if (args.length > 1)
- try
- {
+ long lSecondsToRun = 365 * 24 * 3600; // run for 1 year (is it enough
+ // ?)
+ if (args.length > 1) try
+ {
lSecondsToRun = Long.parseLong(args[1]);
}
catch (Exception e)
@@ -63,112 +67,158 @@
try
{
boot = new StandAloneBootStrapper(configName);
- if (lSecondsToRun < 5)
- lSecondsToRun = 5;
- long lRunTo = System.currentTimeMillis()+1000*lSecondsToRun;
+ if (lSecondsToRun < 5) lSecondsToRun = 5;
+ long lRunTo = System.currentTimeMillis() + 1000 * lSecondsToRun;
while (System.currentTimeMillis() < lRunTo)
- try { Thread.sleep(1000); }
- catch (InterruptedException e) { break; }
- }
- finally
+ {
+ try
+ {
+ Thread.sleep(1000);
+ }
+ catch (InterruptedException e)
+ {
+ break;
+ }
+ }
+ } finally
{
- if (null!=boot)
- boot.requestEnd();
+ if (null != boot) boot.requestEnd();
}
}
-
- public StandAloneBootStrapper (String configName) throws Exception
+
+ public StandAloneBootStrapper (String configName) throws ConfigurationException
{
this(configName, null);
}
-
- public StandAloneBootStrapper (String configName, String validationFileName) throws Exception
+
+ public StandAloneBootStrapper (String configName, String validationFileName)
+ throws ConfigurationException
{
runBefore();
- String listenerConfig ="jbossesb-listener.xml";
- String gatewayConfig ="jbossesb-gateway.xml";
+ // TODO hardwired names?
+ String listenerConfig = "jbossesb-listener.xml";
+ String gatewayConfig = "jbossesb-gateway.xml";
+
try
{
File configFile = new File(configName);
String sParent = configFile.getParent();
- if (null==sParent)
- sParent=new File("").getAbsolutePath();
- else if (sParent.endsWith("/.") || sParent.endsWith("\\."))
- sParent = sParent.substring(0,-2+sParent.length());
- configFile = new File(sParent,configFile.getName());
+ if (null == sParent) sParent = new File("").getAbsolutePath();
+ else
+ if (sParent.endsWith("/.") || sParent.endsWith("\\."))
+ sParent = sParent.substring(0, -2 + sParent.length());
+ configFile = new File(sParent, configFile.getName());
- _confController = initiateController(configFile.getAbsolutePath(), validationFileName, gatewayConfig,listenerConfig);
+ _confController = initiateController(configFile.getAbsolutePath(),
+ validationFileName, gatewayConfig, listenerConfig);
- listenerConfig = new File(sParent,listenerConfig).getAbsolutePath();
- _logger.debug("starting message aware listener with config file - " +listenerConfig);
+ listenerConfig = new File(sParent, listenerConfig)
+ .getAbsolutePath();
+ _logger
+ .debug("starting message aware listener with config file - " + listenerConfig);
_manager = ListenerUtil.launchManager(listenerConfig, true);
_manager.waitUntilReady();
- gatewayConfig = new File(sParent,gatewayConfig).getAbsolutePath();
- _logger.info("starting gateway listener with config file - " + gatewayConfig);
+ gatewayConfig = new File(sParent, gatewayConfig).getAbsolutePath();
+ _logger
+ .info("starting gateway listener with config file - " + gatewayConfig);
_gatewayController = new GatewayListenerController(gatewayConfig);
new Thread(_gatewayController).start();
- System.out.println("**Listeners Ready**");
+
+ _logger.info("Listeners Ready");
}
- catch (Exception e)
+ catch (ConfigurationException ex)
{
requestEnd();
- throw new Exception("Cannot instantiate "+this.getClass().getSimpleName(),e);
- }
+
+ throw ex;
+ }
+ catch (InterruptedException e)
+ {
+ requestEnd();
+
+ throw new ConfigurationException("Thread interrupted", e);
+ }
+ catch (Exception ex)
+ {
+ requestEnd();
+
+ throw new ConfigurationException("Cannot instantiate "+this.getClass().getSimpleName(),ex);
+ }
- } //________________________________
-
- public void requestEnd()
+ } // ________________________________
+
+ public void requestEnd ()
{
- if (null!= _gatewayController)
- _gatewayController.requestEnd();
- if (null!= _manager)
- _manager.requestEnd();
- if (null!= _confController)
- _confController.requestEnd();
+ if (null != _gatewayController) _gatewayController.requestEnd();
+ if (null != _manager) _manager.requestEnd();
+ if (null != _confController) _confController.requestEnd();
runAfter();
- } //________________________________
-
- protected void runBefore() {} // placeholder for classes that extend this bootstrapper
- protected void runAfter () {} // placeholder for classes that extend this bootstrapper
-
- public ConfigurationController initiateController(String configName, String validationName, String gwConf, String esbConf)
- throws Exception
+ } // ________________________________
+
+ protected void runBefore ()
{
- if (null==configName)
- throw new IllegalArgumentException("Null configuration file specified");
-
+ } // placeholder for classes that extend this bootstrapper
+
+ protected void runAfter ()
+ {
+ } // placeholder for classes that extend this bootstrapper
+
+ public ConfigurationController initiateController (String configName,
+ String validationName, String gwConf, String esbConf)
+ throws ConfigurationException
+ {
+ if (null == configName)
+ throw new IllegalArgumentException(
+ "Null configuration file specified");
+
File configFile = new File(configName);
if (!configFile.exists())
- throw new IllegalArgumentException("Missing esb configuration file: "+configFile);
-
- //Remove the listener and gateway configuration files if the exist
+ throw new IllegalArgumentException(
+ "Missing esb configuration file: " + configFile);
+
+ // Remove the listener and gateway configuration files if the exist
File configDir = configFile.getParentFile();
- if (null==configDir)
- configDir=new File("");
- File listenerFile = new File(configDir,esbConf);
- if (listenerFile.exists()) {
+ if (null == configDir) configDir = new File("");
+ File listenerFile = new File(configDir, esbConf);
+ if (listenerFile.exists())
+ {
listenerFile.delete();
}
- File gatewayFile = new File(configDir,gwConf);
- if (gatewayFile.exists()) {
+ File gatewayFile = new File(configDir, gwConf);
+ if (gatewayFile.exists())
+ {
gatewayFile.delete();
}
- ConfigurationController conf = new ConfigurationController(configFile.toString(), validationName);
+ ConfigurationController conf = new ConfigurationController(configFile
+ .toString(), validationName);
new Thread(conf).start();
- for (int i1=0; i1<10; i1++)
+ boolean terminate = false;
+
+ for (int i1 = 0; (i1 < 10) && !terminate; i1++)
{
if (listenerFile.exists() && gatewayFile.exists())
return conf;
else
- Thread.sleep(800);
+ {
+ try
+ {
+ Thread.sleep(800); // TODO magic number
+ }
+ catch (InterruptedException ex)
+ {
+ terminate = true;
+ }
+ }
}
+
conf.requestEnd();
- throw new Exception("Unable to generate gateway and listener configurations");
- } //________________________________
+ throw new ConfigurationException(
+ "Unable to generate gateway and listener configurations");
+ } // ________________________________
}
Modified: labs/jbossesb/trunk/product/core/listeners/src/org/jboss/soa/esb/listeners/gateway/GatewayListenerController.java
===================================================================
--- labs/jbossesb/trunk/product/core/listeners/src/org/jboss/soa/esb/listeners/gateway/GatewayListenerController.java 2007-01-20 09:09:48 UTC (rev 8932)
+++ labs/jbossesb/trunk/product/core/listeners/src/org/jboss/soa/esb/listeners/gateway/GatewayListenerController.java 2007-01-20 09:33:16 UTC (rev 8933)
@@ -25,6 +25,7 @@
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
+import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
@@ -59,7 +60,7 @@
private static String _sRldSecs = null;
- public static void main(String[] args) throws Exception
+ public static void main (String[] args) throws Exception
{
GatewayListenerController oProc = new GatewayListenerController(args[0]);
oProc.run();
@@ -96,12 +97,12 @@
* @return Map - a shallow copy of the attributes Map
*/
@SuppressWarnings("unchecked")
- public Map<String, Object> getControllerAttributes()
+ public Map<String, Object> getControllerAttributes ()
{
return (Map<String, Object>) _attributes.clone();
}
- public State getState()
+ public State getState ()
{
return _status;
}
@@ -113,12 +114,12 @@
Exception m_oException = null;
- public int getCompletionCode()
+ public int getCompletionCode ()
{
return m_iCompletionCode;
};
- public Exception getException()
+ public Exception getException ()
{
return m_oException;
}
@@ -127,7 +128,7 @@
/**
* Package private default constructor.
*/
- protected GatewayListenerController()
+ protected GatewayListenerController ()
{
}
@@ -137,10 +138,10 @@
*
* @param p_sParameterName
* Name of the Repository entry containing the configuration.
- * @throws Exception
+ * @throws ConfigurationException
* Unable to load/use the named configuration.
*/
- public GatewayListenerController(String p_sParameterName) throws Exception
+ public GatewayListenerController (String p_sParameterName) throws ConfigurationException, IOException, ParamRepositoryException, SAXException
{
this(GatewayListenerController.getListenerConfig(p_sParameterName));
_sParametersName = p_sParameterName;
@@ -151,10 +152,10 @@
*
* @param config
* The configuration.
- * @throws Exception
+ * @throws ConfigurationException
* Unable to load/use the supplied configuration.
*/
- public GatewayListenerController(ConfigTree config) throws Exception
+ public GatewayListenerController (ConfigTree config) throws ConfigurationException
{
_config = config;
_status = State.Loading_parameters;
@@ -163,16 +164,15 @@
{
checkParms(_config);
}
- catch (Exception e)
+ catch (ConfigurationException e)
{
String configSource = config.getAttribute("configSource");
_status = State.Exception_thrown;
_status.m_oException = e;
_logger
.fatal(
- "Listener configuration and startup error. Config Source: "
- + (configSource != null ? configSource
- : "unknown"), e);
+ "Listener configuration and startup error. Config Source: " + (configSource != null ? configSource : "unknown"),
+ e);
throw e;
}
}
@@ -192,7 +192,7 @@
* @throws SAXException
* Unable to parse the configuration.
*/
- private static ConfigTree getListenerConfig(String reposParam)
+ private static ConfigTree getListenerConfig (String reposParam)
throws IOException, ParamRepositoryException, SAXException
{
String sXml = ParamRepositoryFactory.getInstance().get(reposParam);
@@ -210,11 +210,11 @@
* @param p_oP
* ConfigTree - Where to look for the mandatory/optional
* configuration attributes
- * @throws Exception -
+ * @throws ConfigurationException -
* If attributes are wrong or not enough for a proper runtime
* configuration
*/
- public void checkParms(ConfigTree p_oP) throws Exception
+ public void checkParms (ConfigTree p_oP) throws ConfigurationException
{
// We've just loaded - set to false until next reload requested
_reloadRequested = false;
@@ -225,29 +225,38 @@
_paramFileTimeStamps.put(_sParametersName, file.lastModified());
}
- _commandQueue = createCommandQueue(p_oP);
-
- // Open the command queue...
- if (null != _commandQueue)
- _commandQueue.open(p_oP);
-
- setNextReloadTime(p_oP);
- // if END_TIME_TAG not set try to run forever
- // not a good practice if command queue is not set
- // Expected date format is "yyyyMMdd hh:mm:ss"
- String sEndT = p_oP.getAttribute(END_TIME_TAG);
- _endTime = (null == sEndT) ? Long.MAX_VALUE : _dateFormat.parse(sEndT)
- .getTime();
-
- if (null == sEndT)
+ try
{
- String sMsg = (null == _commandQueue) ? " - Listener will run until parent container/process terminates."
- : " - Listener will run until stopped by command sent to queue.";
- _logger.info("No value specified for: " + END_TIME_TAG + sMsg);
+ _commandQueue = createCommandQueue(p_oP);
+
+ // Open the command queue...
+ if (null != _commandQueue) _commandQueue.open(p_oP);
+
+ setNextReloadTime(p_oP);
+ // if END_TIME_TAG not set try to run forever
+ // not a good practice if command queue is not set
+ // Expected date format is "yyyyMMdd hh:mm:ss"
+ String sEndT = p_oP.getAttribute(END_TIME_TAG);
+ _endTime = (null == sEndT) ? Long.MAX_VALUE : _dateFormat.parse(sEndT)
+ .getTime();
+
+ if (null == sEndT)
+ {
+ String sMsg = (null == _commandQueue) ? " - Listener will run until parent container/process terminates." : " - Listener will run until stopped by command sent to queue.";
+ _logger.info("No value specified for: " + END_TIME_TAG + sMsg);
+ }
}
+ catch (ParseException ex)
+ {
+ throw new ConfigurationException(ex);
+ }
+ catch (CommandQueueException ex)
+ {
+ throw new ConfigurationException(ex);
+ }
} // ________________________________
- private void setNextReloadTime(ConfigTree tree)
+ private void setNextReloadTime (ConfigTree tree)
{
// if RELOAD_SECONDS_TAG not set, and no command queue
// then reload every 10 minutes
@@ -256,21 +265,16 @@
synchronized (_synchReload)
{
- _nextReload = (null != _sRldSecs) ? System.currentTimeMillis()
- + 1000 * Long.parseLong(_sRldSecs)
- : (null == _commandQueue) ? Long.MAX_VALUE : System
- .currentTimeMillis()
- + _defaultReloadMillis;
+ _nextReload = (null != _sRldSecs) ? System.currentTimeMillis() + 1000 * Long
+ .parseLong(_sRldSecs) : (null == _commandQueue) ? Long.MAX_VALUE : System
+ .currentTimeMillis() + _defaultReloadMillis;
}
if (null == _sRldSecs)
{
- String sMsg = (null == _commandQueue) ? " - Using default of "
- + _sRldSecs
- : " - Listener will run until stopped by command sent to queue";
+ String sMsg = (null == _commandQueue) ? " - Using default of " + _sRldSecs : " - Listener will run until stopped by command sent to queue";
_logger
- .warn("No value specified for: " + RELOAD_SECONDS_TAG
- + sMsg);
+ .warn("No value specified for: " + RELOAD_SECONDS_TAG + sMsg);
}
} // ________________________________
@@ -282,7 +286,7 @@
* GatewayListener config.
* @return GatewayListener CommandQueue instance.
*/
- private CommandQueue createCommandQueue(ConfigTree config)
+ private CommandQueue createCommandQueue (ConfigTree config)
{
String commandQueueClass = config.getAttribute("command-queue-class");
@@ -295,9 +299,10 @@
}
catch (Exception e)
{
- _logger.error("Failed to instantiate CommandQueue ["
- + commandQueueClass
- + "]. Defaulting to no Command Queue", e);
+ _logger
+ .error(
+ "Failed to instantiate CommandQueue [" + commandQueueClass + "]. Defaulting to no Command Queue",
+ e);
}
}
@@ -311,7 +316,7 @@
* @param defaultCommandQueue
* The defaultCommandQueue to set.
*/
- public static void setDefaultCommandQueue(CommandQueue defaultCommandQueue)
+ public static void setDefaultCommandQueue (CommandQueue defaultCommandQueue)
{
GatewayListenerController._defaultCommandQueue = defaultCommandQueue;
}
@@ -327,16 +332,15 @@
* end of run period expired <p/>or 2) Just sleep if there's no command
* queue to listen on
*/
- public void run()
+ public void run ()
{
boolean relaunch = true;
while (endNotRequested())
{
_status = State.Running;
- if (relaunch)
- for (ConfigTree oCurr : _config.getAllChildren())
- tryToLaunchGateway(oCurr);
+ if (relaunch) for (ConfigTree oCurr : _config.getAllChildren())
+ tryToLaunchGateway(oCurr);
waitForCmdOrSleep();
@@ -365,8 +369,10 @@
}
catch (Exception e)
{
- _logger.error("Failed to reload parameters"
- + " - Continuing with cached version", e);
+ _logger
+ .error(
+ "Failed to reload parameters" + " - Continuing with cached version",
+ e);
}
}
// _status = State.Shutting_down;
@@ -379,8 +385,7 @@
// Close the command queue...
try
{
- if (null != _commandQueue)
- _commandQueue.close();
+ if (null != _commandQueue) _commandQueue.close();
}
catch (CommandQueueException e)
{
@@ -388,19 +393,18 @@
}
} // ________________________________
- private void tryToLaunchGateway(ConfigTree p_oP)
+ private void tryToLaunchGateway (ConfigTree p_oP)
{
String sClass = p_oP.getAttribute(GATEWAY_CLASS_TAG);
- if (Util.isNullString(sClass))
- return;
+ if (Util.isNullString(sClass)) return;
try
{
Class oListener = Class.forName(sClass);
- Constructor oConst = oListener.getConstructor(new Class[]
- { this.getClass(), ConfigTree.class });
- Runnable oRun = (Runnable) oConst.newInstance(new Object[]
- { this, p_oP });
+ Constructor oConst = oListener.getConstructor(new Class[] { this
+ .getClass(), ConfigTree.class });
+ Runnable oRun = (Runnable) oConst
+ .newInstance(new Object[] { this, p_oP });
new Thread(oRun).start();
}
catch (Exception e)
@@ -410,7 +414,7 @@
}
} // ________________________________
- long millisToWait()
+ long millisToWait ()
{
synchronized (_synchReload)
{
@@ -418,7 +422,7 @@
}
} // ________________________________
- private void waitForCmdOrSleep()
+ private void waitForCmdOrSleep ()
{
long lToGo = millisToWait();
@@ -446,8 +450,8 @@
{
try
{
- _logger.info("Waiting for command ... timeout=" + lToGo
- + " millis");
+ _logger
+ .info("Waiting for command ... timeout=" + lToGo + " millis");
String oM = _commandQueue.receiveCommand(lToGo);
if (null == oM)
@@ -498,10 +502,9 @@
* Message received from the command queue.
*
*/
- private void processCommand(String sTxt)
+ private void processCommand (String sTxt)
{
- if (null == sTxt)
- return;
+ if (null == sTxt) return;
String sLow = sTxt.trim().toLowerCase();
if (sLow.startsWith("shutdown"))
@@ -522,8 +525,7 @@
try
{
String sDate = sa[1];
- String sTime = (sa.length < 3 || null == sa[2]) ? "23:59:59"
- : sa[2];
+ String sTime = (sa.length < 3 || null == sa[2]) ? "23:59:59" : sa[2];
Date oEnd = _dateFormat.parse(sDate + " " + sTime);
_logger.info("New end date set to : " + oEnd);
_endTime = oEnd.getTime();
@@ -541,12 +543,12 @@
* @return boolean if processing has to stop (all child threads will be
* allowed to finish)
*/
- public boolean endRequested()
+ public boolean endRequested ()
{
return _endRequested || System.currentTimeMillis() >= _endTime;
}
- public void requestEnd()
+ public void requestEnd ()
{
_endRequested = true;
_endTime = 0;
@@ -559,7 +561,7 @@
* @return boolean - true if run time has not expired and quiesce has not
* been requested
*/
- public boolean endNotRequested()
+ public boolean endNotRequested ()
{
return !endRequested();
}
@@ -573,27 +575,22 @@
*
* @return boolean - true if it's time to reload parameters
*/
- private boolean isReloadNeeded()
+ private boolean isReloadNeeded ()
{
// command to reload was received - force reload
- if (_reloadRequested)
- return refreshNextReload();
+ if (_reloadRequested) return refreshNextReload();
// Still not time to reload
- if (System.currentTimeMillis() < _nextReload)
- return false;
+ if (System.currentTimeMillis() < _nextReload) return false;
- if (null == _sParametersName)
- return refreshNextReload();
+ if (null == _sParametersName) return refreshNextReload();
File paramFile = new File(_sParametersName);
- if (!paramFile.exists())
- return refreshNextReload();
+ if (!paramFile.exists()) return refreshNextReload();
// check the TS on the file.
Long previousTimeStamp = _paramFileTimeStamps.get(_sParametersName);
- if (null == previousTimeStamp)
- return refreshNextReload();
+ if (null == previousTimeStamp) return refreshNextReload();
Long currentTimeStamp = paramFile.lastModified();
if (!previousTimeStamp.equals(currentTimeStamp))
@@ -603,7 +600,7 @@
return false;
}
- private boolean refreshNextReload()
+ private boolean refreshNextReload ()
{
setNextReloadTime(_config);
return true;
@@ -616,7 +613,7 @@
* @return boolean - true if runtime is not expired and not time yet to
* reload parameters
*/
- public boolean continueLooping()
+ public boolean continueLooping ()
{
return (endNotRequested() && !isReloadNeeded());
} // ________________________________
@@ -631,22 +628,22 @@
* @param p_sDefault
* String -default value if requested attribute is not there
* @return String - value of attribute, or default value (if null)
- * @throws Exception -
+ * @throws ConfigurationException -
* If requested attribute not found and no default value
* supplied by invoker
*/
- public String obtainAtt(ConfigTree p_oP, String p_sAtt, String p_sDefault)
+ public String obtainAtt (ConfigTree p_oP, String p_sAtt, String p_sDefault)
throws ConfigurationException
{
String sVal = p_oP.getAttribute(p_sAtt);
if ((null == sVal) && (null == p_sDefault))
- throw new ConfigurationException("Missing or invalid <" + p_sAtt
- + "> attribute");
+ throw new ConfigurationException(
+ "Missing or invalid <" + p_sAtt + "> attribute");
return (null != sVal) ? sVal : p_sDefault;
} // ________________________________
- private static EPRManager getEprManager()
+ private static EPRManager getEprManager ()
{
PropertyManager manager = ModulePropertyManager
.getPropertyManager(ModulePropertyManager.CORE_MODULE);
@@ -655,7 +652,7 @@
return EPRManager.getInstance(sDir);
}
- public Collection<EPR> getEprs(String category, String name)
+ public Collection<EPR> getEprs (String category, String name)
throws RegistryException
{
if ("eprManager".equals(category))
@@ -668,8 +665,8 @@
}
catch (IOException e)
{
- throw new RegistryException("No EPRs found for <" + category
- + "><" + name + ">");
+ throw new RegistryException(
+ "No EPRs found for <" + category + "><" + name + ">");
}
}
@@ -683,8 +680,7 @@
}
catch (RegistryException e)
{
- if (null == eReg)
- eReg = e;
+ if (null == eReg) eReg = e;
try
{
Thread.sleep(500);
@@ -703,7 +699,7 @@
* @param name
* @param address
*/
- public void register(String name, EPR address)
+ public void register (String name, EPR address)
{
try
{
@@ -720,7 +716,7 @@
* serviceName, EPR epr) instead.
* @param name
*/
- public void unRegister(String name)
+ public void unRegister (String name)
{
try
{
@@ -743,7 +739,7 @@
*
* @throws RegistryException
*/
- public void register(ConfigTree config, EPR epr) throws RegistryException
+ public void register (ConfigTree config, EPR epr) throws RegistryException
{
String serviceCategoryName = config
.getAttribute(ListenerTagNames.SERVICE_CATEGORY_NAME_TAG);
@@ -773,7 +769,7 @@
* @param epr
* @throws RegistryException
*/
- public void unRegister(String serviceCategoryName, String serviceName,
+ public void unRegister (String serviceCategoryName, String serviceName,
EPR epr) throws RegistryException
{
if ("eprManager".equalsIgnoreCase(serviceCategoryName))
@@ -805,8 +801,9 @@
private long _endTime = Long.MAX_VALUE;
protected int _defaultReloadMillis = 180000; // default interval between
- // parameter reloads
+ // parameter reloads
+
public static final SimpleDateFormat _dateFormat = new SimpleDateFormat(
"yyyyMMdd hh:mm:ss");
Modified: labs/jbossesb/trunk/product/core/listeners/src/org/jboss/soa/esb/listeners/gateway/JmsGatewayListener.java
===================================================================
--- labs/jbossesb/trunk/product/core/listeners/src/org/jboss/soa/esb/listeners/gateway/JmsGatewayListener.java 2007-01-20 09:09:48 UTC (rev 8932)
+++ labs/jbossesb/trunk/product/core/listeners/src/org/jboss/soa/esb/listeners/gateway/JmsGatewayListener.java 2007-01-20 09:33:16 UTC (rev 8933)
@@ -23,13 +23,13 @@
package org.jboss.soa.esb.listeners.gateway;
import java.io.ByteArrayOutputStream;
+import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Enumeration;
-import javax.enterprise.deploy.spi.exceptions.ConfigurationException;
import javax.jms.BytesMessage;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
@@ -43,6 +43,7 @@
import javax.naming.NamingException;
import org.apache.log4j.Logger;
+import org.jboss.soa.esb.ConfigurationException;
import org.jboss.soa.esb.addressing.EPR;
import org.jboss.soa.esb.addressing.eprs.JMSEpr;
import org.jboss.soa.esb.couriers.Courier;
@@ -58,325 +59,442 @@
public class JmsGatewayListener implements Runnable
{
- public JmsGatewayListener(GatewayListenerController commandListener, ConfigTree listenerConfig)
- throws Exception
- {
- _config = listenerConfig;
- _controller = commandListener;
- _sleepForRetries = 3000; // milliseconds
- checkMyParms();
- } // __________________________________
+ public JmsGatewayListener (GatewayListenerController commandListener,
+ ConfigTree listenerConfig) throws ConfigurationException
+ {
+ _config = listenerConfig;
+ _controller = commandListener;
+ _sleepForRetries = 3000; // milliseconds TODO magic number
+ checkMyParms();
+ } // __________________________________
- public void run()
+ public void run ()
{
- _logger.debug("run() method of "+this.getClass().getSimpleName()
- +" started on thread "+Thread.currentThread().getName());
- if (null!=_serviceName)
- try { _controller.register(_config,_myEpr); }
- catch (RegistryException e1)
- { _logger.warn("unable to register service",e1); }
+ _logger
+ .debug("run() method of " + this.getClass().getSimpleName() + " started on thread " + Thread
+ .currentThread().getName());
+ if (null != _serviceName) try
+ {
+ _controller.register(_config, _myEpr);
+ }
+ catch (RegistryException e1)
+ {
+ _logger.warn("unable to register service", e1);
+ }
- while (_controller.continueLooping())
- {
- javax.jms.Message msgIn = receiveOne();
- if (null!=msgIn)
- try
- {
- Object obj = _processMethod.invoke(_composer,new Object[] {msgIn} );
- if (null==obj)
- {
- _logger.warn("Action class method <"+_processMethod.getName()+"> returned a null object");
- continue;
- }
- // try to deliver the composed message, using the appropriate courier
- // to the target service
- try
- {
- boolean bSent = false;
- for (EPR current : _targetEprs)
- {
- _courier = CourierFactory.getCourier(current);
- if (_courier.deliver((org.jboss.soa.esb.message.Message)obj))
- {
- bSent = true;
- break;
- }
- }
- if (! bSent)
- {
- String text = "Target service <"+_targetServiceCategory+","+_targetServiceName+"> is not registered";
- throw new Exception(text);
- }
- }
- catch (ClassCastException e)
- {
- _logger.error("Action class method <"+_processMethod.getName()+"> returned a non Message object", e);
- continue;
- }
- catch (CourierException e)
- {
- String text = (null!=_courier) ?
- "Courier <"+_courier.getClass().getName()+".deliver(Message) FAILED"
- :
- "NULL courier can't deliver Message";
- _logger.error(text, e);
- continue;
- }
- continue;
- }
- catch (InvocationTargetException e)
- {
- _logger.error("Problems invoking method <"+_processMethod.getName()+">",e);
- }
- catch (IllegalAccessException e)
- {
- _logger.error("Problems invoking method <"+_processMethod.getName()+">",e);
- }
- catch (Exception e)
- {
- _logger.error("Unexpected problem",e);
- }
- }
-
- if (null!=_serviceName)
- try { _controller.unRegister(_serviceCategory, _serviceName,_myEpr); }
- catch (RegistryException e1){ _logger.warn("unable to unRegister service",e1); }
-
+ while (_controller.continueLooping())
+ {
+ javax.jms.Message msgIn = receiveOne();
+ if (null != msgIn)
+ try
+ {
+ Object obj = _processMethod.invoke(_composer,
+ new Object[] { msgIn });
+ if (null == obj)
+ {
+ _logger.warn("Action class method <" + _processMethod
+ .getName() + "> returned a null object");
+ continue;
+ }
+ // try to deliver the composed message, using the
+ // appropriate courier
+ // to the target service
+ try
+ {
+ boolean bSent = false;
+ for (EPR current : _targetEprs)
+ {
+ _courier = CourierFactory.getCourier(current);
+ if (_courier
+ .deliver((org.jboss.soa.esb.message.Message) obj))
+ {
+ bSent = true;
+ break;
+ }
+ }
+ if (!bSent)
+ {
+ String text = "Target service <" + _targetServiceCategory + "," + _targetServiceName + "> is not registered";
+ throw new Exception(text);
+ }
+ }
+ catch (ClassCastException e)
+ {
+ _logger.error("Action class method <" + _processMethod
+ .getName() + "> returned a non Message object",
+ e);
+ continue;
+ }
+ catch (CourierException e)
+ {
+ String text = (null != _courier) ? "Courier <" + _courier
+ .getClass().getName() + ".deliver(Message) FAILED" : "NULL courier can't deliver Message";
+ _logger.error(text, e);
+ continue;
+ }
+ continue;
+ }
+ catch (InvocationTargetException e)
+ {
+ _logger.error("Problems invoking method <" + _processMethod
+ .getName() + ">", e);
+ }
+ catch (IllegalAccessException e)
+ {
+ _logger.error("Problems invoking method <" + _processMethod
+ .getName() + ">", e);
+ }
+ catch (Exception e)
+ {
+ _logger.error("Unexpected problem", e);
+ }
+ }
- if (null != _messageReceiver)
- try { _messageReceiver.close(); }
- catch (Exception e1) {/* Tried my best - Just continue */ }
- if (null != _queueSession)
- try { _queueSession.close(); }
- catch (Exception e1) {/* Tried my best - Just continue */ }
- if (null != _queueConnection)
- try { _queueConnection.close(); }
- catch (Exception e2) {/* Tried my best - Just continue */ }
- _logger.debug("run() method of "+this.getClass().getSimpleName()
- +" finished on thread "+Thread.currentThread().getName());
- } // ________________________________
+ if (null != _serviceName) try
+ {
+ _controller.unRegister(_serviceCategory, _serviceName, _myEpr);
+ }
+ catch (RegistryException e1)
+ {
+ _logger.warn("unable to unRegister service", e1);
+ }
- /**
- * Check for mandatory and optional attributes in parameter tree
- *
- * @throws Exception -
- * if mandatory atts are not right or actionClass not in
- * classpath
- */
- protected void checkMyParms() throws Exception
- {
- // Third arg is null - Exception will be thrown if attribute is not found
- _targetServiceCategory = _controller.obtainAtt(_config, ListenerTagNames.TARGET_SERVICE_CATEGORY_TAG, null);
- _targetServiceName = _controller.obtainAtt(_config, ListenerTagNames.TARGET_SERVICE_NAME_TAG, null);
- _targetEprs = _controller.getEprs(_targetServiceCategory,_targetServiceName);
- if (null==_targetEprs || _targetEprs.size() < 1)
- throw new ConfigurationException("EPR <"+_targetServiceName+"> not found in registry");
+ if (null != _messageReceiver) try
+ {
+ _messageReceiver.close();
+ }
+ catch (Exception e1)
+ {/* Tried my best - Just continue */
+ }
+ if (null != _queueSession) try
+ {
+ _queueSession.close();
+ }
+ catch (Exception e1)
+ {/* Tried my best - Just continue */
+ }
+ if (null != _queueConnection) try
+ {
+ _queueConnection.close();
+ }
+ catch (Exception e2)
+ {/* Tried my best - Just continue */
+ }
+ _logger
+ .debug("run() method of " + this.getClass().getSimpleName() + " finished on thread " + Thread
+ .currentThread().getName());
+ } // ________________________________
- _queueName = _controller.obtainAtt(_config, JMSEpr.DESTINATION_NAME_TAG, null);
-
- resolveComposerClass();
-
- // No problem if selector is null - everything in queue will be returned
- _messageSelector = _config.getAttribute(JMSEpr.MESSAGE_SELECTOR_TAG);
- _logger.debug("No value specified for: "+JMSEpr.MESSAGE_SELECTOR_TAG
- +" - All messages in queue will be received by this listener");
-
- prepareMessageReceiver();
- } // ________________________________
-
- protected void resolveComposerClass() throws Exception
- {
- // Look for first "action" element - only first one will be used
- String tagName = ListenerTagNames.ACTION_ELEMENT_TAG;
- ConfigTree actionElement = _config.getFirstChild(tagName);
- String sProcessMethod = null;
- if (null!=actionElement)
- { // class attribute
- _composerName = _controller.obtainAtt(actionElement,ListenerTagNames.ACTION_CLASS_TAG,null);
- _composerClass = Class.forName(_composerName);
- Constructor oConst = _composerClass.getConstructor(new Class[] {ConfigTree.class});
- _composer= oConst.newInstance(_config);
- tagName = ListenerTagNames.PROCESS_METHOD_TAG;
- sProcessMethod = _controller.obtainAtt(_config,tagName,tagName);
- }
- else
- {
- _composerName = PackageJmsMessageContents.class.getName();
- _composerClass= PackageJmsMessageContents.class;
- _composer = new PackageJmsMessageContents();
- sProcessMethod = "process";
- _logger.warn("No <"+ListenerTagNames.ACTION_ELEMENT_TAG+"> element found in cofiguration"
- +" - Using default composer class : "+_composerName);
- }
+ /**
+ * Check for mandatory and optional attributes in parameter tree
+ *
+ * @throws ConfigurationException -
+ * if mandatory atts are not right or actionClass not in
+ * classpath
+ */
+ protected void checkMyParms () throws ConfigurationException
+ {
+ try
+ {
+ // Third arg is null - Exception will be thrown if attribute is not
+ // found
+ _targetServiceCategory = _controller.obtainAtt(_config,
+ ListenerTagNames.TARGET_SERVICE_CATEGORY_TAG, null);
+ _targetServiceName = _controller.obtainAtt(_config,
+ ListenerTagNames.TARGET_SERVICE_NAME_TAG, null);
+ _targetEprs = _controller.getEprs(_targetServiceCategory,
+ _targetServiceName);
+ if (null == _targetEprs || _targetEprs.size() < 1)
+ throw new ConfigurationException(
+ "EPR <" + _targetServiceName + "> not found in registry");
+
+ _queueName = _controller.obtainAtt(_config,
+ JMSEpr.DESTINATION_NAME_TAG, null);
+
+ resolveComposerClass();
+
+ // No problem if selector is null - everything in queue will be returned
+ _messageSelector = _config.getAttribute(JMSEpr.MESSAGE_SELECTOR_TAG);
+ _logger
+ .debug("No value specified for: " + JMSEpr.MESSAGE_SELECTOR_TAG + " - All messages in queue will be received by this listener");
+
+ prepareMessageReceiver();
+ }
+ catch (JMSException ex)
+ {
+ _logger.warn("Received underlying JMS exception from prepareMessageReceiver.", ex);
+
+ throw new ConfigurationException(ex);
+ }
+ catch (RegistryException ex)
+ {
+ _logger.warn("Problem with registry.", ex);
+
+ throw new ConfigurationException(ex);
+ }
+ } // ________________________________
- _processMethod = _composerClass.getMethod(sProcessMethod,new Class[] {Object.class});
- } //________________________________
+ protected void resolveComposerClass () throws ConfigurationException
+ {
+ try
+ {
+ // Look for first "action" element - only first one will be used
+ String tagName = ListenerTagNames.ACTION_ELEMENT_TAG;
+ ConfigTree actionElement = _config.getFirstChild(tagName);
+ String sProcessMethod = null;
+ if (null != actionElement)
+ { // class attribute
+ _composerName = _controller.obtainAtt(actionElement,
+ ListenerTagNames.ACTION_CLASS_TAG, null);
+ _composerClass = Class.forName(_composerName);
+ Constructor oConst = _composerClass
+ .getConstructor(new Class[] { ConfigTree.class });
+ _composer = oConst.newInstance(_config);
+ tagName = ListenerTagNames.PROCESS_METHOD_TAG;
+ sProcessMethod = _controller.obtainAtt(_config, tagName, tagName);
+ }
+ else
+ {
+ _composerName = PackageJmsMessageContents.class.getName();
+ _composerClass = PackageJmsMessageContents.class;
+ _composer = new PackageJmsMessageContents();
+ sProcessMethod = "process";
+ _logger
+ .warn("No <" + ListenerTagNames.ACTION_ELEMENT_TAG + "> element found in cofiguration" + " - Using default composer class : " + _composerName);
+ }
+
+ _processMethod = _composerClass.getMethod(sProcessMethod,
+ new Class[] { Object.class });
+ }
+ catch (Exception ex)
+ {
+ throw new ConfigurationException(ex);
+ }
+ } // ________________________________
- private void prepareMessageReceiver() throws Exception
- {
- _queueConnection = null;
- _queueSession = null;
- _queue = null;
+ private void prepareMessageReceiver () throws ConfigurationException, JMSException
+ {
+ _queueConnection = null;
+ _queueSession = null;
+ _queue = null;
- String sJndiURL = _controller.obtainAtt(_config, JMSEpr.JNDI_URL_TAG, NamingContext.JBOSS_PROVIDER_URL);
- if (null==_config.getAttribute(JMSEpr.JNDI_URL_TAG))
- _logger.debug("No value specified for "+JMSEpr.JNDI_URL_TAG+" attribute"
- +" - Using default of: '"+sJndiURL+"'");
- String sJndiContextFactory = _controller.obtainAtt(_config, JMSEpr.JNDI_CONTEXT_FACTORY_TAG,NamingContext.JBOSS_INITIAL_CONTEXT_FACTORY);
- if (null==_config.getAttribute(JMSEpr.JNDI_CONTEXT_FACTORY_TAG))
- _logger.debug("No value specified for "+JMSEpr.JNDI_CONTEXT_FACTORY_TAG+" attribute"
- +" - Using default of: '"+sJndiContextFactory+"'");
- String sJndiPkgPrefix = _controller.obtainAtt(_config, JMSEpr.JNDI_PKG_PREFIX_TAG,NamingContext.JBOSS_PROVIDER_URL);
- if (null==_config.getAttribute(JMSEpr.JNDI_PKG_PREFIX_TAG))
- _logger.debug("No value specified for "+JMSEpr.JNDI_PKG_PREFIX_TAG+" attribute"
- +" - Using default of: '"+sJndiPkgPrefix+"'");
- Context oJndiCtx = NamingContext.getServerContext(sJndiURL,sJndiContextFactory,sJndiPkgPrefix);
- if (null==oJndiCtx)
- throw new Exception("Unable fo obtain jndi context <"+sJndiURL
- +","+sJndiContextFactory+","+sJndiPkgPrefix+">");
+ String sJndiURL = _controller.obtainAtt(_config, JMSEpr.JNDI_URL_TAG,
+ NamingContext.JBOSS_PROVIDER_URL);
+ if (null == _config.getAttribute(JMSEpr.JNDI_URL_TAG))
+ _logger
+ .debug("No value specified for " + JMSEpr.JNDI_URL_TAG + " attribute" + " - Using default of: '" + sJndiURL + "'");
+ String sJndiContextFactory = _controller.obtainAtt(_config,
+ JMSEpr.JNDI_CONTEXT_FACTORY_TAG,
+ NamingContext.JBOSS_INITIAL_CONTEXT_FACTORY);
+ if (null == _config.getAttribute(JMSEpr.JNDI_CONTEXT_FACTORY_TAG))
+ _logger
+ .debug("No value specified for " + JMSEpr.JNDI_CONTEXT_FACTORY_TAG + " attribute" + " - Using default of: '" + sJndiContextFactory + "'");
+ String sJndiPkgPrefix = _controller.obtainAtt(_config,
+ JMSEpr.JNDI_PKG_PREFIX_TAG, NamingContext.JBOSS_PROVIDER_URL);
+ if (null == _config.getAttribute(JMSEpr.JNDI_PKG_PREFIX_TAG))
+ _logger
+ .debug("No value specified for " + JMSEpr.JNDI_PKG_PREFIX_TAG + " attribute" + " - Using default of: '" + sJndiPkgPrefix + "'");
+ Context oJndiCtx = NamingContext.getServerContext(sJndiURL,
+ sJndiContextFactory, sJndiPkgPrefix);
+ if (null == oJndiCtx)
+ throw new ConfigurationException(
+ "Unable fo obtain jndi context <" + sJndiURL + "," + sJndiContextFactory + "," + sJndiPkgPrefix + ">");
- String sFactClass = _controller.obtainAtt(_config,JMSEpr.CONNECTION_FACTORY_TAG, "ConnectionFactory");
- if (null==_config.getAttribute(JMSEpr.CONNECTION_FACTORY_TAG))
- _logger.debug("No value specified for "+JMSEpr.CONNECTION_FACTORY_TAG+" attribute"
- +" - Using default of: '"+sFactClass+"'");
- _serviceCategory= _config.getAttribute(ListenerTagNames.SERVICE_CATEGORY_NAME_TAG);
- _serviceName = _config.getAttribute(ListenerTagNames.SERVICE_NAME_TAG);
- _myEpr = (null==_serviceName) ? null
- : new JMSEpr(JMSEpr.QUEUE_TYPE,_queueName,sFactClass,sJndiURL,sJndiContextFactory,sJndiPkgPrefix,_messageSelector);
-
- Object tmp = oJndiCtx.lookup(sFactClass);
- QueueConnectionFactory qcf = (QueueConnectionFactory) tmp;
+ String sFactClass = _controller.obtainAtt(_config,
+ JMSEpr.CONNECTION_FACTORY_TAG, "ConnectionFactory");
+ if (null == _config.getAttribute(JMSEpr.CONNECTION_FACTORY_TAG))
+ _logger
+ .debug("No value specified for " + JMSEpr.CONNECTION_FACTORY_TAG + " attribute" + " - Using default of: '" + sFactClass + "'");
+ _serviceCategory = _config
+ .getAttribute(ListenerTagNames.SERVICE_CATEGORY_NAME_TAG);
+ _serviceName = _config.getAttribute(ListenerTagNames.SERVICE_NAME_TAG);
+ _myEpr = (null == _serviceName) ? null : new JMSEpr(JMSEpr.QUEUE_TYPE,
+ _queueName, sFactClass, sJndiURL, sJndiContextFactory,
+ sJndiPkgPrefix, _messageSelector);
+
+ Object tmp = null;
+
+ try
+ {
+ tmp = oJndiCtx.lookup(sFactClass);
+ }
+ catch (NamingException ex)
+ {
+ throw new ConfigurationException(ex);
+ }
+
+ QueueConnectionFactory qcf = (QueueConnectionFactory) tmp;
- _queueConnection = qcf.createQueueConnection();
- _queueSession = _queueConnection.createQueueSession(false,QueueSession.AUTO_ACKNOWLEDGE);
- try {
- _queue = (Queue) oJndiCtx.lookup(_queueName);
- } catch (NamingException ne) {
- _queue = _queueSession.createQueue(_queueName);
- }
- _queueConnection.start();
+ _queueConnection = qcf.createQueueConnection();
+ _queueSession = _queueConnection.createQueueSession(false,
+ QueueSession.AUTO_ACKNOWLEDGE);
+ try
+ {
+ _queue = (Queue) oJndiCtx.lookup(_queueName);
+ }
+ catch (NamingException ne)
+ {
+ _queue = _queueSession.createQueue(_queueName);
+ }
+ _queueConnection.start();
- _messageReceiver = _queueSession.createReceiver(_queue, _messageSelector);
+ _messageReceiver = _queueSession.createReceiver(_queue,
+ _messageSelector);
- } // ________________________________
+ } // ________________________________
/**
* Receive one message and retry if connection
+ *
* @return javax.jms.Message - One input message, or null
*/
- protected javax.jms.Message receiveOne()
- {
- while (_controller.continueLooping())
- try
- {
- long lWait = _controller.millisToWait();
- if (lWait < 1)
- return null;
- javax.jms.Message ret = _messageReceiver.receive(Math.min(lWait,100));
- if (null!= ret)
- return ret;
- try { Thread.sleep(100); }
- catch (InterruptedException e) { break; }
- }
- catch (JMSException oJ)
- {
- _logger.error("JMS error on receive. Attempting JMS Destination reconnect.", oJ);
- try { prepareMessageReceiver(); }
- // try to reconnect to the queue
- catch (Exception e)
- {
- _logger.error("Reconnecting to Queue", e);
- try { Thread.sleep(_sleepForRetries); }
- catch (InterruptedException e1)
- { // Just return
- _logger.error("Unexpected thread interupt exception.", e);
- return null;
- }
- }
- }
- return null;
- } //________________________________
-
-/**
- * Default gateway action for plain jms messages
- * <p/>It will just drop the jms message contents into a esb Message
- * @author <a href="mailto:schifest at heuristica.com.ar">schifest at heuristica.com.ar</a>
- * @since Version 4.0
- *
- */
- private static class PackageJmsMessageContents
- {
- @SuppressWarnings("unchecked")
- public Message process (Object obj) throws Exception
- {
- if (! (obj instanceof javax.jms.Message))
- throw new Exception ("Object must be instance of javax.jms.Message");
- byte[] bytes = getMessageContent((javax.jms.Message)obj);
- if (null==bytes)
- return null;
+ protected javax.jms.Message receiveOne ()
+ {
+ while (_controller.continueLooping())
+ try
+ {
+ long lWait = _controller.millisToWait();
+ if (lWait < 1) return null;
+ javax.jms.Message ret = _messageReceiver.receive(Math.min(
+ lWait, 100));
+ if (null != ret) return ret;
+ try
+ {
+ Thread.sleep(100);
+ }
+ catch (InterruptedException e)
+ {
+ break;
+ }
+ }
+ catch (JMSException oJ)
+ {
+ _logger
+ .error(
+ "JMS error on receive. Attempting JMS Destination reconnect.",
+ oJ);
+ try
+ {
+ prepareMessageReceiver();
+ }
+ // try to reconnect to the queue
+ catch (Exception e)
+ {
+ _logger.error("Reconnecting to Queue", e);
+ try
+ {
+ Thread.sleep(_sleepForRetries);
+ }
+ catch (InterruptedException e1)
+ { // Just return
+ _logger.error("Unexpected thread interupt exception.",
+ e);
+ return null;
+ }
+ }
+ }
+ return null;
+ } // ________________________________
- javax.jms.Message jmsMsg = (javax.jms.Message)obj;
- Message message = MessageFactory.getInstance().getMessage();
- message.getBody().setContents(getMessageContent(jmsMsg));
- Enumeration<String> EE = jmsMsg.getPropertyNames();
- if(null!=EE)
- while (EE.hasMoreElements())
- {
- String name = EE.nextElement();
- Object value = jmsMsg.getObjectProperty(name);
- if (null!=value)
- message.getProperties().setProperty(name, value);
- }
- return message;
- }
-
- private byte[] getMessageContent(javax.jms.Message jMess) throws Exception
- {
- if (jMess instanceof TextMessage)
- return ((TextMessage)jMess).getText().getBytes();
+ /**
+ * Default gateway action for plain jms messages <p/>It will just drop the
+ * jms message contents into a esb Message
+ *
+ * @author <a
+ * href="mailto:schifest at heuristica.com.ar">schifest at heuristica.com.ar</a>
+ * @since Version 4.0
+ *
+ */
+ private static class PackageJmsMessageContents
+ {
+ @SuppressWarnings("unchecked")
+ public Message process (Object obj) throws JMSException, IOException
+ {
+ if (!(obj instanceof javax.jms.Message))
+ throw new IllegalArgumentException(
+ "Object must be instance of javax.jms.Message");
+ byte[] bytes = getMessageContent((javax.jms.Message) obj);
+ if (null == bytes) return null;
- if (jMess instanceof BytesMessage)
- {
- BytesMessage jBytes =(BytesMessage)jMess;
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- byte[] ba = new byte[1000];
- int iQread;
- while (-1!= (iQread=jBytes.readBytes(ba)))
- if (iQread > 0)
- out.write(ba,0,iQread);
- out.close();
- return out.toByteArray();
- }
+ javax.jms.Message jmsMsg = (javax.jms.Message) obj;
+ Message message = MessageFactory.getInstance().getMessage();
+ message.getBody().setContents(getMessageContent(jmsMsg));
+ Enumeration<String> EE = jmsMsg.getPropertyNames();
+ if (null != EE)
+ {
+ while (EE.hasMoreElements())
+ {
+ String name = EE.nextElement();
+ Object value = jmsMsg.getObjectProperty(name);
+ if (null != value)
+ message.getProperties().setProperty(name, value);
+ }
+ }
+ return message;
+ }
- if (jMess instanceof ObjectMessage)
- return ((ObjectMessage)jMess).getObject().toString().getBytes();
- _logger.warn("Message type "+jMess.getClass().getSimpleName()
- +" not supported - Message is ignored");
- return null;
- }
- } //____________________________________________________
+ private byte[] getMessageContent (javax.jms.Message jMess) throws JMSException, IOException
+ {
+ if (jMess instanceof TextMessage)
+ return ((TextMessage) jMess).getText().getBytes();
- protected final static Logger _logger = Logger.getLogger(JmsGatewayListener.class);
+ if (jMess instanceof BytesMessage)
+ {
+ BytesMessage jBytes = (BytesMessage) jMess;
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ byte[] ba = new byte[1000];
+ int iQread;
+ while (-1 != (iQread = jBytes.readBytes(ba)))
+ if (iQread > 0) out.write(ba, 0, iQread);
+ out.close();
+ return out.toByteArray();
+ }
- protected String _queueName;
- protected QueueConnection _queueConnection;
- protected QueueSession _queueSession;
- protected Queue _queue;
- protected MessageConsumer _messageReceiver;
- protected String _messageSelector;
- protected ConfigTree _config;
- protected GatewayListenerController _controller;
- protected final long _sleepForRetries; // milliseconds
+ if (jMess instanceof ObjectMessage)
+ return ((ObjectMessage) jMess).getObject().toString()
+ .getBytes();
+ _logger
+ .warn("Message type " + jMess.getClass().getSimpleName() + " not supported - Message is ignored");
+ return null;
+ }
+ } // ____________________________________________________
- protected String _serviceCategory ,_serviceName;
- protected String _targetServiceCategory ,_targetServiceName;
- protected EPR _myEpr;
- protected Collection<EPR> _targetEprs;
+ protected final static Logger _logger = Logger
+ .getLogger(JmsGatewayListener.class);
- protected String _composerName;
- protected Class _composerClass;
- protected Object _composer;
- protected Method _processMethod;
-
- protected Courier _courier;
-}
+ protected String _queueName;
+
+ protected QueueConnection _queueConnection;
+
+ protected QueueSession _queueSession;
+
+ protected Queue _queue;
+
+ protected MessageConsumer _messageReceiver;
+
+ protected String _messageSelector;
+
+ protected ConfigTree _config;
+
+ protected GatewayListenerController _controller;
+
+ protected final long _sleepForRetries; // milliseconds
+
+ protected String _serviceCategory, _serviceName;
+
+ protected String _targetServiceCategory, _targetServiceName;
+
+ protected EPR _myEpr;
+
+ protected Collection<EPR> _targetEprs;
+
+ protected String _composerName;
+
+ protected Class _composerClass;
+
+ protected Object _composer;
+
+ protected Method _processMethod;
+
+ protected Courier _courier;
+}
Modified: labs/jbossesb/trunk/product/core/listeners/src/org/jboss/soa/esb/listeners/gateway/SqlTableGatewayListener.java
===================================================================
--- labs/jbossesb/trunk/product/core/listeners/src/org/jboss/soa/esb/listeners/gateway/SqlTableGatewayListener.java 2007-01-20 09:09:48 UTC (rev 8932)
+++ labs/jbossesb/trunk/product/core/listeners/src/org/jboss/soa/esb/listeners/gateway/SqlTableGatewayListener.java 2007-01-20 09:33:16 UTC (rev 8933)
@@ -77,20 +77,21 @@
public class SqlTableGatewayListener implements Runnable
{
- public SqlTableGatewayListener(GatewayListenerController commandListener,
- ConfigTree config) throws Exception
+ public SqlTableGatewayListener (GatewayListenerController commandListener,
+ ConfigTree config) throws ConfigurationException
{
_config = config;
_controller = commandListener;
- _sleepBetweenPolls = 10000; // milliseconds
+ _sleepBetweenPolls = 10000; // milliseconds TODO magic number
checkMyParms();
} // __________________________________
- public void run()
+ public void run ()
{
- _logger.debug("run() method of " + this.getClass().getSimpleName()
- + " started on thread " + Thread.currentThread().getName());
-
+ _logger
+ .debug("run() method of " + this.getClass().getSimpleName() + " started on thread " + Thread
+ .currentThread().getName());
+
if (null != _serviceName)
{
try
@@ -104,7 +105,7 @@
}
boolean bSleep = false;
-
+
while (_controller.continueLooping())
{
// only sleep in between - not the first time
@@ -116,42 +117,38 @@
try
{
// TODO magic number
-
+
Thread.sleep(1000);
}
catch (InterruptedException e)
{
lUntil = 0;
}
- if (!_controller.continueLooping())
- break;
+ if (!_controller.continueLooping()) break;
}
}
else
bSleep = true;
-
- if (!_controller.continueLooping())
- break;
+ if (!_controller.continueLooping()) break;
+
for (Map<String, Object> row : pollForCandidates())
{
_currentRow = row;
// Try to mark as 'in process' - if unsuccessful, somebody else
// got it first
- if (!changeStatusToWorking())
- continue;
+ if (!changeStatusToWorking()) continue;
Throwable thrown = null;
String text = null;
try
{
- Object obj = _processMethod.invoke(_composer, new Object[]
- { _currentRow });
+ Object obj = _processMethod.invoke(_composer,
+ new Object[] { _currentRow });
if (null == obj)
{
- _logger.warn("Action class method <"
- + _processMethod.getName()
- + "> returned a null object");
+ _logger.warn("Action class method <" + _processMethod
+ .getName() + "> returned a null object");
continue;
}
Message message = (Message) obj;
@@ -177,47 +174,41 @@
}
if (!bSent)
{
- text = "Target service <" + _targetServiceCategory
- + "," + _targetServiceName
- + "> is not registered";
+ text = "Target service <" + _targetServiceCategory + "," + _targetServiceName + "> is not registered";
thrown = new Exception(text);
}
}
catch (InvocationTargetException e)
{
thrown = e;
- text = "Problems invoking method <"
- + _processMethod.getName() + ">";
+ text = "Problems invoking method <" + _processMethod
+ .getName() + ">";
}
catch (IllegalAccessException e)
{
thrown = e;
- text = "Problems invoking method <"
- + _processMethod.getName() + ">";
+ text = "Problems invoking method <" + _processMethod
+ .getName() + ">";
}
catch (ClassCastException e)
{
thrown = e;
- text = "Action class method <" + _processMethod.getName()
- + "> returned a non Message object";
+ text = "Action class method <" + _processMethod.getName() + "> returned a non Message object";
}
catch (CourierException e)
{
thrown = e;
- text = "Courier <" + _courier.getClass().getName()
- + ".deliver(Message) FAILED";
+ text = "Courier <" + _courier.getClass().getName() + ".deliver(Message) FAILED";
}
catch (MalformedEPRException ex)
{
thrown = ex;
- text = "Courier <" + _courier.getClass().getName()
- + ".deliver(Message) FAILED with malformed EPR.";
+ text = "Courier <" + _courier.getClass().getName() + ".deliver(Message) FAILED with malformed EPR.";
}
if (null == thrown)
{
- if (_deleteAfterOK)
- deleteCurrentRow();
+ if (_deleteAfterOK) deleteCurrentRow();
else
changeStatusToDone();
}
@@ -242,148 +233,152 @@
}
}
- if (null != _dbConn)
- _dbConn.release();
- _logger.debug("run() method of " + this.getClass().getSimpleName()
- + " finished on thread " + Thread.currentThread().getName());
+ if (null != _dbConn) _dbConn.release();
+ _logger
+ .debug("run() method of " + this.getClass().getSimpleName() + " finished on thread " + Thread
+ .currentThread().getName());
} // ________________________________
/**
* Check for mandatory and optional attributes in parameter tree
*
- * @throws Exception -
+ * @throws ConfigurationException -
* if mandatory atts are not right or actionClass not in
* classpath
*/
- protected void checkMyParms() throws Exception
+ protected void checkMyParms () throws ConfigurationException
{
- // Third arg is null - Exception will be thrown if attribute is not
- // found
- _targetServiceCategory = _controller.obtainAtt(_config,
- ListenerTagNames.TARGET_SERVICE_CATEGORY_TAG, null);
- _targetServiceName = _controller.obtainAtt(_config,
- ListenerTagNames.TARGET_SERVICE_NAME_TAG, null);
- _targetEprs = _controller.getEprs(_targetServiceCategory,
- _targetServiceName);
- if (null == _targetEprs || _targetEprs.size() < 1)
- throw new ConfigurationException("EPR <" + _targetServiceName
- + "> not found in registry");
-
- // Polling interval
- String sAux = _config
- .getAttribute(ListenerTagNames.POLL_LATENCY_SECS_TAG);
-
- if (!Util.isNullString(sAux))
+ try
{
- try
+ // Third arg is null - Exception will be thrown if attribute is not
+ // found
+ _targetServiceCategory = _controller.obtainAtt(_config,
+ ListenerTagNames.TARGET_SERVICE_CATEGORY_TAG, null);
+ _targetServiceName = _controller.obtainAtt(_config,
+ ListenerTagNames.TARGET_SERVICE_NAME_TAG, null);
+ _targetEprs = _controller.getEprs(_targetServiceCategory,
+ _targetServiceName);
+ if (null == _targetEprs || _targetEprs.size() < 1)
+ throw new ConfigurationException(
+ "EPR <" + _targetServiceName + "> not found in registry");
+
+ // Polling interval
+ String sAux = _config
+ .getAttribute(ListenerTagNames.POLL_LATENCY_SECS_TAG);
+
+ if (!Util.isNullString(sAux))
{
- _sleepBetweenPolls = 1000 * Long.parseLong(sAux);
+ try
+ {
+ _sleepBetweenPolls = 1000 * Long.parseLong(sAux);
+ }
+ catch (NumberFormatException e)
+ {
+ _logger
+ .warn("Invalid poll latency - keeping default of " + (_sleepBetweenPolls / 1000));
+ }
}
- catch (NumberFormatException e)
+ else
{
- _logger.warn("Invalid poll latency - keeping default of "
- + (_sleepBetweenPolls / 1000));
+ _logger
+ .warn("No value specified for: " + ListenerTagNames.POLL_LATENCY_SECS_TAG + " - Using default of " + (_sleepBetweenPolls / 1000));
}
- }
- else
- {
- _logger.warn("No value specified for: "
- + ListenerTagNames.POLL_LATENCY_SECS_TAG
- + " - Using default of " + (_sleepBetweenPolls / 1000));
- }
-
- resolveComposerClass();
-
- _driver = _controller.obtainAtt(_config, JDBCEpr.DRIVER_TAG, null);
- _url = _controller.obtainAtt(_config, JDBCEpr.URL_TAG, null);
- _user = _controller.obtainAtt(_config, JDBCEpr.USERNAME_TAG, null);
- _password = _controller.obtainAtt(_config, JDBCEpr.PASSWORD_TAG, "");
-
- _tableName = _config.getAttribute(ListenerTagNames.SQL_TABLE_NAME_TAG);
- if (null == _tableName)
- _tableName = _config.getAttribute(JDBCEpr.TABLE_NAME_TAG, null);
- if (Util.isNullString(_tableName))
- throw new ConfigurationException("Empty or invalid table name");
-
- _selectFields = _controller.obtainAtt(_config,
- ListenerTagNames.SQL_SELECT_FIELDS_TAG, "*");
- if (Util.isNullString(_selectFields))
- throw new ConfigurationException(
- "Empty or invalid list of select fields");
- _keyFields = _config.getAttribute(ListenerTagNames.SQL_KEY_FIELDS_TAG);
- if (null == _keyFields)
- _keyFields = _config.getAttribute(JDBCEpr.MESSAGE_ID_COLUMN_TAG,
- null);
- if (Util.isNullString(_keyFields))
- throw new ConfigurationException(
- "Empty or invalid list of key fields");
- _inProcessField = _config
- .getAttribute(ListenerTagNames.SQL_IN_PROCESS_FIELD_TAG);
- if (null == _inProcessField)
- _inProcessField = _config.getAttribute(JDBCEpr.STATUS_COLUMN_TAG);
- if (Util.isNullString(_inProcessField))
- throw new ConfigurationException(
- "A valid inProcessField attribute must be specified");
-
- _where = _controller.obtainAtt(_config,
- ListenerTagNames.SQL_WHERE_CONDITION_TAG, "");
- if (_where.trim().length() < 1)
- _logger.debug("No value specified for: "
- + ListenerTagNames.SQL_WHERE_CONDITION_TAG);
- _orderBy = _controller.obtainAtt(_config,
- ListenerTagNames.SQL_ORDER_BY_TAG, "");
- if (_orderBy.trim().length() < 1)
- _logger.debug("No value specified for: "
- + ListenerTagNames.SQL_ORDER_BY_TAG);
- _inProcessVals = _controller.obtainAtt(_config,
- ListenerTagNames.SQL_IN_PROCESS_VALUES_TAG,
- DEFAULT_IN_PROCESS_STATES);
-
- _deleteAfterOK = Boolean.parseBoolean(_controller.obtainAtt(_config,
- ListenerTagNames.SQL_POST_DEL_TAG, "false"));
- if (null == _config.getAttribute(ListenerTagNames.SQL_POST_DEL_TAG))
- _logger
- .debug("No value specified for: "
- + ListenerTagNames.SQL_POST_DEL_TAG
- + " - trigger row will not be deleted - 'in process field' will be used to show processing status");
-
- if (_inProcessVals.length() < 4)
- throw new Exception("Parameter <"
- + ListenerTagNames.SQL_IN_PROCESS_VALUES_TAG
- + "> must be at least 4 characters long (PWED)");
-
- _columns = _selectFields.split(",");
- if (_columns.length < 1)
- throw new Exception("Empty list of select fields");
-
- _keys = _keyFields.split(",");
- if (!"*".equals(_selectFields))
- {
- Set<String> colSet = new HashSet<String>(Arrays.asList(_columns));
- if (_keys.length < 1)
- throw new Exception("Empty list of keyFields");
- for (String currKey : _keys)
+
+ resolveComposerClass();
+
+ _driver = _controller.obtainAtt(_config, JDBCEpr.DRIVER_TAG, null);
+ _url = _controller.obtainAtt(_config, JDBCEpr.URL_TAG, null);
+ _user = _controller.obtainAtt(_config, JDBCEpr.USERNAME_TAG, null);
+ _password = _controller.obtainAtt(_config, JDBCEpr.PASSWORD_TAG, "");
+
+ _tableName = _config.getAttribute(ListenerTagNames.SQL_TABLE_NAME_TAG);
+ if (null == _tableName)
+ _tableName = _config.getAttribute(JDBCEpr.TABLE_NAME_TAG, null);
+ if (Util.isNullString(_tableName))
+ throw new ConfigurationException("Empty or invalid table name");
+
+ _selectFields = _controller.obtainAtt(_config,
+ ListenerTagNames.SQL_SELECT_FIELDS_TAG, "*");
+ if (Util.isNullString(_selectFields))
+ throw new ConfigurationException(
+ "Empty or invalid list of select fields");
+ _keyFields = _config.getAttribute(ListenerTagNames.SQL_KEY_FIELDS_TAG);
+ if (null == _keyFields)
+ _keyFields = _config.getAttribute(JDBCEpr.MESSAGE_ID_COLUMN_TAG,
+ null);
+ if (Util.isNullString(_keyFields))
+ throw new ConfigurationException(
+ "Empty or invalid list of key fields");
+ _inProcessField = _config
+ .getAttribute(ListenerTagNames.SQL_IN_PROCESS_FIELD_TAG);
+ if (null == _inProcessField)
+ _inProcessField = _config.getAttribute(JDBCEpr.STATUS_COLUMN_TAG);
+ if (Util.isNullString(_inProcessField))
+ throw new ConfigurationException(
+ "A valid inProcessField attribute must be specified");
+
+ _where = _controller.obtainAtt(_config,
+ ListenerTagNames.SQL_WHERE_CONDITION_TAG, "");
+ if (_where.trim().length() < 1)
+ _logger
+ .debug("No value specified for: " + ListenerTagNames.SQL_WHERE_CONDITION_TAG);
+ _orderBy = _controller.obtainAtt(_config,
+ ListenerTagNames.SQL_ORDER_BY_TAG, "");
+ if (_orderBy.trim().length() < 1)
+ _logger
+ .debug("No value specified for: " + ListenerTagNames.SQL_ORDER_BY_TAG);
+ _inProcessVals = _controller.obtainAtt(_config,
+ ListenerTagNames.SQL_IN_PROCESS_VALUES_TAG,
+ DEFAULT_IN_PROCESS_STATES);
+
+ _deleteAfterOK = Boolean.parseBoolean(_controller.obtainAtt(_config,
+ ListenerTagNames.SQL_POST_DEL_TAG, "false"));
+ if (null == _config.getAttribute(ListenerTagNames.SQL_POST_DEL_TAG))
+ _logger
+ .debug("No value specified for: " + ListenerTagNames.SQL_POST_DEL_TAG + " - trigger row will not be deleted - 'in process field' will be used to show processing status");
+
+ if (_inProcessVals.length() < 4)
+ throw new ConfigurationException(
+ "Parameter <" + ListenerTagNames.SQL_IN_PROCESS_VALUES_TAG + "> must be at least 4 characters long (PWED)");
+
+ _columns = _selectFields.split(",");
+ if (_columns.length < 1)
+ throw new ConfigurationException("Empty list of select fields");
+
+ _keys = _keyFields.split(",");
+ if (!"*".equals(_selectFields))
{
- if (colSet.contains(currKey))
- continue;
- else
+ Set<String> colSet = new HashSet<String>(Arrays.asList(_columns));
+ if (_keys.length < 1)
+ throw new ConfigurationException("Empty list of keyFields");
+ for (String currKey : _keys)
{
- StringBuilder sb = new StringBuilder().append(
- "All key field names in the <").append(
- ListenerTagNames.SQL_KEY_FIELDS_TAG).append(
- "> attribute must be in the ").append(
- ListenerTagNames.SQL_SELECT_FIELDS_TAG).append(
- "list - '").append(currKey)
- .append("' is not there");
- ;
- throw new ConfigurationException(sb.toString());
+ if (colSet.contains(currKey)) continue;
+ else
+ {
+ StringBuilder sb = new StringBuilder().append(
+ "All key field names in the <").append(
+ ListenerTagNames.SQL_KEY_FIELDS_TAG).append(
+ "> attribute must be in the ").append(
+ ListenerTagNames.SQL_SELECT_FIELDS_TAG).append(
+ "list - '").append(currKey)
+ .append("' is not there");
+ ;
+ throw new ConfigurationException(sb.toString());
+ }
}
}
+ prepareStatements();
}
- prepareStatements();
+ catch (RegistryException ex)
+ {
+ _logger.error("Could not contact Registry during configuration.", ex);
+
+ throw new ConfigurationException(ex);
+ }
} // ________________________________
- protected void prepareStatements() throws ConfigurationException
+ protected void prepareStatements () throws ConfigurationException
{
try
{
@@ -399,39 +394,77 @@
}
} // ________________________________
- protected void resolveComposerClass() throws Exception
+ /*
+ * Throw ConfigurationException for anything to do with setup. Ultimately
+ * could do with finer grained error handling. Probably need different types
+ * of setup exceptions.
+ */
+
+ protected void resolveComposerClass () throws ConfigurationException
{
- // Look for first "action" element - only first one will be used
- String tagName = ListenerTagNames.ACTION_ELEMENT_TAG;
- ConfigTree actionElement = _config.getFirstChild(tagName);
- String sProcessMethod = null;
- if (null != actionElement)
- { // class attribute
- _composerName = _controller.obtainAtt(actionElement,
- ListenerTagNames.ACTION_CLASS_TAG, null);
- _composerClass = Class.forName(_composerName);
- Constructor oConst = _composerClass.getConstructor(new Class[]
- { ConfigTree.class });
- _composer = oConst.newInstance(_config);
- tagName = ListenerTagNames.PROCESS_METHOD_TAG;
- sProcessMethod = _controller.obtainAtt(_config, tagName, tagName);
+ try
+ {
+ // Look for first "action" element - only first one will be used
+ String tagName = ListenerTagNames.ACTION_ELEMENT_TAG;
+ ConfigTree actionElement = _config.getFirstChild(tagName);
+ String sProcessMethod = null;
+ if (null != actionElement)
+ { // class attribute
+ _composerName = _controller.obtainAtt(actionElement,
+ ListenerTagNames.ACTION_CLASS_TAG, null);
+ _composerClass = Class.forName(_composerName);
+ Constructor oConst = _composerClass
+ .getConstructor(new Class[] { ConfigTree.class });
+ _composer = oConst.newInstance(_config);
+ tagName = ListenerTagNames.PROCESS_METHOD_TAG;
+ sProcessMethod = _controller.obtainAtt(_config, tagName, tagName);
+ }
+ else
+ {
+ _composerName = PackageRowContents.class.getName();
+ _composerClass = PackageRowContents.class;
+ _composer = new PackageRowContents();
+ sProcessMethod = "process";
+ _logger
+ .warn("No <" + ListenerTagNames.ACTION_ELEMENT_TAG + "> element found in cofiguration" + " - Using default composer class : " + _composerName);
+ }
+
+ _processMethod = _composerClass.getMethod(sProcessMethod,
+ new Class[] { Object.class });
}
- else
+ catch (InvocationTargetException ex)
{
- _composerName = PackageRowContents.class.getName();
- _composerClass = PackageRowContents.class;
- _composer = new PackageRowContents();
- sProcessMethod = "process";
- _logger.warn("No <" + ListenerTagNames.ACTION_ELEMENT_TAG
- + "> element found in cofiguration"
- + " - Using default composer class : " + _composerName);
+ _logger.error(ex);
+
+ throw new ConfigurationException(ex);
}
-
- _processMethod = _composerClass.getMethod(sProcessMethod, new Class[]
- { Object.class });
+ catch (IllegalAccessException ex)
+ {
+ _logger.error(ex);
+
+ throw new ConfigurationException(ex);
+ }
+ catch (InstantiationException ex)
+ {
+ _logger.error(ex);
+
+ throw new ConfigurationException(ex);
+ }
+ catch (ClassNotFoundException ex)
+ {
+ _logger.error(ex);
+
+ throw new ConfigurationException(ex);
+ }
+ catch (NoSuchMethodException ex)
+ {
+ _logger.error(ex);
+
+ throw new ConfigurationException(ex);
+ }
} // ________________________________
- protected List<Map<String, Object>> pollForCandidates()
+ protected List<Map<String, Object>> pollForCandidates ()
{
JdbcCleanConn oConn = null;
List<Map<String, Object>> oResults = new ArrayList<Map<String, Object>>();
@@ -468,18 +501,25 @@
* Obtain a new database connection with parameter info
*
* @return A new connection
- * @throws Exception -
+ * @throws ConfigurationException -
* if problems are encountered
*/
- protected JdbcCleanConn getDbConn() throws Exception
+ protected JdbcCleanConn getDbConn () throws ConfigurationException
{
- if (null == _dbConn)
+ try
{
- DataSource oDS = new SimpleDataSource(_driver, _url, _user,
- _password);
- _dbConn = new JdbcCleanConn(oDS);
+ if (null == _dbConn)
+ {
+ DataSource oDS = new SimpleDataSource(_driver, _url, _user,
+ _password);
+ _dbConn = new JdbcCleanConn(oDS);
+ }
+ return _dbConn;
}
- return _dbConn;
+ catch (IllegalArgumentException ex)
+ {
+ throw new ConfigurationException(ex);
+ }
} // ________________________________
/**
@@ -487,14 +527,13 @@
*
* @return - The resulting SQL statement
*/
- protected String scanStatement()
+ protected String scanStatement ()
{
StringBuilder sb = new StringBuilder().append("select ").append(
_selectFields).append(" from ").append(_tableName);
boolean bWhere = !Util.isNullString(_where);
- if (bWhere)
- sb.append(" where ").append(_where);
+ if (bWhere) sb.append(" where ").append(_where);
sb.append((bWhere) ? " and " : " where ");
String sLike = _inProcessVals.substring(0, 1).toUpperCase();
@@ -515,7 +554,7 @@
*
* @return - The resulting SQL statement
*/
- protected String updateStatement()
+ protected String updateStatement ()
{
StringBuilder sb = new StringBuilder().append("update ").append(
_tableName).append(" set ").append(_inProcessField).append(
@@ -523,8 +562,7 @@
int iCurr = 0;
for (String sCurr : _keys)
{
- if (iCurr++ > 0)
- sb.append(" and ");
+ if (iCurr++ > 0) sb.append(" and ");
sb.append(sCurr).append(" = ?");
}
return sb.toString();
@@ -539,7 +577,7 @@
*
* @return - The resulting SQL statement
*/
- protected String selectForUpdStatement()
+ protected String selectForUpdStatement ()
{
StringBuilder sb = new StringBuilder().append("select ").append(
_inProcessField).append(" from ").append(_tableName).append(
@@ -547,8 +585,7 @@
int iCurr = 0;
for (String sCurr : _keys)
{
- if (iCurr++ > 0)
- sb.append(" and ");
+ if (iCurr++ > 0) sb.append(" and ");
sb.append(sCurr).append(" = ?");
}
return sb.append(" for update").toString();
@@ -560,15 +597,14 @@
*
* @return - The resulting SQL statement
*/
- protected String deleteStatement()
+ protected String deleteStatement ()
{
StringBuilder sb = new StringBuilder().append("delete from ").append(
_tableName).append(" where ");
int iCurr = 0;
for (String sCurr : _keys)
{
- if (iCurr++ > 0)
- sb.append(" and ");
+ if (iCurr++ > 0) sb.append(" and ");
sb.append(sCurr).append(" = ?");
}
return sb.toString();
@@ -579,7 +615,7 @@
*
* @return true if row deletion was successful - false otherwise
*/
- protected boolean deleteCurrentRow()
+ protected boolean deleteCurrentRow ()
{
try
{
@@ -624,28 +660,28 @@
return false;
} // ________________________________
- protected String getStatus(ROW_STATE p_oState)
+ protected String getStatus (ROW_STATE p_oState)
{
int iPos = p_oState.ordinal();
return _inProcessVals.substring(iPos, ++iPos);
} // ________________________________
- protected boolean changeStatusToWorking()
+ protected boolean changeStatusToWorking ()
{
return changeStatus(ROW_STATE.Pending, ROW_STATE.Working);
} // ________________________________
- protected boolean changeStatusToDone()
+ protected boolean changeStatusToDone ()
{
return changeStatus(ROW_STATE.Working, ROW_STATE.Done);
} // ________________________________
- protected boolean changeStatusToError()
+ protected boolean changeStatusToError ()
{
return changeStatus(ROW_STATE.Working, ROW_STATE.Error);
} // ________________________________
- protected boolean changeStatus(ROW_STATE fromState, ROW_STATE toState)
+ protected boolean changeStatus (ROW_STATE fromState, ROW_STATE toState)
{
try
{
@@ -684,29 +720,26 @@
if (_logger.isDebugEnabled())
_logger
- .debug("Successfully changed row state from "
- + fromState
- + " to "
- + toState
- + ".");
+ .debug("Successfully changed row state from " + fromState + " to " + toState + ".");
return true;
}
else
{
- _logger.warn("Cannot change row state from "
- + fromState + " to " + toState
- + ". Row not in state " + fromState);
+ _logger
+ .warn("Cannot change row state from " + fromState + " to " + toState + ". Row not in state " + fromState);
return false;
}
}
- _logger.error("Row status change to " + toState
- + " has failed. Rolling back!!");
+ _logger
+ .error("Row status change to " + toState + " has failed. Rolling back!!");
}
catch (Exception e)
{
- _logger.error("Row status change to " + toState
- + " has failed. Rolling back!!", e);
+ _logger
+ .error(
+ "Row status change to " + toState + " has failed. Rolling back!!",
+ e);
}
try
@@ -715,8 +748,9 @@
}
catch (Exception e)
{
- _logger.error("Unable to rollback row status change to "
- + fromState.name(), e);
+ _logger.error(
+ "Unable to rollback row status change to " + fromState
+ .name(), e);
}
}
catch (Exception e)
@@ -738,10 +772,10 @@
*/
public static class PackageRowContents
{
- public Message process(Object obj) throws Exception
+ public Message process (Object obj)
{
if (!(obj instanceof Map))
- throw new Exception("Object must be instance of Map");
+ throw new IllegalArgumentException("Object must be instance of Map");
Message message = MessageFactory.getInstance().getMessage();
org.jboss.soa.esb.message.Properties props = message
Modified: labs/jbossesb/trunk/product/core/listeners/src/org/jboss/soa/esb/listeners/message/MessageAwareListener.java
===================================================================
--- labs/jbossesb/trunk/product/core/listeners/src/org/jboss/soa/esb/listeners/message/MessageAwareListener.java 2007-01-20 09:09:48 UTC (rev 8932)
+++ labs/jbossesb/trunk/product/core/listeners/src/org/jboss/soa/esb/listeners/message/MessageAwareListener.java 2007-01-20 09:33:16 UTC (rev 8933)
@@ -41,12 +41,13 @@
import org.jboss.soa.esb.util.Util;
/**
- * Esb Message aware transport independent listener.
- * <p/> Relies on the CourierFactory to obtain an appropriate Courier
- * for the EPR this listener will be listening on
- * <br/>Keeps a thread pool to instantiate ActionProcessingPipelines whenever a Message is received
+ * Esb Message aware transport independent listener. <p/> Relies on the
+ * CourierFactory to obtain an appropriate Courier for the EPR this listener
+ * will be listening on <br/>Keeps a thread pool to instantiate
+ * ActionProcessingPipelines whenever a Message is received
*
- * @author <a href="mailto:schifest at heuristica.com.ar">schifest at heuristica.com.ar</a>
+ * @author <a
+ * href="mailto:schifest at heuristica.com.ar">schifest at heuristica.com.ar</a>
* @since Version 4.0
*/
@@ -54,158 +55,188 @@
{
/**
* public constructor
- * @param controller ListenerManager - the controlling process
- * @param config ConfigTree - Containing 'static' configuration for this instance
- * @throws Exception
+ *
+ * @param controller
+ * ListenerManager - the controlling process
+ * @param config
+ * ConfigTree - Containing 'static' configuration for this
+ * instance
+ * @throws ConfigurationException
*/
- public MessageAwareListener(ListenerManager controller, ConfigTree config)
- throws ConfigurationException
- {
- super (controller, config);
- } // _______________________________
+ public MessageAwareListener (ListenerManager controller, ConfigTree config)
+ throws ConfigurationException
+ {
+ super(controller, config);
+ } // _______________________________
- /**
- * Check for mandatory and optional attributes in parameter tree
- *
- * @throws ConfigurationException -
- * if mandatory atts are not right or actionClass not in
- * classpath
- */
- protected void checkMyParms() throws ConfigurationException
- {
- super.checkMyParms();
+ /**
+ * Check for mandatory and optional attributes in parameter tree
+ *
+ * @throws ConfigurationException -
+ * if mandatory atts are not right or actionClass not in
+ * classpath
+ */
+ protected void checkMyParms () throws ConfigurationException
+ {
+ super.checkMyParms();
- if (Util.isNullString(_eprCategoryName))
- throw new ConfigurationException("Missing or invalid "+ListenerTagNames.SERVICE_CATEGORY_NAME_TAG);
- if (Util.isNullString(_eprName))
- throw new ConfigurationException("Missing or invalid "+ListenerTagNames.SERVICE_NAME_TAG);
-
- ConfigTree eprElement = _config.getFirstChild(ListenerTagNames.EPR_TAG);
- if (null==eprElement)
- throw new ConfigurationException("Missing or invalid "+ListenerTagNames.EPR_TAG+" element");
- _epr = ListenerUtil.assembleEpr(eprElement);
-// _logger.debug(EPRHelper.toXMLString(_epr));
- } // ________________________________
-
+ if (Util.isNullString(_eprCategoryName))
+ throw new ConfigurationException(
+ "Missing or invalid " + ListenerTagNames.SERVICE_CATEGORY_NAME_TAG);
+ if (Util.isNullString(_eprName))
+ throw new ConfigurationException(
+ "Missing or invalid " + ListenerTagNames.SERVICE_NAME_TAG);
+
+ ConfigTree eprElement = _config.getFirstChild(ListenerTagNames.EPR_TAG);
+ if (null == eprElement)
+ throw new ConfigurationException(
+ "Missing or invalid " + ListenerTagNames.EPR_TAG + " element");
+ _epr = ListenerUtil.assembleEpr(eprElement);
+ // _logger.debug(EPRHelper.toXMLString(_epr));
+ } // ________________________________
+
@Override
- public boolean isMessageAware() { return true; }
-
-
+ public boolean isMessageAware ()
+ {
+ return true;
+ }
+
@Override
- public boolean initializeRun()
+ public boolean initializeRun ()
{
- try
- {
- registerProcess();
- }
- catch (Exception re)
- {
- _logger.fatal("Could not register service " + re.getLocalizedMessage(),re);
- try { Thread.sleep(1000); }
- catch (Exception iE) {/* OK do nothing */}
+ try
+ {
+ registerProcess();
+ }
+ catch (Exception re)
+ {
+ _logger.fatal("Could not register service " + re
+ .getLocalizedMessage(), re);
+ try
+ {
+ Thread.sleep(1000);
+ }
+ catch (Exception iE)
+ {/* OK do nothing */
+ }
return false;
}
try
{
Method setPollLatency = null;
- _pickUpCourier = CourierFactory.getPickupCourier(_epr);
- try
- {
- setPollLatency = _pickUpCourier.getClass()
- .getMethod("setPollLatency", new Class[] {Long.class} );
- }
- catch (NoSuchMethodException e)
- {
- // OK, just leave it null
- }
+ _pickUpCourier = CourierFactory.getPickupCourier(_epr);
+ try
+ {
+ setPollLatency = _pickUpCourier.getClass().getMethod(
+ "setPollLatency", new Class[] { Long.class });
+ }
+ catch (NoSuchMethodException e)
+ {
+ // OK, just leave it null
+ }
- if (null!=setPollLatency)
- {
- String latency = _config.getAttribute(ListenerTagNames.POLL_LATENCY_SECS_TAG);
- long lSeconds = 10;
- if (null!=latency)
- try
- {
- lSeconds = Integer.parseInt(latency);
- }
- catch (NumberFormatException e)
- {
- _logger.warn("Invalid number format <"+latency+"> using default value ("+lSeconds+")");
- }
- try
- {
- setPollLatency.invoke(_pickUpCourier, new Long(1000*lSeconds));
- }
- catch (Exception e)
- {
- _logger.warn("Problems invoking setPollLatency(long)",e);
- return false;
- }
- }
-
- return true;
+ if (null != setPollLatency)
+ {
+ String latency = _config
+ .getAttribute(ListenerTagNames.POLL_LATENCY_SECS_TAG);
+ long lSeconds = 10;
+ if (null != latency)
+ {
+ try
+ {
+ lSeconds = Integer.parseInt(latency);
+ }
+ catch (NumberFormatException e)
+ {
+ _logger
+ .warn("Invalid number format <" + latency + "> using default value (" + lSeconds + ")");
+ }
+ }
+
+ try
+ {
+ setPollLatency.invoke(_pickUpCourier, new Long(
+ 1000 * lSeconds));
+ }
+ catch (Exception e)
+ {
+ _logger.warn("Problems invoking setPollLatency(long)", e);
+ return false;
+ }
+ }
+
+ return true;
}
catch (MalformedEPRException ex)
{
- _logger.fatal("Malformed EPR: "+_epr);
-
+ _logger.fatal("Malformed EPR: " + _epr);
+
return false;
}
catch (CourierException e)
{
- _logger.fatal("No appropriate courier can be obtained for " + _epr.toString(),e);
+ _logger.fatal("No appropriate courier can be obtained for " + _epr
+ .toString(), e);
return false;
}
- } //________________________________
+ } // ________________________________
@Override
- public boolean finalizeRun()
+ public boolean finalizeRun ()
{
- try
- {
- CourierUtil.cleanCourier(_pickUpCourier);
- unregisterProcess();
- return true;
- }
- catch (RegistryException re)
- {
- _logger.warn("Could not un register service " + re.getLocalizedMessage());
- return false;
- }
+ try
+ {
+ CourierUtil.cleanCourier(_pickUpCourier);
+ unregisterProcess();
+ return true;
+ }
+ catch (RegistryException re)
+ {
+ _logger.warn("Could not un register service " + re
+ .getLocalizedMessage());
+ return false;
+ }
- } //________________________________
+ } // ________________________________
@Override
- public void waitForEventAndProcess(long maxWaitMillis)
+ public void waitForEventAndProcess (long maxWaitMillis)
{
Message message = null;
- try { message = (maxWaitMillis > 0 ) ? _pickUpCourier.pickup(maxWaitMillis) : null; }
- catch (CourierTimeoutException e) { return; }
- catch (CourierException e)
+ try
{
- _logger.error("Courier Exception",e);
+ message = (maxWaitMillis > 0) ? _pickUpCourier
+ .pickup(maxWaitMillis) : null;
+ }
+ catch (CourierTimeoutException e)
+ {
return;
}
+ catch (CourierException e)
+ {
+ _logger.error("Courier Exception", e);
+ return;
+ }
- if (null!=message)
- {
- ActionProcessingPipeline chain = null;
+ if (null != message)
+ {
+ ActionProcessingPipeline chain = null;
- try
- {
- chain = new ActionProcessingPipeline(message,_config);
- chain.addObserver(this);
- updateThreadCount(+1);
- _execService.execute(chain);
- }
- catch (Exception e)
- {
- _logger.error("ActionProcessingPipeline exception",e);
- return;
- }
- }
-
- } //________________________________
+ try
+ {
+ chain = new ActionProcessingPipeline(message, _config);
+ chain.addObserver(this);
+ updateThreadCount(+1);
+ _execService.execute(chain);
+ }
+ catch (Exception e)
+ {
+ _logger.error("ActionProcessingPipeline exception", e);
+ return;
+ }
+ }
- protected PickUpOnlyCourier _pickUpCourier;
-}
+ } // ________________________________
+
+ protected PickUpOnlyCourier _pickUpCourier;
+}
Modified: labs/jbossesb/trunk/product/core/rosetta/src/org/jboss/internal/soa/esb/command/JmsCommandQueue.java
===================================================================
--- labs/jbossesb/trunk/product/core/rosetta/src/org/jboss/internal/soa/esb/command/JmsCommandQueue.java 2007-01-20 09:09:48 UTC (rev 8932)
+++ labs/jbossesb/trunk/product/core/rosetta/src/org/jboss/internal/soa/esb/command/JmsCommandQueue.java 2007-01-20 09:33:16 UTC (rev 8933)
@@ -26,22 +26,23 @@
import org.jboss.soa.esb.util.Util;
/**
- * JMS based Command Queue implementation.
- * <p/>
- * This code was simply pulled from the GpListener.
+ * JMS based Command Queue implementation. <p/> This code was simply pulled from
+ * the GpListener.
+ *
* @author <a href="mailto:tom.fennelly at jboss.com">tom.fennelly at jboss.com</a>
* @since Version 4.0
*/
-public class JmsCommandQueue implements CommandQueue {
+public class JmsCommandQueue implements CommandQueue
+{
private static Logger logger = Logger.getLogger(JmsCommandQueue.class);
public static final String COMMAND_CONN_FACTORY = "commandConnFactoryClass";
public static final String COMMAND_JNDI_URL = "commandJndiURL";
-
+
public static final String COMMAND_JNDI_CONTEXT_FACTORY = "commandJndiContextFactory";
-
+
public static final String COMMAND_JNDI_PKG_PREFIX = "commandJndiUrlPkgPrefix";
public static final String COMMAND_IS_TOPIC = "commandIsTopic";
@@ -49,67 +50,96 @@
public static final String COMMAND_JNDI_NAME = "commandJndiName";
public static final String COMMAND_MSG_SELECTOR = "messageSelector";
-
+
private MessageConsumer m_oCmdSrc;
private Session m_oJmsSess;
private Connection m_oJmsConn;
-
- public void open(ConfigTree config) throws CommandQueueException {
- try {
+
+ public void open (ConfigTree config) throws CommandQueueException
+ {
+ try
+ {
initialiseJMS(config);
- } catch (Exception e) {
- throw new CommandQueueException("Failed to initialise JMS Command Queue.", e);
}
+ catch (Exception e)
+ {
+ throw new CommandQueueException(
+ "Failed to initialise JMS Command Queue.", e);
+ }
}
- public void close() throws CommandQueueException {
- if (null != m_oJmsSess) {
- try {
+ public void close () throws CommandQueueException
+ {
+ if (null != m_oJmsSess)
+ {
+ try
+ {
m_oJmsSess.close();
- } catch (JMSException eS) {/* Tried my best - Just continue */
}
+ catch (JMSException eS)
+ {/* Tried my best - Just continue */
+ }
}
- if (null != m_oJmsConn) {
- try {
+ if (null != m_oJmsConn)
+ {
+ try
+ {
m_oJmsConn.close();
- } catch (JMSException eC) {/* Tried my best - Just continue */
}
+ catch (JMSException eC)
+ {/* Tried my best - Just continue */
+ }
}
}
- public String receiveCommand(long timeout) throws CommandQueueException {
- try {
+ public String receiveCommand (long timeout) throws CommandQueueException
+ {
+ try
+ {
Message jmsMessage = m_oCmdSrc.receive(timeout);
-
- if (null == jmsMessage)
- return null;
- if (jmsMessage instanceof TextMessage) {
- return ((TextMessage)jmsMessage).getText();
- } else {
- logger.warn("Message in command queue IGNORED - should be instanceof TextMessage");
+
+ if (null == jmsMessage) return null;
+ if (jmsMessage instanceof TextMessage)
+ {
+ return ((TextMessage) jmsMessage).getText();
}
- } catch(Exception e) {
- throw new CommandQueueException("Exception receiving message from JMS Command Queue.", e);
+ else
+ {
+ logger
+ .warn("Message in command queue IGNORED - should be instanceof TextMessage");
+ }
}
-
+ catch (Exception e)
+ {
+ throw new CommandQueueException(
+ "Exception receiving message from JMS Command Queue.", e);
+ }
+
return null;
}
- private void initialiseJMS(ConfigTree p_oP) throws Exception {
+ private void initialiseJMS (ConfigTree p_oP) throws ConfigurationException, JMSException
+ {
// Only check for JMS attributes if a queue JNDI name was specified
String sJndiName = p_oP.getAttribute(COMMAND_JNDI_NAME);
- if (!Util.isNullString(sJndiName)) {
+
+ if (!Util.isNullString(sJndiName))
+ {
Map<String, Object> oNewAtts = new HashMap<String, Object>();
oNewAtts.put(COMMAND_JNDI_NAME, sJndiName);
- String sJndiURL = obtainAtt(p_oP, COMMAND_JNDI_URL, NamingContext.JBOSS_PROVIDER_URL);
+ String sJndiURL = obtainAtt(p_oP, COMMAND_JNDI_URL,
+ NamingContext.JBOSS_PROVIDER_URL);
oNewAtts.put(COMMAND_JNDI_URL, sJndiURL);
- String sJndiContextFactory = obtainAtt(p_oP, COMMAND_JNDI_CONTEXT_FACTORY, NamingContext.JBOSS_INITIAL_CONTEXT_FACTORY);
+ String sJndiContextFactory = obtainAtt(p_oP,
+ COMMAND_JNDI_CONTEXT_FACTORY,
+ NamingContext.JBOSS_INITIAL_CONTEXT_FACTORY);
oNewAtts.put(COMMAND_JNDI_CONTEXT_FACTORY, sJndiContextFactory);
- String sJndiPkgPrefix = obtainAtt(p_oP, COMMAND_JNDI_PKG_PREFIX, NamingContext.JBOSS_URL_PKG_PREFIX);
+ String sJndiPkgPrefix = obtainAtt(p_oP, COMMAND_JNDI_PKG_PREFIX,
+ NamingContext.JBOSS_URL_PKG_PREFIX);
oNewAtts.put(COMMAND_JNDI_PKG_PREFIX, sJndiPkgPrefix);
Context oJndiCtx = NamingContext.getServerContext(sJndiURL,
sJndiContextFactory, sJndiPkgPrefix);
@@ -119,7 +149,16 @@
oNewAtts.put(COMMAND_CONN_FACTORY, sFactClass);
if (Util.isNullString(sFactClass))
sFactClass = "ConnectionFactory";
- Object oFactCls = oJndiCtx.lookup(sFactClass);
+ Object oFactCls = null;
+
+ try
+ {
+ oFactCls = oJndiCtx.lookup(sFactClass);
+ }
+ catch (NamingException ex)
+ {
+ throw new ConfigurationException(ex);
+ }
String sMsgSelector = p_oP.getAttribute(COMMAND_MSG_SELECTOR);
if (null != sMsgSelector)
@@ -127,30 +166,39 @@
boolean bIsTopic = Boolean.parseBoolean(obtainAtt(p_oP,
COMMAND_IS_TOPIC, "false"));
- if (bIsTopic) {
+ if (bIsTopic)
+ {
TopicConnectionFactory tcf = (TopicConnectionFactory) oFactCls;
TopicConnection oTC = tcf.createTopicConnection();
TopicSession oSess = oTC.createTopicSession(false,
TopicSession.AUTO_ACKNOWLEDGE);
Topic oTopic = null;
- try {
+ try
+ {
oTopic = (Topic) oJndiCtx.lookup(sJndiName);
- } catch (NamingException ne) {
+ }
+ catch (NamingException ne)
+ {
oTopic = oSess.createTopic(sJndiName);
}
m_oJmsConn = oTC;
m_oJmsSess = oSess;
oTC.start();
m_oCmdSrc = oSess.createSubscriber(oTopic, sMsgSelector, true);
- } else {
+ }
+ else
+ {
QueueConnectionFactory qcf = (QueueConnectionFactory) oFactCls;
QueueConnection oQC = qcf.createQueueConnection();
QueueSession oSess = oQC.createQueueSession(false,
TopicSession.AUTO_ACKNOWLEDGE);
javax.jms.Queue oQ = null;
- try {
+ try
+ {
oQ = (javax.jms.Queue) oJndiCtx.lookup(sJndiName);
- } catch (NamingException ne) {
+ }
+ catch (NamingException ne)
+ {
oQ = oSess.createQueue(sJndiName);
}
oQC.start();
@@ -171,15 +219,17 @@
* @param p_sDefault
* String -default value if requested attribute is not there
* @return String - value of attribute, or default value (if null)
- * @throws Exception -
+ * @throws ConfigurationException -
* If requested attribute not found and no default value
* supplied by invoker
*/
- private String obtainAtt(ConfigTree p_oP, String p_sAtt, String p_sDefault)
- throws ConfigurationException {
+ private String obtainAtt (ConfigTree p_oP, String p_sAtt, String p_sDefault)
+ throws ConfigurationException
+ {
String sVal = p_oP.getAttribute(p_sAtt);
if ((null == sVal) && (null == p_sDefault))
- throw new ConfigurationException("Missing or invalid <" + p_sAtt + "> attribute");
+ throw new ConfigurationException(
+ "Missing or invalid <" + p_sAtt + "> attribute");
return (null != sVal) ? sVal : p_sDefault;
} // ________________________________
Modified: labs/jbossesb/trunk/product/core/rosetta/src/org/jboss/internal/soa/esb/couriers/JmsCourier.java
===================================================================
--- labs/jbossesb/trunk/product/core/rosetta/src/org/jboss/internal/soa/esb/couriers/JmsCourier.java 2007-01-20 09:09:48 UTC (rev 8932)
+++ labs/jbossesb/trunk/product/core/rosetta/src/org/jboss/internal/soa/esb/couriers/JmsCourier.java 2007-01-20 09:33:16 UTC (rev 8933)
@@ -24,6 +24,7 @@
import java.io.IOException;
import java.io.Serializable;
+import java.net.URISyntaxException;
import java.util.List;
import javax.jms.Connection;
@@ -45,6 +46,8 @@
import javax.xml.parsers.ParserConfigurationException;
import org.apache.log4j.Logger;
+import org.jboss.soa.esb.ConfigurationException;
+import org.jboss.soa.esb.addressing.MalformedEPRException;
import org.jboss.soa.esb.addressing.eprs.JMSEpr;
import org.jboss.soa.esb.couriers.CourierException;
import org.jboss.soa.esb.helpers.KeyValuePair;
@@ -53,316 +56,457 @@
import org.jboss.soa.esb.util.Util;
import org.xml.sax.SAXException;
-public class JmsCourier implements PickUpOnlyCourier, DeliverOnlyCourier
+public class JmsCourier implements PickUpOnlyCourier, DeliverOnlyCourier
{
/**
* disable default constructor
*/
- private JmsCourier() { }
+ private JmsCourier ()
+ {
+ }
/**
- * package protected constructor - Objects of Courier should only be instantiated by the Factory
+ * package protected constructor - Objects of Courier should only be
+ * instantiated by the Factory
+ *
* @param epr
*/
- JmsCourier(JMSEpr epr) throws CourierException { this(epr,false); }
+ JmsCourier (JMSEpr epr) throws CourierException
+ {
+ this(epr, false);
+ }
/**
- * package protected constructor - Objects of Courier should only be instantiated by the Factory
+ * package protected constructor - Objects of Courier should only be
+ * instantiated by the Factory
+ *
* @param epr
*/
- JmsCourier(JMSEpr epr, boolean isReceiver) throws CourierException
+ JmsCourier (JMSEpr epr, boolean isReceiver) throws CourierException
{
_isReceiver = isReceiver;
- _epr = epr;
- _sleepForRetries = 3000;
+ _epr = epr;
+ _sleepForRetries = 3000;
- if (! _isReceiver)
- try { _messageProperties = Util.propertiesFromSelector(_epr.getMessageSelector()); }
- catch (Exception e) { throw new CourierException(e); }
-
- } //________________________________
+ if (!_isReceiver)
+ try
+ {
+ _messageProperties = Util.propertiesFromSelector(_epr
+ .getMessageSelector());
+ }
+ catch (Exception e)
+ {
+ throw new CourierException(e);
+ }
- void cleanup()
+ } // ________________________________
+
+ void cleanup ()
{
- if (null != _messageProducer)
- try { _messageProducer.close(); }
- catch (JMSException e) {/* OK do nothing */ }
-
- if (null != _messageConsumer)
- try { _messageConsumer.close(); }
- catch (JMSException e) {/* OK do nothing */ }
-
- if (null != _jmsSession)
- try { _jmsSession.close(); }
- catch (JMSException e) {/* OK do nothing */ }
-
- if (null != _jmsConnection)
- try { _jmsConnection.close(); }
- catch (JMSException e) {/* OK do nothing */ }
+ if (null != _messageProducer) try
+ {
+ _messageProducer.close();
+ }
+ catch (JMSException e)
+ {/* OK do nothing */
+ }
- _messageProducer = null;
- _messageConsumer = null;
- _jmsSession = null;
- _jmsConnection = null;
- } //________________________________
+ if (null != _messageConsumer) try
+ {
+ _messageConsumer.close();
+ }
+ catch (JMSException e)
+ {/* OK do nothing */
+ }
+ if (null != _jmsSession) try
+ {
+ _jmsSession.close();
+ }
+ catch (JMSException e)
+ {/* OK do nothing */
+ }
+
+ if (null != _jmsConnection) try
+ {
+ _jmsConnection.close();
+ }
+ catch (JMSException e)
+ {/* OK do nothing */
+ }
+
+ _messageProducer = null;
+ _messageConsumer = null;
+ _jmsSession = null;
+ _jmsConnection = null;
+ } // ________________________________
+
/**
* package the ESB message in a javax.jms.ObjectMessage, and send it
- * @param message Message - the message to deliver
+ *
+ * @param message
+ * Message - the message to deliver
* @return boolean - the result of the delivery
- * @throws CourierException - if problems were encountered
+ * @throws CourierException -
+ * if problems were encountered
*/
- public boolean deliver(Message message) throws CourierException
+ public boolean deliver (Message message) throws CourierException
{
if (_isReceiver)
throw new CourierException("This is a read-only Courier");
- if (null==message)
- return false;
- if (null==_messageProducer)
- try { createMessageProducer();}
- catch (Exception e) {throw new CourierException(e); }
+ if (null == message) return false;
+ if (null == _messageProducer) try
+ {
+ createMessageProducer();
+ }
+ catch (Exception e)
+ {
+ throw new CourierException(e);
+ }
- while (null!=_messageProducer)
+ while (null != _messageProducer)
{
- try
+ try
{
- // obtain Serializable version of arg0 and package it in a jms ObjectMessage
- ObjectMessage msg = _jmsSession.createObjectMessage(Util.serialize(message));
+ // obtain Serializable version of arg0 and package it in a jms
+ // ObjectMessage
+ ObjectMessage msg = _jmsSession.createObjectMessage(Util
+ .serialize(message));
for (KeyValuePair kvp : _messageProperties)
msg.setStringProperty(kvp.getKey(), kvp.getValue());
sendMessage(msg);
return true;
}
- catch (JMSException e) { jmsConnectRetry(e); }
- catch (Exception e) { throw new CourierException(e);}
+ catch (JMSException e)
+ {
+ jmsConnectRetry(e);
+ }
+ catch (Exception e)
+ {
+ throw new CourierException(e);
+ }
}
return false;
- } //________________________________
-
+ } // ________________________________
+
/**
- * send/publish a javax.jms.ObjectMessage (that will contain the serialized ESB Message)
+ * send/publish a javax.jms.ObjectMessage (that will contain the serialized
+ * ESB Message)
+ *
* @param jmsMessage
*/
- private void sendMessage(javax.jms.Message jmsMessage) throws JMSException
- {
- if (_messageProducer instanceof TopicPublisher)
- ((TopicPublisher)_messageProducer).publish(jmsMessage);
- else
- _messageProducer.send(jmsMessage);
- } //________________________________
-
- private void jmsConnectRetry(Exception exc)
- {
- _logger.error("JMS error. Attempting JMS reconnect.", exc);
- _jmsConnection = null;
- _jmsSession = null;
- _messageProducer= null;
- _messageConsumer= null;
+ private void sendMessage (javax.jms.Message jmsMessage) throws JMSException
+ {
+ if (_messageProducer instanceof TopicPublisher) ((TopicPublisher) _messageProducer)
+ .publish(jmsMessage);
+ else
+ _messageProducer.send(jmsMessage);
+ } // ________________________________
+ private void jmsConnectRetry (Exception exc)
+ {
+ _logger.error("JMS error. Attempting JMS reconnect.", exc);
+ _jmsConnection = null;
+ _jmsSession = null;
+ _messageProducer = null;
+ _messageConsumer = null;
+
for (int i1 = 0; i1 < 5; i1++)
{
- // try to reconnect to the queue
- try
- {
- if (_isReceiver)
- createMessageConsumer();
- else
- createMessageProducer();
- }
- catch (Exception e)
- {
- _logger.error("Reconnecting to JMS", e);
- try { Thread.sleep(_sleepForRetries); }
- catch (InterruptedException e1)
- { // Just return after logging
- _logger.error("Unexpected thread interupt exception.", e);
- break;
- }
- }
+ // try to reconnect to the queue
+ try
+ {
+ if (_isReceiver) createMessageConsumer();
+ else
+ createMessageProducer();
+ }
+ catch (Exception e)
+ {
+ _logger.error("Reconnecting to JMS", e);
+ try
+ {
+ Thread.sleep(_sleepForRetries);
+ }
+ catch (InterruptedException e1)
+ { // Just return after logging
+ _logger.error("Unexpected thread interupt exception.", e);
+ break;
+ }
+ }
}
- } //________________________________
-
- private void createMessageProducer() throws Exception
- {
- String sJndiConnectionFactory = _epr.getJndiContextFactory();
- if (Util.isNullString(sJndiConnectionFactory))
- sJndiConnectionFactory = NamingContext.JBOSS_INITIAL_CONTEXT_FACTORY;
- String sJndiURL = _epr.getJndiURL();
- if (Util.isNullString(sJndiURL))
- sJndiURL = NamingContext.JBOSS_PROVIDER_URL;
- String sJndiPkgPrefix = _epr.getJndiPkgPrefix();
- if (Util.isNullString(sJndiPkgPrefix))
- sJndiPkgPrefix = NamingContext.JBOSS_URL_PKG_PREFIX;
- Context oJndiCtx = NamingContext.getServerContext(sJndiURL, sJndiConnectionFactory, sJndiPkgPrefix);
+ } // ________________________________
- String sFactoryClass = _epr.getConnectionFactory();
- if (Util.isNullString(sFactoryClass))
- sFactoryClass = "ConnectionFactory";
-
- Object tmp = oJndiCtx.lookup(sFactoryClass);
-
- String sType = _epr.getDestinationType();
- if (JMSEpr.QUEUE_TYPE.equals(sType))
- {
- QueueConnectionFactory qcf = (QueueConnectionFactory) tmp;
- QueueConnection qConn = qcf.createQueueConnection();
- QueueSession qSess = qConn.createQueueSession(false,QueueSession.AUTO_ACKNOWLEDGE);
- javax.jms.Queue queue = null;
- try {
- queue = (javax.jms.Queue) oJndiCtx.lookup(_epr.getDestinationName());
- } catch (NamingException ne){
- queue = qSess.createQueue(_epr.getDestinationName());
- }
- _jmsConnection = qConn;
- _jmsSession = qSess;
- _messageProducer = qSess.createSender(queue);
- }
- else if(JMSEpr.TOPIC_TYPE.equals(sType))
- {
- TopicConnectionFactory tcf = (TopicConnectionFactory) tmp;
- TopicConnection tConn = tcf.createTopicConnection();
- TopicSession tSess = tConn.createTopicSession(false,TopicSession.AUTO_ACKNOWLEDGE);
- Topic topic = null;
- try {
- topic = (Topic) oJndiCtx.lookup(_epr.getDestinationName());
- } catch (NamingException ne) {
- topic = tSess.createTopic(_epr.getDestinationName());
- }
- _jmsConnection = tConn;
- _jmsSession = tSess;
- _messageProducer = tSess.createPublisher(topic);
- }
- else
- throw new CourierException("Unknown destination type");
-
- } //________________________________
+ private void createMessageProducer () throws CourierException,
+ MalformedEPRException
+ {
+ try
+ {
+ String sJndiConnectionFactory = _epr.getJndiContextFactory();
+ if (Util.isNullString(sJndiConnectionFactory))
+ sJndiConnectionFactory = NamingContext.JBOSS_INITIAL_CONTEXT_FACTORY;
+ String sJndiURL = _epr.getJndiURL();
+ if (Util.isNullString(sJndiURL))
+ sJndiURL = NamingContext.JBOSS_PROVIDER_URL;
+ String sJndiPkgPrefix = _epr.getJndiPkgPrefix();
+ if (Util.isNullString(sJndiPkgPrefix))
+ sJndiPkgPrefix = NamingContext.JBOSS_URL_PKG_PREFIX;
+ Context oJndiCtx = NamingContext.getServerContext(sJndiURL,
+ sJndiConnectionFactory, sJndiPkgPrefix);
- public Message pickup(long millis) throws CourierException
+ String sFactoryClass = _epr.getConnectionFactory();
+ if (Util.isNullString(sFactoryClass))
+ sFactoryClass = "ConnectionFactory";
+
+ Object tmp = oJndiCtx.lookup(sFactoryClass);
+
+ String sType = _epr.getDestinationType();
+ if (JMSEpr.QUEUE_TYPE.equals(sType))
+ {
+ QueueConnectionFactory qcf = (QueueConnectionFactory) tmp;
+ QueueConnection qConn = qcf.createQueueConnection();
+ QueueSession qSess = qConn.createQueueSession(false,
+ QueueSession.AUTO_ACKNOWLEDGE);
+ javax.jms.Queue queue = null;
+ try
+ {
+ queue = (javax.jms.Queue) oJndiCtx.lookup(_epr
+ .getDestinationName());
+ }
+ catch (NamingException ne)
+ {
+ queue = qSess.createQueue(_epr.getDestinationName());
+ }
+ _jmsConnection = qConn;
+ _jmsSession = qSess;
+ _messageProducer = qSess.createSender(queue);
+ }
+ else
+ if (JMSEpr.TOPIC_TYPE.equals(sType))
+ {
+ TopicConnectionFactory tcf = (TopicConnectionFactory) tmp;
+ TopicConnection tConn = tcf.createTopicConnection();
+ TopicSession tSess = tConn.createTopicSession(false,
+ TopicSession.AUTO_ACKNOWLEDGE);
+ Topic topic = null;
+ try
+ {
+ topic = (Topic) oJndiCtx.lookup(_epr
+ .getDestinationName());
+ }
+ catch (NamingException ne)
+ {
+ topic = tSess.createTopic(_epr.getDestinationName());
+ }
+ _jmsConnection = tConn;
+ _jmsSession = tSess;
+ _messageProducer = tSess.createPublisher(topic);
+ }
+ else
+ throw new CourierException("Unknown destination type");
+ }
+ catch (JMSException ex)
+ {
+ _logger.error("Error from JMS system.", ex);
+
+ throw new CourierException(ex);
+ }
+ catch (NamingException ex)
+ {
+ _logger.error("JMX lookup error.", ex);
+
+ throw new CourierException(ex);
+ }
+ catch (URISyntaxException ex)
+ {
+ throw new MalformedEPRException(ex);
+ }
+
+ } // ________________________________
+
+ public Message pickup (long millis) throws CourierException
{
- if (! _isReceiver)
+ if (!_isReceiver)
throw new CourierException("This is an outgoing-only Courier");
if (millis < 1)
throw new IllegalArgumentException("Timeout millis must be > 0");
- if (null==_messageConsumer)
- try { createMessageConsumer();}
- catch (Exception e)
+ if (null == _messageConsumer) try
+ {
+ createMessageConsumer();
+ }
+ catch (Exception e)
+ {
+ try
{
- try { Thread.sleep(1000); }
- catch (InterruptedException eI) {/* OK do nothing */}
- throw new CourierException("Unable to create Message Consumer", e);
+ Thread.sleep(1000); // TODO magic number
}
-
- javax.jms.Message jmsMessage = null;
- while (null!=_messageConsumer)
+ catch (InterruptedException eI)
+ {/* OK do nothing */
+ }
+ throw new CourierException("Unable to create Message Consumer", e);
+ }
+
+ javax.jms.Message jmsMessage = null;
+ while (null != _messageConsumer)
{
- try
- {
- jmsMessage = _messageConsumer.receive(millis);
- break;
+ try
+ {
+ jmsMessage = _messageConsumer.receive(millis);
+ break;
}
- catch (JMSException e) { jmsConnectRetry(e); }
- catch (Exception e) { throw new CourierException(e);}
+ catch (JMSException e)
+ {
+ jmsConnectRetry(e);
+ }
+ catch (Exception e)
+ {
+ throw new CourierException(e);
+ }
}
- if (null == jmsMessage)
- return null;
+ if (null == jmsMessage) return null;
- if (!(jmsMessage instanceof ObjectMessage))
- {
- _logger.error("Unsupported JMS message type: " + jmsMessage.getClass().getName());
- return null;
- }
- try
- {
- Serializable obj = (Serializable)((ObjectMessage)jmsMessage).getObject();
- return Util.deserialize(obj);
- }
- catch (JMSException e1)
- { _logger.error("Failed to read Serialized Object from JMS message.", e1);
- return null;
- }
- catch (ClassCastException e2)
- { _logger.error("Object in JMS message is not a org.jboss.soa.esb.message.Message", e2);
- }
- catch (IOException e3)
- { _logger.error("Object in JMS message is not a Serializeable", e3);
- }
- catch (ParserConfigurationException e4)
- { _logger.error("Object in JMS message has invalid XML", e4);
- }
- catch (SAXException e5)
- { _logger.error("Object in JMS message has invalid XML", e5);
- }
- return null;
- } //________________________________
+ if (!(jmsMessage instanceof ObjectMessage))
+ {
+ _logger.error("Unsupported JMS message type: " + jmsMessage
+ .getClass().getName());
+ return null;
+ }
+ try
+ {
+ Serializable obj = (Serializable) ((ObjectMessage) jmsMessage)
+ .getObject();
+ return Util.deserialize(obj);
+ }
+ catch (JMSException e1)
+ {
+ _logger.error("Failed to read Serialized Object from JMS message.",
+ e1);
+ return null;
+ }
+ catch (ClassCastException e2)
+ {
+ _logger
+ .error(
+ "Object in JMS message is not a org.jboss.soa.esb.message.Message",
+ e2);
+ }
+ catch (IOException e3)
+ {
+ _logger.error("Object in JMS message is not a Serializeable", e3);
+ }
+ catch (ParserConfigurationException e4)
+ {
+ _logger.error("Object in JMS message has invalid XML", e4);
+ }
+ catch (SAXException e5)
+ {
+ _logger.error("Object in JMS message has invalid XML", e5);
+ }
+ return null;
+ } // ________________________________
- private void createMessageConsumer() throws Exception
- {
- String sJndiConnectionFactory = _epr.getJndiContextFactory();
- if (Util.isNullString(sJndiConnectionFactory))
- sJndiConnectionFactory = NamingContext.JBOSS_INITIAL_CONTEXT_FACTORY;
- String sJndiURL = _epr.getJndiURL();
- if (Util.isNullString(sJndiURL))
- sJndiURL = NamingContext.JBOSS_PROVIDER_URL;
- String sJndiPkgPrefix = _epr.getJndiPkgPrefix();
- if (Util.isNullString(sJndiPkgPrefix))
- sJndiPkgPrefix = NamingContext.JBOSS_URL_PKG_PREFIX;
- Context oJndiCtx = NamingContext.getServerContext(sJndiURL, sJndiConnectionFactory, sJndiPkgPrefix);
- if (null==oJndiCtx)
- throw new Exception("Unable fo obtain jndi context <"+sJndiURL
- +","+sJndiConnectionFactory+","+sJndiPkgPrefix+">");
+ private void createMessageConsumer () throws CourierException, ConfigurationException, MalformedEPRException
+ {
+ try
+ {
+ String sJndiConnectionFactory = _epr.getJndiContextFactory();
+ if (Util.isNullString(sJndiConnectionFactory))
+ sJndiConnectionFactory = NamingContext.JBOSS_INITIAL_CONTEXT_FACTORY;
+ String sJndiURL = _epr.getJndiURL();
+ if (Util.isNullString(sJndiURL))
+ sJndiURL = NamingContext.JBOSS_PROVIDER_URL;
+ String sJndiPkgPrefix = _epr.getJndiPkgPrefix();
+ if (Util.isNullString(sJndiPkgPrefix))
+ sJndiPkgPrefix = NamingContext.JBOSS_URL_PKG_PREFIX;
+ Context oJndiCtx = NamingContext.getServerContext(sJndiURL,
+ sJndiConnectionFactory, sJndiPkgPrefix);
+ if (null == oJndiCtx)
+ throw new ConfigurationException(
+ "Unable fo obtain jndi context <" + sJndiURL + "," + sJndiConnectionFactory + "," + sJndiPkgPrefix + ">");
+
+ String sFactoryClass = _epr.getConnectionFactory();
+ if (Util.isNullString(sFactoryClass))
+ sFactoryClass = "ConnectionFactory";
+
+ Object tmp = oJndiCtx.lookup(sFactoryClass);
+
+ String sType = _epr.getDestinationType();
+ if (JMSEpr.QUEUE_TYPE.equals(sType))
+ {
+ QueueConnectionFactory qcf = (QueueConnectionFactory) tmp;
+ QueueConnection qConn = qcf.createQueueConnection();
+ QueueSession qSess = qConn.createQueueSession(false,
+ QueueSession.AUTO_ACKNOWLEDGE);
+ javax.jms.Queue queue = null;
+ try
+ {
+ queue = (javax.jms.Queue) oJndiCtx.lookup(_epr
+ .getDestinationName());
+ }
+ catch (NamingException ne)
+ {
+ queue = qSess.createQueue(_epr.getDestinationName());
+ }
+ _jmsConnection = qConn;
+ _jmsSession = qSess;
+ _messageConsumer = qSess.createReceiver(queue, _epr
+ .getMessageSelector());
+ qConn.start();
+ }
+ else
+ {
+ if (JMSEpr.TOPIC_TYPE.equals(sType))
+ {
+ TopicConnectionFactory tcf = (TopicConnectionFactory) tmp;
+ TopicConnection tConn = tcf.createTopicConnection();
+ TopicSession tSess = tConn.createTopicSession(false,
+ TopicSession.AUTO_ACKNOWLEDGE);
+ Topic topic = tSess.createTopic(_epr.getDestinationName());
+ _jmsConnection = tConn;
+ _jmsSession = tSess;
+ _messageConsumer = tSess.createConsumer(topic, _epr
+ .getMessageSelector());
+ tConn.start();
+ }
+ else
+ throw new CourierException("Unknown destination type");
+ }
+ }
+ catch (JMSException ex)
+ {
+ _logger.error("Error from JMS system.", ex);
+
+ throw new CourierException(ex);
+ }
+ catch (NamingException ex)
+ {
+ throw new ConfigurationException(ex);
+ }
+ catch (URISyntaxException ex)
+ {
+ throw new MalformedEPRException(ex);
+ }
+ } // ________________________________
- String sFactoryClass = _epr.getConnectionFactory();
- if (Util.isNullString(sFactoryClass))
- sFactoryClass = "ConnectionFactory";
-
- Object tmp = oJndiCtx.lookup(sFactoryClass);
-
- String sType = _epr.getDestinationType();
- if (JMSEpr.QUEUE_TYPE.equals(sType))
- {
- QueueConnectionFactory qcf = (QueueConnectionFactory) tmp;
- QueueConnection qConn = qcf.createQueueConnection();
- QueueSession qSess = qConn.createQueueSession(false,QueueSession.AUTO_ACKNOWLEDGE);
- javax.jms.Queue queue = null;
- try {
- queue = (javax.jms.Queue)oJndiCtx.lookup(_epr.getDestinationName());
- } catch (NamingException ne) {
- queue = qSess.createQueue(_epr.getDestinationName());
- }
- _jmsConnection = qConn;
- _jmsSession = qSess;
- _messageConsumer = qSess.createReceiver(queue,_epr.getMessageSelector());
- qConn.start();
- }
- else if(JMSEpr.TOPIC_TYPE.equals(sType))
- {
- TopicConnectionFactory tcf = (TopicConnectionFactory) tmp;
- TopicConnection tConn = tcf.createTopicConnection();
- TopicSession tSess = tConn.createTopicSession(false,TopicSession.AUTO_ACKNOWLEDGE);
- Topic topic = tSess.createTopic(_epr.getDestinationName());
- _jmsConnection = tConn;
- _jmsSession = tSess;
- _messageConsumer = tSess.createConsumer(topic,_epr.getMessageSelector());
- tConn.start();
- }
- else
- throw new CourierException("Unknown destination type");
+ long _sleepForRetries = 3000; // milliseconds
-
- } //________________________________
+ protected boolean _isReceiver;
- long _sleepForRetries = 3000; // milliseconds
+ protected JMSEpr _epr;
- protected boolean _isReceiver;
- protected JMSEpr _epr;
- protected Logger _logger = Logger.getLogger(JmsCourier.class);
- protected String _messageSelector;
- protected Connection _jmsConnection;
- protected Session _jmsSession;
- protected MessageProducer _messageProducer;
- protected MessageConsumer _messageConsumer;
- protected List<KeyValuePair> _messageProperties;
+ protected Logger _logger = Logger.getLogger(JmsCourier.class);
+ protected String _messageSelector;
+
+ protected Connection _jmsConnection;
+
+ protected Session _jmsSession;
+
+ protected MessageProducer _messageProducer;
+
+ protected MessageConsumer _messageConsumer;
+
+ protected List<KeyValuePair> _messageProperties;
+
}
Modified: labs/jbossesb/trunk/product/core/rosetta/src/org/jboss/internal/soa/esb/couriers/SqlTableCourier.java
===================================================================
--- labs/jbossesb/trunk/product/core/rosetta/src/org/jboss/internal/soa/esb/couriers/SqlTableCourier.java 2007-01-20 09:09:48 UTC (rev 8932)
+++ labs/jbossesb/trunk/product/core/rosetta/src/org/jboss/internal/soa/esb/couriers/SqlTableCourier.java 2007-01-20 09:33:16 UTC (rev 8933)
@@ -32,6 +32,7 @@
import org.apache.log4j.Logger;
import org.jboss.soa.esb.addressing.Call;
+import org.jboss.soa.esb.addressing.MalformedEPRException;
import org.jboss.soa.esb.addressing.eprs.JDBCEpr;
import org.jboss.soa.esb.couriers.CourierException;
import org.jboss.soa.esb.helpers.persist.JdbcCleanConn;
@@ -70,7 +71,7 @@
{
_isReceiver = isReceiver;
_epr = epr;
- _sleepForRetries = 3000;
+ _sleepForRetries = 3000; // TODO magic number - configurable?
try
{
_postDelete = Boolean.TRUE.equals(Boolean.valueOf(epr
@@ -88,6 +89,7 @@
void cleanup()
{
if (null != _conn)
+ {
try
{
_conn.release();
@@ -96,6 +98,7 @@
{
_logger.info("Unable to release connection", e);
}
+ }
} // ________________________________
@@ -132,6 +135,7 @@
}
if (null == _conn)
+ {
try
{
_conn = getConn();
@@ -140,6 +144,7 @@
{
throw new CourierException(e);
}
+ }
while (_conn != null)
{
@@ -159,6 +164,7 @@
catch (SQLException e)
{
if (null != _conn)
+ {
try
{
_conn.rollback();
@@ -167,6 +173,8 @@
{
_logger.error(roll);
}
+ }
+
_logger.error("SQL error", e);
throw new CourierException(e);
}
@@ -280,7 +288,7 @@
return null;
} // ________________________________
- private void deleteMsg(String messageId) throws Exception
+ private void deleteMsg(String messageId) throws SQLException
{
int iParm = 1;
deleteStatement().setString(iParm++, messageId);
@@ -289,7 +297,7 @@
}
- private void changeStatus(String messageId, State to) throws Exception
+ private void changeStatus(String messageId, State to) throws SQLException
{
int iParm = 1;
updateStatusStatement().setString(iParm++, to.getColumnValue());
@@ -302,6 +310,7 @@
private ResultSet getRowList() throws CourierException
{
if (null == _conn)
+ {
try
{
_conn = getConn();
@@ -310,6 +319,7 @@
{
throw new CourierException(e);
}
+ }
while (_conn != null)
{
try
@@ -353,13 +363,20 @@
}
} // ________________________________
- private JdbcCleanConn getConn() throws Exception
+ private JdbcCleanConn getConn() throws SQLException, MalformedEPRException
{
if (null == _conn)
{
- SimpleDataSource DS = new SimpleDataSource(_epr.getDriver(), _epr
- .getURL(), _epr.getUserName(), _epr.getPassword());
- _conn = new JdbcCleanConn(DS);
+ try
+ {
+ SimpleDataSource DS = new SimpleDataSource(_epr.getDriver(), _epr
+ .getURL(), _epr.getUserName(), _epr.getPassword());
+ _conn = new JdbcCleanConn(DS);
+ }
+ catch (URISyntaxException ex)
+ {
+ throw new MalformedEPRException(ex);
+ }
}
return _conn;
} // ________________________________
Modified: labs/jbossesb/trunk/product/core/rosetta/src/org/jboss/internal/soa/esb/util/EdtFtpImpl.java
===================================================================
--- labs/jbossesb/trunk/product/core/rosetta/src/org/jboss/internal/soa/esb/util/EdtFtpImpl.java 2007-01-20 09:09:48 UTC (rev 8932)
+++ labs/jbossesb/trunk/product/core/rosetta/src/org/jboss/internal/soa/esb/util/EdtFtpImpl.java 2007-01-20 09:33:16 UTC (rev 8933)
@@ -30,6 +30,7 @@
import java.util.List;
import org.apache.log4j.Logger;
+import org.jboss.soa.esb.ConfigurationException;
import org.jboss.soa.esb.addressing.eprs.FTPEpr;
import org.jboss.soa.esb.addressing.eprs.FileEpr;
import org.jboss.soa.esb.common.Environment;
@@ -87,7 +88,7 @@
*
* @param p_oP
* ConfigTree
- * @throws Exception :
+ * @throws ConfigurationException :
* if parameters are invalid or incomplete
* <li>Parameters: (XML attributes at the root level) </li>
* <li> ftpServer = name or IP of FTP server </li>
@@ -99,15 +100,16 @@
* in remote computer </li>
*/
- public EdtFtpImpl(ConfigTree p_oP, boolean p_bConnect) throws Exception
+ public EdtFtpImpl (ConfigTree p_oP, boolean p_bConnect)
+ throws ConfigurationException, RemoteFileSystemException
{
m_oParms = p_oP;
initialize(p_bConnect);
}
- public EdtFtpImpl(FTPEpr p_oP, boolean p_bConnect) throws Exception
+ public EdtFtpImpl (FTPEpr p_oP, boolean p_bConnect)
+ throws ConfigurationException, RemoteFileSystemException
{
-
m_oEpr = p_oP;
URL url = null;
@@ -117,23 +119,20 @@
}
catch (MalformedURLException e)
{
- throw new RemoteFileSystemException(e);
+ throw new ConfigurationException(e);
}
catch (URISyntaxException e)
{
- throw new RemoteFileSystemException(e);
+ throw new ConfigurationException(e);
}
m_sFtpServer = url.getHost();
String[] sa = null;
- if (url.getUserInfo() != null)
- sa = url.getUserInfo().split(":");
+ if (url.getUserInfo() != null) sa = url.getUserInfo().split(":");
- if (sa == null)
- sa = new String[]
- { "", "" };
+ if (sa == null) sa = new String[] { "", "" };
m_sUser = (sa.length < 1) ? "" : sa[0];
m_sPasswd = (sa.length < 2) ? "" : sa[1];
@@ -147,8 +146,7 @@
Environment.FTP_REMOTEDIR, tmpdir);
m_iPort = url.getPort();
- if (m_iPort < 0)
- m_iPort = url.getDefaultPort();
+ if (m_iPort < 0) m_iPort = url.getDefaultPort();
m_sLocalDir = ModulePropertyManager.getPropertyManager(
ModulePropertyManager.TRANSPORTS_MODULE).getProperty(
@@ -169,11 +167,10 @@
configTreeFromEpr();
initialize(p_bConnect);
-
}
- public EdtFtpImpl(List<KeyValuePair> p_oAttribs, boolean p_bConnect)
- throws Exception
+ public EdtFtpImpl (List<KeyValuePair> p_oAttribs, boolean p_bConnect)
+ throws ConfigurationException, RemoteFileSystemException
{
m_oParms = new ConfigTree("fromProps");
for (KeyValuePair oCurr : p_oAttribs)
@@ -181,38 +178,55 @@
initialize(p_bConnect);
}
- private void checkParms() throws Exception
+ private void checkParms () throws ConfigurationException
{
String att = m_oParms.getAttribute(FileEpr.URL_TAG);
- URL url = (null == att) ? null : new URL(att);
+ URL url = null;
+
+ try
+ {
+ if (att != null)
+ url = new URL(att);
+ }
+ catch (MalformedURLException ex)
+ {
+ throw new ConfigurationException(ex);
+ }
+
m_sFtpServer = (null != url) ? url.getHost() : m_oParms
.getAttribute(PARMS_FTP_SERVER);
if (null == m_sFtpServer)
- throw new Exception("No FTP server specified");
+ throw new ConfigurationException("No FTP server specified");
String[] sa = (null == url) ? null : url.getUserInfo().split(":");
m_sUser = (null != sa) ? sa[0] : m_oParms.getAttribute(PARMS_USER);
if (null == m_sUser)
- throw new Exception("No username specified for FTP");
+ throw new ConfigurationException("No username specified for FTP");
m_sPasswd = (null != sa) ? sa[1] : m_oParms.getAttribute(PARMS_PASSWD);
if (null == m_sPasswd)
- throw new Exception("No password specified for FTP");
+ throw new ConfigurationException("No password specified for FTP");
m_sRemoteDir = (null != url) ? url.getFile() : m_oParms
.getAttribute(PARMS_REMOTE_DIR);
- if (null == m_sRemoteDir)
- m_sRemoteDir = "";
+ if (null == m_sRemoteDir) m_sRemoteDir = "";
m_sLocalDir = m_oParms.getAttribute(PARMS_LOCAL_DIR);
- if (null == m_sLocalDir)
- m_sLocalDir = ".";
+ if (null == m_sLocalDir) m_sLocalDir = ".";
String sAux = m_oParms.getAttribute(PARMS_PORT);
m_iPort = (null != url) ? url.getPort() : (null == sAux) ? 21 : Integer
.parseInt(sAux);
- if (m_iPort < 0)
- m_iPort = new URL("ftp://").getDefaultPort();
+
+ try
+ {
+ if (m_iPort < 0)
+ m_iPort = new URL("ftp://").getDefaultPort();
+ }
+ catch (MalformedURLException ex)
+ {
+ throw new ConfigurationException(ex);
+ }
// Dec-2006 (b_georges): it has been decided to set the Type to binary.
m_oXferType = FTPTransferType.BINARY;
@@ -224,7 +238,7 @@
return;
}
- private void configTreeFromEpr() throws RemoteFileSystemException
+ private void configTreeFromEpr () throws RemoteFileSystemException
{
m_oParms = new ConfigTree("fromEpr");
try
@@ -255,7 +269,7 @@
*
* @see org.jboss.soa.esb.util.RemoteFileSystem#deleteRemoteFile(java.lang.String)
*/
- public void deleteRemoteFile(String p_sFile) throws Exception
+ public void deleteRemoteFile (String p_sFile) throws RemoteFileSystemException
{
try
{
@@ -263,12 +277,12 @@
}
catch (Exception ex)
{
- // TODO better error handling
-
/*
* It seems as though we have a race condition whereby one thread
* tries to remove a file when another renames it!
*/
+
+ throw new RemoteFileSystemException(ex);
}
}
@@ -278,8 +292,8 @@
* @see org.jboss.soa.esb.util.RemoteFileSystem#downloadFile(java.lang.String,
* java.lang.String)
*/
- public void downloadFile(String p_sFile, String p_sFinalName)
- throws Exception
+ public void downloadFile (String p_sFile, String p_sFinalName)
+ throws IOException, RemoteFileSystemException
{
File oLocalDir = new File(m_sLocalDir);
File oLclFile = File.createTempFile("Rosetta_", TMP_SUFFIX, oLocalDir);
@@ -292,11 +306,17 @@
{
}
- m_oConn.get(FtpUtils.fileToFtpString(oLclFile), p_sFile);
+ try
+ {
+ m_oConn.get(FtpUtils.fileToFtpString(oLclFile), p_sFile);
+ }
+ catch (FTPException ex)
+ {
+ throw new RemoteFileSystemException(ex);
+ }
File oNew = new File(oLocalDir, p_sFinalName);
- if (oNew.exists())
- oNew.delete();
+ if (oNew.exists()) oNew.delete();
oLclFile.renameTo(oNew);
}
@@ -305,44 +325,46 @@
*
* @see org.jboss.soa.esb.util.RemoteFileSystem#getFileListFromRemoteDir(java.lang.String)
*/
- public String[] getFileListFromRemoteDir(String p_sSuffix) throws Exception
+ public String[] getFileListFromRemoteDir (String p_sSuffix)
+ throws RemoteFileSystemException, IOException
{
String sSuffix = (null == p_sSuffix) ? "*" : "*" + p_sSuffix;
-
+
try
{
return m_oConn.dir(sSuffix);
}
catch (FTPException ex)
{
- String msg = ex.getMessage();
- int rc = ex.getReplyCode();
- if (rc == 550) // means File Not Found - see JBESB-303
- {
- _logger.debug("No matching file or directory. Server returns: ["+ rc+"] "+msg);
- return null;
- }
- else
- {
- // TODO Test with different FTP Servers
- String sMess = this.getClass().getSimpleName()
- + " can't list "+ sSuffix + " due to: [" + rc + "] "+msg;
- throw new Exception(sMess);
- }
- }
- }
-
+ String msg = ex.getMessage();
+ int rc = ex.getReplyCode();
+ if (rc == 550) // means File Not Found - see JBESB-303
+ {
+ _logger
+ .debug("No matching file or directory. Server returns: [" + rc + "] " + msg);
+ return null;
+ }
+ else
+ {
+ // TODO Test with different FTP Servers
+ String sMess = this.getClass().getSimpleName() + " can't list " + sSuffix + " due to: [" + rc + "] " + msg;
+ throw new RemoteFileSystemException(sMess);
+ }
+ }
+ }
+
/*
* (non-Javadoc)
*
* @see org.jboss.soa.esb.util.RemoteFileSystem#getRemoteDir()
*/
- public String getRemoteDir()
+ public String getRemoteDir ()
{
return m_sRemoteDir;
}
- private void initialize(boolean bConnect) throws Exception
+ private void initialize (boolean bConnect) throws ConfigurationException,
+ RemoteFileSystemException
{
checkParms();
if (bConnect)
@@ -353,23 +375,59 @@
}
catch (UnknownHostException ex)
{
- // ex.printStackTrace();
+ _logger.error("Unknown host for FTP.", ex);
- throw ex;
+ throw new ConfigurationException(ex);
}
- m_oConn.setRemotePort(m_iPort);
-
- m_oConn.connect();
- for (int i1 = 0; i1 < 10 && !m_oConn.connected(); i1++)
- Thread.sleep(200); // TODO arbitrary MAGIC number!
- // Configurable?
- if (!m_oConn.connected())
- throw new Exception("Can't connect to FTP server");
- m_oConn.user(m_sUser);
- m_oConn.password(m_sPasswd);
- m_oConn.setConnectMode((m_bPassive) ? FTPConnectMode.PASV
- : FTPConnectMode.ACTIVE);
- m_oConn.setType(m_oXferType);
+ catch (IOException ex)
+ {
+ _logger.error("Caught IOException", ex);
+
+ throw new RemoteFileSystemException(ex);
+ }
+ catch (FTPException ex)
+ {
+ _logger.error("Caught FTPException.", ex);
+
+ throw new RemoteFileSystemException(ex);
+ }
+
+ try
+ {
+ m_oConn.setRemotePort(m_iPort);
+
+ m_oConn.connect();
+ for (int i1 = 0; i1 < 10 && !m_oConn.connected(); i1++)
+ {
+ try
+ {
+ Thread.sleep(200); // TODO arbitrary MAGIC number!
+ }
+ catch (InterruptedException ex)
+ {
+ }
+ }
+
+ // Configurable?
+ if (!m_oConn.connected())
+ throw new RemoteFileSystemException(
+ "Can't connect to FTP server");
+ m_oConn.user(m_sUser);
+ m_oConn.password(m_sPasswd);
+ m_oConn
+ .setConnectMode((m_bPassive) ? FTPConnectMode.PASV : FTPConnectMode.ACTIVE);
+ m_oConn.setType(m_oXferType);
+ }
+ catch (IOException ex)
+ {
+ throw new RemoteFileSystemException(ex);
+ }
+ catch (FTPException ex)
+ {
+ _logger.error("Caught FTPException.", ex);
+
+ throw new RemoteFileSystemException(ex);
+ }
}
}
@@ -378,7 +436,7 @@
*
* @see org.jboss.soa.esb.util.RemoteFileSystem#quit()
*/
- public void quit()
+ public void quit ()
{
if (null != m_oConn)
{
@@ -397,9 +455,20 @@
*
* @see org.jboss.soa.esb.util.RemoteFileSystem#remoteDelete(java.io.File)
*/
- public void remoteDelete(File p_oFile) throws Exception
+ public void remoteDelete (File p_oFile) throws RemoteFileSystemException
{
- m_oConn.delete(getRemoteDir() + "/" + p_oFile.getName());
+ try
+ {
+ m_oConn.delete(getRemoteDir() + "/" + p_oFile.getName());
+ }
+ catch (IOException ex)
+ {
+ throw new RemoteFileSystemException(ex);
+ }
+ catch (FTPException ex)
+ {
+ throw new RemoteFileSystemException(ex);
+ }
}
/*
@@ -408,7 +477,7 @@
* @see org.jboss.soa.esb.util.RemoteFileSystem#remoteRename(java.io.File,
* java.io.File)
*/
- public void remoteRename(File p_oFrom, File p_oTo) throws Exception
+ public void remoteRename (File p_oFrom, File p_oTo) throws RemoteFileSystemException
{
try
{
@@ -417,27 +486,28 @@
}
catch (FTPException ex)
{
- if (ex.getReplyCode() == 550) // EdtFtp error code meaning File Not Found
+ if (ex.getReplyCode() == 550) // EdtFtp error code meaning File
+ // Not Found
{
- _logger.debug("EdtFtpImpl tried to rename file that had moved.");
-
- throw new IOException("File not found.");
+ _logger
+ .debug("EdtFtpImpl tried to rename file that had moved.");
+
+ throw new RemoteFileSystemException("File not found.");
}
else
- {
- ex.printStackTrace();
-
- throw ex;
+ {
+ _logger.error("Caught FTPException.", ex);
+
+ throw new RemoteFileSystemException(ex);
}
}
catch (Exception e)
{
e.printStackTrace();
- String sMess = this.getClass().getSimpleName()
- + " can't rename in remote directory <" + e.getMessage()
- + ">";
- throw new Exception(sMess);
+ String sMess = this.getClass().getSimpleName() + " can't rename in remote directory <" + e
+ .getMessage() + ">";
+ throw new RemoteFileSystemException(sMess);
}
}
@@ -447,23 +517,22 @@
* @see org.jboss.soa.esb.util.RemoteFileSystem#renameInRemoteDir(java.lang.String,
* java.lang.String)
*/
- public void renameInRemoteDir(String p_sFrom, String p_sTo)
- throws Exception
+ public void renameInRemoteDir (String p_sFrom, String p_sTo)
+ throws RemoteFileSystemException
{
String sRmtFrom = new File(p_sFrom).getName();
String sRmtTo = new File(p_sTo).getName();
try
{
- m_oConn.rename(getRemoteDir() + "/" + sRmtFrom, getRemoteDir()
- + "/" + sRmtTo);
+ m_oConn.rename(getRemoteDir() + "/" + sRmtFrom,
+ getRemoteDir() + "/" + sRmtTo);
}
catch (Exception e)
{
- String sMess = this.getClass().getSimpleName()
- + " can't rename in remote directory <" + e.getMessage()
- + ">";
- throw new Exception(sMess);
+ String sMess = this.getClass().getSimpleName() + " can't rename in remote directory <" + e
+ .getMessage() + ">";
+ throw new RemoteFileSystemException(sMess);
}
}
@@ -472,11 +541,23 @@
*
* @see org.jboss.soa.esb.util.RemoteFileSystem#setRemoteDir(java.lang.String)
*/
- public void setRemoteDir(String p_sDir) throws Exception
+ public void setRemoteDir (String p_sDir) throws RemoteFileSystemException
{
- // TODO deal with null string
-
- m_oConn.chdir(p_sDir);
+ if (p_sDir == null)
+ throw new IllegalArgumentException();
+
+ try
+ {
+ m_oConn.chdir(p_sDir);
+ }
+ catch (IOException ex)
+ {
+ throw new RemoteFileSystemException(ex);
+ }
+ catch (FTPException ex)
+ {
+ throw new RemoteFileSystemException(ex);
+ }
}
/*
@@ -485,13 +566,25 @@
* @see org.jboss.soa.esb.util.RemoteFileSystem#uploadFile(java.io.File,
* java.lang.String)
*/
- public void uploadFile(File p_oFile, String p_sRemoteName) throws Exception
+ public void uploadFile (File p_oFile, String p_sRemoteName)
+ throws RemoteFileSystemException
{
String sRemoteOK = getRemoteDir() + "/" + p_sRemoteName;
String sRemoteTmp = sRemoteOK + TMP_SUFFIX;
- m_oConn.put(FtpUtils.fileToFtpString(p_oFile), sRemoteTmp);
- m_oConn.rename(sRemoteTmp, sRemoteOK);
+ try
+ {
+ m_oConn.put(FtpUtils.fileToFtpString(p_oFile), sRemoteTmp);
+ m_oConn.rename(sRemoteTmp, sRemoteOK);
+ }
+ catch (IOException ex)
+ {
+ throw new RemoteFileSystemException(ex);
+ }
+ catch (FTPException ex)
+ {
+ throw new RemoteFileSystemException(ex);
+ }
}
}
Modified: labs/jbossesb/trunk/product/core/rosetta/src/org/jboss/soa/esb/helpers/ConfigTree.java
===================================================================
--- labs/jbossesb/trunk/product/core/rosetta/src/org/jboss/soa/esb/helpers/ConfigTree.java 2007-01-20 09:09:48 UTC (rev 8932)
+++ labs/jbossesb/trunk/product/core/rosetta/src/org/jboss/soa/esb/helpers/ConfigTree.java 2007-01-20 09:33:16 UTC (rev 8933)
@@ -26,6 +26,7 @@
import javax.xml.transform.stream.StreamResult;
import org.apache.log4j.Logger;
+import org.jboss.soa.esb.ConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
@@ -140,14 +141,14 @@
* @return String - the value assigned to the specified key
*/
public String getAttribute(String name, String defaultValue)
- throws Exception
+ throws ConfigurationException
{
String ret = (null==_attributes) ? null : _attributes.get(name);
if (null!=ret)
return ret;
if (null!=defaultValue)
return defaultValue;
- throw new Exception("Invalid or missing <"+name+"> attribute ");
+ throw new ConfigurationException("Invalid or missing <"+name+"> attribute ");
} // _______________________________
/**
* obtain the list of all attribute names
Modified: labs/jbossesb/trunk/product/core/rosetta/src/org/jboss/soa/esb/helpers/persist/JdbcCleanConn.java
===================================================================
--- labs/jbossesb/trunk/product/core/rosetta/src/org/jboss/soa/esb/helpers/persist/JdbcCleanConn.java 2007-01-20 09:09:48 UTC (rev 8932)
+++ labs/jbossesb/trunk/product/core/rosetta/src/org/jboss/soa/esb/helpers/persist/JdbcCleanConn.java 2007-01-20 09:33:16 UTC (rev 8933)
@@ -25,6 +25,7 @@
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
+import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
@@ -42,13 +43,13 @@
protected Logger m_oLogger;
- public JdbcCleanConn(DataSource p_oDS) throws Exception
+ public JdbcCleanConn(DataSource p_oDS)
{
m_oDS = p_oDS;
m_oLogger = Logger.getLogger(this.getClass());
}
- public void commit() throws Exception
+ public void commit() throws SQLException
{
if (null != m_conn)
{
@@ -56,7 +57,7 @@
}
}
- public void rollback() throws Exception
+ public void rollback() throws SQLException
{
if (null != m_conn)
{
@@ -97,7 +98,7 @@
} // __________________________________
public PreparedStatement prepareStatement(String p_sSt, int p_i1, int p_i2)
- throws Exception
+ throws SQLException
{
if (null == m_conn)
{
@@ -108,7 +109,7 @@
return PS;
} // __________________________________
- public PreparedStatement prepareStatement(String p_sSt) throws Exception
+ public PreparedStatement prepareStatement(String p_sSt) throws SQLException
{
if (null == m_conn)
{
@@ -121,14 +122,14 @@
} // __________________________________
public ResultSet execQueryWait(PreparedStatement p_PS, int p_iQtry)
- throws Exception
+ throws SQLException
{
if (null == m_conn)
{
connect();
}
- Exception eRet = null;
+ SQLException eRet = null;
int iQtry = (p_iQtry < 1) ? 1 : (p_iQtry < 50) ? p_iQtry : 50;
for (int i1 = 0; i1 < iQtry; i1++)
{
@@ -136,15 +137,22 @@
{
return p_PS.executeQuery();
}
- catch (Exception e)
+ catch (SQLException e)
{
if (null == eRet)
- eRet = new Exception(e.getMessage());
+ eRet = e;
// TODO magic number!!
- Thread.sleep(100 + (new Double(100 * Math.random()))
- .longValue());
+ try
+ {
+ Thread.sleep(100 + (new Double(100 * Math.random()))
+ .longValue());
+ }
+ catch (InterruptedException ex)
+ {
+ m_oLogger.warn("Thread interrupted.", ex);
+ }
}
}
m_oLogger.error("execQueryWait() FAILED", eRet);
@@ -152,14 +160,14 @@
} // __________________________________
public void execUpdWait(PreparedStatement p_PS, int p_iQtry)
- throws Exception
+ throws SQLException
{
if (null == m_conn)
{
connect();
}
- Exception eRet = null;
+ SQLException eRet = null;
int iQtry = (p_iQtry < 1) ? 1 : (p_iQtry < 50) ? p_iQtry : 50;
for (int i1 = 0; i1 < iQtry; i1++)
{
@@ -168,27 +176,34 @@
p_PS.executeUpdate();
return;
}
- catch (Exception e)
+ catch (SQLException e)
{
if (null == eRet)
eRet = e;
- // System.out.println("Retrying "+i1);
- Thread.sleep(100 + (new Double(100 * Math.random()))
- .longValue());
+
+ try
+ {
+ Thread.sleep(100 + (new Double(100 * Math.random()))
+ .longValue());
+ }
+ catch (InterruptedException ex)
+ {
+ m_oLogger.warn("Thread interrupted.", ex);
+ }
}
}
m_oLogger.error("execUpdWait() FAILED", eRet);
throw eRet;
} // __________________________________
- private void connect() throws Exception
+ private void connect() throws SQLException
{
if (m_conn != null)
{
return;
}
- Exception eRet = null;
+ SQLException eRet = null;
for (int i1 = 0; i1 < 5; i1++)
{
try
@@ -197,15 +212,22 @@
eRet = null;
break;
}
- catch (Exception e)
+ catch (SQLException e)
{
if (null == eRet)
eRet = e;
// TODO magic number!!
- Thread.sleep(2000 + (new Double(100 * Math.random()))
- .longValue());
+ try
+ {
+ Thread.sleep(2000 + (new Double(100 * Math.random()))
+ .longValue());
+ }
+ catch (InterruptedException ex)
+ {
+ m_oLogger.warn("Thread interrupted.", ex);
+ }
}
}
Modified: labs/jbossesb/trunk/product/core/rosetta/src/org/jboss/soa/esb/helpers/persist/SimpleDataSource.java
===================================================================
--- labs/jbossesb/trunk/product/core/rosetta/src/org/jboss/soa/esb/helpers/persist/SimpleDataSource.java 2007-01-20 09:09:48 UTC (rev 8932)
+++ labs/jbossesb/trunk/product/core/rosetta/src/org/jboss/soa/esb/helpers/persist/SimpleDataSource.java 2007-01-20 09:33:16 UTC (rev 8933)
@@ -43,21 +43,31 @@
* @see JdbcCleanConn
* @see ConfigTree
*/
-public class SimpleDataSource implements DataSource {
+public class SimpleDataSource implements DataSource
+{
private PrintWriter m_oPW = new PrintWriter(System.out);
private int m_iTO = 10;
+
private String m_sUrl, m_sUsr, m_sPwd;
+
private Connection m_oConn;
+
public static final String DRIVER = "driver-class";
+
public static final String URL = "connection-url";
+
public static final String USER = "user-name";
+
public static final String PASSWORD = "password";
-
- private static final Logger _logger = Logger.getLogger(SimpleDataSource.class);
+ private static final Logger _logger = Logger
+ .getLogger(SimpleDataSource.class);
+
// Disable default constructor
- private SimpleDataSource() { }
+ private SimpleDataSource ()
+ {
+ }
/**
* Obtain a DataSource by providing connection parameters. ConfigTree
@@ -77,9 +87,10 @@
* @see SimpleDataSource#SimpleDataSource(String,String,String,String)
* @see javax.sql.DataSource
*/
- public SimpleDataSource(ConfigTree p_oP) throws Exception {
- this(p_oP.getAttribute(DRIVER), p_oP.getAttribute(URL), p_oP.getAttribute(USER), p_oP
- .getAttribute(PASSWORD));
+ public SimpleDataSource (ConfigTree p_oP) throws Exception
+ {
+ this(p_oP.getAttribute(DRIVER), p_oP.getAttribute(URL), p_oP
+ .getAttribute(USER), p_oP.getAttribute(PASSWORD));
} // ________________________________
/**
@@ -99,43 +110,59 @@
* @see DriverManager#getConnection(String,String,String)
* @see javax.sql.DataSource
*/
- public SimpleDataSource(String p_sDriver, String p_sDbURL, String p_sUsr,
- String p_sPwd) throws Exception {
- Class.forName(p_sDriver);
- m_sUrl = p_sDbURL;
- getConnection(p_sUsr, p_sPwd);
+ public SimpleDataSource (String p_sDriver, String p_sDbURL, String p_sUsr,
+ String p_sPwd)
+ {
+ try
+ {
+ Class.forName(p_sDriver);
+ m_sUrl = p_sDbURL;
+ getConnection(p_sUsr, p_sPwd);
+ }
+ catch (ClassNotFoundException ex)
+ {
+ throw new IllegalArgumentException(ex);
+ }
} // ________________________________
- public Connection getConnection() {
+ public Connection getConnection ()
+ {
return m_oConn;
}
- public Connection getConnection(String username, String password) {
+ public Connection getConnection (String username, String password)
+ {
m_sUsr = username;
m_sPwd = password;
- try {
+ try
+ {
m_oConn = DriverManager.getConnection(m_sUrl, m_sUsr, m_sPwd);
- } catch (Exception e)
+ }
+ catch (Exception e)
{
- _logger.error("Can't obtain datasource",e);
+ _logger.error("Can't obtain datasource", e);
m_oConn = null;
}
return m_oConn;
} // ________________________________
- public int getLoginTimeout() {
+ public int getLoginTimeout ()
+ {
return m_iTO;
}
- public PrintWriter getLogWriter() {
+ public PrintWriter getLogWriter ()
+ {
return m_oPW;
}
- public void setLoginTimeout(int seconds) {
+ public void setLoginTimeout (int seconds)
+ {
m_iTO = seconds;
}
- public void setLogWriter(PrintWriter out) {
+ public void setLogWriter (PrintWriter out)
+ {
m_oPW = out;
}
} // ______________________________________________________
More information about the jboss-svn-commits
mailing list