001package io.ebean.cache;
002
003import io.ebean.config.CurrentTenantProvider;
004
005import java.io.Serializable;
006import java.util.Objects;
007
008/**
009 * Tenant aware handling for caching.
010 */
011public class TenantAwareKey {
012
013  private final CurrentTenantProvider tenantProvider;
014
015  /**
016   * Construct with a tenant provider than can be null.
017   */
018  public TenantAwareKey(CurrentTenantProvider tenantProvider) {
019    this.tenantProvider = tenantProvider;
020  }
021
022  /**
023   * Return a tenant aware key.
024   */
025  public Object key(Object key) {
026    if (tenantProvider != null) {
027      return new CacheKey(key, tenantProvider.currentId());
028    } else {
029      return key;
030    }
031  }
032
033  /**
034   * We use a combined key, if this serverCache is per tenant.
035   */
036  public static final class CacheKey implements Serializable {
037
038    private static final long serialVersionUID = 1L;
039
040    final Object key;
041    final Object tenantId;
042
043    /**
044     * Create with optional tenantId.
045     */
046    public CacheKey(Object key, Object tenantId) {
047      this.key = key;
048      this.tenantId = tenantId;
049    }
050
051    @Override
052    public int hashCode() {
053      int result = key.hashCode();
054      result = 92821 * result + Objects.hashCode(tenantId);
055      return result;
056    }
057
058    @Override
059    public boolean equals(Object obj) {
060      if (obj instanceof CacheKey) {
061        CacheKey that = (CacheKey) obj;
062        return Objects.equals(that.key, this.key)
063          && Objects.equals(that.tenantId, this.tenantId);
064      }
065      return false;
066    }
067
068    @Override
069    public String toString() {
070      StringBuilder sb = new StringBuilder(key.toString());
071      if (tenantId != null) {
072        sb.append(":").append(tenantId);
073      }
074      return sb.toString();
075    }
076  }
077}