geronimo-scm mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From ga...@apache.org
Subject svn commit: r939890 - in /geronimo/server/trunk/framework/modules: geronimo-cli/src/main/java/org/apache/geronimo/cli/client/ geronimo-cli/src/main/java/org/apache/geronimo/cli/deployer/ geronimo-cli/src/main/java/org/apache/geronimo/cli/shutdown/ gero...
Date Sat, 01 May 2010 01:09:34 GMT
Author: gawor
Date: Sat May  1 01:09:33 2010
New Revision: 939890

URL: http://svn.apache.org/viewvc?rev=939890&view=rev
Log:
cleanup framework startup code

Added:
    geronimo/server/trunk/framework/modules/geronimo-main/src/main/java/org/apache/geronimo/main/FrameworkLauncher.java   (with props)
    geronimo/server/trunk/framework/modules/geronimo-main/src/main/java/org/apache/geronimo/main/StringMap.java   (with props)
Removed:
    geronimo/server/trunk/framework/modules/geronimo-main/src/main/java/org/apache/geronimo/main/StartLevelListener.java
Modified:
    geronimo/server/trunk/framework/modules/geronimo-cli/src/main/java/org/apache/geronimo/cli/client/ClientCLI.java
    geronimo/server/trunk/framework/modules/geronimo-cli/src/main/java/org/apache/geronimo/cli/deployer/DeployerCLI.java
    geronimo/server/trunk/framework/modules/geronimo-cli/src/main/java/org/apache/geronimo/cli/shutdown/ShutdownCLI.java
    geronimo/server/trunk/framework/modules/geronimo-main/src/main/java/org/apache/geronimo/main/Bootstrapper.java
    geronimo/server/trunk/framework/modules/geronimo-main/src/main/java/org/apache/geronimo/main/Utils.java

Modified: geronimo/server/trunk/framework/modules/geronimo-cli/src/main/java/org/apache/geronimo/cli/client/ClientCLI.java
URL: http://svn.apache.org/viewvc/geronimo/server/trunk/framework/modules/geronimo-cli/src/main/java/org/apache/geronimo/cli/client/ClientCLI.java?rev=939890&r1=939889&r2=939890&view=diff
==============================================================================
--- geronimo/server/trunk/framework/modules/geronimo-cli/src/main/java/org/apache/geronimo/cli/client/ClientCLI.java (original)
+++ geronimo/server/trunk/framework/modules/geronimo-cli/src/main/java/org/apache/geronimo/cli/client/ClientCLI.java Sat May  1 01:09:33 2010
@@ -46,7 +46,7 @@ public class ClientCLI extends AbstractC
     protected Bootstrapper createBootstrapper() {
         Bootstrapper boot = super.createBootstrapper();
         boot.setWaitForStop(false);
-        boot.setUniqueStorage(true);
+        boot.setUniqueInstance(true);
         boot.setStartBundles(Arrays.asList("org.apache.geronimo.framework/client-system//car"));
         boot.setLog4jConfigFile("var/log/client-log4j.properties");
         return boot;

Modified: geronimo/server/trunk/framework/modules/geronimo-cli/src/main/java/org/apache/geronimo/cli/deployer/DeployerCLI.java
URL: http://svn.apache.org/viewvc/geronimo/server/trunk/framework/modules/geronimo-cli/src/main/java/org/apache/geronimo/cli/deployer/DeployerCLI.java?rev=939890&r1=939889&r2=939890&view=diff
==============================================================================
--- geronimo/server/trunk/framework/modules/geronimo-cli/src/main/java/org/apache/geronimo/cli/deployer/DeployerCLI.java (original)
+++ geronimo/server/trunk/framework/modules/geronimo-cli/src/main/java/org/apache/geronimo/cli/deployer/DeployerCLI.java Sat May  1 01:09:33 2010
@@ -56,7 +56,7 @@ public class DeployerCLI extends Abstrac
     protected Bootstrapper createBootstrapper() {
         Bootstrapper boot = super.createBootstrapper();
         boot.setWaitForStop(false);
-        boot.setUniqueStorage(true);
+        boot.setUniqueInstance(true);
         boot.setStartBundles(Arrays.asList("org.apache.geronimo.framework/online-deployer//car"));
         boot.setLog4jConfigFile("var/log/deployer-log4j.properties");
         return boot;

Modified: geronimo/server/trunk/framework/modules/geronimo-cli/src/main/java/org/apache/geronimo/cli/shutdown/ShutdownCLI.java
URL: http://svn.apache.org/viewvc/geronimo/server/trunk/framework/modules/geronimo-cli/src/main/java/org/apache/geronimo/cli/shutdown/ShutdownCLI.java?rev=939890&r1=939889&r2=939890&view=diff
==============================================================================
--- geronimo/server/trunk/framework/modules/geronimo-cli/src/main/java/org/apache/geronimo/cli/shutdown/ShutdownCLI.java (original)
+++ geronimo/server/trunk/framework/modules/geronimo-cli/src/main/java/org/apache/geronimo/cli/shutdown/ShutdownCLI.java Sat May  1 01:09:33 2010
@@ -46,7 +46,7 @@ public class ShutdownCLI extends Abstrac
     protected Bootstrapper createBootstrapper() {
         Bootstrapper boot = super.createBootstrapper();
         boot.setWaitForStop(false);
-        boot.setUniqueStorage(true);
+        boot.setUniqueInstance(true);
         boot.setStartBundles(Arrays.asList(
                 "org.apache.geronimo.framework/shutdown//car"));
         boot.setLog4jConfigFile("var/log/server-log4j.properties");

Modified: geronimo/server/trunk/framework/modules/geronimo-main/src/main/java/org/apache/geronimo/main/Bootstrapper.java
URL: http://svn.apache.org/viewvc/geronimo/server/trunk/framework/modules/geronimo-main/src/main/java/org/apache/geronimo/main/Bootstrapper.java?rev=939890&r1=939889&r2=939890&view=diff
==============================================================================
--- geronimo/server/trunk/framework/modules/geronimo-main/src/main/java/org/apache/geronimo/main/Bootstrapper.java (original)
+++ geronimo/server/trunk/framework/modules/geronimo-main/src/main/java/org/apache/geronimo/main/Bootstrapper.java Sat May  1 01:09:33 2010
@@ -17,33 +17,19 @@
 package org.apache.geronimo.main;
 
 import java.io.File;
-import java.io.IOException;
 import java.util.List;
-import java.util.concurrent.Semaphore;
-import java.util.concurrent.TimeUnit;
+import java.util.Properties;
 
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.BundleException;
-import org.osgi.framework.Constants;
 import org.osgi.util.tracker.ServiceTracker;
 
 /**
  *
  * @version $Rev$ $Date$
  */
-public class Bootstrapper {
+public class Bootstrapper extends FrameworkLauncher {
     
-    private org.apache.felix.karaf.main.Main karafMain;
     private boolean waitForStop = true;    
     private List<String> bundles;
-    private int defaultStartLevel = 100;
-    private boolean uniqueStorage = false;   
-    private ServerInfo serverInfo;
-    private String log4jFile;
-    
-    private Semaphore startSemaphore;
-    private Throwable startException;
 
     public Bootstrapper() {
     }
@@ -55,58 +41,28 @@ public class Bootstrapper {
     public void setStartBundles(List<String> bundles) {
         this.bundles = bundles;
     }
-    
-    public void setUniqueStorage(boolean uniqueStorage) {
-        this.uniqueStorage = uniqueStorage;
-    }
-    
-    public void setLog4jConfigFile(String log4jFile) {
-        this.log4jFile = log4jFile;
-    }
-    
-    public int execute(Object opaque) {
-        int exitCode;
-        
-        exitCode = launch();
-        if (exitCode != 0) {
-            return exitCode;
-        }
         
-        karafMain.getFramework().getBundleContext().registerService(ServerInfo.class.getName(), serverInfo, null);
-        
-        if (bundles != null) {
-            startSemaphore = new Semaphore(0);
-            StartLevelListener listener = new StartLevelListener(this);
-            listener.start();    
-            
-            try {
-                if (!startSemaphore.tryAcquire(60, TimeUnit.SECONDS)) {
-                    return -1;
-                }
-            } catch (InterruptedException e) {
-                return -1;
-            }
-
-            if (startException != null) {
-                System.err.println("Error starting bundles: " + startException.getMessage());
-                startException.printStackTrace();
-                return -1;
-            }
+    public int execute(Object opaque) {
+        try {
+            launch();
+        } catch (Exception e) {
+            return -1;
         }
-                
-        Main geronimo_main = getMain();
-        
-        if (geronimo_main == null) {
+                              
+        Main geronimoMain = getMain();        
+        if (geronimoMain == null) {
             System.err.println("Main not found");
             stop(false);
             return -1;
         }
 
+        int exitCode = 0;
+        
         ClassLoader oldTCCL = Thread.currentThread().getContextClassLoader();
         try {
-            ClassLoader newTCCL = geronimo_main.getClass().getClassLoader();
+            ClassLoader newTCCL = geronimoMain.getClass().getClassLoader();
             Thread.currentThread().setContextClassLoader(newTCCL);
-            exitCode = geronimo_main.execute(opaque);
+            exitCode = geronimoMain.execute(opaque);
             stop(waitForStop);
         } catch (Throwable e) {
             e.printStackTrace();
@@ -114,11 +70,12 @@ public class Bootstrapper {
         } finally {
             Thread.currentThread().setContextClassLoader(oldTCCL);
         }
+        
         return exitCode;
     }
 
     public Main getMain() {
-        ServiceTracker tracker = new ServiceTracker(karafMain.getFramework().getBundleContext(), Main.class.getName(), null);
+        ServiceTracker tracker = new ServiceTracker(getFramework().getBundleContext(), Main.class.getName(), null);
         tracker.open();
         
         Main geronimoMain = null;
@@ -130,119 +87,64 @@ public class Bootstrapper {
         }
         return geronimoMain;
     }
-    
-    public int launch() {      
-        try {
-            File geronimoHome = Utils.getGeronimoHome();
-            File geronimoBase = Utils.getGeronimoBase(geronimoHome);
-            File temporaryDir = Utils.getTempDirectory(geronimoBase);
-            File log4jConfigFile = Utils.getLog4jConfigurationFile(geronimoBase, log4jFile);
-            
-            System.setProperty(Utils.HOME_DIR_SYS_PROP, 
-                               geronimoHome.getAbsolutePath());
-            
-            System.setProperty(Utils.SERVER_DIR_SYS_PROP,
-                                geronimoBase.getAbsolutePath());
-            
-            System.setProperty("java.io.tmpdir", 
-                               temporaryDir.getAbsolutePath());
-            
-            if (log4jConfigFile != null) {
-                System.setProperty("org.apache.geronimo.log4jservice.configuration",
-                                   log4jConfigFile.getAbsolutePath());
-            }
-            
-            serverInfo = new ServerInfo(geronimoHome, geronimoBase);
-                        
-            System.setProperty(Constants.FRAMEWORK_STORAGE, 
-                               getStorageDirectory());
-            
-            System.setProperty(Constants.FRAMEWORK_BEGINNING_STARTLEVEL, 
-                               String.valueOf(defaultStartLevel));       
-                      
-            if (System.getProperty(org.apache.felix.karaf.main.Main.PROPERTY_USE_LOCK) == null) {
-                System.setProperty(org.apache.felix.karaf.main.Main.PROPERTY_USE_LOCK, 
-                                   (uniqueStorage) ? "false" : "true");
-            }
-            
-        } catch (IOException e) {
-            e.printStackTrace();
-            return -1;
-        }
-        
-        karafMain = new org.apache.felix.karaf.main.Main(null);
         
-        try {           
-            karafMain.launch();
-        } catch (Exception e) {
-            e.printStackTrace();           
-        }
-        
-        return karafMain.getExitCode();
-    }
-    
     public void stop(boolean await) {
         try {
-            karafMain.destroy(await);
+            destroy(await);
         } catch (Exception e) {
             e.printStackTrace();           
         }
     }
                 
-    protected BundleContext getBundleContext() {
-        return karafMain.getFramework().getBundleContext();
-    }
-            
-    public void startLevelChanged(int startLevel) {
-        if (startLevel == defaultStartLevel) {
-            try {
-                startBundles();
-                startException = null;
-            } catch (Throwable e) {
-                startException = e;
-            } finally {
-                startSemaphore.release();
-            }
-        }        
-    }
-    
-    public void startBundles() throws BundleException, IOException {
-        BundleContext context = getBundleContext();
+    @Override
+    protected List<BundleInfo> loadStartupProperties(Properties startupProps, List<File> bundleDirs) {
+        List<BundleInfo> startList = super.loadStartupProperties(startupProps, bundleDirs);
+        
         for (String location : bundles) {
             String[] parts = location.split("/");
             
-            File fileLocation = getBundleLocation(parts);
-            if (fileLocation == null) {
+            File file = getBundleLocation(bundleDirs, parts);
+            if (file == null) {
                 System.err.println("Artifact " + location + " not found");
                 continue;
             }
             
-            parts[2] = fileLocation.getParentFile().getName();
-            parts[3] = fileLocation.getName().substring(fileLocation.getName().lastIndexOf('.') + 1);
+            parts[2] = file.getParentFile().getName();
+            parts[3] = file.getName().substring(file.getName().lastIndexOf('.') + 1);
             
             String mvnLocation = getMvnLocation(parts);
-            Bundle b = context.installBundle(mvnLocation, fileLocation.toURI().toURL().openStream());
-            if (b != null) {
-                b.start(Bundle.START_TRANSIENT);
-            }
+            
+            BundleInfo info = new BundleInfo();
+            info.location = file;
+            info.mvnLocation = mvnLocation;
+            
+            startList.add(info);            
         }
+        
+        return startList;
     }
     
     private String getMvnLocation(String[] parts) {
         return "mvn:" + parts[0] + "/" + parts[1] + "/" + parts[2] + "/" + parts[3]; 
     }
     
-    private File getBundleLocation(String[] parts) {
+    private static File getBundleLocation(List<File> bundleDirs, String[] parts) {
+        for (File bundleDir : bundleDirs) {
+            File file = getBundleLocation(bundleDir, parts);
+            if (file != null) {
+                return file;
+            }
+        }
+        return null;
+    }
+    
+    private static File getBundleLocation(File bundleDir, String[] parts) {
         String group = parts[0].replace('.', '/').trim();
         String artifactId = parts[1].trim();
         String version = parts[2].trim();
         String type = parts[3].trim();
-                        
-        String defaultRepo = System.getProperty(org.apache.felix.karaf.main.Main.DEFAULT_REPO);
-        
-        File repo = new File(getHome(), defaultRepo);
-        
-        File base = new File(repo, group + "/" + artifactId);
+                                        
+        File base = new File(bundleDir, group + "/" + artifactId);
         if (base.exists()) {
             File versionFile = findFile(base, version);
             if (versionFile != null) {
@@ -256,7 +158,7 @@ public class Bootstrapper {
         return null;
     }
     
-    private File findFile(File base, String name) {
+    private static File findFile(File base, String name) {
         File[] files = base.listFiles();
         if (name.length() == 0) {
             return (files.length > 0) ? files[0] : null;
@@ -268,60 +170,5 @@ public class Bootstrapper {
         }
         return null;
     }
-    
-    private String getStorageDirectory() throws IOException {
-        final File storage;
-        if (uniqueStorage) {
-            File var = new File(getServer(), "var");
-            File tmpFile = File.createTempFile("appclient-", "", var);
-            storage = new File(var, tmpFile.getName() + "-cache");
-            tmpFile.delete();
-            // register shutdown hook to remove the instance's cache directory
-            Runtime.getRuntime().addShutdownHook(new Thread() {
-                public void run() {
-                    recursiveDelete(storage);
-                }
-            });
-        } else {
-            storage = new File(getServer(), "var/cache");
-        }
-                
-        storage.mkdirs();
-        return storage.getAbsolutePath();
-    }
-    
-    private String getHome() {
-        return serverInfo.getBase().getAbsolutePath();
-    }
-    
-    private String getServer() {
-        return serverInfo.getBaseServer().getAbsolutePath();
-    }
-    
-    private static boolean recursiveDelete(File root) {
-        if (root == null) {
-            return true;
-        }
-
-        boolean ok = true;
-        
-        if (root.isDirectory()) {
-            File[] files = root.listFiles();
-            if (files != null) {
-                for (int i = 0; i < files.length; i++) {
-                    File file = files[i];
-                    if (file.isDirectory()) {
-                        ok = ok && recursiveDelete(file);
-                    } else {
-                        ok = ok && file.delete();
-                    }
-                }
-            }
-        }
-        
-        ok = ok && root.delete();
-        
-        return ok;
-    }
-   
+       
 }

Added: geronimo/server/trunk/framework/modules/geronimo-main/src/main/java/org/apache/geronimo/main/FrameworkLauncher.java
URL: http://svn.apache.org/viewvc/geronimo/server/trunk/framework/modules/geronimo-main/src/main/java/org/apache/geronimo/main/FrameworkLauncher.java?rev=939890&view=auto
==============================================================================
--- geronimo/server/trunk/framework/modules/geronimo-main/src/main/java/org/apache/geronimo/main/FrameworkLauncher.java (added)
+++ geronimo/server/trunk/framework/modules/geronimo-main/src/main/java/org/apache/geronimo/main/FrameworkLauncher.java Sat May  1 01:09:33 2010
@@ -0,0 +1,444 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.geronimo.main;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.lang.reflect.Method;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.security.Provider;
+import java.security.Security;
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Properties;
+import java.util.ServiceLoader;
+import java.util.logging.Logger;
+
+import org.osgi.framework.Bundle;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.Constants;
+import org.osgi.framework.FrameworkEvent;
+import org.osgi.framework.launch.Framework;
+import org.osgi.framework.launch.FrameworkFactory;
+import org.osgi.service.startlevel.StartLevel;
+
+public class FrameworkLauncher {
+    
+    /**
+     * The default name used for the system properties file.
+     */
+    public static final String SYSTEM_PROPERTIES_FILE_NAME = "system.properties";
+    
+    /**
+     * The default name used for the configuration properties file.
+     */
+    public static final String CONFIG_PROPERTIES_FILE_NAME = "config.properties";
+    
+    /**
+     * The default name used for the startup properties file.
+     */
+    public static final String STARTUP_PROPERTIES_FILE_NAME = "startup.properties";
+    
+    /**
+     * The system property for specifying the Karaf home directory.  The home directory
+     * hold the binary install of Karaf.
+     */
+    private static final String PROP_KARAF_HOME = "karaf.home";
+
+    /**
+     * The system property for specifying the Karaf base directory.  The base directory
+     * holds the configuration and data for a Karaf instance.
+     */
+    private static final String PROP_KARAF_BASE = "karaf.base";
+        
+    private static final String DEFAULT_REPO = "karaf.default.repository";
+    
+    private static final String KARAF_FRAMEWORK = "karaf.framework";
+       
+    private static final Logger LOG = Logger.getLogger(FrameworkLauncher.class.getName());
+
+    private boolean uniqueInstance = false;
+    private String log4jFile;
+    private String startupFile = STARTUP_PROPERTIES_FILE_NAME;
+    
+    private ServerInfo serverInfo;    
+    private File geronimoHome;
+    private File geronimoBase;
+    
+    private Properties configProps = null;
+    private Framework framework = null;
+    private int defaultStartLevel = 100;
+    
+    public void setLog4jConfigFile(String log4jFile) {
+        this.log4jFile = log4jFile;
+    }
+    
+    public void setStartupFile(String startupFile) {
+        this.startupFile = startupFile;
+    }
+    
+    public void setUniqueInstance(boolean uniqueInstance) {
+        this.uniqueInstance = uniqueInstance;
+    }
+    
+    public void launch() throws Exception {
+        geronimoHome = Utils.getGeronimoHome();
+        geronimoBase = Utils.getGeronimoBase(geronimoHome);
+        
+        Utils.setTempDirectory(geronimoBase);        
+        Utils.setLog4jConfigurationFile(geronimoBase, log4jFile);
+        
+        System.setProperty(Utils.HOME_DIR_SYS_PROP, geronimoHome.getAbsolutePath());        
+        System.setProperty(Utils.SERVER_DIR_SYS_PROP, geronimoBase.getAbsolutePath());
+                
+        System.setProperty(PROP_KARAF_HOME, geronimoHome.getPath());
+        System.setProperty(PROP_KARAF_BASE, geronimoBase.getPath());
+
+        // Load system properties.
+        loadSystemProperties(geronimoBase);
+
+        // Read configuration properties.
+        configProps = loadConfigProperties(geronimoBase);
+        
+        // Copy framework properties from the system properties.
+        copySystemProperties(configProps);
+
+        updateClassLoader(configProps);
+
+        processSecurityProperties(configProps);
+
+        setFrameworkStorage(configProps);
+                
+        defaultStartLevel = Integer.parseInt(configProps.getProperty(Constants.FRAMEWORK_BEGINNING_STARTLEVEL));
+
+        configProps.setProperty(Constants.FRAMEWORK_BEGINNING_STARTLEVEL, "1");
+        // Start up the OSGI framework
+
+        ServiceLoader<FrameworkFactory> loader = ServiceLoader.load(FrameworkFactory.class);
+        FrameworkFactory factory = loader.iterator().next();
+        framework = factory.newFramework(new StringMap(configProps, false));
+        framework.start();
+                
+        serverInfo = new ServerInfo(geronimoHome, geronimoBase);        
+        framework.getBundleContext().registerService(ServerInfo.class.getName(), serverInfo, null);
+        
+        List<BundleInfo> startList = loadStartupProperties();
+        startBundles(startList);        
+    }
+
+    public void destroy(boolean await) throws Exception {
+        if (framework == null) {
+            return;
+        }
+        if (await) {
+            while (true) {
+                FrameworkEvent event = framework.waitForStop(0);
+                if (event.getType() != FrameworkEvent.STOPPED_UPDATE) {
+                    break;
+                }
+            }
+        }
+
+        if (framework.getState() == Bundle.ACTIVE) {
+            framework.stop();
+        }
+    }
+
+    public Framework getFramework() {
+        return framework;
+    }
+    
+    private void setFrameworkStorage(Properties configProps) throws IOException {
+        if (configProps.getProperty(Constants.FRAMEWORK_STORAGE) != null) {
+            return;
+        }
+        
+        final File storage;
+        if (uniqueInstance) {
+            File var = new File(geronimoBase, "var");
+            File tmpFile = File.createTempFile("instance-", "", var);
+            storage = new File(var, tmpFile.getName() + "-cache");
+            tmpFile.delete();
+            // register shutdown hook to remove the instance's cache directory
+            Runtime.getRuntime().addShutdownHook(new Thread() {
+                public void run() {
+                    Utils.recursiveDelete(storage);
+                }
+            });
+        } else {
+            storage = new File(geronimoBase, "var/cache");
+        }
+                
+        storage.mkdirs();
+        configProps.setProperty(Constants.FRAMEWORK_STORAGE, storage.getAbsolutePath());
+    }
+    
+    private static void processSecurityProperties(Properties m_configProps) {
+        String prop = m_configProps.getProperty("org.apache.felix.karaf.security.providers");
+        if (prop != null) {
+            String[] providers = prop.split(",");
+            for (String provider : providers) {
+                try {
+                    Security.addProvider((Provider) Class.forName(provider).newInstance());
+                } catch (Throwable t) {
+                    System.err.println("Unable to register security provider: " + t);
+                }
+            }
+        }
+    }
+
+    /**
+     * <p>
+     * Loads the properties in the system property file associated with the
+     * framework installation into <tt>System.setProperty()</tt>. These properties
+     * are not directly used by the framework in anyway. By default, the system
+     * property file is located in the <tt>conf/</tt> directory of the Felix
+     * installation directory and is called "<tt>system.properties</tt>". The
+     * installation directory of Felix is assumed to be the parent directory of
+     * the <tt>felix.jar</tt> file as found on the system class path property.
+     * The precise file from which to load system properties can be set by
+     * initializing the "<tt>felix.system.properties</tt>" system property to an
+     * arbitrary URL.
+     * </p>
+     */
+    protected static void loadSystemProperties(File baseDir) throws IOException {
+        File file = new File(new File(baseDir, "etc"), SYSTEM_PROPERTIES_FILE_NAME);
+        Properties props = Utils.loadPropertiesFile(file, false);
+        
+        // Perform variable substitution on specified properties.
+        for (Enumeration e = props.propertyNames(); e.hasMoreElements();) {
+            String name = (String) e.nextElement();
+            String value = System.getProperty(name, props.getProperty(name));
+            System.setProperty(name, Utils.substVars(value, name, null, null));
+        }
+    }
+
+    private static Properties loadConfigProperties(File baseDir) throws Exception {        
+        File configFile = new File(new File(baseDir, "etc"), CONFIG_PROPERTIES_FILE_NAME);
+        Properties configProps = Utils.loadPropertiesFile(configFile, false);
+                
+        // Perform variable substitution for system properties.
+        for (Enumeration e = configProps.propertyNames(); e.hasMoreElements();) {
+            String name = (String) e.nextElement();
+            configProps.setProperty(name,
+                                    Utils.substVars(configProps.getProperty(name), name, null, configProps));
+        }
+
+        return configProps;
+    }
+
+    protected static void copySystemProperties(Properties configProps) {
+        for (Enumeration e = System.getProperties().propertyNames(); e.hasMoreElements();) {
+            String key = (String) e.nextElement();
+            if (key.startsWith("felix.") ||
+                    key.startsWith("karaf.") ||
+                    key.startsWith("org.osgi.framework.")) {
+                configProps.setProperty(key, System.getProperty(key));
+            }
+        }
+    }
+    
+    private void updateClassLoader(Properties configProps) throws Exception {
+    	String framework = configProps.getProperty(KARAF_FRAMEWORK);
+        if (framework == null) {
+            throw new IllegalArgumentException("Property " + KARAF_FRAMEWORK + " must be set in the etc/" + CONFIG_PROPERTIES_FILE_NAME + " configuration file");
+        }
+        String bundle = configProps.getProperty(KARAF_FRAMEWORK + "." + framework);
+        if (bundle == null) {
+            throw new IllegalArgumentException("Property " + KARAF_FRAMEWORK + "." + framework + " must be set in the etc/" + CONFIG_PROPERTIES_FILE_NAME + " configuration file");
+        }
+        File bundleFile = new File(geronimoBase, bundle);
+        if (!bundleFile.exists()) {
+            bundleFile = new File(geronimoHome, bundle);
+        }
+        if (!bundleFile.exists()) {
+            throw new FileNotFoundException(bundleFile.getAbsolutePath());
+        }
+
+        URLClassLoader classLoader = (URLClassLoader) FrameworkLauncher.class.getClassLoader();
+        Method mth = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
+        mth.setAccessible(true);
+        mth.invoke(classLoader, bundleFile.toURL());
+    }
+
+    private void startBundles(List<BundleInfo> startList) throws Exception {
+        BundleContext context = framework.getBundleContext();
+        
+        // Retrieve the Start Level service, since it will be needed
+        // to set the start level of the installed bundles.
+        StartLevel sl = (StartLevel) context.getService(context.getServiceReference(StartLevel.class.getName()));
+        
+        // Set the default bundle start level
+        int ibsl = Integer.parseInt(configProps.getProperty("karaf.startlevel.bundle", "60"));
+        sl.setInitialBundleStartLevel(ibsl);
+        
+        for (BundleInfo info : startList) {
+            InputStream in = new FileInputStream(info.location);
+            Bundle bundle = null;
+            try {
+                bundle = context.installBundle(info.mvnLocation, in);
+            } finally {
+                try { in.close(); } catch (Exception e) {}
+            }
+            if (info.startLevel > 0) {
+                sl.setBundleStartLevel(bundle, info.startLevel);
+            }
+            
+            info.bundle = bundle;
+        }
+        
+        for (BundleInfo info : startList) {
+            info.bundle.start();
+        }
+        
+        sl.setStartLevel(defaultStartLevel);
+    }
+    
+    private List<BundleInfo> loadStartupProperties() throws Exception {        
+        File etc = new File(geronimoBase, "etc");
+                
+        File file = new File(etc, startupFile);
+        Properties startupProps = Utils.loadPropertiesFile(file, true);
+        
+        ArrayList<File> bundleDirs = new ArrayList<File>();
+        
+        String defaultRepo = System.getProperty(DEFAULT_REPO, "repository");
+
+        if (geronimoBase.equals(geronimoHome)) {
+            bundleDirs.add(new File(geronimoHome, defaultRepo));
+        } else {
+            bundleDirs.add(new File(geronimoBase, defaultRepo));
+            bundleDirs.add(new File(geronimoHome, defaultRepo));
+        }
+        
+        return loadStartupProperties(startupProps, bundleDirs);
+    }
+    
+    protected List<BundleInfo> loadStartupProperties(Properties startupProps, List<File> bundleDirs) {
+        List<BundleInfo> startList = new ArrayList<BundleInfo>();
+
+        for (Iterator iterator = startupProps.keySet().iterator(); iterator.hasNext();) {
+            String location = (String) iterator.next();
+            
+            File file = findFile(bundleDirs, location);
+            
+            if (file == null) {
+                System.err.println("Artifact " + location + " not found");
+                continue;
+            }
+            
+            int level;
+            try {
+                level = Integer.parseInt(startupProps.getProperty(location).trim());
+            } catch (NumberFormatException e1) {
+                System.err.print("Ignoring " + location + " (run level must be an integer)");
+                continue;
+            }
+                        
+            String mvnLocation = toMvnUrl(location);
+            
+            BundleInfo info = new BundleInfo();
+            info.location = file;
+            info.mvnLocation = mvnLocation;
+            info.startLevel = level;
+            
+            startList.add(info);
+        }
+        
+        return startList;
+    }
+          
+    private static File findFile(List<File> bundleDirs, String name) {
+        for (File bundleDir : bundleDirs) {
+            File file = findFile(bundleDir, name);
+            if (file != null) {
+                return file;
+            }
+        }
+        return null;
+    }
+
+    private static File findFile(File dir, String name) {
+        File theFile = new File(dir, name);
+
+        if (theFile.exists() && !theFile.isDirectory()) {
+            return theFile;
+        }
+
+        for (File file : dir.listFiles()) {
+            if (file.isDirectory()) {
+                return findFile(file, name);
+            }
+        }
+
+        return null;
+    }
+    
+    private static String toMvnUrl(String location) {
+        String[] p = location.split("/");
+        if (p.length >= 4 && p[p.length-1].startsWith(p[p.length-3] + "-" + p[p.length-2])) {
+            String groupId = null;
+            String artifactId = p[p.length-3];
+            String version = p[p.length-2];
+            String classifier;
+            String type;
+            String artifactIdVersion = artifactId + "-" + version;
+            StringBuffer sb = new StringBuffer();
+            if (p[p.length-1].charAt(artifactIdVersion.length()) == '-') {
+                classifier = p[p.length-1].substring(artifactIdVersion.length() + 1, p[p.length-1].lastIndexOf('.'));
+            } else {
+                classifier = null;
+            }
+            type = p[p.length-1].substring(p[p.length-1].lastIndexOf('.') + 1);
+            sb.append("mvn:");
+            for (int j = 0; j < p.length - 3; j++) {
+                if (j > 0) {
+                    sb.append('.');
+                }
+                sb.append(p[j]);
+            }
+            sb.append('/').append(artifactId).append('/').append(version);
+            if (!"jar".equals(type) || classifier != null) {
+                sb.append('/');
+                if (!"jar".equals(type)) {
+                    sb.append(type);
+                }
+                if (classifier != null) {
+                    sb.append('/').append(classifier);
+                }
+            }
+            return sb.toString();
+        } else {
+            return location;
+        }
+    }
+    
+    static class BundleInfo {        
+        File location;
+        String mvnLocation;
+        int startLevel;
+        Bundle bundle;
+    }
+}

Propchange: geronimo/server/trunk/framework/modules/geronimo-main/src/main/java/org/apache/geronimo/main/FrameworkLauncher.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: geronimo/server/trunk/framework/modules/geronimo-main/src/main/java/org/apache/geronimo/main/FrameworkLauncher.java
------------------------------------------------------------------------------
    svn:keywords = Date Revision

Propchange: geronimo/server/trunk/framework/modules/geronimo-main/src/main/java/org/apache/geronimo/main/FrameworkLauncher.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: geronimo/server/trunk/framework/modules/geronimo-main/src/main/java/org/apache/geronimo/main/StringMap.java
URL: http://svn.apache.org/viewvc/geronimo/server/trunk/framework/modules/geronimo-main/src/main/java/org/apache/geronimo/main/StringMap.java?rev=939890&view=auto
==============================================================================
--- geronimo/server/trunk/framework/modules/geronimo-main/src/main/java/org/apache/geronimo/main/StringMap.java (added)
+++ geronimo/server/trunk/framework/modules/geronimo-main/src/main/java/org/apache/geronimo/main/StringMap.java Sat May  1 01:09:33 2010
@@ -0,0 +1,97 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.geronimo.main;
+
+import java.util.Comparator;
+import java.util.Map;
+import java.util.TreeMap;
+
+/**
+ * Simple utility class that creates a map for string-based keys by
+ * extending <tt>TreeMap</tt>. This map can be set to use case-sensitive
+ * or case-insensitive comparison when searching for the key.
+ * Any keys put into this map will be converted to
+ * a <tt>String</tt> using the <tt>toString()</tt> method,
+ * since it is only intended to compare strings.
+**/
+public class StringMap extends TreeMap
+{
+    public StringMap()
+    {
+        this(true);
+    }
+
+    public StringMap(boolean caseSensitive)
+    {
+        super(new StringComparator(caseSensitive));
+    }
+
+    public StringMap(Map map, boolean caseSensitive)
+    {
+        this(caseSensitive);
+        putAll(map);
+    }
+
+    public Object put(Object key, Object value)
+    {
+        return super.put(key.toString(), value);
+    }
+
+    public boolean isCaseSensitive()
+    {
+        return ((StringComparator) comparator()).isCaseSensitive();
+    }
+
+    public void setCaseSensitive(boolean b)
+    {
+        ((StringComparator) comparator()).setCaseSensitive(b);
+    }
+
+    private static class StringComparator implements Comparator
+    {
+        private boolean m_isCaseSensitive = true;
+
+        public StringComparator(boolean b)
+        {
+            m_isCaseSensitive = b;
+        }
+
+        public int compare(Object o1, Object o2)
+        {
+            if (m_isCaseSensitive)
+            {
+                return o1.toString().compareTo(o2.toString());
+            }
+            else
+            {
+                return o1.toString().compareToIgnoreCase(o2.toString());
+            }
+        }
+
+        public boolean isCaseSensitive()
+        {
+            return m_isCaseSensitive;
+        }
+
+        public void setCaseSensitive(boolean b)
+        {
+            m_isCaseSensitive = b;
+        }
+    }
+}

Propchange: geronimo/server/trunk/framework/modules/geronimo-main/src/main/java/org/apache/geronimo/main/StringMap.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: geronimo/server/trunk/framework/modules/geronimo-main/src/main/java/org/apache/geronimo/main/StringMap.java
------------------------------------------------------------------------------
    svn:keywords = Date Revision

Propchange: geronimo/server/trunk/framework/modules/geronimo-main/src/main/java/org/apache/geronimo/main/StringMap.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Modified: geronimo/server/trunk/framework/modules/geronimo-main/src/main/java/org/apache/geronimo/main/Utils.java
URL: http://svn.apache.org/viewvc/geronimo/server/trunk/framework/modules/geronimo-main/src/main/java/org/apache/geronimo/main/Utils.java?rev=939890&r1=939889&r2=939890&view=diff
==============================================================================
--- geronimo/server/trunk/framework/modules/geronimo-main/src/main/java/org/apache/geronimo/main/Utils.java (original)
+++ geronimo/server/trunk/framework/modules/geronimo-main/src/main/java/org/apache/geronimo/main/Utils.java Sat May  1 01:09:33 2010
@@ -19,16 +19,23 @@
 package org.apache.geronimo.main;
 
 import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
 import java.io.IOException;
-import java.net.URL;
+import java.io.InputStream;
 import java.net.JarURLConnection;
 import java.net.URI;
+import java.net.URL;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
 
 public class Utils {
 
     public static final String SERVER_NAME_SYS_PROP = "org.apache.geronimo.server.name";
     public static final String SERVER_DIR_SYS_PROP = "org.apache.geronimo.server.dir";
     public static final String HOME_DIR_SYS_PROP = "org.apache.geronimo.home.dir";
+    public static final String LOG4J_CONFIG_PROP = "org.apache.geronimo.log4jservice.configuration";
     
     public static File getGeronimoHome() throws IOException {
         File rc = null;
@@ -87,7 +94,7 @@ public class Utils {
         return baseServerDir;
     }
     
-    public static File getTempDirectory(File base) {
+    public static void setTempDirectory(File base) {
         String tmpDirPath = System.getProperty("java.io.tmpdir", "temp");
         File tmpDir = new File(tmpDirPath);
         if (!tmpDir.isAbsolute()) {
@@ -96,21 +103,18 @@ public class Utils {
         
         validateDirectoryExists(tmpDir, "The temporary directory could not be determined");
         
-        return tmpDir;
+        System.setProperty("java.io.tmpdir", tmpDir.getAbsolutePath());
     }
     
-    public static File getLog4jConfigurationFile(File base, String defaultFile) {
-        File log4jFile = null;
-        
-        String log4jFilePath = System.getProperty("org.apache.geronimo.log4jservice.configuration", defaultFile);       
+    public static void setLog4jConfigurationFile(File base, String defaultFile) {
+        String log4jFilePath = System.getProperty(LOG4J_CONFIG_PROP, defaultFile);       
         if (log4jFilePath != null) {                   
-            log4jFile = new File(log4jFilePath);
+            File log4jFile = new File(log4jFilePath);
             if (!log4jFile.isAbsolute()) {
                 log4jFile = new File(base, log4jFilePath);
             }
-        }
-        
-        return log4jFile;
+            System.setProperty(LOG4J_CONFIG_PROP, log4jFile.getAbsolutePath());
+        }        
     }
     
     public static File validateDirectoryExists(String path, String errPrefix) {
@@ -132,5 +136,169 @@ public class Utils {
         }
         return rc;
     }
-  
+      
+    public static Properties loadPropertiesFile(File file, boolean critical) throws IOException {
+        // Read the properties file.
+        Properties configProps = new Properties();
+        InputStream is = null;
+        try {
+            is = new FileInputStream(file);
+            configProps.load(is);
+        } catch (FileNotFoundException ex) {
+            if (critical) {
+                throw ex;
+            }
+        } catch (IOException ex) {
+            System.err.println("Error loading properties from " + file);
+            return null;
+        } finally {
+            if (is != null) {
+                try { is.close(); } catch (Exception e) {}
+            }
+        }
+        return configProps;
+    }
+    
+    private static final String DELIM_START = "${";
+    private static final String DELIM_STOP = "}";
+
+    /**
+     * <p>
+     * This method performs property variable substitution on the
+     * specified value. If the specified value contains the syntax
+     * <tt>${&lt;prop-name&gt;}</tt>, where <tt>&lt;prop-name&gt;</tt>
+     * refers to either a configuration property or a system property,
+     * then the corresponding property value is substituted for the variable
+     * placeholder. Multiple variable placeholders may exist in the
+     * specified value as well as nested variable placeholders, which
+     * are substituted from inner most to outer most. Configuration
+     * properties override system properties.
+     * </p>
+     *
+     * @param val         The string on which to perform property substitution.
+     * @param currentKey  The key of the property being evaluated used to
+     *                    detect cycles.
+     * @param cycleMap    Map of variable references used to detect nested cycles.
+     * @param configProps Set of configuration properties.
+     * @return The value of the specified string after system property substitution.
+     * @throws IllegalArgumentException If there was a syntax error in the
+     *                                  property placeholder syntax or a recursive variable reference.
+     */
+    public static String substVars(String val, String currentKey,
+                                   Map<String, String> cycleMap, 
+                                   Properties configProps)
+            throws IllegalArgumentException {
+        // If there is currently no cycle map, then create
+        // one for detecting cycles for this invocation.
+        if (cycleMap == null) {
+            cycleMap = new HashMap<String, String>();
+        }
+
+        // Put the current key in the cycle map.
+        cycleMap.put(currentKey, currentKey);
+
+        // Assume we have a value that is something like:
+        // "leading ${foo.${bar}} middle ${baz} trailing"
+
+        // Find the first ending '}' variable delimiter, which
+        // will correspond to the first deepest nested variable
+        // placeholder.
+        int stopDelim = val.indexOf(DELIM_STOP);
+
+        // Find the matching starting "${" variable delimiter
+        // by looping until we find a start delimiter that is
+        // greater than the stop delimiter we have found.
+        int startDelim = val.indexOf(DELIM_START);
+        while (stopDelim >= 0) {
+            int idx = val.indexOf(DELIM_START, startDelim + DELIM_START.length());
+            if ((idx < 0) || (idx > stopDelim)) {
+                break;
+            } else if (idx < stopDelim) {
+                startDelim = idx;
+            }
+        }
+
+        // If we do not have a start or stop delimiter, then just
+        // return the existing value.
+        if ((startDelim < 0) && (stopDelim < 0)) {
+            return val;
+        }
+        // At this point, we found a stop delimiter without a start,
+        // so throw an exception.
+        else if (((startDelim < 0) || (startDelim > stopDelim))
+                && (stopDelim >= 0)) {
+            throw new IllegalArgumentException(
+                    "stop delimiter with no start delimiter: "
+                            + val);
+        }
+
+        // At this point, we have found a variable placeholder so
+        // we must perform a variable substitution on it.
+        // Using the start and stop delimiter indices, extract
+        // the first, deepest nested variable placeholder.
+        String variable =
+                val.substring(startDelim + DELIM_START.length(), stopDelim);
+
+        // Verify that this is not a recursive variable reference.
+        if (cycleMap.get(variable) != null) {
+            throw new IllegalArgumentException(
+                    "recursive variable reference: " + variable);
+        }
+
+        // Get the value of the deepest nested variable placeholder.
+        // Try to configuration properties first.
+        String substValue = (configProps != null)
+                ? configProps.getProperty(variable, null)
+                : null;
+        if (substValue == null) {
+            // Ignore unknown property values.
+            substValue = System.getProperty(variable, "");
+        }
+
+        // Remove the found variable from the cycle map, since
+        // it may appear more than once in the value and we don't
+        // want such situations to appear as a recursive reference.
+        cycleMap.remove(variable);
+
+        // Append the leading characters, the substituted value of
+        // the variable, and the trailing characters to get the new
+        // value.
+        val = val.substring(0, startDelim)
+                + substValue
+                + val.substring(stopDelim + DELIM_STOP.length(), val.length());
+
+        // Now perform substitution again, since there could still
+        // be substitutions to make.
+        val = substVars(val, currentKey, cycleMap, configProps);
+
+        // Return the value.
+        return val;
+    }
+    
+    public static boolean recursiveDelete(File root) {
+        if (root == null) {
+            return true;
+        }
+
+        boolean ok = true;
+        
+        if (root.isDirectory()) {
+            File[] files = root.listFiles();
+            if (files != null) {
+                for (int i = 0; i < files.length; i++) {
+                    File file = files[i];
+                    if (file.isDirectory()) {
+                        ok = ok && recursiveDelete(file);
+                    } else {
+                        ok = ok && file.delete();
+                    }
+                }
+            }
+        }
+        
+        ok = ok && root.delete();
+        
+        return ok;
+    }
+        
 }



Mime
View raw message