// Copyright (C) 2015 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.gerrit.server.util;

import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gerrit.server.InternalUser;
import com.google.gwtorm.server.OrmException;
import com.google.gwtorm.server.SchemaFactory;
import com.google.inject.Inject;
import com.google.inject.Singleton;

/**
 * Helper to create one-off request contexts.
 * <p>
 * Each call to {@link #open()} opens a new {@link ReviewDb}, so this class
 * should only be used in a bounded try/finally block.
 * <p>
 * The user in the request context is {@link InternalUser}.
 */
@Singleton
public class OneOffRequestContext {
  private final InternalUser.Factory userFactory;
  private final SchemaFactory<ReviewDb> schemaFactory;
  private final ThreadLocalRequestContext requestContext;

  @Inject
  OneOffRequestContext(InternalUser.Factory userFactory,
      SchemaFactory<ReviewDb> schemaFactory,
      ThreadLocalRequestContext requestContext) {
    this.userFactory = userFactory;
    this.schemaFactory = schemaFactory;
    this.requestContext = requestContext;
  }

  public ManualRequestContext open() throws OrmException {
    return new ManualRequestContext(userFactory.create(),
        schemaFactory, requestContext);
  }
}

@@ -680,23 +680,121 @@
 wdb.
-server.ReviewDb
+client.Account;%0Aimport com.google.gerrit.reviewdb.server.ReviewDb;%0Aimport com.google.gerrit.server.IdentifiedUser
 ;%0Aim
@@ -1253,16 +1253,94 @@
 nalUser%7D
+ or the%0A * %7B@link IdentifiedUser%7D associated to the userId passed as parameter
 .%0A */%0A@S
@@ -1546,16 +1546,85 @@
 Context;
+%0A  private final IdentifiedUser.GenericFactory identifiedUserFactory;
 %0A%0A  @Inj
@@ -1775,16 +1775,75 @@
 tContext
+,%0A      IdentifiedUser.GenericFactory identifiedUserFactory
 ) %7B%0A    
@@ -1956,16 +1956,72 @@
 ontext;%0A
+    this.identifiedUserFactory = identifiedUserFactory;%0A
   %7D%0A%0A  p
@@ -2076,16 +2076,16 @@
 ption %7B%0A
-
     retu
@@ -2177,11 +2177,208 @@
 xt);%0A  %7D
+%0A%0A  public ManualRequestContext openAs(Account.Id userId) throws OrmException %7B%0A    return new ManualRequestContext(identifiedUserFactory.create(userId),%0A        schemaFactory, requestContext);%0A  %7D
 %0A%7D%0A

One-off request context on behalf of a user