Skip to content

Commit

Permalink
Added a key/value context store to PrincipalExtended
Browse files Browse the repository at this point in the history
  • Loading branch information
hylkevds committed Sep 18, 2023
1 parent dccebb0 commit c3e35f2
Showing 1 changed file with 81 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@

import java.security.Principal;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
Expand All @@ -40,6 +42,7 @@ public class PrincipalExtended implements Principal {
private final String name;
private final boolean admin;
private final Set<String> roles;
private Map<String, Object> context;

public PrincipalExtended(String name, boolean admin, Set<String> roles) {
this.name = name;
Expand All @@ -65,6 +68,84 @@ public String toString() {
return name + " (" + admin + ")";
}

/**
* Get the current context map.
*
* @return the current context map.
*/
public Map<String, Object> getContext() {
return context;
}

/**
* Add an item to the context, or replace an existing item if an item with
* the given key already exists.
*
* @param key The key to store the item under.
* @param value The value to associate with the given key.
* @return this.
*/
public PrincipalExtended addContextItem(String key, Object value) {
if (context == null) {
context = new HashMap<>();
}
context.put(key, value);
return this;
}

/**
* Check if the context has an item for the given key.
*
* @param key the key to check.
* @return true if there is a context item for the given key, false
* otherwise.
*/
public boolean hasContextItem(String key) {
if (context == null) {
return false;
}
return context.containsKey(key);
}

/**
* Get the context item with the given key, or dflt if there is no such
* item.
*
* @param key The key to get the item for.
* @param dflt The value to return if there is no value for the given key.
* @return The value for the given key, or dflt if there is no such item.
*/
public Object getContextItem(String key, Object dflt) {
if (context == null) {
return dflt;
}
Object value = context.get(key);
if (value == null) {
return dflt;
}
return value;
}

/**
* Get the context item with the given key, or null if there is no such
* item.
*
* @param key The key to get the item for.
* @return The value for the given key, or null if there is no such item.
*/
public Object getContextItem(String key) {
return getContextItem(key, null);
}

/**
* Replace the current context with the given value.
*
* @param context The context map to replace the current context with.
*/
public void setContext(Map<String, Object> context) {
this.context = context;
}

/**
* Turns the given principal into a PrincipalExtended. A null value will
* turn into an anonymous principal extended.
Expand Down

0 comments on commit c3e35f2

Please sign in to comment.