Initial version of Scala scripting provider

Allows script files with .scala extension
under $GERRIT_SITE/plugins to be loaded as ServerPlugins.

Manifest is automatically generated on-the-fly based
on the Guice Module classes defined in the Scala script.
When no Guice Modules are defined, classes are automatically
registered as in standard Jar plugins.

At the moment all Scala scripts are defined as PLUGIN
type: it is not yet possible to define a Gerrit EXTENSION type.

All Scala script plugins are defined as hot-reloadable.

Change-Id: Id7ad0b51bf07b57b093ddf3148165bdfc51fd685
diff --git a/BUCK b/BUCK
new file mode 100644
index 0000000..9b7e306
--- /dev/null
+++ b/BUCK
@@ -0,0 +1,47 @@
+include_defs('//lib/maven.defs')
+
+define_license(name = 'scala')
+
+gerrit_plugin(
+  name = 'scala-provider',
+  srcs = glob(['src/main/java/**/*.java']),
+  resources = glob(['src/main/**/*']),
+  manifest_entries = [
+    'Implementation-Title: Scala Provider',
+    'Implementation-URL: https://gerrit.googlesource.com/plugins/scripting/scala-provider',
+    'Gerrit-PluginName: scala-provider',
+    'Gerrit-Module: com.googlesource.gerrit.plugins.scripting.scala.Module'
+  ],
+  deps = [
+    ':scala-compiler',
+    ':scala-reflect',
+    ':scala-library',
+  ],
+)
+
+maven_jar(
+  name = 'scala-compiler',
+  id = 'org.scala-lang:scala-compiler:2.11.0',
+  sha1 = '75d94f0ddcabb626832a992607acb6e2d6bc2a4a',
+  license = 'Apache2.0',
+  deps = [
+    ':scala-reflect',
+  ],
+)
+
+maven_jar(
+  name = 'scala-reflect',
+  id = 'org.scala-lang:scala-reflect:2.11.0',
+  sha1 = '90be1e4ead42b3e9ac53044bfe1b032cd9d78229',
+  license = 'Apache2.0',
+  deps = [
+    ':scala-library',
+  ],
+)
+
+maven_jar(
+  name = 'scala-library',
+  id = 'org.scala-lang:scala-library:2.11.0',
+  sha1 = 'aa8f7553253318c468f90ce58a85f94bd1a224eb',
+  license = 'Apache2.0',
+)
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..11069ed
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,201 @@
+                              Apache License
+                        Version 2.0, January 2004
+                     http://www.apache.org/licenses/
+
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+   "License" shall mean the terms and conditions for use, reproduction,
+   and distribution as defined by Sections 1 through 9 of this document.
+
+   "Licensor" shall mean the copyright owner or entity authorized by
+   the copyright owner that is granting the License.
+
+   "Legal Entity" shall mean the union of the acting entity and all
+   other entities that control, are controlled by, or are under common
+   control with that entity. For the purposes of this definition,
+   "control" means (i) the power, direct or indirect, to cause the
+   direction or management of such entity, whether by contract or
+   otherwise, or (ii) ownership of fifty percent (50%) or more of the
+   outstanding shares, or (iii) beneficial ownership of such entity.
+
+   "You" (or "Your") shall mean an individual or Legal Entity
+   exercising permissions granted by this License.
+
+   "Source" form shall mean the preferred form for making modifications,
+   including but not limited to software source code, documentation
+   source, and configuration files.
+
+   "Object" form shall mean any form resulting from mechanical
+   transformation or translation of a Source form, including but
+   not limited to compiled object code, generated documentation,
+   and conversions to other media types.
+
+   "Work" shall mean the work of authorship, whether in Source or
+   Object form, made available under the License, as indicated by a
+   copyright notice that is included in or attached to the work
+   (an example is provided in the Appendix below).
+
+   "Derivative Works" shall mean any work, whether in Source or Object
+   form, that is based on (or derived from) the Work and for which the
+   editorial revisions, annotations, elaborations, or other modifications
+   represent, as a whole, an original work of authorship. For the purposes
+   of this License, Derivative Works shall not include works that remain
+   separable from, or merely link (or bind by name) to the interfaces of,
+   the Work and Derivative Works thereof.
+
+   "Contribution" shall mean any work of authorship, including
+   the original version of the Work and any modifications or additions
+   to that Work or Derivative Works thereof, that is intentionally
+   submitted to Licensor for inclusion in the Work by the copyright owner
+   or by an individual or Legal Entity authorized to submit on behalf of
+   the copyright owner. For the purposes of this definition, "submitted"
+   means any form of electronic, verbal, or written communication sent
+   to the Licensor or its representatives, including but not limited to
+   communication on electronic mailing lists, source code control systems,
+   and issue tracking systems that are managed by, or on behalf of, the
+   Licensor for the purpose of discussing and improving the Work, but
+   excluding communication that is conspicuously marked or otherwise
+   designated in writing by the copyright owner as "Not a Contribution."
+
+   "Contributor" shall mean Licensor and any individual or Legal Entity
+   on behalf of whom a Contribution has been received by Licensor and
+   subsequently incorporated within the Work.
+
+2. Grant of Copyright License. Subject to the terms and conditions of
+   this License, each Contributor hereby grants to You a perpetual,
+   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+   copyright license to reproduce, prepare Derivative Works of,
+   publicly display, publicly perform, sublicense, and distribute the
+   Work and such Derivative Works in Source or Object form.
+
+3. Grant of Patent License. Subject to the terms and conditions of
+   this License, each Contributor hereby grants to You a perpetual,
+   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+   (except as stated in this section) patent license to make, have made,
+   use, offer to sell, sell, import, and otherwise transfer the Work,
+   where such license applies only to those patent claims licensable
+   by such Contributor that are necessarily infringed by their
+   Contribution(s) alone or by combination of their Contribution(s)
+   with the Work to which such Contribution(s) was submitted. If You
+   institute patent litigation against any entity (including a
+   cross-claim or counterclaim in a lawsuit) alleging that the Work
+   or a Contribution incorporated within the Work constitutes direct
+   or contributory patent infringement, then any patent licenses
+   granted to You under this License for that Work shall terminate
+   as of the date such litigation is filed.
+
+4. Redistribution. You may reproduce and distribute copies of the
+   Work or Derivative Works thereof in any medium, with or without
+   modifications, and in Source or Object form, provided that You
+   meet the following conditions:
+
+   (a) You must give any other recipients of the Work or
+       Derivative Works a copy of this License; and
+
+   (b) You must cause any modified files to carry prominent notices
+       stating that You changed the files; and
+
+   (c) You must retain, in the Source form of any Derivative Works
+       that You distribute, all copyright, patent, trademark, and
+       attribution notices from the Source form of the Work,
+       excluding those notices that do not pertain to any part of
+       the Derivative Works; and
+
+   (d) If the Work includes a "NOTICE" text file as part of its
+       distribution, then any Derivative Works that You distribute must
+       include a readable copy of the attribution notices contained
+       within such NOTICE file, excluding those notices that do not
+       pertain to any part of the Derivative Works, in at least one
+       of the following places: within a NOTICE text file distributed
+       as part of the Derivative Works; within the Source form or
+       documentation, if provided along with the Derivative Works; or,
+       within a display generated by the Derivative Works, if and
+       wherever such third-party notices normally appear. The contents
+       of the NOTICE file are for informational purposes only and
+       do not modify the License. You may add Your own attribution
+       notices within Derivative Works that You distribute, alongside
+       or as an addendum to the NOTICE text from the Work, provided
+       that such additional attribution notices cannot be construed
+       as modifying the License.
+
+   You may add Your own copyright statement to Your modifications and
+   may provide additional or different license terms and conditions
+   for use, reproduction, or distribution of Your modifications, or
+   for any such Derivative Works as a whole, provided Your use,
+   reproduction, and distribution of the Work otherwise complies with
+   the conditions stated in this License.
+
+5. Submission of Contributions. Unless You explicitly state otherwise,
+   any Contribution intentionally submitted for inclusion in the Work
+   by You to the Licensor shall be under the terms and conditions of
+   this License, without any additional terms or conditions.
+   Notwithstanding the above, nothing herein shall supersede or modify
+   the terms of any separate license agreement you may have executed
+   with Licensor regarding such Contributions.
+
+6. Trademarks. This License does not grant permission to use the trade
+   names, trademarks, service marks, or product names of the Licensor,
+   except as required for reasonable and customary use in describing the
+   origin of the Work and reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty. Unless required by applicable law or
+   agreed to in writing, Licensor provides the Work (and each
+   Contributor provides its Contributions) on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+   implied, including, without limitation, any warranties or conditions
+   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+   PARTICULAR PURPOSE. You are solely responsible for determining the
+   appropriateness of using or redistributing the Work and assume any
+   risks associated with Your exercise of permissions under this License.
+
+8. Limitation of Liability. In no event and under no legal theory,
+   whether in tort (including negligence), contract, or otherwise,
+   unless required by applicable law (such as deliberate and grossly
+   negligent acts) or agreed to in writing, shall any Contributor be
+   liable to You for damages, including any direct, indirect, special,
+   incidental, or consequential damages of any character arising as a
+   result of this License or out of the use or inability to use the
+   Work (including but not limited to damages for loss of goodwill,
+   work stoppage, computer failure or malfunction, or any and all
+   other commercial damages or losses), even if such Contributor
+   has been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability. While redistributing
+   the Work or Derivative Works thereof, You may choose to offer,
+   and charge a fee for, acceptance of support, warranty, indemnity,
+   or other liability obligations and/or rights consistent with this
+   License. However, in accepting such obligations, You may act only
+   on Your own behalf and on Your sole responsibility, not on behalf
+   of any other Contributor, and only if You agree to indemnify,
+   defend, and hold each Contributor harmless for any liability
+   incurred by, or claims asserted against, such Contributor by reason
+   of your accepting any such warranty or additional liability.
+
+END OF TERMS AND CONDITIONS
+
+APPENDIX: How to apply the Apache License to your work.
+
+   To apply the Apache License to your work, attach the following
+   boilerplate notice, with the fields enclosed by brackets "[]"
+   replaced with your own identifying information. (Don't include
+   the brackets!)  The text should be enclosed in the appropriate
+   comment syntax for the file format. We also recommend that a
+   file or class name and description of purpose be included on the
+   same "printed page" as the copyright notice for easier
+   identification within third-party archives.
+
+Copyright [yyyy] [name of copyright owner]
+
+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.
diff --git a/LICENSE-scala b/LICENSE-scala
new file mode 100644
index 0000000..02ea9ad
--- /dev/null
+++ b/LICENSE-scala
@@ -0,0 +1,11 @@
+Copyright (c) 2002-2014 EPFL
+Copyright (c) 2011-2014 Typesafe, Inc.
+
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+
+Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
+Neither the name of the EPFL nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..f4ede5a
--- /dev/null
+++ b/README.md
@@ -0,0 +1,36 @@
+Gerrit Scala Provider Plugin
+=============================
+
+This plugin provides Scala runtime environment for Gerrit plugins in Scala.
+
+To test this series must be applied on top of Gerrit master [1].
+
+To build link this directory under Gerrit's tree plugins directory and run:
+
+```
+  buck build plugins/scala-provider:scala-provider
+```
+
+The resulting artifact can be found under:
+
+```
+ buck-out/gen/plugins/scala-provider/scala-provider.jar
+```
+
+A sample Scala hello world script is:
+```
+  import com.google.gerrit.sshd._
+  import com.google.gerrit.extensions.annotations._
+
+  @Export("scala")
+  class ScalaCommand extends SshCommand {
+    override def run = stdout println "Hello from Scala!"
+  }
+```
+
+Copy and past the above sample Scala fragment into the file $GERRIT_SITE/plugin/hello-1.0.scala.
+
+The "hello" plugin version 1.0 will be automatically loaded into Gerrit and will provide a new
+SSH command "hello scala".
+
+* [1] https://gerrit-review.googlesource.com/#/q/status:open+project:gerrit+branch:master+topic:scripting-reloaded
diff --git a/src/main/java/com/googlesource/gerrit/plugins/scripting/scala/Module.java b/src/main/java/com/googlesource/gerrit/plugins/scripting/scala/Module.java
new file mode 100644
index 0000000..4675c4e
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/scripting/scala/Module.java
@@ -0,0 +1,30 @@
+// Copyright (C) 2014 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.googlesource.gerrit.plugins.scripting.scala;
+
+import com.google.gerrit.extensions.registration.DynamicSet;
+import com.google.gerrit.server.plugins.ServerPluginProvider;
+import com.google.inject.AbstractModule;
+
+public class Module extends AbstractModule {
+
+  @Override
+  protected void configure() {
+    DynamicSet.bind(binder(), ServerPluginProvider.class).to(
+        ScalaPluginProvider.class);
+    bind(ScalaSettings.class);
+    bind(ScalaReporter.class);
+    bind(ScalaPluginScriptEngine.class);
+  }
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/scripting/scala/ScalaPluginProvider.java b/src/main/java/com/googlesource/gerrit/plugins/scripting/scala/ScalaPluginProvider.java
new file mode 100644
index 0000000..1c46c7b
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/scripting/scala/ScalaPluginProvider.java
@@ -0,0 +1,85 @@
+// 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.googlesource.gerrit.plugins.scripting.scala;
+
+import com.google.gerrit.server.PluginUser;
+import com.google.gerrit.server.plugins.InvalidPluginException;
+import com.google.gerrit.server.plugins.ServerPlugin;
+import com.google.gerrit.server.plugins.ServerPluginProvider;
+import com.google.inject.Inject;
+import com.google.inject.Provider;
+import com.google.inject.Singleton;
+
+import org.eclipse.jgit.internal.storage.file.FileSnapshot;
+
+import java.io.File;
+
+/**
+ * Scala scripting plugins.
+ *
+ * Allows to define a Groovy class to implement any type of Gerrit plugin.
+ *
+ * Example of Scala SSH Plugin (hello-1.0.scala):
+ * ------------------------------------------------ TBD
+ *
+ * The above example add a "hello scala" command to Gerrit SSH interface that
+ * displays "Hello Gerrit from Scala !"
+ *
+ * import com.google.gerrit.sshd._
+ * import com.google.gerrit.extensions.annotations._
+ *
+ * @Export("scala")
+ * class MyClass extends SshCommand {
+ *   override def run = stdout println "Hello Gerrit from Scala!"
+ * }
+ *
+ */
+@Singleton
+class ScalaPluginProvider implements ServerPluginProvider {
+  private static final String SCALA_EXTENSION = ".scala";
+
+  private final Provider<ScalaPluginScriptEngine> scriptEngineProvider;
+
+  @Inject
+  public ScalaPluginProvider(Provider<ScalaPluginScriptEngine> scriptEngineProvider) {
+    this.scriptEngineProvider = scriptEngineProvider;
+  }
+
+  @Override
+  public ServerPlugin get(String name, File srcFile, PluginUser pluginUser,
+      FileSnapshot snapshot, String pluginCanonicalWebUrl, File pluginDataDir)
+      throws InvalidPluginException {
+    ScalaPluginScriptEngine scriptEngine = scriptEngineProvider.get();
+    return new ServerPlugin(name, pluginCanonicalWebUrl, pluginUser, srcFile,
+        snapshot, new ScalaPluginScanner(name, srcFile, scriptEngine),
+        pluginDataDir, scriptEngine.getClassLoader());
+  }
+
+  @Override
+  public boolean handles(File srcFile) {
+    return srcFile.getName().toLowerCase().endsWith(SCALA_EXTENSION);
+  }
+
+  @Override
+  public String getPluginName(File srcFile) {
+    String srcFileName = srcFile.getName();
+    int endPos = srcFileName.lastIndexOf('-');
+    if (endPos == -1) {
+      endPos = srcFileName.lastIndexOf('.');
+    }
+    return srcFileName.substring(0, endPos);
+  }
+}
+
diff --git a/src/main/java/com/googlesource/gerrit/plugins/scripting/scala/ScalaPluginScanner.java b/src/main/java/com/googlesource/gerrit/plugins/scripting/scala/ScalaPluginScanner.java
new file mode 100644
index 0000000..4c7cf71
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/scripting/scala/ScalaPluginScanner.java
@@ -0,0 +1,143 @@
+// Copyright (C) 2014 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.googlesource.gerrit.plugins.scripting.scala;
+
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Sets;
+import com.google.gerrit.extensions.annotations.Export;
+import com.google.gerrit.server.plugins.InvalidPluginException;
+import com.google.gerrit.server.plugins.PluginScanner;
+import com.google.gerrit.sshd.CommandModule;
+import com.google.inject.Module;
+import com.google.inject.servlet.ServletModule;
+
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Modifier;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.Map;
+import java.util.Set;
+import java.util.jar.Manifest;
+
+public class ScalaPluginScanner implements PluginScanner {
+  private final String pluginName;
+  private final String pluginVersion;
+  private final Set<Class<?>> scriptClasses;
+  private Class<? extends Module> sshModule;
+  private Class<? extends Module> httpModule;
+  private Class<? extends Module> sysModule;
+
+  public ScalaPluginScanner(String pluginName, File srcFile,
+      ScalaPluginScriptEngine scriptEngine)
+      throws InvalidPluginException {
+    this.pluginName = pluginName;
+    this.pluginVersion = getPluginVersion(srcFile);
+    this.scriptClasses = loadScriptClasses(srcFile, scriptEngine);
+    loadGuiceModules(this.scriptClasses);
+  }
+
+  private String getPluginVersion(File srcFile) {
+    String srcFileName = srcFile.getName();
+    int startPos = srcFileName.lastIndexOf('-');
+    if(startPos == -1) {
+      return "0";
+    }
+    int endPos = srcFileName.lastIndexOf('.');
+    return srcFileName.substring(startPos+1, endPos);
+  }
+
+  private Set<Class<?>> loadScriptClasses(File srcFile,
+      ScalaPluginScriptEngine scriptEngine) throws InvalidPluginException {
+    try {
+      return scriptEngine.eval(srcFile);
+    } catch (ClassNotFoundException | IOException e) {
+      throw new InvalidPluginException(
+          "Cannot evaluate script file " + srcFile, e);
+    }
+  }
+
+  @SuppressWarnings("unchecked")
+  private void loadGuiceModules(Set<Class<?>> scriptClasses) {
+    for (Class<?> scriptClass : scriptClasses) {
+      if (CommandModule.class.isAssignableFrom(scriptClass)) {
+        sshModule = ((Class<? extends Module>) scriptClass);
+      } else if (ServletModule.class.isAssignableFrom(scriptClass)) {
+        httpModule = ((Class<? extends Module>) scriptClass);
+      } else if (Module.class.isAssignableFrom(scriptClass)) {
+        sysModule = ((Class<? extends Module>) scriptClass);
+      }
+    }
+  }
+
+  @Override
+  public Manifest getManifest() throws IOException {
+    String manifestString =
+            "PluginName: " + pluginName + "\n" +
+            "Implementation-Version: " + pluginVersion + "\n" +
+            "Gerrit-ReloadMode: restart\n" +
+            (sysModule == null ? "":("Gerrit-Module: " + sysModule.getName() + "\n")) +
+            (httpModule == null ? "":("Gerrit-HttpModule: " + httpModule.getName() + " \n")) +
+            (sshModule == null ? "":("Gerrit-SshModule: " + sshModule.getName() + "\n")) +
+            "Gerrit-ApiType: PLUGIN\n";
+    return new Manifest(new ByteArrayInputStream(manifestString.getBytes()));
+  }
+
+  @Override
+  public Map<Class<? extends Annotation>, Iterable<ExtensionMetaData>> scan(
+      String pluginName, Iterable<Class<? extends Annotation>> annotations)
+      throws InvalidPluginException {
+    ImmutableMap.Builder<Class<? extends Annotation>, Iterable<ExtensionMetaData>> result =
+        ImmutableMap.builder();
+
+    for (Class<? extends Annotation> annotation : annotations) {
+      Set<ExtensionMetaData> classMetaDataSet = Sets.newHashSet();
+      result.put(annotation, classMetaDataSet);
+
+      for (Class<?> scriptClass : scriptClasses) {
+        if (!Modifier.isAbstract(scriptClass.getModifiers())
+            && scriptClass.getAnnotation(annotation) != null) {
+          classMetaDataSet.add(new ExtensionMetaData(scriptClass.getName(),
+              getExportAnnotationValue(scriptClass, annotation)));
+        }
+      }
+    }
+    return result.build();
+  }
+
+  private String getExportAnnotationValue(Class<?> scriptClass,
+      Class<? extends Annotation> annotation) {
+    return annotation == Export.class ? scriptClass.getAnnotation(Export.class)
+        .value() : "";
+  }
+
+  @Override
+  public <T> T getResource(String resourcePath, Class<? extends T> resourceClass) {
+    return null;
+  }
+
+  @Override
+  public InputStream getResourceInputStream(String resourcePath)
+      throws IOException {
+    return null;
+  }
+
+  @Override
+  public <T> Enumeration<T> resources(Class<? extends T> resourceClass) {
+    return Collections.emptyEnumeration();
+  }
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/scripting/scala/ScalaPluginScriptEngine.java b/src/main/java/com/googlesource/gerrit/plugins/scripting/scala/ScalaPluginScriptEngine.java
new file mode 100644
index 0000000..1a5ce8b
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/scripting/scala/ScalaPluginScriptEngine.java
@@ -0,0 +1,153 @@
+// Copyright (C) 2013 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.googlesource.gerrit.plugins.scripting.scala;
+
+import static scala.collection.JavaConversions.asScalaBuffer;
+
+import com.google.common.collect.Sets;
+import com.google.inject.Inject;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import scala.Char;
+import scala.Option;
+import scala.collection.Iterator;
+import scala.collection.immutable.Seq;
+import scala.collection.mutable.Map;
+import scala.reflect.internal.util.BatchSourceFile;
+import scala.reflect.internal.util.SourceFile;
+import scala.reflect.io.AbstractFile;
+import scala.tools.nsc.Global;
+import scala.tools.nsc.Global.Run;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Set;
+
+public class ScalaPluginScriptEngine {
+  private static final Logger LOG = LoggerFactory
+      .getLogger(ScalaPluginScriptEngine.class);
+
+  // private final IMain scalaEngine;
+  private final ScalaClassLoader classLoader;
+  private Global globalEngine;
+  private ScalaReporter reporter;
+
+  public class ScalaClassLoader extends ClassLoader {
+    private Map<String, AbstractFile> scalaClasses;
+
+    public ScalaClassLoader(ScalaSettings settings) {
+      super(ScalaClassLoader.class.getClassLoader());
+      scalaClasses =
+          settings.getVirtualDirectory()
+              .scala$reflect$io$VirtualDirectory$$files();
+    }
+
+    @Override
+    protected Class<?> findClass(String name) throws ClassNotFoundException {
+      Option<AbstractFile> classFile = scalaClasses.get(name + ".class");
+      if (classFile.isEmpty()) {
+        throw new ClassNotFoundException("Cannot find Scala class " + name);
+      }
+
+      byte[] ba;
+      try {
+        ba = classFile.get().toByteArray();
+        return defineClass(name, ba, 0, ba.length);
+      } catch (IOException e) {
+        throw new ClassNotFoundException("Cannot open Scala class file "
+            + classFile.get(), e);
+      }
+    }
+
+    public Set<String> getAllLoadedClassNames() {
+      Set<String> classNames = Sets.newHashSet();
+      for (Iterator<String> keysIter = scalaClasses.keys().iterator(); keysIter
+          .hasNext();) {
+        String classFileName = keysIter.next();
+        classNames.add(classFileName.substring(0, classFileName.length()
+            - ".class".length()));
+      }
+      return classNames;
+    }
+  }
+
+  @Inject
+  public ScalaPluginScriptEngine(ScalaSettings settings,
+      ScalaReporter reporter) {
+    this.classLoader = new ScalaClassLoader(settings);
+    globalEngine =
+        new Global(settings.getSettings(), reporter.getConsoleReporter());
+    this.reporter = reporter;
+  }
+
+  public Set<Class<?>> eval(File scalaFile) throws IOException,
+      ClassNotFoundException {
+    Set<Class<?>> classes = Sets.newHashSet();
+
+    SourceFile sourceFile =
+        new BatchSourceFile(scalaFile.getName(), readScalaFile(scalaFile));
+    Run run = globalEngine.new Run();
+    reporter.reset();
+    run.compileSources(asScalaBuffer(Arrays.asList(sourceFile)).toList());
+    if (reporter.hasErrors()) {
+      LOG.error("Error compiling scala file " + scalaFile);
+      LOG.error(reporter.getOutput());
+      throw new IOException("Invalid Scala file " + scalaFile);
+    } else {
+      String output = reporter.getOutput();
+      if(output.length() > 0) {
+        LOG.info("Scala file " + scalaFile + " loaded successfully");
+        LOG.info(output);
+      }
+    }
+
+    for (String className : classLoader.getAllLoadedClassNames()) {
+      Class<?> clazz = classLoader.loadClass(className);
+      classes.add(clazz);
+    }
+    return classes;
+  }
+
+  private Seq<Object> readScalaFile(File scalaFile) throws IOException {
+    BufferedReader reader = new BufferedReader(new FileReader(scalaFile));
+    StringBuilder scalaCode = new StringBuilder();
+    try {
+      String line;
+      while (null != (line = reader.readLine())) {
+        scalaCode.append(line);
+        scalaCode.append("\n");
+      }
+    } finally {
+      reader.close();
+    }
+
+    List<Object> chars = new ArrayList<Object>();
+    for (char c : scalaCode.toString().toCharArray()) {
+      chars.add(Char.unbox(c));
+    }
+
+    return asScalaBuffer(chars).toList();
+  }
+
+  public ScalaClassLoader getClassLoader() {
+    return classLoader;
+  }
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/scripting/scala/ScalaReporter.java b/src/main/java/com/googlesource/gerrit/plugins/scripting/scala/ScalaReporter.java
new file mode 100644
index 0000000..f5514e6
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/scripting/scala/ScalaReporter.java
@@ -0,0 +1,56 @@
+// Copyright (C) 2014 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.googlesource.gerrit.plugins.scripting.scala;
+
+import com.google.inject.Inject;
+
+import scala.tools.nsc.reporters.ConsoleReporter;
+import scala.tools.nsc.reporters.Reporter;
+
+import java.io.BufferedReader;
+import java.io.ByteArrayOutputStream;
+import java.io.InputStreamReader;
+import java.io.PrintWriter;
+
+public class ScalaReporter {
+
+  private final ConsoleReporter consoleReporter;
+  private final ByteArrayOutputStream buffer;
+  private int bufferPos;
+
+  @Inject
+  public ScalaReporter(ScalaSettings settings) {
+    buffer = new ByteArrayOutputStream();
+    consoleReporter =
+        new ConsoleReporter(settings.getSettings(), new BufferedReader(
+            new InputStreamReader(System.in)), new PrintWriter(buffer, true));
+  }
+
+  public String getOutput() {
+    return new String(buffer.toByteArray()).substring(bufferPos);
+  }
+
+  public void reset() {
+    consoleReporter.reset();
+    bufferPos = new String(buffer.toByteArray()).length();
+  }
+
+  public boolean hasErrors() {
+    return consoleReporter.hasErrors();
+  }
+
+  public Reporter getConsoleReporter() {
+    return consoleReporter;
+  }
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/scripting/scala/ScalaSettings.java b/src/main/java/com/googlesource/gerrit/plugins/scripting/scala/ScalaSettings.java
new file mode 100644
index 0000000..322cff1
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/scripting/scala/ScalaSettings.java
@@ -0,0 +1,74 @@
+// Copyright (C) 2014 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.googlesource.gerrit.plugins.scripting.scala;
+
+import com.google.gerrit.server.plugins.PluginLoader;
+import com.google.inject.Inject;
+
+import scala.Option;
+import scala.reflect.io.VirtualDirectory;
+import scala.tools.nsc.Settings;
+
+import java.net.URL;
+import java.net.URLClassLoader;
+
+public class ScalaSettings {
+  private static final String CLASSPATH_DEBUG = "false";
+  private static final String VERBOSE_COMPILE_OUTPUT = "false";
+
+  private VirtualDirectory virtualDirectory;
+  private final Settings settings;
+
+  @Inject
+  public ScalaSettings() {
+    settings = new Settings();
+    settings.usejavacp().tryToSetFromPropertyValue("true");
+    settings.exposeEmptyPackage().tryToSetFromPropertyValue("true");
+    settings.Ylogcp().tryToSetFromPropertyValue(CLASSPATH_DEBUG);
+    settings.verbose().tryToSetFromPropertyValue(VERBOSE_COMPILE_OUTPUT);
+
+    settings.outputDirs().setSingleOutput(initVirtualDirectory());
+    settings.classpath().tryToSetFromPropertyValue(
+        classPathOf(PluginLoader.class) + ":" + classPathOf(this.getClass()));
+  }
+
+  private VirtualDirectory initVirtualDirectory() {
+    virtualDirectory =
+        new VirtualDirectory("(memory)", Option.apply((VirtualDirectory) null));
+    return virtualDirectory;
+  }
+
+  private String classPathOf(Class<?> clazz) {
+    StringBuilder currentClassPath = new StringBuilder();
+    for (URL url : ((URLClassLoader) (clazz.getClassLoader())).getURLs()) {
+      if (url.getProtocol().equals("file")) {
+        if (currentClassPath.length() > 0) {
+          currentClassPath.append(":");
+        }
+        currentClassPath.append(url.getPath());
+      }
+    }
+    String currentClassPathString = currentClassPath.toString();
+    return currentClassPathString;
+  }
+
+  public Settings getSettings() {
+    return settings;
+  }
+
+  public VirtualDirectory getVirtualDirectory() {
+    return virtualDirectory;
+  }
+
+}
diff --git a/src/main/resources/Documentation/about.md b/src/main/resources/Documentation/about.md
new file mode 100644
index 0000000..d8f25a5
--- /dev/null
+++ b/src/main/resources/Documentation/about.md
@@ -0,0 +1,14 @@
+Gerrit Scala Provider Plugin.
+
+This plugin provides Scala runtime environment for Gerrit plugins in Scala.
+Scala language level and library is Ver. 2.11.0 and does not require any
+external installation as everything is provided by this plugin as embedded
+engine.
+
+To test this series must be applied on top of Gerrit master [1].
+
+To test deploy the review plugin [2] and copy this Scala Provider plugin
+under `$gerrit_site/plugins` directory.
+
+* [1] https://gerrit-review.googlesource.com/#/q/status:open+project:gerrit+branch:master+topic:scripting-reloaded
+* [2] https://github.com/davido/gerrit-scala-plugin
diff --git a/src/main/resources/Documentation/build.md b/src/main/resources/Documentation/build.md
new file mode 100644
index 0000000..c4fe2d1
--- /dev/null
+++ b/src/main/resources/Documentation/build.md
@@ -0,0 +1,23 @@
+Build
+=====
+
+This plugin is built with Buck.
+
+Clone or link this plugin to the plugins directory of Gerrit's source
+tree, and issue the command:
+
+```
+  buck build plugins/scala-provider
+```
+
+The output is created in
+
+```
+  buck-out/gen/plugins/scala-provider/scala-provider.jar
+```
+
+This project can be imported into the Eclipse IDE:
+
+```
+  ./tools/eclipse/project.py
+```