svn commit: r15547 - trunk/src/argouml-app/src/org/argouml: moduleloader profile/init

[email protected]
Newsgroups gmane.comp.lang.uml.argouml.cvs
Message-ID <[email protected]>
Author: maurelio1234
Date: 2008-08-11 09:44:34-0700
New Revision: 15547

Added:
   trunk/src/argouml-app/src/org/argouml/profile/init/ProfileLoader.java
Modified:
   trunk/src/argouml-app/src/org/argouml/moduleloader/ModuleLoader2.java
   trunk/src/argouml-app/src/org/argouml/profile/init/InitProfileSubsystem.java

Log:

applying patch for issue 5029



Modified: trunk/src/argouml-app/src/org/argouml/moduleloader/ModuleLoader2.java
Url: http://argouml.tigris.org/source/browse/argouml/trunk/src/argouml-app/src/org/argouml/moduleloader/ModuleLoader2.java?view=diff&rev=15547&p1=trunk/src/argouml-app/src/org/argouml/moduleloader/ModuleLoader2.java&p2=trunk/src/argouml-app/src/org/argouml/moduleloader/ModuleLoader2.java&r1=15546&r2=15547
==============================================================================
--- trunk/src/argouml-app/src/org/argouml/moduleloader/ModuleLoader2.java	(original)
+++ trunk/src/argouml-app/src/org/argouml/moduleloader/ModuleLoader2.java	2008-08-11 09:44:34-0700
@@ -109,6 +109,7 @@
      */
     private ModuleLoader2() {
 	moduleStatus = new HashMap<ModuleInterface, ModuleStatus>();
+        computeExtensionLocations();
     }
 
     /**
@@ -453,67 +454,72 @@
     /**
      * Find and enable modules from our "ext" directory and from the
      * directory specified in "argo.ext.dir".<p>
-     *
-     * TODO: This does a calculation of where our "ext" directory is.
-     *       We should eventually make sure that this calculation is
-     *       only present in one place in the code and not several.
      */
     private void huntForModulesFromExtensionDir() {
-	// Use a little trick to find out where Argo is being loaded from.
+        for (String location : extensionLocations) {
+            huntModulesFromNamedDirectory(location);            
+        }
+    }
+
+    /**
+     * This does a calculation of where our "ext" directory is.
+     * TODO: We should eventually make sure that this calculation is
+     *       only present in one place in the code and not several.
+     */
+    private void computeExtensionLocations() {
+        // Use a little trick to find out where Argo is being loaded from.
         String extForm = getClass().getResource(Argo.ARGOINI).toExternalForm();
-	String argoRoot =
-	    extForm.substring(0,
-			      extForm.length() - Argo.ARGOINI.length());
-
-	// If it's a jar, clean it up and make it look like a file url
-	if (argoRoot.startsWith(JAR_PREFIX)) {
-	    argoRoot = argoRoot.substring(JAR_PREFIX.length());
-	    if (argoRoot.endsWith("!")) {
-	        argoRoot = argoRoot.substring(0, argoRoot.length() - 1);
-	    }
-	}
+        String argoRoot =
+            extForm.substring(0,
+                              extForm.length() - Argo.ARGOINI.length());
+
+        // If it's a jar, clean it up and make it look like a file url
+        if (argoRoot.startsWith(JAR_PREFIX)) {
+            argoRoot = argoRoot.substring(JAR_PREFIX.length());
+            if (argoRoot.endsWith("!")) {
+                argoRoot = argoRoot.substring(0, argoRoot.length() - 1);
+            }
+        }
 
-	String argoHome = null;
+        String argoHome = null;
 
-	if (argoRoot != null) {
-	    LOG.info("argoRoot is " + argoRoot);
-	    if (argoRoot.startsWith(FILE_PREFIX)) {
-	        argoHome =
-	            new File(argoRoot.substring(FILE_PREFIX.length()))
-	            	.getAbsoluteFile().getParent();
-	    } else {
-	        argoHome = new File(argoRoot).getAbsoluteFile().getParent();
-	    }
+        if (argoRoot != null) {
+            LOG.info("argoRoot is " + argoRoot);
+            if (argoRoot.startsWith(FILE_PREFIX)) {
+                argoHome =
+                    new File(argoRoot.substring(FILE_PREFIX.length()))
+                        .getAbsoluteFile().getParent();
+            } else {
+                argoHome = new File(argoRoot).getAbsoluteFile().getParent();
+            }
 
-	    try {
-		argoHome = java.net.URLDecoder.decode(argoHome, 
+            try {
+                argoHome = java.net.URLDecoder.decode(argoHome, 
                         Argo.getEncoding());
-	    } catch (UnsupportedEncodingException e) {
-		LOG.warn("Encoding " 
+            } catch (UnsupportedEncodingException e) {
+                LOG.warn("Encoding " 
                         + Argo.getEncoding() 
                         + " is unknown.");
-	    }
+            }
 
-	    LOG.info("argoHome is " + argoHome);
-	}
+            LOG.info("argoHome is " + argoHome);
+        }
 
-	if (argoHome != null) {
+        if (argoHome != null) {
             String extdir;
-	    if (argoHome.startsWith(FILE_PREFIX)) {
-	        extdir = argoHome.substring(FILE_PREFIX.length())
+            if (argoHome.startsWith(FILE_PREFIX)) {
+                extdir = argoHome.substring(FILE_PREFIX.length())
                         + File.separator + "ext";
-	    } else {
-	        extdir = argoHome + File.separator + "ext";
-	    }
+            } else {
+                extdir = argoHome + File.separator + "ext";
+            }
             extensionLocations.add(extdir);
-	    huntModulesFromNamedDirectory(extdir);
-	}
+        }
 
         String extdir = System.getProperty("argo.ext.dir");
-	if (extdir != null) {
+        if (extdir != null) {
             extensionLocations.add(extdir);
-	    huntModulesFromNamedDirectory(extdir);
-	}
+        }
     }
     
     /**

Modified: trunk/src/argouml-app/src/org/argouml/profile/init/InitProfileSubsystem.java
Url: http://argouml.tigris.org/source/browse/argouml/trunk/src/argouml-app/src/org/argouml/profile/init/InitProfileSubsystem.java?view=diff&rev=15547&p1=trunk/src/argouml-app/src/org/argouml/profile/init/InitProfileSubsystem.java&p2=trunk/src/argouml-app/src/org/argouml/profile/init/InitProfileSubsystem.java&r1=15546&r2=15547
==============================================================================
--- trunk/src/argouml-app/src/org/argouml/profile/init/InitProfileSubsystem.java	(original)
+++ trunk/src/argouml-app/src/org/argouml/profile/init/InitProfileSubsystem.java	2008-08-11 09:44:34-0700
@@ -52,6 +52,9 @@
         /* Set up the property panels for critics: */
         PropPanelFactory factory = new ProfilePropPanelFactory();
         PropPanelFactoryManager.addPropPanelFactory(factory);    
+        
+        /* init profiles defined in jar files */
+        new ProfileLoader().doLoad();
     }
 
 }

Added: trunk/src/argouml-app/src/org/argouml/profile/init/ProfileLoader.java
Url: http://argouml.tigris.org/source/browse/argouml/trunk/src/argouml-app/src/org/argouml/profile/init/ProfileLoader.java?view=auto&rev=15547
==============================================================================
--- (empty file)
+++ trunk/src/argouml-app/src/org/argouml/profile/init/ProfileLoader.java	2008-08-11 09:44:34-0700
@@ -0,0 +1,234 @@
+// $Id: eclipse-argo-codetemplates.xml 11347 2006-10-26 22:37:44Z linus $
+// Copyright (c) 2008 The Regents of the University of California. All
+// Rights Reserved. Permission to use, copy, modify, and distribute this
+// software and its documentation without fee, and without a written
+// agreement is hereby granted, provided that the above copyright notice
+// and this paragraph appear in all copies. This software program and
+// documentation are copyrighted by The Regents of the University of
+// California. The software program and documentation are supplied "AS
+// IS", without any accompanying services from The Regents. The Regents
+// does not warrant that the operation of the program will be
+// uninterrupted or error-free. The end-user understands that the program
+// was developed for research purposes and is advised not to rely
+// exclusively on the program for any reason. IN NO EVENT SHALL THE
+// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
+// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,
+// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
+// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
+// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY
+// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
+// PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
+// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,
+// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+
+package org.argouml.profile.init;
+
+import java.io.File;
+import java.io.FileFilter;
+import java.io.IOException;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.StringTokenizer;
+import java.util.jar.Attributes;
+import java.util.jar.JarFile;
+import java.util.jar.Manifest;
+
+import org.apache.log4j.Logger;
+import org.argouml.cognitive.Critic;
+import org.argouml.i18n.Translator;
+import org.argouml.moduleloader.ModuleLoader2;
+import org.argouml.profile.ProfileException;
+import org.argouml.profile.ProfileFacade;
+import org.argouml.profile.UserDefinedProfile;
+
+/**
+ * This is the profile loader that loads modules profiles
+ * 
+ * @author maurelio1234
+ */
+public final class ProfileLoader {
+    /**
+     * Logger.
+     */
+    private static final Logger LOG = Logger.getLogger(ProfileLoader.class);
+    
+    /**
+     * The prefix in URL:s that are jars.
+     */
+    private static final String JAR_PREFIX = "jar:";
+    
+    /**
+     * The prefix in URL:s that are files.
+     */
+    private static final String FILE_PREFIX = "file:";
+    
+    /**
+     * Looks for profiles in the jars in the directories used by the 
+     * ModuleLoader to load modules
+     */
+    public void doLoad() {
+        List<String> extDirs = 
+            ModuleLoader2.getInstance().getExtensionLocations();
+        
+        for (String extDir : extDirs) {
+            huntForProfilesInDir(extDir);
+        }
+    }
+
+    private void huntForProfilesInDir(String dir) {
+        LOG.info("Looking for Profiles in " + dir);
+        
+        File extensionDir = new File(dir);
+        if (extensionDir.isDirectory()) {
+            File[] files = extensionDir.listFiles(new JarFileFilter());
+            for (File file : files) {
+                JarFile jarfile = null;
+                try {
+                    jarfile = new JarFile(file);
+                    if (jarfile != null) {
+                        LOG.info("Looking for Profiles in the Jar "
+                                + jarfile.getName());
+
+                        ClassLoader classloader = new URLClassLoader(
+                                new URL[] {file.toURI().toURL()});
+                        loadProfilesFromJarFile(jarfile.getManifest(), file,
+                                classloader);
+                    }
+                } catch (IOException ioe) {
+                    LOG.debug("Cannot open Jar file " + file, ioe);
+                }
+            }
+        }
+
+    }
+
+    /**
+     * Interprets the MANIFEST file in the JAR in order to load the declared
+     * profile.
+     * 
+     * @param file the file object referencing the Jar
+     * @param manifest the manifest file of the Jar
+     * @param classloader the classloader that loads the classes referenced by
+     *            the Jar
+     */
+    private void loadProfilesFromJarFile(Manifest manifest, File file,
+            ClassLoader classloader) {
+        Map<String, Attributes> entries = manifest.getEntries();
+        boolean classLoaderAlreadyAdded = false;
+
+        for (String entryName : entries.keySet()) {
+            Attributes attr = entries.get(entryName);
+            if (new Boolean(attr.getValue("Profile") + "").booleanValue()) {
+                try {
+                    // we only need to add the classloader once
+                    // and if and only if there is at least a profile
+                    // in the JAR
+                    if (!classLoaderAlreadyAdded) {
+                        Translator.addClassLoader(classloader);
+                        classLoaderAlreadyAdded = true;
+                    }
+                    Set<Critic> critics = loadJavaCriticsForProfile(attr,
+                            classloader);
+                    String modelPath = attr.getValue("Model");
+                    URL modelURL = null;
+
+                    if (modelPath != null) {
+                        modelURL = new URL(JAR_PREFIX + FILE_PREFIX
+                                + file.getCanonicalPath() + "!" + modelPath);
+                    }
+
+                    UserDefinedProfile udp = new UserDefinedProfile(entryName,
+                            modelURL, critics,
+                            loadManifestDependenciesForProfile(attr));
+
+                    ProfileFacade.getManager().registerProfile(udp);
+                    LOG.debug("Registered Profile: " + udp.getDisplayName()
+                            + "...");
+                } catch (ProfileException e) {
+                    LOG.error("Exception", e);
+                } catch (IOException e) {
+                    LOG.error("Exception", e);
+                }
+            }
+
+        }
+    }
+
+    /**
+     * Resolves the dependencies for a Profile
+     * 
+     * @param attr a group of attributes in the MANIFEST file for this JAR
+     * 
+     * @return the set of defined profiles
+     */
+    private Set<String> loadManifestDependenciesForProfile(Attributes attr) {
+        Set<String> ret = new HashSet<String>();
+        String value = attr.getValue("Depends-on");
+        if (value != null) {
+            StringTokenizer st = new StringTokenizer(value, ",");
+
+            while (st.hasMoreElements()) {
+                String entry = st.nextToken().trim();
+                ret.add(entry);
+            }
+        }
+
+        return ret;
+    }
+
+    /**
+     * Loads the Java critics defined by a profile
+     * 
+     * @param attr the Manifest section of the profile
+     * @param classloader the classloader of the Jar
+     * 
+     * @return the set of defined critics
+     */
+    private Set<Critic> loadJavaCriticsForProfile(Attributes attr,
+            ClassLoader classloader) {
+        Set<Critic> ret = new HashSet<Critic>();
+
+        String value = attr.getValue("Java-Critics");
+        if (value != null) {
+            StringTokenizer st = new StringTokenizer(value, ",");
+
+            while (st.hasMoreElements()) {
+                String entry = st.nextToken().trim();
+
+                try {
+                    Class cl = classloader.loadClass(entry);
+                    Critic critic = (Critic) cl.newInstance();
+                    ret.add(critic);
+                } catch (ClassNotFoundException e) {
+                    LOG.error("Error loading class: " + entry, e);
+                } catch (InstantiationException e) {
+                    LOG.error("Error instantianting class: " + entry, e);
+                } catch (IllegalAccessException e) {
+                    LOG.error("Exception", e);
+                }
+            }
+        }
+
+        return ret;
+    }
+    
+    /**
+     * The file filter that selects Jar files.
+     */
+    static class JarFileFilter implements FileFilter {
+        /*
+         * @see java.io.FileFilter#accept(java.io.File)
+         */
+        public boolean accept(File pathname) {
+            return (pathname.canRead()
+                    && pathname.isFile()
+                    && pathname.getPath().toLowerCase().endsWith(".jar"));
+        }
+    }
+    
+}
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.