001package io.ebean.test;
002
003/**
004 * Use in test code when the CurrentUserProvider and/or CurrentTenantProvider were configured by
005 * this ebean-test-config plugin.
006 * <p>
007 * That is, the ebean-test-config plugin will check if there ia a CurrentUserProvider and if not
008 * automatically set one and that provider reads the 'current user' from this UserContext.
009 * <pre>{@code
010 *
011 *   // set the current userId which will be put
012 *   // into 'WhoCreated' and 'WhoModified' properties
013 *
014 *       UserContext.setUserId("U1");
015 *
016 *       // persist bean that has ... a 'WhoModified' property
017 *   Content content = new Content();
018 *   content.setName("hello");
019 *
020 *   content.save();
021 *
022 * }</pre>
023 */
024public class UserContext {
025
026  private static final UserContextThreadLocal local = new UserContextThreadLocal();
027
028  private Object userId;
029  private Object tenantId;
030
031  private UserContext() {
032  }
033
034  /**
035   * Return the current user.
036   */
037  public static Object currentUserId() {
038    return local.get().userId;
039  }
040
041  /**
042   * Return the current tenantId.
043   */
044  public static Object currentTenantId() {
045    return local.get().tenantId;
046  }
047
048  /**
049   * Set the current userId - this value is put into 'WhoCreated' and 'WhoModified' properties.
050   */
051  public static void setUserId(Object userId) {
052    local.get().userId = userId;
053  }
054
055  /**
056   * Set the current tenantId.
057   */
058  public static void setTenantId(Object tenantId) {
059    local.get().tenantId = tenantId;
060  }
061
062  /**
063   * Clear both the current userId and tenantId.
064   */
065  public static void reset() {
066    local.remove();
067  }
068
069  /**
070   * Set both the current userId and current tenantId.
071   */
072  public static void set(Object userId, String tenantId) {
073    UserContext userContext = local.get();
074    userContext.userId = userId;
075    userContext.tenantId = tenantId;
076  }
077
078  private static class UserContextThreadLocal extends ThreadLocal<UserContext> {
079
080    @Override
081    protected UserContext initialValue() {
082      return new UserContext();
083    }
084  }
085}