Merge "Add documentation on releasing plugin API JAR"
diff --git a/Documentation/dev-contributing.txt b/Documentation/dev-contributing.txt
index 2609b05..2ede544 100644
--- a/Documentation/dev-contributing.txt
+++ b/Documentation/dev-contributing.txt
@@ -191,6 +191,7 @@
     on slow links.  If the action buttons are disabled, they cannot
     be resubmitted and the user can see that Gerrit is still busy.
   * GWT EventBus is the new way forward.
+  * ...and so is Guava (previously known as Google Collections).
 
 
 Tests
diff --git a/Documentation/install.txt b/Documentation/install.txt
index b90bbce..9cec83d 100644
--- a/Documentation/install.txt
+++ b/Documentation/install.txt
@@ -3,7 +3,7 @@
 
 [[requirements]]
 Requirements
------------
+------------
 To run the Gerrit service, the following requirements must be met on
 the host:
 
@@ -222,6 +222,13 @@
 * http://www.kernel.org/pub/software/scm/git/docs/git-daemon.html[man git-daemon]
 
 
+[[plugins]]
+Plugins
+-------
+
+Place Gerrit plugins in the review_site/plugins directory to have them loaded on Gerrit startup.
+
+
 External Documentation Links
 ----------------------------
 
diff --git a/gerrit-pgm/src/main/java/com/google/gerrit/pgm/Daemon.java b/gerrit-pgm/src/main/java/com/google/gerrit/pgm/Daemon.java
index 25b7699..8cef4d7 100644
--- a/gerrit-pgm/src/main/java/com/google/gerrit/pgm/Daemon.java
+++ b/gerrit-pgm/src/main/java/com/google/gerrit/pgm/Daemon.java
@@ -50,6 +50,7 @@
 import com.google.gerrit.server.ssh.NoSshModule;
 import com.google.gerrit.sshd.SshModule;
 import com.google.gerrit.sshd.commands.MasterCommandModule;
+import com.google.gerrit.sshd.commands.MasterPluginsModule;
 import com.google.gerrit.sshd.commands.SlaveCommandModule;
 import com.google.inject.Injector;
 import com.google.inject.Module;
@@ -242,6 +243,7 @@
         modules.add(new SlaveCommandModule());
       } else {
         modules.add(new MasterCommandModule());
+        modules.add(cfgInjector.getInstance(MasterPluginsModule.class));
       }
     } else {
       modules.add(new NoSshModule());
diff --git a/gerrit-server/src/main/java/com/google/gerrit/common/Plugin.java b/gerrit-server/src/main/java/com/google/gerrit/common/Plugin.java
new file mode 100644
index 0000000..73ccde4
--- /dev/null
+++ b/gerrit-server/src/main/java/com/google/gerrit/common/Plugin.java
@@ -0,0 +1,33 @@
+// Copyright (C) 2012 The Android Open Source Project
+//
+// Licensed 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 com.google.gerrit.common;
+
+import com.google.inject.Module;
+
+public class Plugin {
+  public final String name;
+
+  public final Class<? extends Module> moduleClass;
+
+  public Plugin(String name, Class<? extends Module> moduleClass) {
+    this.name = name;
+    this.moduleClass = moduleClass;
+  }
+
+  @Override
+  public String toString() {
+    return "Plugin [" + name + "]: ModuleClass=" + moduleClass.getName();
+  }
+}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/common/PluginLoader.java b/gerrit-server/src/main/java/com/google/gerrit/common/PluginLoader.java
new file mode 100644
index 0000000..7d3a36c
--- /dev/null
+++ b/gerrit-server/src/main/java/com/google/gerrit/common/PluginLoader.java
@@ -0,0 +1,144 @@
+// Copyright (C) 2012 The Android Open Source Project
+//
+// Licensed 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 com.google.gerrit.common;
+
+import com.google.gerrit.server.config.SitePaths;
+import com.google.inject.Inject;
+import com.google.inject.Module;
+import com.google.inject.Singleton;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.File;
+import java.io.FileFilter;
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.jar.JarFile;
+import java.util.jar.Manifest;
+
+@Singleton
+public class PluginLoader {
+  private static Logger log = LoggerFactory.getLogger(PluginLoader.class);
+
+  private File pluginsDir;
+
+  private Map<String, Plugin> pluginCache;
+
+  @Inject
+  public PluginLoader(SitePaths sitePaths) {
+    pluginsDir = sitePaths.plugins_dir;
+  }
+
+  private synchronized void initialize() {
+    if (pluginCache != null) {
+      return;
+    }
+
+    pluginCache = new HashMap<String, Plugin>();
+    loadPlugins();
+  }
+
+  public Plugin get(String pluginName) {
+    initialize();
+    return pluginCache.get(pluginName);
+  }
+
+  public Collection<Plugin> getPlugins() {
+    initialize();
+    return pluginCache.values();
+  }
+
+  private void loadPlugins() {
+    Collection<File> pluginJars;
+    try {
+      pluginJars = getPluginFiles();
+    } catch (IOException e) {
+      log.error("Cannot scan Gerrit plugins directory looking for jar files", e);
+      return;
+    }
+
+    for (File jarFile : pluginJars) {
+      Plugin plugin;
+      try {
+        plugin = loadPlugin(jarFile);
+        pluginCache.put(plugin.name, plugin);
+      } catch (IOException e) {
+        log.error("Cannot access plugin jar " + jarFile, e);
+      } catch (ClassNotFoundException e) {
+        log.error("Cannot load plugin class module from " + jarFile, e);
+      }
+    }
+  }
+
+  @SuppressWarnings("unchecked")
+  private Plugin loadPlugin(File jarFile) throws IOException,
+      ClassNotFoundException {
+    Manifest jarManifest = new JarFile(jarFile).getManifest();
+    ClassLoader parentLoader = PluginLoader.class.getClassLoader();
+    ClassLoader jarClassLoader =
+        new URLClassLoader(getPluginURLs(jarFile), parentLoader);
+
+    String pluginName = getMandatoryAttribute(jarManifest, "Gerrit-Plugin");
+    String moduleName = getMandatoryAttribute(jarManifest, "Gerrit-SshModule");
+
+    Class<?> moduleClass = Class.forName(moduleName, false, jarClassLoader);
+    if (!Module.class.isAssignableFrom(moduleClass)) {
+      throw new ClassNotFoundException("Class "
+          + moduleClass.getName() + " is not a Guice Module");
+    }
+
+    return new Plugin(pluginName, (Class<? extends Module>) moduleClass);
+  }
+
+  private String getMandatoryAttribute(Manifest manifest, String attrName) throws IOException {
+    String value = manifest.getMainAttributes().getValue(attrName);
+    if(value == null || value.trim().isEmpty())
+      throw new IOException("Missing mandatory attribute " + attrName + " in manifest");
+
+    return value;
+  }
+
+  private URL[] getPluginURLs(File jarFile) throws MalformedURLException {
+    return new URL[] {jarFile.toURI().toURL()};
+  }
+
+  private List<File> getPluginFiles() throws IOException {
+    if (pluginsDir == null || !pluginsDir.exists()) {
+      return Collections.emptyList();
+    }
+
+    File[] plugins = pluginsDir.listFiles(new FileFilter() {
+      @Override
+      public boolean accept(File pathname) {
+        return pathname.isFile() && pathname.getName().endsWith(".jar");
+      }
+    });
+    if (plugins == null) {
+      log.error("Cannot list " + pluginsDir.getAbsolutePath());
+      return Collections.emptyList();
+    }
+
+    return Arrays.asList(plugins);
+  }
+}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/SitePaths.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/SitePaths.java
index ab52a9d..9565831 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/SitePaths.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/SitePaths.java
@@ -29,6 +29,7 @@
   public final File etc_dir;
   public final File lib_dir;
   public final File logs_dir;
+  public final File plugins_dir;
   public final File mail_dir;
   public final File hooks_dir;
   public final File static_dir;
@@ -62,6 +63,7 @@
     bin_dir = new File(site_path, "bin");
     etc_dir = new File(site_path, "etc");
     lib_dir = new File(site_path, "lib");
+    plugins_dir = new File(site_path, "plugins");
     logs_dir = new File(site_path, "logs");
     mail_dir = new File(etc_dir, "mail");
     hooks_dir = new File(site_path, "hooks");
diff --git a/gerrit-sshd/src/main/java/com/google/gerrit/sshd/commands/MasterPluginsModule.java b/gerrit-sshd/src/main/java/com/google/gerrit/sshd/commands/MasterPluginsModule.java
new file mode 100644
index 0000000..d8049f8
--- /dev/null
+++ b/gerrit-sshd/src/main/java/com/google/gerrit/sshd/commands/MasterPluginsModule.java
@@ -0,0 +1,57 @@
+// Copyright (C) 2012 The Android Open Source Project
+//
+// Licensed 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 com.google.gerrit.sshd.commands;
+
+import com.google.gerrit.common.Plugin;
+import com.google.gerrit.common.PluginLoader;
+import com.google.gerrit.sshd.CommandModule;
+import com.google.inject.Inject;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Collection;
+
+public class MasterPluginsModule extends CommandModule {
+  private static final Logger log =
+      LoggerFactory.getLogger(MasterPluginsModule.class);
+
+  private PluginLoader pluginLoader;
+
+  @Inject
+  MasterPluginsModule(PluginLoader loader) {
+    pluginLoader = loader;
+  }
+
+  @Override
+  protected void configure() {
+    Collection<Plugin> plugins = pluginLoader.getPlugins();
+    for (Plugin p : plugins) {
+      if (PluginCommandModule.class.isAssignableFrom(p.moduleClass)) {
+        @SuppressWarnings("unchecked")
+        Class<PluginCommandModule> c = (Class<PluginCommandModule>) p.moduleClass;
+        try {
+          PluginCommandModule module = c.newInstance();
+          module.initSshModule(p.name);
+          install(module);
+        } catch (InstantiationException e) {
+          log.warn("Initialization of plugin module '" + p.name + "' failed");
+        } catch (IllegalAccessException e) {
+          log.warn("Initialization of plugin module '" + p.name + "' failed");
+        }
+      }
+    }
+  }
+}
diff --git a/gerrit-war/src/main/java/com/google/gerrit/httpd/WebAppInitializer.java b/gerrit-war/src/main/java/com/google/gerrit/httpd/WebAppInitializer.java
index 01b4a44..8ffc531 100644
--- a/gerrit-war/src/main/java/com/google/gerrit/httpd/WebAppInitializer.java
+++ b/gerrit-war/src/main/java/com/google/gerrit/httpd/WebAppInitializer.java
@@ -43,6 +43,7 @@
 import com.google.gerrit.server.schema.SchemaVersionCheck;
 import com.google.gerrit.sshd.SshModule;
 import com.google.gerrit.sshd.commands.MasterCommandModule;
+import com.google.gerrit.sshd.commands.MasterPluginsModule;
 import com.google.inject.AbstractModule;
 import com.google.inject.CreationException;
 import com.google.inject.Guice;
@@ -211,6 +212,7 @@
     final List<Module> modules = new ArrayList<Module>();
     modules.add(new SshModule());
     modules.add(new MasterCommandModule());
+    modules.add(cfgInjector.getInstance(MasterPluginsModule.class));
     return sysInjector.createChildInjector(modules);
   }