Skip to content

Commit

Permalink
Redesigned thread-local app context.
Browse files Browse the repository at this point in the history
  • Loading branch information
nmihajlovski committed Jan 18, 2015
1 parent d4d685d commit 53f1135
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 17 deletions.
57 changes: 42 additions & 15 deletions rapidoid-utils/src/main/java/org/rapidoid/util/AppCtx.java
Expand Up @@ -26,34 +26,61 @@ public class AppCtx {

private String username;

private Object extra;
private Object exchange;

private AppCtx() {
}

public static String username() {
return CTXS.get().username;
private static AppCtx ctx() {
AppCtx ctx = CTXS.get();
U.must(ctx != null, "App ctx wasn't set!");
return ctx;
}

@SuppressWarnings("unchecked")
public static <T> T extra() {
return (T) CTXS.get().extra;
}
private static AppCtx provideCtx() {
AppCtx ctx = CTXS.get();

public static void set(String username, Object extra) {
U.must(CTXS.get() == null, "The app context is already set!");
if (ctx == null) {
ctx = new AppCtx();
CTXS.set(ctx);
}

return ctx;
}

AppCtx ctx = new AppCtx();
public static void reset() {
CTXS.remove();
}

public static void setUsername(String username) {
AppCtx ctx = provideCtx();
U.must(ctx.username == null, "The username was already set!");
ctx.username = username;
ctx.extra = extra;
}

CTXS.set(ctx);
public static String username() {
return ctx().username;
}

public static void reset() {
U.must(CTXS.get() != null, "The app context is already empty!");
CTXS.remove();
public static void delUsername() {
AppCtx ctx = ctx();
ctx.username = null;
}

public static void setExchange(Object exchange) {
AppCtx ctx = provideCtx();
U.must(ctx.exchange == null, "The exchange was already set!");
ctx.exchange = exchange;
}

@SuppressWarnings("unchecked")
public static <T> T exchange() {
return (T) ctx().exchange;
}

public static void delExchange() {
AppCtx ctx = ctx();
ctx.exchange = null;
}

}
Expand Up @@ -31,13 +31,16 @@ public void testAppCtx() {
@Override
public void run() {

AppCtx.reset();

String username = rndStr(10);
Integer n = rnd();

AppCtx.set(username, n);
AppCtx.setUsername(username);
AppCtx.setExchange(n);

eq(AppCtx.username(), username);
eq(AppCtx.extra(), n);
eq(AppCtx.exchange(), n);

AppCtx.reset();
}
Expand Down

0 comments on commit 53f1135

Please sign in to comment.