Merge branch 'stable-2.13'

* stable-2.13:
  Replace EasyMock with Mockito

Change-Id: I28fae8d964fca37580f6779b6b3819688eecd4ff
diff --git a/.buckconfig b/.buckconfig
index 2b818b6..275ec6a 100644
--- a/.buckconfig
+++ b/.buckconfig
@@ -6,7 +6,8 @@
 [java]
   jar_spool_mode = direct_to_jar
   src_roots = java, resources
-
+  source_level = 8
+  target_level = 8
 [project]
   ignore = .git, eclipse-out/
   parallel_parsing = true
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/BUCK b/BUCK
index bd6696e..1126b12 100644
--- a/BUCK
+++ b/BUCK
@@ -5,11 +5,7 @@
 SOURCES = glob(['src/main/java/**/*.java'])
 RESOURCES = glob(['src/main/resources/**/*'])
 
-DEPS = [
-  ':wiremock',
-]
-
-TEST_DEPS = GERRIT_PLUGIN_API + GERRIT_TESTS + DEPS + [
+TEST_DEPS = GERRIT_PLUGIN_API + GERRIT_TESTS + [
   ':sync-index__plugin',
   ':mockito',
 ]
@@ -27,8 +23,6 @@
     'Implementation-URL: https://gerrit-review.googlesource.com/#/admin/projects/plugins/sync-index',
     'Implementation-Vendor: Ericsson',
   ],
-  provided_deps = GERRIT_TESTS,
-  deps = DEPS,
 )
 
 java_sources(
@@ -50,8 +44,8 @@
 
 maven_jar(
   name = 'wiremock',
-  id = 'com.github.tomakehurst:wiremock:1.58:standalone',
-  sha1 = '21c8386a95c5dc54a9c55839c5a95083e42412ae',
+  id = 'com.github.tomakehurst:wiremock-standalone:2.1.12',
+  sha1 = 'fee73e0913ff3801cf83e660a14d6e4aac9a9cbd',
   license = 'Apache2.0',
   attach_source = False,
 )
diff --git a/BUILD b/BUILD
new file mode 100644
index 0000000..ed6ffe4
--- /dev/null
+++ b/BUILD
@@ -0,0 +1,34 @@
+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",
+        "@mockito//jar",
+        "@byte-buddy//jar",
+        "@objenesis//jar",
+        ":sync-index__plugin",
+    ],
+)
diff --git a/WORKSPACE b/WORKSPACE
new file mode 100644
index 0000000..c4582eb
--- /dev/null
+++ b/WORKSPACE
@@ -0,0 +1,51 @@
+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",
+)
+
+maven_jar(
+    name = 'mockito',
+    artifact = 'org.mockito:mockito-core:2.5.0',
+    sha1 = 'be28d46a52c7f2563580adeca350145e9ce916f8',
+)
+
+maven_jar(
+    name = 'byte-buddy',
+    artifact = 'net.bytebuddy:byte-buddy:1.5.12',
+    sha1 = 'b1ba1d15f102b36ed43b826488114678d6d413da',
+)
+
+maven_jar(
+    name = 'objenesis',
+    artifact = 'org.objenesis:objenesis:2.4',
+    sha1 = '2916b6c96b50c5b3ec4452ed99401db745aabb27',
+)
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/lib/gerrit/BUCK b/lib/gerrit/BUCK
index f83d917..8d5f0e9 100644
--- a/lib/gerrit/BUCK
+++ b/lib/gerrit/BUCK
@@ -1,12 +1,11 @@
 include_defs('//bucklets/maven_jar.bucklet')
 
-VER = '2.13'
-REPO = MAVEN_CENTRAL
+VER = '2.14-SNAPSHOT'
+REPO = MAVEN_LOCAL
 
 maven_jar(
   name = 'acceptance-framework',
   id = 'com.google.gerrit:gerrit-acceptance-framework:' + VER,
-  sha1 = 'a6913a61196a8fccdb45e761f43a0b7e21867c90',
   license = 'Apache2.0',
   attach_source = False,
   repository = REPO,
@@ -15,7 +14,6 @@
 maven_jar(
   name = 'plugin-api',
   id = 'com.google.gerrit:gerrit-plugin-api:' + VER,
-  sha1 = 'e25d55b8f41627c4ae6b9d2069ec398638b219a3',
   license = 'Apache2.0',
   attach_source = False,
   repository = REPO,
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 3b2f177..07cad78 100644
--- a/src/main/java/com/ericsson/gerrit/plugins/syncindex/HttpClientProvider.java
+++ b/src/main/java/com/ericsson/gerrit/plugins/syncindex/HttpClientProvider.java
@@ -91,10 +91,9 @@
 
   private HttpRequestRetryHandler customRetryHandler() {
     return new HttpRequestRetryHandler() {
-
       @Override
       public boolean retryRequest(IOException exception, int executionCount,
-          HttpContext context) {
+          HttpContext httpContext) {
         if (executionCount > cfg.getMaxTries()
             || exception instanceof SSLException) {
           return false;
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/src/test/java/com/ericsson/gerrit/plugins/syncindex/IndexEventHandlerTest.java b/src/test/java/com/ericsson/gerrit/plugins/syncindex/IndexEventHandlerTest.java
index 045aefa..bb83dcc 100644
--- a/src/test/java/com/ericsson/gerrit/plugins/syncindex/IndexEventHandlerTest.java
+++ b/src/test/java/com/ericsson/gerrit/plugins/syncindex/IndexEventHandlerTest.java
@@ -102,8 +102,9 @@
   public void testSyncIndexTaskHashCodeAndEquals() {
     SyncIndexTask task = indexEventHandler.new SyncIndexTask(CHANGE_ID, false);
 
-    assertThat(task.equals(task)).isTrue();
-    assertThat(task.hashCode()).isEqualTo(task.hashCode());
+    SyncIndexTask sameTask = task;
+    assertThat(task.equals(sameTask)).isTrue();
+    assertThat(task.hashCode()).isEqualTo(sameTask.hashCode());
 
     SyncIndexTask identicalTask =
         indexEventHandler.new SyncIndexTask(CHANGE_ID, false);
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..cb18eda
--- /dev/null
+++ b/tools/eclipse/BUILD
@@ -0,0 +1,27 @@
+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",
+      "@mockito//jar",
+      "@byte-buddy//jar",
+      "@objenesis//jar",
+      "//:sync-index__plugin",
+    ],
+)
+
+classpath_collector(
+  name = "main_classpath_collect",
+  deps = PLUGIN_DEPS + PLUGIN_TEST_DEPS + [
+    "@wiremock//jar",
+    "@mockito//jar",
+    "@byte-buddy//jar",
+    "@objenesis//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 .)