Implement Bazel build

There is a known limitation with this change: because of the way the
manifest file is generated in Bazlet:

  deploy_manifest_lines = manifest_entries + [
      "Gerrit-ApiType: plugin",
      "Implementation-Vendor: Gerrit Code Review",
  ],

the specified 'Implementation-Vendor: Ericsson' entry is overwritten in
the jar manifest file.

Also by: David Ostrovsky <david.ostrovsky@gmail.com>

Change-Id: I185c3f914ecf1a1aaee27da8d63a37a4fb602d24
diff --git a/.gitignore b/.gitignore
index c27e17f..9556f7c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -4,6 +4,13 @@
 /.project
 /.settings/
 /.watchmanconfig
+/.primary_build_tool
 /buck-out/
 /bucklets
 /eclipse-out/
+/bazel-bin
+/bazel-genfiles
+/bazel-out
+/bazel-reviewers
+/bazel-testlogs
+/bazel-sync-index
diff --git a/BUILD b/BUILD
new file mode 100644
index 0000000..32842a8
--- /dev/null
+++ b/BUILD
@@ -0,0 +1,31 @@
+load("//tools/bzl:junit.bzl", "junit_tests")
+load(
+    "//tools/bzl:plugin.bzl",
+    "gerrit_plugin",
+    "PLUGIN_DEPS",
+    "PLUGIN_TEST_DEPS",
+)
+
+gerrit_plugin(
+    name = "sync-index",
+    srcs = glob(["src/main/java/**/*.java"]),
+    resources = glob(["src/main/resources/**/*"]),
+    manifest_entries = [
+        'Gerrit-PluginName: sync-index',
+        'Gerrit-Module: com.ericsson.gerrit.plugins.syncindex.Module',
+        'Gerrit-HttpModule: com.ericsson.gerrit.plugins.syncindex.HttpModule',
+        'Implementation-Title: sync-index plugin',
+        'Implementation-URL: https://gerrit-review.googlesource.com/#/admin/projects/plugins/sync-index',
+        'Implementation-Vendor: Ericsson',
+    ],
+)
+
+junit_tests(
+    name = "sync_index_tests",
+    srcs = glob(["src/test/java/**/*.java"]),
+    tags = ["sync-index", "local"],
+    deps = PLUGIN_DEPS + PLUGIN_TEST_DEPS + [
+        "@wiremock//jar",
+        ":sync-index__plugin",
+    ],
+)
diff --git a/WORKSPACE b/WORKSPACE
new file mode 100644
index 0000000..0121fc2
--- /dev/null
+++ b/WORKSPACE
@@ -0,0 +1,33 @@
+workspace(name = "sync_index")
+load("//:bazlets.bzl", "load_bazlets")
+
+load_bazlets(
+    commit = "8a4cbdc993f41fcfe7290e7d1007cfedf8d87c18",
+    #local_path = "/home/davido/projects/bazlets",
+)
+
+#Snapshot Plugin API
+load(
+    "@com_googlesource_gerrit_bazlets//:gerrit_api_maven_local.bzl",
+    "gerrit_api_maven_local",
+)
+
+# Load snapshot Plugin API
+gerrit_api_maven_local()
+
+# Release Plugin API
+#load(
+#   "@com_googlesource_gerrit_bazlets//:gerrit_api.bzl",
+#   "gerrit_api",
+#)
+
+# Load release Plugin API
+#gerrit_api()
+
+load("@com_googlesource_gerrit_bazlets//tools:maven_jar.bzl", "maven_jar")
+
+maven_jar(
+    name = "wiremock",
+    artifact = "com.github.tomakehurst:wiremock-standalone:2.4.1",
+    sha1 = "228d3047147fffa0f12771f5dc2b3cd3b38c454b",
+)
diff --git a/WORKSPACE.in_gerrit_tree b/WORKSPACE.in_gerrit_tree
new file mode 100644
index 0000000..511225c
--- /dev/null
+++ b/WORKSPACE.in_gerrit_tree
@@ -0,0 +1,6 @@
+
+maven_jar(
+    name = "wiremock",
+    artifact = "com.github.tomakehurst:wiremock-standalone:2.4.1",
+    sha1 = "228d3047147fffa0f12771f5dc2b3cd3b38c454b",
+)
diff --git a/bazlets.bzl b/bazlets.bzl
new file mode 100644
index 0000000..e14e488
--- /dev/null
+++ b/bazlets.bzl
@@ -0,0 +1,17 @@
+NAME = "com_googlesource_gerrit_bazlets"
+
+def load_bazlets(
+    commit,
+    local_path = None
+  ):
+  if not local_path:
+      native.git_repository(
+          name = NAME,
+          remote = "https://gerrit.googlesource.com/bazlets",
+          commit = commit,
+      )
+  else:
+      native.local_repository(
+          name = NAME,
+          path = local_path,
+      )
diff --git a/src/main/java/com/ericsson/gerrit/plugins/syncindex/HttpClientProvider.java b/src/main/java/com/ericsson/gerrit/plugins/syncindex/HttpClientProvider.java
index 1e34a18..07cad78 100644
--- a/src/main/java/com/ericsson/gerrit/plugins/syncindex/HttpClientProvider.java
+++ b/src/main/java/com/ericsson/gerrit/plugins/syncindex/HttpClientProvider.java
@@ -38,6 +38,7 @@
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import java.io.IOException;
 import java.net.URI;
 import java.security.KeyManagementException;
 import java.security.NoSuchAlgorithmException;
@@ -89,19 +90,23 @@
   }
 
   private HttpRequestRetryHandler customRetryHandler() {
-    return (exception, executionCount, context) -> {
-      if (executionCount > cfg.getMaxTries()
-          || exception instanceof SSLException) {
-        return false;
+    return new HttpRequestRetryHandler() {
+      @Override
+      public boolean retryRequest(IOException exception, int executionCount,
+          HttpContext httpContext) {
+        if (executionCount > cfg.getMaxTries()
+            || exception instanceof SSLException) {
+          return false;
+        }
+        logRetry(exception.getMessage());
+        try {
+          Thread.sleep(cfg.getRetryInterval());
+        } catch (InterruptedException e) {
+          Thread.currentThread().interrupt();
+          return false;
+        }
+        return true;
       }
-      logRetry(exception.getMessage());
-      try {
-        Thread.sleep(cfg.getRetryInterval());
-      } catch (InterruptedException e) {
-        Thread.currentThread().interrupt();
-        return false;
-      }
-      return true;
     };
   }
 
diff --git a/src/main/resources/Documentation/build.md b/src/main/resources/Documentation/build.md
index 3babed2..7e65e73 100644
--- a/src/main/resources/Documentation/build.md
+++ b/src/main/resources/Documentation/build.md
@@ -1,21 +1,61 @@
-Build
-=====
+# Build
 
-This plugin is built with Buck.
+This plugin can be built with Bazel or Buck and two build modes are supported:
+ * Standalone
+ * In Gerrit tree.
 
-Two build modes are supported: Standalone and in Gerrit tree. Standalone
-build mode is recommended, as this mode doesn't require local Gerrit
-tree to exist.
+Standalone build mode is recommended, as this mode doesn't require local Gerrit
+tree to exist. Moreover, there are some limitations and additional manual steps
+required when building in Gerrit tree mode (see corresponding sections).
 
-Build standalone
-----------------
+## Build standalone
+
+### Bazel
+
+To build the plugin, issue the following command:
+
+```
+  bazel build @PLUGIN@
+```
+
+The output is created in
+
+```
+  bazel-genfiles/@PLUGIN@.jar
+```
+
+To package the plugin sources run:
+
+```
+  bazel build libsync-index__plugin-src.jar
+```
+
+The output is created in:
+
+```
+  bazel-bin/libsync-index__plugin-src.jar
+```
+
+To execute the tests run:
+
+```
+  bazel test sync_index_tests
+```
+
+This project can be imported into the Eclipse IDE:
+
+```
+  ./tools/eclipse.py
+```
+
+### Buck
 
 Clone bucklets library:
 
 ```
   git clone https://gerrit.googlesource.com/bucklets
-
 ```
+
 and link it to @PLUGIN@ directory:
 
 ```
@@ -51,6 +91,9 @@
 ```
   ./bucklets/tools/eclipse.py
 ```
+* Note: wiremock jar should be added manually to classpath. In Eclipse:
+`Project -> Java Build Path -> Add External JARS -> <location of
+wiremock-standalone.jar in local file system>`
 
 To execute the tests run:
 
@@ -70,11 +113,59 @@
   buck-out/gen/@PLUGIN@-sources.jar
 ```
 
-Build in Gerrit tree
---------------------
+## Build in Gerrit tree
 
-Clone or link this plugin to the plugins directory of Gerrit's source
-tree, and issue the command:
+### Bazel
+
+Clone or link this plugin to the plugins directory of Gerrit's source tree, and
+issue the command:
+
+```
+  bazel build plugins/@PLUGIN@
+```
+
+The output is created in
+
+```
+  bazel-genfiles/plugins/@PLUGIN@/@PLUGIN@.jar
+```
+
+This project can be imported into the Eclipse IDE. First, list the plugin in the
+custom plugin list, in `gerrit/tools/bzl/plugins.bzl`:
+
+```
+CUSTOM_PLUGINS = [
+  ...
+  '@PLUGIN@',
+]
+```
+
+and issue the command:
+
+```
+  ./tools/eclipse/project_bzl.py
+```
+
+* Note: wiremock jar should be added manually to classpath. In Eclipse:
+`Project -> Java Build Path -> Add External JARS -> <location of
+wiremock-standalone.jar in local file system>`
+
+To execute the tests, Gerrit WORKSPACE should be patched:
+
+```
+  cat plugins/sync-index/WORKSPACE.in_gerrit_tree >> WORKSPACE
+```
+
+then run:
+
+```
+  bazel test plugins/@PLUGIN@:sync_index_tests
+```
+
+### Buck
+
+Clone or link this plugin to the plugins directory of Gerrit's source tree, and
+issue the command:
 
 ```
   buck build plugins/@PLUGIN@
@@ -92,6 +183,11 @@
   ./tools/eclipse/project.py
 ```
 
+* Note: wiremock jar should be added manually to classpath. In Eclipse:
+`Project -> Java Build Path -> Add External JARS -> <location of
+wiremock-standalone.jar in local file system>`
+
+
 To execute the tests run:
 
 ```
diff --git a/tools/BUILD b/tools/BUILD
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/tools/BUILD
diff --git a/tools/bazel.rc b/tools/bazel.rc
new file mode 100644
index 0000000..4ed16cf
--- /dev/null
+++ b/tools/bazel.rc
@@ -0,0 +1,2 @@
+build --workspace_status_command=./tools/workspace-status.sh
+test --build_tests_only
diff --git a/tools/bzl/BUILD b/tools/bzl/BUILD
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/tools/bzl/BUILD
diff --git a/tools/bzl/junit.bzl b/tools/bzl/junit.bzl
new file mode 100644
index 0000000..3af7e58
--- /dev/null
+++ b/tools/bzl/junit.bzl
@@ -0,0 +1,4 @@
+load(
+    "@com_googlesource_gerrit_bazlets//tools:junit.bzl",
+    "junit_tests",
+)
diff --git a/tools/bzl/plugin.bzl b/tools/bzl/plugin.bzl
new file mode 100644
index 0000000..a2e438f
--- /dev/null
+++ b/tools/bzl/plugin.bzl
@@ -0,0 +1,6 @@
+load(
+    "@com_googlesource_gerrit_bazlets//:gerrit_plugin.bzl",
+    "gerrit_plugin",
+    "PLUGIN_DEPS",
+    "PLUGIN_TEST_DEPS",
+)
diff --git a/tools/eclipse/BUILD b/tools/eclipse/BUILD
new file mode 100644
index 0000000..9c68d0f
--- /dev/null
+++ b/tools/eclipse/BUILD
@@ -0,0 +1,21 @@
+load("@com_googlesource_gerrit_bazlets//tools:commons.bzl",
+     "PLUGIN_DEPS",
+     "PLUGIN_TEST_DEPS",)
+load("@com_googlesource_gerrit_bazlets//tools:classpath.bzl",
+     "classpath_collector")
+
+java_library(
+  name = "classpath",
+    runtime_deps = PLUGIN_DEPS + PLUGIN_TEST_DEPS + [
+      "@wiremock//jar",
+      "//:sync-index__plugin",
+    ],
+)
+
+classpath_collector(
+  name = "main_classpath_collect",
+  deps = PLUGIN_DEPS + PLUGIN_TEST_DEPS + [
+    "@wiremock//jar",
+    "//:sync-index__plugin"
+  ],
+)
diff --git a/tools/eclipse/project.py b/tools/eclipse/project.py
new file mode 100755
index 0000000..88ca4b0
--- /dev/null
+++ b/tools/eclipse/project.py
@@ -0,0 +1,179 @@
+#!/usr/bin/env python
+# Copyright (C) 2016 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.
+#
+
+from __future__ import print_function
+# TODO(davido): use Google style for importing instead:
+# import optparse
+#
+# optparse.OptionParser
+from optparse import OptionParser
+from os import environ, path, makedirs
+from subprocess import CalledProcessError, check_call, check_output
+from xml.dom import minidom
+import re
+import sys
+
+MAIN = '//tools/eclipse:classpath'
+JRE = '/'.join([
+  'org.eclipse.jdt.launching.JRE_CONTAINER',
+  'org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType',
+  'JavaSE-1.8',
+])
+# Map of targets to corresponding classpath collector rules
+cp_targets = {
+  MAIN: '//tools/eclipse:main_classpath_collect',
+}
+
+ROOT = path.abspath(__file__)
+while not path.exists(path.join(ROOT, 'WORKSPACE')):
+  ROOT = path.dirname(ROOT)
+
+opts = OptionParser()
+opts.add_option('--name', help='name of the generated project',
+                action='store', default='sync-index', dest='project_name')
+args, _ = opts.parse_args()
+
+def retrieve_ext_location():
+  return check_output(['bazel', 'info', 'output_base']).strip()
+
+def gen_primary_build_tool():
+  bazel = check_output(['which', 'bazel']).strip()
+  with open(path.join(ROOT, ".primary_build_tool"), 'w') as fd:
+    fd.write("bazel=%s\n" % bazel)
+    fd.write("PATH=%s\n" % environ["PATH"])
+
+def _query_classpath(target):
+  deps = []
+  t = cp_targets[target]
+  try:
+    check_call(['bazel', 'build', t])
+  except CalledProcessError:
+    exit(1)
+  name = 'bazel-bin/tools/eclipse/' + t.split(':')[1] + '.runtime_classpath'
+  deps = [line.rstrip('\n') for line in open(name)]
+  return deps
+
+def gen_project(name='gerrit', root=ROOT):
+  p = path.join(root, '.project')
+  with open(p, 'w') as fd:
+    print("""\
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+  <name>%(name)s</name>
+  <buildSpec>
+    <buildCommand>
+      <name>org.eclipse.jdt.core.javabuilder</name>
+    </buildCommand>
+  </buildSpec>
+  <natures>
+    <nature>org.eclipse.jdt.core.javanature</nature>
+  </natures>
+</projectDescription>\
+    """ % {"name": name}, file=fd)
+
+def gen_classpath(ext):
+  def make_classpath():
+    impl = minidom.getDOMImplementation()
+    return impl.createDocument(None, 'classpath', None)
+
+  def classpathentry(kind, path, src=None, out=None, exported=None):
+    e = doc.createElement('classpathentry')
+    e.setAttribute('kind', kind)
+    # TODO(davido): Remove this and other exclude BUILD files hack
+    # when this Bazel bug is fixed:
+    # https://github.com/bazelbuild/bazel/issues/1083
+    if kind == 'src':
+      e.setAttribute('excluding', '**/BUILD')
+    e.setAttribute('path', path)
+    if src:
+      e.setAttribute('sourcepath', src)
+    if out:
+      e.setAttribute('output', out)
+    if exported:
+      e.setAttribute('exported', 'true')
+    doc.documentElement.appendChild(e)
+
+  doc = make_classpath()
+  src = set()
+  lib = set()
+
+  # Classpath entries are absolute for cross-cell support
+  java_library = re.compile('bazel-out/local-fastbuild/bin/lib[^/]+[.]jar$')
+  srcs = re.compile('(.*/external/[^/]+)/jar/(.*)[.]jar')
+  for p in _query_classpath(MAIN):
+    m = java_library.match(p)
+    if m:
+      src.add(".")
+    else:
+      if p.startswith("external"):
+        p = path.join(ext, p)
+      lib.add(p)
+
+  for s in sorted(src):
+    out = None
+
+    if s.startswith('lib/'):
+      out = 'eclipse-out/lib'
+
+    p = path.join(s, 'java')
+    if path.exists(p):
+      classpathentry('src', p, out=out)
+      continue
+
+    for env in ['main', 'test']:
+      o = None
+      if out:
+        o = out + '/' + env
+      elif env == 'test':
+        o = 'eclipse-out/test'
+
+      for srctype in ['java', 'resources']:
+        p = path.join(s, 'src', env, srctype)
+        if path.exists(p):
+          classpathentry('src', p, out=o)
+
+  for libs in [lib]:
+    for j in sorted(libs):
+      s = None
+      m = srcs.match(j)
+      if m:
+        prefix = m.group(1)
+        suffix = m.group(2)
+        p = path.join(prefix, "src", "%s-src.jar" % suffix)
+        if path.exists(p):
+          s = p
+      classpathentry('lib', j, s)
+
+  classpathentry('con', JRE)
+  classpathentry('output', 'eclipse-out/classes')
+
+  p = path.join(ROOT, '.classpath')
+  with open(p, 'w') as fd:
+    doc.writexml(fd, addindent='\t', newl='\n', encoding='UTF-8')
+
+try:
+  ext_location = retrieve_ext_location()
+  gen_project(args.project_name)
+  gen_classpath(ext_location)
+  gen_primary_build_tool()
+
+  try:
+    check_call(['bazel', 'build', MAIN])
+  except CalledProcessError:
+    exit(1)
+except KeyboardInterrupt:
+  print('Interrupted by user', file=sys.stderr)
+  exit(1)
diff --git a/tools/workspace-status.sh b/tools/workspace-status.sh
new file mode 100755
index 0000000..3102f64
--- /dev/null
+++ b/tools/workspace-status.sh
@@ -0,0 +1,17 @@
+#!/bin/bash
+
+# This script will be run by bazel when the build process starts to
+# generate key-value information that represents the status of the
+# workspace. The output should be like
+#
+# KEY1 VALUE1
+# KEY2 VALUE2
+#
+# If the script exits with non-zero code, it's considered as a failure
+# and the output will be discarded.
+
+function rev() {
+  cd $1; git describe --always --match "v[0-9].*" --dirty
+}
+
+echo STABLE_BUILD_SYNC-INDEX_LABEL $(rev .)