Skip to content

Instantly share code, notes, and snippets.

@jose-mgmaestre
Last active January 17, 2018 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jose-mgmaestre/06a2247698ed1612803ec426a2472fb9 to your computer and use it in GitHub Desktop.
Save jose-mgmaestre/06a2247698ed1612803ec426a2472fb9 to your computer and use it in GitHub Desktop.
Multitenancy junit test : Using a global tenant
/**
* It specify what Tenant should be used:
* <p>
* <p>
* There are 2 modes of resolving the identifier using {@link #resolveCurrentTenantIdentifier()}:
*
* <li> Using a global tenant identifier for junit testing
* <li> Using the http session to get the tenant for deployed applications
*
* @author jm
*/
public class CurrentTenantIdentifierResolverImpl implements CurrentTenantIdentifierResolver {
// public TenantResolverStrategy tenantStrategy;
private boolean contextInitialized;
private static String globalTenant; //static because is for all the classes
public CurrentTenantIdentifierResolverImpl() {
contextInitialized = false;
globalTenant = DEFAULT_TENANTID;
}
@Override
public String resolveCurrentTenantIdentifier() {
String tenant;
if(contextInitialized){
tenant = resolveTenantByHttpSession();
}
else{
tenant = globalTenant;
}
return tenant;
}
/**
* Get tenantId in the session attribute KEY_TENANTID
* @return TenantId on KEY_TENANTID
*/
private String resolveTenantByHttpSession() {
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//If session attribute exists returns tenantId saved on the session
if(attr != null){
HttpSession session = attr.getRequest().getSession(false); // true == allow create
if(session != null){
String tenant = (String) session.getAttribute(KEY_TENANTID_SESSION);
if(tenant != null){
return tenant;
}
}
}
//otherwise return default tenant
return DEFAULT_TENANTID;
}
public static void setContextInitialized(boolean initialized) {
contextInitialized = false;
globalTenant = DEFAULT_TENANTID;
}
/**
* Used when create the initial entities
* @param tenant
*/
public static void setGlobalTenant(String tenant)
{
globalTenant = tenant;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment