db-ojb-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From arm...@apache.org
Subject svn commit: r410626 - in /db/ojb/branches/OJB_1_0_RELEASE/src: doc/forrest/src/documentation/content/xdocs/docu/guides/ java/org/apache/ojb/broker/metadata/ test/org/apache/ojb/broker/metadata/
Date Wed, 31 May 2006 18:20:31 GMT
Author: arminw
Date: Wed May 31 11:20:30 2006
New Revision: 410626

URL: http://svn.apache.org/viewvc?rev=410626&view=rev
Log:
OJB-109, improve repository.xml reading

Modified:
    db/ojb/branches/OJB_1_0_RELEASE/src/doc/forrest/src/documentation/content/xdocs/docu/guides/repository.xml
    db/ojb/branches/OJB_1_0_RELEASE/src/java/org/apache/ojb/broker/metadata/MetadataManager.java
    db/ojb/branches/OJB_1_0_RELEASE/src/java/org/apache/ojb/broker/metadata/RepositoryPersistor.java
    db/ojb/branches/OJB_1_0_RELEASE/src/test/org/apache/ojb/broker/metadata/MetadataTest.java

Modified: db/ojb/branches/OJB_1_0_RELEASE/src/doc/forrest/src/documentation/content/xdocs/docu/guides/repository.xml
URL: http://svn.apache.org/viewvc/db/ojb/branches/OJB_1_0_RELEASE/src/doc/forrest/src/documentation/content/xdocs/docu/guides/repository.xml?rev=410626&r1=410625&r2=410626&view=diff
==============================================================================
--- db/ojb/branches/OJB_1_0_RELEASE/src/doc/forrest/src/documentation/content/xdocs/docu/guides/repository.xml
(original)
+++ db/ojb/branches/OJB_1_0_RELEASE/src/doc/forrest/src/documentation/content/xdocs/docu/guides/repository.xml
Wed May 31 11:20:30 2006
@@ -119,7 +119,7 @@
 # repository file settings
 #----------------------------------------------------------------------------------------
 # The repositoryFile entry tells OJB to use this file as as its standard mapping
-# repository. The file is first looked up from the classpath, second as ordinary file.
+# repository. First OJB lookup the file as resource from classpath, second as ordinary file.
 #
 repositoryFile=repository.xml
 ]]></source>

Modified: db/ojb/branches/OJB_1_0_RELEASE/src/java/org/apache/ojb/broker/metadata/MetadataManager.java
URL: http://svn.apache.org/viewvc/db/ojb/branches/OJB_1_0_RELEASE/src/java/org/apache/ojb/broker/metadata/MetadataManager.java?rev=410626&r1=410625&r2=410626&view=diff
==============================================================================
--- db/ojb/branches/OJB_1_0_RELEASE/src/java/org/apache/ojb/broker/metadata/MetadataManager.java
(original)
+++ db/ojb/branches/OJB_1_0_RELEASE/src/java/org/apache/ojb/broker/metadata/MetadataManager.java
Wed May 31 11:20:30 2006
@@ -15,15 +15,24 @@
  * limitations under the License.
  */
 
+import java.io.File;
+import java.io.FileInputStream;
 import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
 import java.io.InputStream;
+import java.net.MalformedURLException;
+import java.net.URL;
 import java.util.Hashtable;
 import java.util.Iterator;
 import java.util.List;
 
 import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang.StringUtils;
 import org.apache.ojb.broker.PBKey;
 import org.apache.ojb.broker.core.PersistenceBrokerConfiguration;
+import org.apache.ojb.broker.util.ClassHelper;
+import org.apache.ojb.broker.util.configuration.Configuration;
+import org.apache.ojb.broker.util.configuration.impl.OjbConfiguration;
 import org.apache.ojb.broker.util.configuration.impl.OjbConfigurator;
 import org.apache.ojb.broker.util.logging.Logger;
 import org.apache.ojb.broker.util.logging.LoggerFactory;
@@ -114,14 +123,15 @@
  * the <a href="#enablePerThreadMode">per thread mode</a> is enabled.
  * </p>
  *
- *
- * @author <a href="mailto:armin@codeAuLait.de">Armin Waibel</a>
  * @version $Id$
  */
 public class MetadataManager
 {
     private static Logger log = LoggerFactory.getLogger(MetadataManager.class);
 
+    private static final String SER_FILE_SUFFIX = "serialized";
+    private static final String SERIALIZED_REPOSITORY_PATH = "serializedRepositoryPath";
+
     private static final String MSG_STR = "* Can't find DescriptorRepository for current
thread, use default one *";
     private static ThreadLocal threadedRepository = new ThreadLocal();
     private static ThreadLocal currentProfileKey = new ThreadLocal();
@@ -142,16 +152,47 @@
     private void init()
     {
         metadataProfiles = new Hashtable();
-        final String repository = ((PersistenceBrokerConfiguration) OjbConfigurator.getInstance()
-                .getConfigurationFor(null)).getRepositoryFilename();
+        Configuration conf = OjbConfigurator.getInstance().getConfigurationFor(null);
+        boolean useSerializedRepository = ((MetadataConfiguration) conf).useSerializedRepository();
+        File serFile = null;
+        if(useSerializedRepository)
+        {
+            // build File object pointing to serialized repository location
+            String pathPrefix = conf.getString(SERIALIZED_REPOSITORY_PATH, ".");
+            serFile = new File(pathPrefix + File.separator + OjbConfiguration.OJB_METADATA_FILE
+                    + "." + SER_FILE_SUFFIX);
+
+            if (serFile.exists() && serFile.length() > 0)
+            {
+                try
+                {
+                    long duration = System.currentTimeMillis();
+                    globalRepository = deserialize(serFile);
+                    log.info("Read serialized repository in " + (System.currentTimeMillis()
- duration) + " ms");
+                }
+                catch(Exception e)
+                {
+                    log.error("error in loading serialized repository. Will try to use XML
version.", e);
+                }
+            }
+        }
+        URL url = buildRepositoryURL(conf);
         try
         {
-            globalRepository     = new RepositoryPersistor().readDescriptorRepository(repository);
-            connectionRepository = new RepositoryPersistor().readConnectionRepository(repository);
+            if(globalRepository == null)
+            {
+                globalRepository     = new RepositoryPersistor().readDescriptorRepository(url);
+                if(useSerializedRepository)
+                {
+                    serialize(globalRepository, serFile);
+                    log.info("Write serialized repository to " + serFile);
+                }
+            }
+            connectionRepository = new RepositoryPersistor().readConnectionRepository(url);
         }
         catch (FileNotFoundException ex)
         {
-            log.warn("Could not access '" + repository + "' or a DOCTYPE/DTD-dependency.
"
+            log.warn("Could not access '" + url + "' or a DOCTYPE/DTD-dependency. "
                      + "(Check letter case for file names and HTTP-access if using DOCTYPE
PUBLIC)"
                      + " Starting with empty metadata and connection configurations.", ex);
             globalRepository     = new DescriptorRepository();
@@ -159,7 +200,7 @@
         }
         catch (Exception ex)
         {
-            throw new MetadataException("Can't read repository file '" + repository + "'",
ex);
+            throw new MetadataException("Can't read repository file '" + url + "'", ex);
         }
     }
 
@@ -634,6 +675,93 @@
                     " thus it's currently not possible to use 'defaultPersistenceBroker()'
" +
                     " convenience method to lookup PersistenceBroker instances. But it's
possible"+
                     " to enable this at runtime using 'setDefaultKey' method.");
+        }
+        return result;
+    }
+
+    protected static URL buildRepositoryURL(Configuration conf)
+    {
+        // 1. search for system property entry
+        String repositoryPath = System.getProperties().getProperty(OjbConfiguration.OJB_METADATA_FILE
, null);
+        String repositoryPath2 = null;
+        // 2. lookup repository file path from OJB.properties file
+        if(repositoryPath == null)
+        {
+            repositoryPath = ((PersistenceBrokerConfiguration) conf).getRepositoryFilename();
+        }
+        URL url = lookupURL(repositoryPath);
+        if(url == null)
+        {
+            // 3. Try to lookup repository file in same directory as OJB.properties file
+            String ojbPropertiesPath = conf.getString(OjbConfiguration.OJB_PROPERTIES_PATH_PROP,
null);
+            if(ojbPropertiesPath != null && ojbPropertiesPath.length() > 0)
+            {
+                ojbPropertiesPath = StringUtils.substringBeforeLast(ojbPropertiesPath, OjbConfiguration.OJB_PROPERTIES_FILE);
+                repositoryPath2 = ojbPropertiesPath + repositoryPath;
+                url = lookupURL(repositoryPath2);
+            }
+        }
+
+        if (url != null)
+        {
+            log.info("OJB Repository file: " + url);
+        }
+        else
+        {
+            log.warn("Can't find OJB Repository file using path '" + repositoryPath + "'
and path '" + repositoryPath2 + "'");
+        }
+        return url;
+    }
+
+    private static URL lookupURL(String repositoryPath)
+    {
+        //j2ee compliant lookup of resources
+        URL url = ClassHelper.getResource(repositoryPath);
+        // don't be too strict: if resource is not on the classpath, try ordinary file lookup
+        if (url == null)
+        {
+            try
+            {
+                File file = new File(repositoryPath);
+                if(file.exists())
+                {
+                    url = file.toURL();
+                }
+            }
+            catch (MalformedURLException ignore)
+            {
+                // ignore
+            }
+        }
+        return url;
+    }
+
+    protected void serialize(DescriptorRepository repository, File file)
+    {
+        try
+        {
+            FileOutputStream fos = new FileOutputStream(file);
+            // serialize repository
+            SerializationUtils.serialize(repository, fos);
+        }
+        catch (Exception e)
+        {
+            log.error("Serialization failed, using output path: " + file.getAbsolutePath(),
e);
+        }
+    }
+
+    protected DescriptorRepository deserialize(File serFile)
+    {
+        DescriptorRepository result = null;
+        try
+        {
+            FileInputStream fis = new FileInputStream(serFile);
+            // deserialize repository
+            result = (DescriptorRepository) SerializationUtils.deserialize(fis);
+        }
+        catch (Exception e)
+        {
+            log.error("Deserialisation failed, using input path: " + serFile.getAbsolutePath(),
e);
         }
         return result;
     }

Modified: db/ojb/branches/OJB_1_0_RELEASE/src/java/org/apache/ojb/broker/metadata/RepositoryPersistor.java
URL: http://svn.apache.org/viewvc/db/ojb/branches/OJB_1_0_RELEASE/src/java/org/apache/ojb/broker/metadata/RepositoryPersistor.java?rev=410626&r1=410625&r2=410626&view=diff
==============================================================================
--- db/ojb/branches/OJB_1_0_RELEASE/src/java/org/apache/ojb/broker/metadata/RepositoryPersistor.java
(original)
+++ db/ojb/branches/OJB_1_0_RELEASE/src/java/org/apache/ojb/broker/metadata/RepositoryPersistor.java
Wed May 31 11:20:30 2006
@@ -19,8 +19,6 @@
 import javax.xml.parsers.SAXParser;
 import javax.xml.parsers.SAXParserFactory;
 import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
@@ -30,7 +28,6 @@
 import java.net.URLConnection;
 import java.util.Date;
 
-import org.apache.commons.lang.SerializationUtils;
 import org.apache.commons.lang.SystemUtils;
 import org.apache.ojb.broker.util.ClassHelper;
 import org.apache.ojb.broker.util.configuration.Configurable;
@@ -51,8 +48,6 @@
  * from and to persistent media.
  * Currently only XML file based persistence is supported.
  *
- * @author <a href="mailto:thma@apache.org">Thomas Mahler<a>
- * @author <a href="mailto:armin@codeAuLait.de">Armin Waibel</a>
  * @version $Id$
  */
 public class RepositoryPersistor implements Configurable
@@ -61,11 +56,6 @@
 
     private static Logger log = LoggerFactory.getLogger(RepositoryPersistor.class);
 
-    private static final String SER_FILE_SUFFIX = "serialized";
-    private static final String SERIALIZED_REPOSITORY_PATH = "serializedRepositoryPath";
-
-    private boolean useSerializedRepository = false;
-
     public RepositoryPersistor()
     {
         OjbConfigurator.getInstance().configure(this);
@@ -73,11 +63,12 @@
 
     public void configure(Configuration pConfig) throws ConfigurationException
     {
-        useSerializedRepository = ((MetadataConfiguration) pConfig).useSerializedRepository();
     }
 
     /**
      * Write the {@link DescriptorRepository} to the given output object.
+     *
+     * @deprecated Will be removed.
      */
     public void writeToFile(DescriptorRepository repository, ConnectionRepository conRepository,
OutputStream out)
     {
@@ -86,30 +77,37 @@
         {
             if (log.isDebugEnabled())
                 log.debug("## Write repository file ##" +
-                        repository.toXML() +
+                        (repository != null ? repository.toXML() : " null ") +
                         "## End of repository file ##");
 
 
             String eol = SystemUtils.LINE_SEPARATOR;
             StringBuffer buf = new StringBuffer();
             // 1. write XML header
-            buf.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + eol);
+            buf.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>").append(eol);
 
-            buf.append("<!DOCTYPE descriptor-repository SYSTEM \"repository.dtd\" >"
+ eol + eol);
+            buf.append("<!DOCTYPE descriptor-repository SYSTEM \"repository.dtd\" >").append(eol).append(eol);
 //            strReturn += "<!DOCTYPE descriptor-repository SYSTEM \"repository.dtd\"
[" + eol;
 //            strReturn += "<!ENTITY database-metadata SYSTEM \""+ConnectionRepository.DATABASE_METADATA_FILENAME+"\">"
+ eol;
 //            strReturn += "<!ENTITY user SYSTEM \"repository_user.xml\">" + eol;
 //            strReturn += "<!ENTITY junit SYSTEM \"repository_junit.xml\">" + eol;
 //            strReturn += "<!ENTITY internal SYSTEM \"repository_internal.xml\"> ]>"
+ eol + eol;
 
-            buf.append("<!-- OJB RepositoryPersistor generated this file on " + new Date().toString()
+ " -->" + eol);
+            buf.append("<!-- OJB RepositoryPersistor generated this file on ")
+                    .append(new Date().toString()).append(" -->").append(eol);
 
-            buf.append(tags.getOpeningTagNonClosingById(RepositoryElements.MAPPING_REPOSITORY)
+ eol);
-            buf.append("  " + tags.getAttribute(RepositoryElements.REPOSITORY_VERSION, DescriptorRepository.getVersion())
+ eol);
-            buf.append("  " + tags.getAttribute(RepositoryElements.ISOLATION_LEVEL, repository.getIsolationLevelAsString())
+ eol);
-            buf.append(">" + eol);
+            buf.append(tags.getOpeningTagNonClosingById(RepositoryElements.MAPPING_REPOSITORY)).append(eol);
+            buf.append("  ").append(tags.getAttribute(
+                    RepositoryElements.REPOSITORY_VERSION, DescriptorRepository.getVersion())).append(eol);
+            if(repository != null)
+            {
+                buf.append("  ").append(tags.getAttribute(
+                        RepositoryElements.ISOLATION_LEVEL, repository.getIsolationLevelAsString())).append(eol);
+            }
+            buf.append(">").append(eol);
 
-            if(conRepository != null) buf.append(eol + eol + conRepository.toXML() + eol
+ eol);
+            if(conRepository != null) buf.append(eol).append(eol).append(conRepository.toXML())
+                    .append(eol).append(eol);
             if(repository != null) buf.append(repository.toXML());
 
             buf.append(tags.getClosingTagById(RepositoryElements.MAPPING_REPOSITORY));
@@ -139,49 +137,21 @@
     public DescriptorRepository readDescriptorRepository(String filename)
             throws MalformedURLException, ParserConfigurationException, SAXException, IOException
     {
-        DescriptorRepository result;
-        if (useSerializedRepository)
-        // use serialized repository
-        {
-            // build File object pointing to serialized repository location
-            Configuration config = OjbConfigurator.getInstance().getConfigurationFor(null);
-            String pathPrefix = config.getString(SERIALIZED_REPOSITORY_PATH, ".");
-            File serFile = new File(pathPrefix + File.separator + filename + "." + SER_FILE_SUFFIX);
-
-            if (serFile.exists() && serFile.length() > 0)
-            // if file exists load serialized version of repository
-            {
-                try
-                {
-                    long duration = System.currentTimeMillis();
-                    result = deserialize(serFile);
-                    log.info("Read serialized repository in " + (System.currentTimeMillis()
- duration) + " ms");
-                }
-                catch (Exception e)
-                {
-                    log.error("error in loading serialized repository. Will try to use XML
version.", e);
-                    result = (DescriptorRepository) buildRepository(filename, DescriptorRepository.class);
-                }
-            }
-            else
-            // if no serialized version exists, read it from xml and write serialized file
-            {
-                long duration = System.currentTimeMillis();
-                result = (DescriptorRepository) buildRepository(filename, DescriptorRepository.class);
-                log.info("Read repository from file took " + (System.currentTimeMillis()
- duration) + " ms");
-                serialize(result, serFile);
-            }
-        }
-        // don't use serialized repository
-        else
-        {
-            long duration = System.currentTimeMillis();
-            result = (DescriptorRepository) buildRepository(filename, DescriptorRepository.class);
-            log.info("Read class descriptors took " + (System.currentTimeMillis() - duration)
+ " ms");
-        }
-        return result;
+        URL url = buildURL(filename);
+        return readDescriptorRepository(url);
     }
 
+    /**
+     * Read the repository configuration file.
+     * <br>
+     * If configuration property <code>useSerializedRepository</code> is <code>true</code>
+     * all subsequent calls read a serialized version of the repository.
+     * The directory where the serialized repository is stored can be specified
+     * with the <code>serializedRepositoryPath</code> entry in OJB.properties.
+     * Once a serialized repository is found changes to repository.xml will be
+     * ignored. To force consideration of these changes the serialized repository
+     * must be deleted manually.
+     */
     public DescriptorRepository readDescriptorRepository(InputStream inst)
             throws MalformedURLException, ParserConfigurationException, SAXException, IOException
     {
@@ -193,13 +163,34 @@
     }
 
     /**
+     * Read the repository configuration file.
+     * <br>
+     * If configuration property <code>useSerializedRepository</code> is <code>true</code>
+     * all subsequent calls read a serialized version of the repository.
+     * The directory where the serialized repository is stored can be specified
+     * with the <code>serializedRepositoryPath</code> entry in OJB.properties.
+     * Once a serialized repository is found changes to repository.xml will be
+     * ignored. To force consideration of these changes the serialized repository
+     * must be deleted manually.
+     */
+    public DescriptorRepository readDescriptorRepository(URL url)
+            throws MalformedURLException, ParserConfigurationException, SAXException, IOException
+    {
+        long duration = System.currentTimeMillis();
+        DescriptorRepository result = (DescriptorRepository) buildRepository(url, DescriptorRepository.class);
+        log.info("Read class descriptors took " + (System.currentTimeMillis() - duration)
+ " ms");
+        return result;
+    }
+
+    /**
      * Read the repository configuration file and extract connection handling information.
      */
     public ConnectionRepository readConnectionRepository(String filename)
             throws MalformedURLException, ParserConfigurationException, SAXException, IOException
     {
         long duration = System.currentTimeMillis();
-        ConnectionRepository result = (ConnectionRepository) buildRepository(filename, ConnectionRepository.class);
+        URL url = buildURL(filename);
+        ConnectionRepository result = (ConnectionRepository) buildRepository(url, ConnectionRepository.class);
         log.info("Read connection repository took " + (System.currentTimeMillis() - duration)
+ " ms");
         return result;
     }
@@ -217,44 +208,25 @@
         return result;
     }
 
-    protected DescriptorRepository deserialize(File serFile)
+    /**
+     * Read the repository configuration file and extract connection handling information.
+     */
+    public ConnectionRepository readConnectionRepository(URL url)
+            throws MalformedURLException, ParserConfigurationException, SAXException, IOException
     {
-        DescriptorRepository result = null;
-        try
-        {
-            FileInputStream fis = new FileInputStream(serFile);
-            // deserialize repository
-            result = (DescriptorRepository) SerializationUtils.deserialize(fis);
-        }
-        catch (Exception e)
-        {
-            log.error("Deserialisation failed, using input path: " + serFile.getAbsolutePath(),
e);
-        }
+        long duration = System.currentTimeMillis();
+        ConnectionRepository result = (ConnectionRepository) buildRepository(url, ConnectionRepository.class);
+        log.info("Read connection repository took " + (System.currentTimeMillis() - duration)
+ " ms");
         return result;
     }
 
-    protected void serialize(DescriptorRepository repository, File file)
-    {
-        try
-        {
-            FileOutputStream fos = new FileOutputStream(file);
-            // serialize repository
-            SerializationUtils.serialize(repository, fos);
-        }
-        catch (Exception e)
-        {
-            log.error("Serialization failed, using output path: " + file.getAbsolutePath(),
e);
-        }
-    }
-
     /**
      *
      * TODO: We should re-design the configuration file reading
      */
-    private Object buildRepository(String repositoryFileName, Class targetRepository)
+    private Object buildRepository(URL url, Class targetRepository)
             throws MalformedURLException, ParserConfigurationException, SAXException, IOException
     {
-        URL url = buildURL(repositoryFileName);
         /*
         arminw:
         strange, when using 'url.openStream()' argument repository
@@ -358,6 +330,7 @@
             }
             catch (MalformedURLException ignore)
             {
+                // ignore
             }
         }
 

Modified: db/ojb/branches/OJB_1_0_RELEASE/src/test/org/apache/ojb/broker/metadata/MetadataTest.java
URL: http://svn.apache.org/viewvc/db/ojb/branches/OJB_1_0_RELEASE/src/test/org/apache/ojb/broker/metadata/MetadataTest.java?rev=410626&r1=410625&r2=410626&view=diff
==============================================================================
--- db/ojb/branches/OJB_1_0_RELEASE/src/test/org/apache/ojb/broker/metadata/MetadataTest.java
(original)
+++ db/ojb/branches/OJB_1_0_RELEASE/src/test/org/apache/ojb/broker/metadata/MetadataTest.java
Wed May 31 11:20:30 2006
@@ -1,6 +1,8 @@
 package org.apache.ojb.broker.metadata;
 
 import java.util.Iterator;
+import java.io.File;
+import java.io.FileInputStream;
 
 import junit.framework.TestCase;
 import org.apache.ojb.broker.Identity;
@@ -64,6 +66,28 @@
         }
     }
 
+    public void testReadRepository() throws Exception
+    {
+        MetadataManager mm = MetadataManager.getInstance();
+
+        FileInputStream inst = new FileInputStream(new File(TEST_CLASS_DESCRIPTOR));
+        DescriptorRepository dr_1 = mm.readDescriptorRepository(inst);
+        inst.close();
+        assertNotNull(dr_1);
+
+        inst = new FileInputStream(new File(TEST_CONNECTION_DESCRIPTOR));
+        ConnectionRepository cr_1 = mm.readConnectionRepository(inst);
+        inst.close();
+        assertNotNull(cr_1);
+
+        dr_1 = mm.readDescriptorRepository(TEST_CLASS_DESCRIPTOR);
+        cr_1 = mm.readConnectionRepository(TEST_CONNECTION_DESCRIPTOR);
+        assertNotNull(dr_1);
+        assertNotNull(cr_1);
+
+
+    }
+
     public void testFindFirstConcreteClassDescriptor()
     {
         DescriptorRepository dr = MetadataManager.getInstance().getRepository();
@@ -71,8 +95,6 @@
         ClassDescriptor firstConcrete = dr.findFirstConcreteClass(cld);
         assertFalse(firstConcrete.isInterface());
         assertFalse(firstConcrete.isAbstract());
-        firstConcrete = dr.findFirstConcreteClass(cld);
-        firstConcrete = dr.findFirstConcreteClass(cld);
     }
 
     public void testDescriptorRepository_1()



---------------------------------------------------------------------
To unsubscribe, e-mail: ojb-dev-unsubscribe@db.apache.org
For additional commands, e-mail: ojb-dev-help@db.apache.org


Mime
View raw message