[jbosscache-commits] JBoss Cache SVN: r6216 - in core/trunk/src: main/java/org/jboss/cache/config/parsing and 1 other directories.

jbosscache-commits at lists.jboss.org jbosscache-commits at lists.jboss.org
Tue Jul 8 12:29:58 EDT 2008


Author: mircea.markus
Date: 2008-07-08 12:29:58 -0400 (Tue, 08 Jul 2008)
New Revision: 6216

Added:
   core/trunk/src/main/java/org/jboss/cache/config/parsing/FileLookup.java
Modified:
   core/trunk/src/main/java/org/jboss/cache/DefaultCacheFactory.java
   core/trunk/src/main/java/org/jboss/cache/config/parsing/CacheConfigsXmlParser.java
   core/trunk/src/main/java/org/jboss/cache/config/parsing/ConfigFilesConvertor.java
   core/trunk/src/main/java/org/jboss/cache/config/parsing/XmlConfigurationParser.java
   core/trunk/src/main/java/org/jboss/cache/config/parsing/XmlConfigurationParser2x.java
   core/trunk/src/test/java/org/jboss/cache/factories/UnitTestCacheConfigurationFactory.java
Log:
added a FIleLookup to reuse the code that knows how to lookup a file in classpaht (context + system) and local disk

Modified: core/trunk/src/main/java/org/jboss/cache/DefaultCacheFactory.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/DefaultCacheFactory.java	2008-07-08 16:27:15 UTC (rev 6215)
+++ core/trunk/src/main/java/org/jboss/cache/DefaultCacheFactory.java	2008-07-08 16:29:58 UTC (rev 6216)
@@ -142,6 +142,7 @@
 
    public Cache<K, V> createCache(InputStream is) throws ConfigurationException
    {
+      //todo mmarkus also try to parse old file types.
       XmlConfigurationParser parser = new XmlConfigurationParser();
       Configuration c = parser.parseStream(is);
       return createCache(c);

Modified: core/trunk/src/main/java/org/jboss/cache/config/parsing/CacheConfigsXmlParser.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/config/parsing/CacheConfigsXmlParser.java	2008-07-08 16:27:15 UTC (rev 6215)
+++ core/trunk/src/main/java/org/jboss/cache/config/parsing/CacheConfigsXmlParser.java	2008-07-08 16:29:58 UTC (rev 6216)
@@ -50,91 +50,75 @@
  * </cache-configs>
  * </pre>
  * <p/>
- * The '....' represents the normal content of the mbean element in a 
+ * The '....' represents the normal content of the mbean element in a
  * JBC -service.xml config file.
- * 
+ *
  * @author <a href="brian.stansberry at jboss.com">Brian Stansberry</a>
  * @version $Revision: 1.1 $
  */
-public class CacheConfigsXmlParser 
- {
-    /** Name of the root element in a cache configs XML document*/
-    public static final String DOCUMENT_ROOT = "cache-configs";
-    /** 
-     * Name of the element that represents an individual cache configuration 
-     * in a cache configs XML document.
-     */
-    public static final String CONFIG_ROOT = "cache-config";
-    /** 
-     * Name of the attribute in a {@link #CONFIG_ROOT cache-config} element that specifies
-     * the name of the configuration.
-     */
-    public static final String CONFIG_NAME = "name";
-    
-    private static final Log log = LogFactory.getLog(CacheConfigsXmlParser.class);
-    
-    private final XmlConfigurationParser2x parser = new XmlConfigurationParser2x();
+public class CacheConfigsXmlParser
+{
+   /**
+    * Name of the root element in a cache configs XML document
+    */
+   public static final String DOCUMENT_ROOT = "cache-configs";
+   /**
+    * Name of the element that represents an individual cache configuration
+    * in a cache configs XML document.
+    */
+   public static final String CONFIG_ROOT = "cache-config";
+   /**
+    * Name of the attribute in a {@link #CONFIG_ROOT cache-config} element that specifies
+    * the name of the configuration.
+    */
+   public static final String CONFIG_NAME = "name";
 
-    public Map<String, Configuration> parseConfigs(String fileName) throws CloneNotSupportedException 
-    {
-       InputStream is = getAsInputStreamFromClassLoader(fileName);
-       if (is == null)
-       {
-          if (log.isDebugEnabled())
-             log.debug("Unable to find configuration file " + fileName + " in classpath; searching for this file on the filesystem instead.");
-          try
-          {
-             is = new FileInputStream(fileName);
-          }
-          catch (FileNotFoundException e)
-          {
-             throw new ConfigurationException("Unable to find config file " + fileName + " either in classpath or on the filesystem!", e);
-          }
-       }
+   private static final Log log = LogFactory.getLog(CacheConfigsXmlParser.class);
 
-       return parseConfigs(is);
-    }
-     
-    public Map<String, Configuration> parseConfigs(InputStream stream) throws CloneNotSupportedException 
-    {            
-       // loop through all elements in XML.
-       Element root = XmlConfigHelper.getDocumentRoot(stream);
-       NodeList list = root.getElementsByTagName(CONFIG_ROOT);
-       if (list == null || list.getLength() == 0) 
-          throw new ConfigurationException("Can't find " + CONFIG_ROOT + " tag");
-         
-       Map<String, Configuration> result = new HashMap<String, Configuration>();
-         
-       for (int i = 0; i < list.getLength(); i++)
-       {
-          Node node = list.item(i);
-          if (node.getNodeType() != Node.ELEMENT_NODE)
-          {
-             continue;
-          }
-            
-          Element element = (Element) node;
-          String name = element.getAttribute(CONFIG_NAME);
-          if (name == null || name.trim().length() == 0)
-              throw new ConfigurationException("Element " + element + " has no name attribute");
-            
-          Configuration c = parser.parseConfiguration(element);
-          // Prove that we can successfully clone it
-          c = c.clone();
-          result.put(name.trim(), c);
-       }
-         
-       return result;
-    }
+   //todo mmarkus make this use the new parser
+   private final XmlConfigurationParser2x parser = new XmlConfigurationParser2x();
 
-    protected InputStream getAsInputStreamFromClassLoader(String filename)
-    {
-       InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(filename);
-       if (is == null)
-       {
-          // check system class loader
-          is = getClass().getClassLoader().getResourceAsStream(filename);
-       }
-       return is;
-    }
- }
\ No newline at end of file
+   public Map<String, Configuration> parseConfigs(String fileName) throws CloneNotSupportedException
+   {
+      FileLookup fileLookup = new FileLookup();
+      InputStream is = fileLookup.lookupFile(fileName);
+      if (is == null)
+      {
+         throw new ConfigurationException("Unable to find config file " + fileName + " either in classpath or on the filesystem!");
+      }
+
+      return parseConfigs(is);
+   }
+
+   public Map<String, Configuration> parseConfigs(InputStream stream) throws CloneNotSupportedException
+   {
+      // loop through all elements in XML.
+      Element root = XmlConfigHelper.getDocumentRoot(stream);
+      NodeList list = root.getElementsByTagName(CONFIG_ROOT);
+      if (list == null || list.getLength() == 0)
+         throw new ConfigurationException("Can't find " + CONFIG_ROOT + " tag");
+
+      Map<String, Configuration> result = new HashMap<String, Configuration>();
+
+      for (int i = 0; i < list.getLength(); i++)
+      {
+         Node node = list.item(i);
+         if (node.getNodeType() != Node.ELEMENT_NODE)
+         {
+            continue;
+         }
+
+         Element element = (Element) node;
+         String name = element.getAttribute(CONFIG_NAME);
+         if (name == null || name.trim().length() == 0)
+            throw new ConfigurationException("Element " + element + " has no name attribute");
+
+         Configuration c = parser.parseConfiguration(element);
+         // Prove that we can successfully clone it
+         c = c.clone();
+         result.put(name.trim(), c);
+      }
+
+      return result;
+   }
+}
\ No newline at end of file

Modified: core/trunk/src/main/java/org/jboss/cache/config/parsing/ConfigFilesConvertor.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/config/parsing/ConfigFilesConvertor.java	2008-07-08 16:27:15 UTC (rev 6215)
+++ core/trunk/src/main/java/org/jboss/cache/config/parsing/ConfigFilesConvertor.java	2008-07-08 16:29:58 UTC (rev 6216)
@@ -13,7 +13,6 @@
 import javax.xml.transform.stream.StreamSource;
 import javax.xml.transform.stream.StreamResult;
 import java.io.*;
-import java.net.URL;
 
 /**
  * Class used for converting a config file from from 2.x version to 3.x verison.
@@ -26,7 +25,7 @@
 
    public void parse(InputStream is, OutputStream os, String xsltFile) throws Exception
    {
-      InputStream xsltInStream = getFileAsStream(xsltFile);
+      InputStream xsltInStream = new FileLookup().lookupFile(xsltFile);
 
       Document document = getInputDocument(is);
 
@@ -41,7 +40,7 @@
 
    public void parse(String inputFile, OutputStream os, String xsltFile) throws Exception 
    {
-      InputStream stream = getFileAsStream(inputFile);
+      InputStream stream = new FileLookup().lookupFile(inputFile);
       try
       {
          parse(stream, os, xsltFile);
@@ -66,32 +65,6 @@
       return builder.parse(is);
    }
 
-   private InputStream getFileAsStream(String fileName) throws Exception
-   {
-      File xsltConvertorFile = new File(fileName);
-      if (!xsltConvertorFile.exists())
-      {
-         ClassLoader ccl = Thread.currentThread().getContextClassLoader();
-         URL resource = ccl.getResource(fileName);
-         if (resource == null)
-         {
-            resource = getClass().getClassLoader().getResource(fileName);
-            if (resource == null)
-               throw new IllegalArgumentException("File " + fileName + " does not exist on disk or on class path");
-            System.out.println("Using xsl file: " + resource);
-         } else
-         {
-            System.out.println("Using xsl file: " + resource);
-         }
-         return ccl.getResourceAsStream(fileName);
-      }
-      else
-      {
-         System.out.println("Using xls file: " + xsltConvertorFile.getAbsolutePath());
-         return new FileInputStream(xsltConvertorFile);
-      }
-   }
-
    public static void main(String[] argv) throws Exception
    {
       String sourceName = System.getProperty("source");

Added: core/trunk/src/main/java/org/jboss/cache/config/parsing/FileLookup.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/config/parsing/FileLookup.java	                        (rev 0)
+++ core/trunk/src/main/java/org/jboss/cache/config/parsing/FileLookup.java	2008-07-08 16:29:58 UTC (rev 6216)
@@ -0,0 +1,82 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.cache.config.parsing;
+
+import org.jboss.cache.config.ConfigurationException;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import java.io.InputStream;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+
+/**
+ * Holds the logic of looking up a file, in the following sequence:
+ * <ol>
+ * <li> try to load it with the curent thread's context ClassLoader</li>
+ * <li> if fails, the system ClassLoader</li>
+ * <li> if fails, try to load it as a file from the disck </li>
+ * </ol>
+ *
+ * @author Mircea.Markus at jboss.com
+ * @since 3.0
+ */
+public class FileLookup
+{
+   private static final Log log = LogFactory.getLog(FileLookup.class);
+
+   /**
+    * Looks up the file, see : {@link org.jboss.cache.config.parsing.FileLookup}.
+    * @param filename might be the name of the file (too look it up in the class path) or an url to a file.
+    * @return an input stream to the file or null if nothing found through all lookup steps.
+    */
+   public InputStream lookupFile(String filename)
+   {
+      InputStream is = getAsInputStreamFromClassLoader(filename);
+      if (is == null)
+      {
+         if (log.isDebugEnabled())
+            log.debug("Unable to find configuration file " + filename + " in classpath; searching for this file on the filesystem instead.");
+         try
+         {
+            is = new FileInputStream(filename);
+         }
+         catch (FileNotFoundException e)
+         {
+            return null;
+         }
+      }
+      return is;
+   }
+
+   protected InputStream getAsInputStreamFromClassLoader(String filename)
+   {
+      ClassLoader cl = Thread.currentThread().getContextClassLoader();
+      InputStream is = cl == null ? null : cl.getResourceAsStream(filename);
+      if (is == null)
+      {
+         // check system class loader
+         is = getClass().getClassLoader().getResourceAsStream(filename);
+      }
+      return is;
+   }
+}

Modified: core/trunk/src/main/java/org/jboss/cache/config/parsing/XmlConfigurationParser.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/config/parsing/XmlConfigurationParser.java	2008-07-08 16:27:15 UTC (rev 6215)
+++ core/trunk/src/main/java/org/jboss/cache/config/parsing/XmlConfigurationParser.java	2008-07-08 16:29:58 UTC (rev 6216)
@@ -24,7 +24,10 @@
 import java.util.Properties;
 
 /**
- * todo mmarkus comment classes
+ * Reads in XMLconfiguration files and spits out a {@link org.jboss.cache.config.Configuration} object.
+ * By default this class uses a validating parser (configurable).
+ * <p/>
+ * Implementation node: this class is stateful and one instance should be used for parsing a single configuration file.
  * todo mmarkus - allow disabling parser validation through -Djbc.config.validation=false
  *
  * @author Mircea.Markus at jboss.com
@@ -34,22 +37,37 @@
 {
    private static final Log log = LogFactory.getLog(XmlConfigurationParser.class);
 
+   /**
+    * the resulting configuration.
+    */
    private Configuration config = new Configuration();
    private Element root;
    private ErrorHandler errorHandler;
    private boolean isValidating = true;
 
+   /**
+    * If validation is on (default) one can specify an error handler for handling validation errors.
+    * The default error handler just logs parsing errors received.
+    */
    public XmlConfigurationParser(ErrorHandler errorHandler)
    {
       this.errorHandler = errorHandler;
    }
 
+   /**
+    * Same as {@link #XmlConfigurationParser(org.xml.sax.ErrorHandler)}.
+    *
+    * @param validating should the underlaying parser disable the validation?
+    */
    public XmlConfigurationParser(boolean validating, ErrorHandler errorHandler)
    {
       isValidating = validating;
       this.errorHandler = errorHandler;
    }
 
+   /**
+    * Constructs a parser having validation enabled with a ErrorHandler that only logs the parser errors.
+    */
    public XmlConfigurationParser()
    {
       this(new LoggingErrorHandler());
@@ -63,34 +81,15 @@
    //todo mmarkus this is duplicated code from 2x parser, extract it in an FileLookup class 
    public Configuration parseFile(String filename)
    {
-      InputStream is = getAsInputStreamFromClassLoader(filename);
+
+      InputStream is = new FileLookup().lookupFile(filename);
       if (is == null)
       {
-         if (log.isDebugEnabled())
-            log.debug("Unable to find configuration file " + filename + " in classpath; searching for this file on the filesystem instead.");
-         try
-         {
-            is = new FileInputStream(filename);
-         }
-         catch (FileNotFoundException e)
-         {
-            throw new ConfigurationException("Unable to find config file " + filename + " either in classpath or on the filesystem!", e);
-         }
+         throw new ConfigurationException("Unable to find config file " + filename + " either in classpath or on the filesystem!");
       }
       return parseStream(is);
    }
 
-   protected InputStream getAsInputStreamFromClassLoader(String filename)
-   {
-      ClassLoader cl = Thread.currentThread().getContextClassLoader();
-      InputStream is = cl == null ? null : cl.getResourceAsStream(filename);
-      if (is == null)
-      {
-         // check system class loader
-         is = getClass().getClassLoader().getResourceAsStream(filename);
-      }
-      return is;
-   }
 
    public Configuration parseStream(InputStream configStream)
    {
@@ -329,6 +328,7 @@
          {
             docBuilderFactory.setValidating(true);
             docBuilderFactory.setNamespaceAware(true);
+            //todo mmarkus load schema from classpath
             docBuilderFactory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
          }
          DocumentBuilder parser = docBuilderFactory.newDocumentBuilder();

Modified: core/trunk/src/main/java/org/jboss/cache/config/parsing/XmlConfigurationParser2x.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/config/parsing/XmlConfigurationParser2x.java	2008-07-08 16:27:15 UTC (rev 6215)
+++ core/trunk/src/main/java/org/jboss/cache/config/parsing/XmlConfigurationParser2x.java	2008-07-08 16:29:58 UTC (rev 6216)
@@ -64,19 +64,10 @@
     */
    public Configuration parseFile(String filename)
    {
-      InputStream is = getAsInputStreamFromClassLoader(filename);
+      InputStream is = new FileLookup().lookupFile(filename);
       if (is == null)
       {
-         if (log.isDebugEnabled())
-            log.debug("Unable to find configuration file " + filename + " in classpath; searching for this file on the filesystem instead.");
-         try
-         {
-            is = new FileInputStream(filename);
-         }
-         catch (FileNotFoundException e)
-         {
-            throw new ConfigurationException("Unable to find config file " + filename + " either in classpath or on the filesystem!", e);
-         }
+         throw new ConfigurationException("Unable to find config file " + filename + " either in classpath or on the filesystem!");
       }
 
       return parseStream(is);
@@ -186,18 +177,6 @@
       }
    }
 
-   protected InputStream getAsInputStreamFromClassLoader(String filename)
-   {
-      ClassLoader cl = Thread.currentThread().getContextClassLoader();
-      InputStream is = cl == null ? null : cl.getResourceAsStream(filename);
-      if (is == null)
-      {
-         // check system class loader
-         is = getClass().getClassLoader().getResourceAsStream(filename);
-      }
-      return is;
-   }
-
    protected Element getMBeanElement(Element root)
    {
       // This is following JBoss convention.

Modified: core/trunk/src/test/java/org/jboss/cache/factories/UnitTestCacheConfigurationFactory.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/factories/UnitTestCacheConfigurationFactory.java	2008-07-08 16:27:15 UTC (rev 6215)
+++ core/trunk/src/test/java/org/jboss/cache/factories/UnitTestCacheConfigurationFactory.java	2008-07-08 16:29:58 UTC (rev 6216)
@@ -14,6 +14,7 @@
 import org.jboss.cache.config.EvictionRegionConfig;
 import org.jboss.cache.config.parsing.XmlConfigHelper;
 import org.jboss.cache.config.parsing.XmlConfigurationParser;
+import org.jboss.cache.config.parsing.FileLookup;
 import org.jboss.cache.eviction.LRUConfiguration;
 import org.jboss.cache.transaction.TransactionSetup;
 import org.jgroups.conf.XmlConfigurator;
@@ -176,7 +177,8 @@
 
       public Configuration parseFile(String filename, CacheMode mode)
       {
-         return parseStream(getAsInputStreamFromClassLoader(filename == null ? DEFAULT_CONFIGURATION_FILE : filename), mode);
+         String finalFileName = filename == null ? DEFAULT_CONFIGURATION_FILE : filename;
+         return parseStream(new FileLookup().lookupFile(finalFileName), mode);
       }
 
       public Configuration parseStream(InputStream stream, CacheMode mode)




More information about the jbosscache-commits mailing list