Merge branch 'stable-2.15'

* stable-2.15:
  Improve LFS locks documentation

Change-Id: Ibf3e332b525619a43e1c5588ceecdc987b258658
diff --git a/BUILD b/BUILD
index 0bcbd51..bb1d8fe 100644
--- a/BUILD
+++ b/BUILD
@@ -9,7 +9,6 @@
 gerrit_plugin(
     name = "lfs",
     srcs = glob(["src/main/java/**/*.java"]),
-    resources = glob(["src/main/resources/**/*"]),
     manifest_entries = [
         "Gerrit-PluginName: lfs",
         "Gerrit-Module: com.googlesource.gerrit.plugins.lfs.Module",
@@ -17,6 +16,7 @@
         "Gerrit-SshModule: com.googlesource.gerrit.plugins.lfs.SshModule",
         "Gerrit-InitStep: com.googlesource.gerrit.plugins.lfs.InitLfs",
     ],
+    resources = glob(["src/main/resources/**/*"]),
     deps = [
         "@jgit_http_apache//jar",
         "@jgit_lfs//jar",
@@ -33,3 +33,13 @@
         "@jgit_lfs//jar",
     ],
 )
+
+java_library(
+    name = "lfs__plugin_test_deps",
+    testonly = 1,
+    visibility = ["//visibility:public"],
+    exports = PLUGIN_DEPS + PLUGIN_TEST_DEPS + [
+        ":lfs__plugin",
+        "@joda_time//jar",
+    ],
+)
diff --git a/WORKSPACE b/WORKSPACE
index 6e7e310..9c27b3c 100644
--- a/WORKSPACE
+++ b/WORKSPACE
@@ -3,27 +3,27 @@
 load("//:bazlets.bzl", "load_bazlets")
 
 load_bazlets(
-    commit = "d9abef15db0f934bfe9adcb40b0c475807fd12bf",
+    commit = "8c91ef43828699c7ed33976897991a427dcfe04b",
     #    local_path = "/home/<user>/projects/bazlets",
 )
 
 # Release Plugin API
-load(
-    "@com_googlesource_gerrit_bazlets//:gerrit_api.bzl",
-    "gerrit_api",
-)
-
-# Snapshot Plugin API
 #load(
-#    "@com_googlesource_gerrit_bazlets//:gerrit_api_maven_local.bzl",
-#    "gerrit_api_maven_local",
+#    "@com_googlesource_gerrit_bazlets//:gerrit_api.bzl",
+#    "gerrit_api",
 #)
 
+# Snapshot Plugin API
+load(
+    "@com_googlesource_gerrit_bazlets//:gerrit_api_maven_local.bzl",
+    "gerrit_api_maven_local",
+)
+
 # Load release Plugin API
-gerrit_api()
+#gerrit_api()
 
 # Load snapshot Plugin API
-#gerrit_api_maven_local()
+gerrit_api_maven_local()
 
 load(":external_plugin_deps.bzl", "external_plugin_deps")
 
diff --git a/external_plugin_deps.bzl b/external_plugin_deps.bzl
index 065ccfd..3fb0fec 100644
--- a/external_plugin_deps.bzl
+++ b/external_plugin_deps.bzl
@@ -1,13 +1,13 @@
 load("//tools/bzl:maven_jar.bzl", "maven_jar", "GERRIT", "MAVEN_LOCAL", "MAVEN_CENTRAL")
 
-JGIT_VERSION = '4.9.2.201712150930-r.4-g085d1f959'
+JGIT_VERSION = '4.10.0.201712302008-r.24-gf3bb0e268'
 REPO = GERRIT
 
 def external_plugin_deps():
   maven_jar(
     name = 'jgit_http_apache',
     artifact = 'org.eclipse.jgit:org.eclipse.jgit.http.apache:' + JGIT_VERSION,
-    sha1 = '13859b30c8a20eb99dca3b9d2bb595e82d90320b',
+    sha1 = '701c6ec6c9a06311055d7468e4d0be021d62f900',
     repository = REPO,
     unsign = True,
     exclude = [
@@ -19,7 +19,7 @@
   maven_jar(
     name = 'jgit_lfs',
     artifact = 'org.eclipse.jgit:org.eclipse.jgit.lfs:' + JGIT_VERSION,
-    sha1 = '70dea6582f956fbaea003391fac8d79d280a9d24',
+    sha1 = 'f0b47053c2d4a71d20a04176e3e78fadc9705695',
     repository = REPO,
     unsign = True,
     exclude = [
@@ -31,7 +31,7 @@
   maven_jar(
     name = 'jgit_lfs_server',
     artifact = 'org.eclipse.jgit:org.eclipse.jgit.lfs.server:' + JGIT_VERSION,
-    sha1 = '1e704bf986e2f882666ca3b8ae1446137346b8ee',
+    sha1 = '18472cf8aa256c8d2f7841898e8007d5fd5c7ab4',
     repository = REPO,
     unsign = True,
     exclude = [
@@ -39,3 +39,10 @@
       'plugin.properties',
     ],
   )
+
+  maven_jar(
+    name = 'joda_time',
+    artifact = 'joda-time:joda-time:2.9.9',
+    sha1 = 'f7b520c458572890807d143670c9b24f4de90897',
+  )
+
diff --git a/src/main/java/com/googlesource/gerrit/plugins/lfs/LfsApiServlet.java b/src/main/java/com/googlesource/gerrit/plugins/lfs/LfsApiServlet.java
index 787ddf5..0036181 100644
--- a/src/main/java/com/googlesource/gerrit/plugins/lfs/LfsApiServlet.java
+++ b/src/main/java/com/googlesource/gerrit/plugins/lfs/LfsApiServlet.java
@@ -18,16 +18,14 @@
 import static com.google.gerrit.extensions.api.lfs.LfsDefinitions.LFS_URL_REGEX_TEMPLATE;
 import static com.google.gerrit.extensions.client.ProjectState.HIDDEN;
 import static com.google.gerrit.extensions.client.ProjectState.READ_ONLY;
+import static com.google.gerrit.server.permissions.ProjectPermission.PUSH_AT_LEAST_ONE_REF;
 import static com.google.gerrit.server.permissions.ProjectPermission.READ;
 
-import com.google.common.base.Strings;
 import com.google.gerrit.common.ProjectUtil;
-import com.google.gerrit.common.data.Capable;
 import com.google.gerrit.reviewdb.client.Project;
 import com.google.gerrit.server.CurrentUser;
 import com.google.gerrit.server.permissions.PermissionBackend;
 import com.google.gerrit.server.project.ProjectCache;
-import com.google.gerrit.server.project.ProjectControl;
 import com.google.gerrit.server.project.ProjectState;
 import com.google.inject.Inject;
 import com.google.inject.Singleton;
@@ -130,17 +128,17 @@
 
   private void authorizeUser(CurrentUser user, ProjectState state, String operation)
       throws LfsUnauthorized {
-    ProjectControl control = state.controlFor(user);
+    Project.NameKey projectName = state.getNameKey();
     if ((operation.equals(DOWNLOAD)
+            && !permissionBackend.user(user).project(projectName).testOrFalse(READ))
+        || (operation.equals(UPLOAD)
             && !permissionBackend
                 .user(user)
-                .project(state.getProject().getNameKey())
-                .testOrFalse(READ))
-        || (operation.equals(UPLOAD) && Capable.OK != control.canPushToAtLeastOneRef())) {
+                .project(projectName)
+                .testOrFalse(PUSH_AT_LEAST_ONE_REF))) {
       String op = operation.toLowerCase();
       String project = state.getProject().getName();
-      String userName =
-          Strings.isNullOrEmpty(user.getUserName()) ? "anonymous" : user.getUserName();
+      String userName = user.getUserName().orElse("anonymous");
       log.debug(
           String.format(
               "operation %s unauthorized for user %s on project %s", op, userName, project));
diff --git a/src/main/java/com/googlesource/gerrit/plugins/lfs/LfsAuthToken.java b/src/main/java/com/googlesource/gerrit/plugins/lfs/LfsAuthToken.java
index a51472d..0cadf7b 100644
--- a/src/main/java/com/googlesource/gerrit/plugins/lfs/LfsAuthToken.java
+++ b/src/main/java/com/googlesource/gerrit/plugins/lfs/LfsAuthToken.java
@@ -15,15 +15,13 @@
 package com.googlesource.gerrit.plugins.lfs;
 
 import com.google.common.base.Joiner;
-import com.google.common.base.Optional;
 import com.google.common.base.Splitter;
 import java.util.List;
-import org.joda.time.DateTime;
-import org.joda.time.DateTimeZone;
-import org.joda.time.format.DateTimeFormatter;
-import org.joda.time.format.ISODateTimeFormat;
+import java.util.Optional;
 
 public abstract class LfsAuthToken {
+  private static final LfsDateTime FORMAT = LfsDateTime.instance();
+
   public abstract static class Processor<T extends LfsAuthToken> {
     private static final char DELIMETER = '~';
 
@@ -40,7 +38,7 @@
     public Optional<T> deserialize(String input) {
       Optional<String> decrypted = cipher.decrypt(input);
       if (!decrypted.isPresent()) {
-        return Optional.absent();
+        return Optional.empty();
       }
 
       return createToken(Splitter.on(DELIMETER).splitToList(decrypted.get()));
@@ -65,12 +63,10 @@
     protected abstract boolean verifyTokenValues();
 
     static boolean onTime(String dateTime) {
-      String now = LfsAuthToken.ISO.print(now());
-      return now.compareTo(dateTime) <= 0;
+      return FORMAT.now().compareTo(dateTime) <= 0;
     }
   }
 
-  static final DateTimeFormatter ISO = ISODateTimeFormat.dateTime();
   public final String expiresAt;
 
   protected LfsAuthToken(int expirationSeconds) {
@@ -82,10 +78,6 @@
   }
 
   static String timeout(int expirationSeconds) {
-    return LfsAuthToken.ISO.print(now().plusSeconds(expirationSeconds));
-  }
-
-  static DateTime now() {
-    return DateTime.now().toDateTime(DateTimeZone.UTC);
+    return FORMAT.now(expirationSeconds);
   }
 }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/lfs/LfsAuthUserProvider.java b/src/main/java/com/googlesource/gerrit/plugins/lfs/LfsAuthUserProvider.java
index ddf46f4..f67e20e 100644
--- a/src/main/java/com/googlesource/gerrit/plugins/lfs/LfsAuthUserProvider.java
+++ b/src/main/java/com/googlesource/gerrit/plugins/lfs/LfsAuthUserProvider.java
@@ -16,7 +16,6 @@
 
 import static com.googlesource.gerrit.plugins.lfs.LfsSshRequestAuthorizer.SSH_AUTH_PREFIX;
 
-import com.google.common.base.Optional;
 import com.google.common.base.Strings;
 import com.google.gerrit.server.AnonymousUser;
 import com.google.gerrit.server.CurrentUser;
@@ -26,6 +25,7 @@
 import com.google.inject.Inject;
 import com.google.inject.Provider;
 import com.google.inject.Singleton;
+import java.util.Optional;
 
 @Singleton
 public class LfsAuthUserProvider {
@@ -62,9 +62,9 @@
             sshAuth.getUserFromValidToken(
                 auth.substring(SSH_AUTH_PREFIX.length()), project, operation);
         if (user.isPresent()) {
-          AccountState acc = accounts.getByUsername(user.get());
-          if (acc != null) {
-            return userFactory.create(acc);
+          Optional<AccountState> acc = accounts.getByUsername(user.get());
+          if (acc.isPresent()) {
+            return userFactory.create(acc.get());
           }
         }
       }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/lfs/LfsCipher.java b/src/main/java/com/googlesource/gerrit/plugins/lfs/LfsCipher.java
index 94bf054..aec332a 100644
--- a/src/main/java/com/googlesource/gerrit/plugins/lfs/LfsCipher.java
+++ b/src/main/java/com/googlesource/gerrit/plugins/lfs/LfsCipher.java
@@ -16,7 +16,6 @@
 
 import static java.nio.charset.StandardCharsets.UTF_8;
 
-import com.google.common.base.Optional;
 import com.google.common.base.Strings;
 import com.google.common.primitives.Bytes;
 import com.google.inject.Singleton;
@@ -25,6 +24,7 @@
 import java.security.NoSuchAlgorithmException;
 import java.security.SecureRandom;
 import java.util.Arrays;
+import java.util.Optional;
 import javax.crypto.Cipher;
 import javax.crypto.KeyGenerator;
 import javax.crypto.SecretKey;
@@ -63,7 +63,7 @@
 
   public Optional<String> decrypt(String input) {
     if (Strings.isNullOrEmpty(input)) {
-      return Optional.absent();
+      return Optional.empty();
     }
 
     byte[] bytes = Base64.decode(input);
@@ -76,7 +76,7 @@
       log.error("Exception was thrown during token verification", e);
     }
 
-    return Optional.absent();
+    return Optional.empty();
   }
 
   private Cipher cipher(byte[] initVector, int mode) throws GeneralSecurityException {
diff --git a/src/main/java/com/googlesource/gerrit/plugins/lfs/LfsDateTime.java b/src/main/java/com/googlesource/gerrit/plugins/lfs/LfsDateTime.java
new file mode 100644
index 0000000..b47eb98
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/lfs/LfsDateTime.java
@@ -0,0 +1,54 @@
+// Copyright (C) 2017 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.lfs;
+
+import java.time.Instant;
+import java.time.ZoneId;
+import java.time.ZoneOffset;
+import java.time.format.DateTimeFormatter;
+import java.util.Locale;
+
+public class LfsDateTime {
+  private final DateTimeFormatter format;
+
+  private LfsDateTime(ZoneId zone) {
+    format =
+        DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ")
+            .withZone(zone)
+            .withLocale(Locale.getDefault());
+  }
+
+  /* Create an instance with the system default time zone. */
+  public static LfsDateTime instance() {
+    return new LfsDateTime(ZoneOffset.systemDefault());
+  }
+
+  /* Create an instance with the specified time zone. */
+  public static LfsDateTime instance(ZoneId zone) {
+    return new LfsDateTime(zone);
+  }
+
+  public String now() {
+    return format.format(Instant.now());
+  }
+
+  public String now(int secondsToAdd) {
+    return format.format(Instant.now().plusSeconds(secondsToAdd));
+  }
+
+  public String format(Instant instant) {
+    return format.format(instant);
+  }
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/lfs/LfsSshRequestAuthorizer.java b/src/main/java/com/googlesource/gerrit/plugins/lfs/LfsSshRequestAuthorizer.java
index 2259db9..22e6b8e 100644
--- a/src/main/java/com/googlesource/gerrit/plugins/lfs/LfsSshRequestAuthorizer.java
+++ b/src/main/java/com/googlesource/gerrit/plugins/lfs/LfsSshRequestAuthorizer.java
@@ -14,12 +14,12 @@
 
 package com.googlesource.gerrit.plugins.lfs;
 
-import com.google.common.base.Optional;
 import com.google.gerrit.server.CurrentUser;
 import com.google.inject.Inject;
 import com.google.inject.Singleton;
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Optional;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -58,20 +58,20 @@
 
   SshAuthInfo generateAuthInfo(CurrentUser user, String project, String operation) {
     LfsSshAuthToken token =
-        new LfsSshAuthToken(user.getUserName(), project, operation, expirationSeconds);
+        new LfsSshAuthToken(user.getUserName().get(), project, operation, expirationSeconds);
     return new SshAuthInfo(processor.serialize(token), token.expiresAt);
   }
 
   Optional<String> getUserFromValidToken(String authToken, String project, String operation) {
     Optional<LfsSshAuthToken> token = processor.deserialize(authToken);
     if (!token.isPresent()) {
-      return Optional.absent();
+      return Optional.empty();
     }
 
     Verifier verifier = new Verifier(token.get(), project, operation);
     if (!verifier.verify()) {
       log.error("Invalid data was provided with auth token {}.", authToken);
-      return Optional.absent();
+      return Optional.empty();
     }
 
     return Optional.of(token.get().user);
@@ -96,7 +96,7 @@
     @Override
     protected Optional<LfsSshAuthToken> createToken(List<String> values) {
       if (values.size() != 4) {
-        return Optional.absent();
+        return Optional.empty();
       }
 
       return Optional.of(
diff --git a/src/main/java/com/googlesource/gerrit/plugins/lfs/fs/LfsFsRequestAuthorizer.java b/src/main/java/com/googlesource/gerrit/plugins/lfs/fs/LfsFsRequestAuthorizer.java
index 1626e38..f27eb62 100644
--- a/src/main/java/com/googlesource/gerrit/plugins/lfs/fs/LfsFsRequestAuthorizer.java
+++ b/src/main/java/com/googlesource/gerrit/plugins/lfs/fs/LfsFsRequestAuthorizer.java
@@ -14,7 +14,6 @@
 
 package com.googlesource.gerrit.plugins.lfs.fs;
 
-import com.google.common.base.Optional;
 import com.google.inject.Inject;
 import com.google.inject.Singleton;
 import com.googlesource.gerrit.plugins.lfs.AuthInfo;
@@ -22,6 +21,7 @@
 import com.googlesource.gerrit.plugins.lfs.LfsCipher;
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Optional;
 import org.eclipse.jgit.lfs.lib.AnyLongObjectId;
 import org.eclipse.jgit.lfs.lib.LongObjectId;
 
@@ -66,7 +66,7 @@
     @Override
     protected Optional<LfsFsAuthToken> createToken(List<String> values) {
       if (values.size() != 3) {
-        return Optional.absent();
+        return Optional.empty();
       }
 
       return Optional.of(
diff --git a/src/main/java/com/googlesource/gerrit/plugins/lfs/locks/LfsGetLocksAction.java b/src/main/java/com/googlesource/gerrit/plugins/lfs/locks/LfsGetLocksAction.java
index 32616f6..b730624 100644
--- a/src/main/java/com/googlesource/gerrit/plugins/lfs/locks/LfsGetLocksAction.java
+++ b/src/main/java/com/googlesource/gerrit/plugins/lfs/locks/LfsGetLocksAction.java
@@ -23,9 +23,9 @@
 import com.google.gerrit.reviewdb.client.Project;
 import com.google.gerrit.server.CurrentUser;
 import com.google.gerrit.server.permissions.PermissionBackend;
+import com.google.gerrit.server.permissions.PermissionBackend.ForProject;
 import com.google.gerrit.server.permissions.PermissionBackendException;
 import com.google.gerrit.server.project.ProjectCache;
-import com.google.gerrit.server.project.ProjectControl;
 import com.google.gerrit.server.project.ProjectState;
 import com.google.inject.Inject;
 import com.google.inject.assistedinject.Assisted;
@@ -34,7 +34,6 @@
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 import org.eclipse.jgit.lfs.errors.LfsException;
-import org.eclipse.jgit.lfs.errors.LfsUnauthorized;
 
 public class LfsGetLocksAction extends LfsLocksAction {
   interface Factory extends LfsLocksAction.Factory<LfsGetLocksAction> {}
@@ -42,8 +41,6 @@
   static final Pattern LFS_LOCKS_URL_PATTERN =
       Pattern.compile(String.format(LFS_URL_REGEX_TEMPLATE, LFS_LOCKS_PATH_REGEX));
 
-  private final PermissionBackend permissionBackend;
-
   @Inject
   LfsGetLocksAction(
       PermissionBackend permissionBackend,
@@ -51,8 +48,7 @@
       LfsAuthUserProvider userProvider,
       LfsLocksHandler handler,
       @Assisted LfsLocksContext context) {
-    super(projectCache, userProvider, handler, context);
-    this.permissionBackend = permissionBackend;
+    super(permissionBackend, projectCache, userProvider, handler, context);
   }
 
   @Override
@@ -66,15 +62,14 @@
   }
 
   @Override
-  protected void authorizeUser(ProjectControl control) throws LfsUnauthorized {
-    try {
-      permissionBackend
-          .user(control.getUser())
-          .project(control.getProject().getNameKey())
-          .check(ACCESS);
-    } catch (AuthException | PermissionBackendException e) {
-      throwUnauthorizedOp("list locks", control);
-    }
+  protected void authorizeUser(ForProject project)
+      throws AuthException, PermissionBackendException {
+    project.check(ACCESS);
+  }
+
+  @Override
+  protected String getAction() {
+    return "list-locks";
   }
 
   @Override
diff --git a/src/main/java/com/googlesource/gerrit/plugins/lfs/locks/LfsLocksAction.java b/src/main/java/com/googlesource/gerrit/plugins/lfs/locks/LfsLocksAction.java
index 8a13514..41bd582 100644
--- a/src/main/java/com/googlesource/gerrit/plugins/lfs/locks/LfsLocksAction.java
+++ b/src/main/java/com/googlesource/gerrit/plugins/lfs/locks/LfsLocksAction.java
@@ -21,12 +21,14 @@
 import static org.apache.http.HttpStatus.SC_UNAUTHORIZED;
 import static org.eclipse.jgit.util.HttpSupport.HDR_AUTHORIZATION;
 
-import com.google.common.base.Strings;
 import com.google.gerrit.common.ProjectUtil;
+import com.google.gerrit.extensions.restapi.AuthException;
 import com.google.gerrit.reviewdb.client.Project;
 import com.google.gerrit.server.CurrentUser;
+import com.google.gerrit.server.permissions.PermissionBackend;
+import com.google.gerrit.server.permissions.PermissionBackend.ForProject;
+import com.google.gerrit.server.permissions.PermissionBackendException;
 import com.google.gerrit.server.project.ProjectCache;
-import com.google.gerrit.server.project.ProjectControl;
 import com.google.gerrit.server.project.ProjectState;
 import com.googlesource.gerrit.plugins.lfs.LfsAuthUserProvider;
 import com.googlesource.gerrit.plugins.lfs.locks.LfsLocksHandler.LfsLockExistsException;
@@ -50,12 +52,15 @@
   protected final LfsAuthUserProvider userProvider;
   protected final LfsLocksHandler handler;
   protected final LfsLocksContext context;
+  protected final PermissionBackend permissionBackend;
 
   protected LfsLocksAction(
+      PermissionBackend permissionBackend,
       ProjectCache projectCache,
       LfsAuthUserProvider userProvider,
       LfsLocksHandler handler,
       LfsLocksContext context) {
+    this.permissionBackend = permissionBackend;
     this.projectCache = projectCache;
     this.userProvider = userProvider;
     this.handler = handler;
@@ -67,8 +72,12 @@
       String name = getProjectName();
       ProjectState project = getProject(name);
       CurrentUser user = getUser(name);
-      ProjectControl control = project.controlFor(user);
-      authorizeUser(control);
+      ProjectState state = projectCache.checkedGet(project.getNameKey());
+      try {
+        authorizeUser(permissionBackend.user(user).project(state.getNameKey()));
+      } catch (AuthException | PermissionBackendException e) {
+        throwUnauthorizedOp(getAction(), project, user);
+      }
       doRun(project, user);
     } catch (LfsUnauthorized e) {
       context.sendError(SC_UNAUTHORIZED, e.getMessage());
@@ -83,7 +92,10 @@
 
   protected abstract String getProjectName() throws LfsException;
 
-  protected abstract void authorizeUser(ProjectControl control) throws LfsUnauthorized;
+  protected abstract String getAction();
+
+  protected abstract void authorizeUser(ForProject project)
+      throws AuthException, PermissionBackendException;
 
   protected abstract void doRun(ProjectState project, CurrentUser user)
       throws LfsException, IOException;
@@ -102,12 +114,10 @@
         context.getHeader(HDR_AUTHORIZATION), project, LFS_LOCKING_OPERATION);
   }
 
-  protected void throwUnauthorizedOp(String op, ProjectControl control) throws LfsUnauthorized {
-    String project = control.getProject().getName();
-    String userName =
-        Strings.isNullOrEmpty(control.getUser().getUserName())
-            ? "anonymous"
-            : control.getUser().getUserName();
+  private void throwUnauthorizedOp(String op, ProjectState state, CurrentUser user)
+      throws LfsUnauthorized {
+    String project = state.getProject().getName();
+    String userName = user.getUserName().orElse("anonymous");
     log.debug(
         String.format(
             "operation %s unauthorized for user %s on project %s", op, userName, project));
diff --git a/src/main/java/com/googlesource/gerrit/plugins/lfs/locks/LfsLocksHandler.java b/src/main/java/com/googlesource/gerrit/plugins/lfs/locks/LfsLocksHandler.java
index f6ea9f1..2fb5ee3 100644
--- a/src/main/java/com/googlesource/gerrit/plugins/lfs/locks/LfsLocksHandler.java
+++ b/src/main/java/com/googlesource/gerrit/plugins/lfs/locks/LfsLocksHandler.java
@@ -28,7 +28,6 @@
 import java.util.List;
 import java.util.Map;
 import java.util.Optional;
-import java.util.function.Function;
 import java.util.stream.Collectors;
 import org.eclipse.jgit.lfs.errors.LfsException;
 import org.slf4j.Logger;
@@ -103,7 +102,7 @@
     }
 
     LfsLock lock = hasLock.get();
-    if (lock.owner.name.equals(user.getUserName())) {
+    if (lock.owner.name.equals(user.getUserName().get())) {
       locks.deleteLock(lock);
       return new LfsLockResponse(lock);
     } else if (input.force) {
@@ -118,15 +117,15 @@
   LfsVerifyLocksResponse verifyLocks(Project.NameKey project, final CurrentUser user) {
     log.debug("Verify list of locks for {} project and user {}", project, user);
     LfsProjectLocks locks = projectLocks.getUnchecked(project);
-    Function<LfsLock, Boolean> isOurs =
-        new Function<LfsLock, Boolean>() {
-          @Override
-          public Boolean apply(LfsLock input) {
-            return input.owner.name.equals(user.getUserName());
-          }
-        };
     Map<Boolean, List<LfsLock>> groupByOurs =
-        locks.getLocks().stream().collect(Collectors.groupingBy(isOurs));
+        locks
+            .getLocks()
+            .stream()
+            .collect(
+                Collectors.groupingBy(
+                    (in) -> {
+                      return in.owner.name.equals(user.getUserName().get());
+                    }));
     return new LfsVerifyLocksResponse(groupByOurs.get(true), groupByOurs.get(false), null);
   }
 
diff --git a/src/main/java/com/googlesource/gerrit/plugins/lfs/locks/LfsProjectLocks.java b/src/main/java/com/googlesource/gerrit/plugins/lfs/locks/LfsProjectLocks.java
index c9e0d28..7dfa103 100644
--- a/src/main/java/com/googlesource/gerrit/plugins/lfs/locks/LfsProjectLocks.java
+++ b/src/main/java/com/googlesource/gerrit/plugins/lfs/locks/LfsProjectLocks.java
@@ -23,6 +23,7 @@
 import com.google.gson.GsonBuilder;
 import com.google.inject.Inject;
 import com.google.inject.assistedinject.Assisted;
+import com.googlesource.gerrit.plugins.lfs.LfsDateTime;
 import com.googlesource.gerrit.plugins.lfs.locks.LfsLocksHandler.LfsLockExistsException;
 import java.io.IOException;
 import java.io.OutputStreamWriter;
@@ -35,10 +36,6 @@
 import java.util.stream.Stream;
 import org.eclipse.jgit.internal.storage.file.LockFile;
 import org.eclipse.jgit.lfs.errors.LfsException;
-import org.joda.time.DateTime;
-import org.joda.time.DateTimeZone;
-import org.joda.time.format.DateTimeFormatter;
-import org.joda.time.format.ISODateTimeFormat;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -48,12 +45,12 @@
   }
 
   private static final Logger log = LoggerFactory.getLogger(LfsProjectLocks.class);
-  private static final DateTimeFormatter ISO = ISODateTimeFormat.dateTime();
   private static final Gson gson =
       new GsonBuilder()
           .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
           .disableHtmlEscaping()
           .create();
+  private static final LfsDateTime FORMAT = LfsDateTime.instance();
 
   private final PathToLockId toLockId;
   private final String project;
@@ -107,7 +104,8 @@
       throw new LfsLockExistsException(lock);
     }
 
-    lock = new LfsLock(lockId, input.path, now(), new LfsLockOwner(user.getUserName()));
+    lock =
+        new LfsLock(lockId, input.path, FORMAT.now(), new LfsLockOwner(user.getUserName().get()));
     LockFile fileLock = new LockFile(locksPath.resolve(lockId).toFile());
     try {
       if (!fileLock.lock()) {
@@ -189,8 +187,4 @@
   Collection<LfsLock> getLocks() {
     return locks.asMap().values();
   }
-
-  private String now() {
-    return ISO.print(DateTime.now().toDateTime(DateTimeZone.UTC));
-  }
 }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/lfs/locks/LfsPutLocksAction.java b/src/main/java/com/googlesource/gerrit/plugins/lfs/locks/LfsPutLocksAction.java
index ffbcc8d..39c7861 100644
--- a/src/main/java/com/googlesource/gerrit/plugins/lfs/locks/LfsPutLocksAction.java
+++ b/src/main/java/com/googlesource/gerrit/plugins/lfs/locks/LfsPutLocksAction.java
@@ -16,13 +16,16 @@
 
 import static com.google.gerrit.extensions.api.lfs.LfsDefinitions.LFS_URL_REGEX_TEMPLATE;
 import static com.google.gerrit.extensions.api.lfs.LfsDefinitions.LFS_VERIFICATION_PATH;
+import static com.google.gerrit.server.permissions.ProjectPermission.PUSH_AT_LEAST_ONE_REF;
 import static com.googlesource.gerrit.plugins.lfs.locks.LfsGetLocksAction.LFS_LOCKS_URL_PATTERN;
 
 import com.google.common.base.Strings;
-import com.google.gerrit.common.data.Capable;
+import com.google.gerrit.extensions.restapi.AuthException;
 import com.google.gerrit.server.CurrentUser;
+import com.google.gerrit.server.permissions.PermissionBackend;
+import com.google.gerrit.server.permissions.PermissionBackend.ForProject;
+import com.google.gerrit.server.permissions.PermissionBackendException;
 import com.google.gerrit.server.project.ProjectCache;
-import com.google.gerrit.server.project.ProjectControl;
 import com.google.gerrit.server.project.ProjectState;
 import com.google.inject.Inject;
 import com.google.inject.assistedinject.Assisted;
@@ -31,7 +34,6 @@
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 import org.eclipse.jgit.lfs.errors.LfsException;
-import org.eclipse.jgit.lfs.errors.LfsUnauthorized;
 
 public class LfsPutLocksAction extends LfsLocksAction {
   interface Factory extends LfsLocksAction.Factory<LfsPutLocksAction> {}
@@ -43,11 +45,12 @@
 
   @Inject
   LfsPutLocksAction(
+      PermissionBackend permissionBackend,
       ProjectCache projectCache,
       LfsAuthUserProvider userProvider,
       LfsLocksHandler handler,
       @Assisted LfsLocksContext context) {
-    super(projectCache, userProvider, handler, context);
+    super(permissionBackend, projectCache, userProvider, handler, context);
   }
 
   @Override
@@ -74,11 +77,15 @@
   }
 
   @Override
-  protected void authorizeUser(ProjectControl control) throws LfsUnauthorized {
+  protected void authorizeUser(ForProject project)
+      throws AuthException, PermissionBackendException {
     // all operations require push permission
-    if (Capable.OK != control.canPushToAtLeastOneRef()) {
-      throwUnauthorizedOp(action.getName(), control);
-    }
+    project.check(PUSH_AT_LEAST_ONE_REF);
+  }
+
+  @Override
+  protected String getAction() {
+    return action.getName();
   }
 
   @Override
diff --git a/src/test/java/com/googlesource/gerrit/plugins/lfs/LfsAuthTokenTest.java b/src/test/java/com/googlesource/gerrit/plugins/lfs/LfsAuthTokenTest.java
index 825a746..c074151 100644
--- a/src/test/java/com/googlesource/gerrit/plugins/lfs/LfsAuthTokenTest.java
+++ b/src/test/java/com/googlesource/gerrit/plugins/lfs/LfsAuthTokenTest.java
@@ -15,31 +15,28 @@
 package com.googlesource.gerrit.plugins.lfs;
 
 import static com.google.common.truth.Truth.assertThat;
-import static com.googlesource.gerrit.plugins.lfs.LfsAuthToken.ISO;
 import static com.googlesource.gerrit.plugins.lfs.LfsAuthToken.Verifier.onTime;
 
-import com.google.common.base.Optional;
+import java.time.Instant;
 import java.util.ArrayList;
 import java.util.List;
-import org.joda.time.DateTime;
-import org.joda.time.DateTimeZone;
+import java.util.Optional;
 import org.junit.Test;
 
 public class LfsAuthTokenTest {
   private final LfsCipher cipher = new LfsCipher();
+  private final LfsDateTime formatter = LfsDateTime.instance();
 
   @Test
   public void testExpiredTime() throws Exception {
-    DateTime now = now();
     // test that even 1ms expiration is enough
-    assertThat(onTime(ISO.print(now.minusMillis(1)))).isFalse();
+    assertThat(onTime(formatter.format(now().minusMillis(1)))).isFalse();
   }
 
   @Test
   public void testOnTime() throws Exception {
-    DateTime now = now();
     // if there is at least 1ms before there is no timeout
-    assertThat(onTime(ISO.print(now.plusMillis(1)))).isTrue();
+    assertThat(onTime(formatter.format(now().plusMillis(1)))).isTrue();
   }
 
   @Test
@@ -69,8 +66,8 @@
     assertThat(verifier.verify()).isFalse();
   }
 
-  private DateTime now() {
-    return DateTime.now().toDateTime(DateTimeZone.UTC);
+  private Instant now() {
+    return Instant.now();
   }
 
   private class TestToken extends LfsAuthToken {
diff --git a/src/test/java/com/googlesource/gerrit/plugins/lfs/LfsCipherTest.java b/src/test/java/com/googlesource/gerrit/plugins/lfs/LfsCipherTest.java
index 5970845..b092a48 100644
--- a/src/test/java/com/googlesource/gerrit/plugins/lfs/LfsCipherTest.java
+++ b/src/test/java/com/googlesource/gerrit/plugins/lfs/LfsCipherTest.java
@@ -16,7 +16,7 @@
 
 import static com.google.common.truth.Truth.assertThat;
 
-import com.google.common.base.Optional;
+import java.util.Optional;
 import org.junit.Test;
 
 public class LfsCipherTest {
diff --git a/src/test/java/com/googlesource/gerrit/plugins/lfs/LfsDateTimeTest.java b/src/test/java/com/googlesource/gerrit/plugins/lfs/LfsDateTimeTest.java
new file mode 100644
index 0000000..99dcfe2
--- /dev/null
+++ b/src/test/java/com/googlesource/gerrit/plugins/lfs/LfsDateTimeTest.java
@@ -0,0 +1,51 @@
+// Copyright (C) 2017 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.lfs;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import java.time.Instant;
+import java.util.TimeZone;
+import org.joda.time.DateTime;
+import org.joda.time.DateTimeZone;
+import org.joda.time.format.ISODateTimeFormat;
+import org.junit.Test;
+import org.junit.experimental.theories.DataPoints;
+import org.junit.experimental.theories.Theories;
+import org.junit.experimental.theories.Theory;
+import org.junit.runner.RunWith;
+
+@RunWith(Theories.class)
+public class LfsDateTimeTest {
+  @DataPoints public static String[] timeZones = {"US/Eastern", "Asia/Tokyo", "UTC"};
+
+  @Test
+  public void formatWithDefaultTimezone() throws Exception {
+    DateTime now = DateTime.now();
+    String jodaFormat = ISODateTimeFormat.dateTime().print(now);
+    LfsDateTime formatter = LfsDateTime.instance();
+    String javaFormat = formatter.format(Instant.ofEpochMilli(now.getMillis()));
+    assertThat(javaFormat).isEqualTo(jodaFormat);
+  }
+
+  @Theory
+  public void formatWithSpecifiedTimezone(String zone) throws Exception {
+    DateTime now = DateTime.now().withZone(DateTimeZone.forID(zone));
+    String jodaFormat = ISODateTimeFormat.dateTime().withZone(DateTimeZone.forID(zone)).print(now);
+    LfsDateTime formatter = LfsDateTime.instance(TimeZone.getTimeZone(zone).toZoneId());
+    String javaFormat = formatter.format(Instant.ofEpochMilli(now.getMillis()));
+    assertThat(javaFormat).isEqualTo(jodaFormat);
+  }
+}