forked from Fascinated/Bat
51 lines
1.5 KiB
Java
51 lines
1.5 KiB
Java
package cc.fascinated.bat.common;
|
|
|
|
import cc.fascinated.bat.BatApplication;
|
|
import lombok.Getter;
|
|
import lombok.SneakyThrows;
|
|
import org.bson.Document;
|
|
|
|
import java.util.HashMap;
|
|
import java.util.Map;
|
|
|
|
/**
|
|
* @author Fascinated (fascinated7)
|
|
*/
|
|
@Getter
|
|
public abstract class ProfileHolder {
|
|
/**
|
|
* The profiles for the holder
|
|
*/
|
|
private final Map<String, Serializable> profiles = new HashMap<>();
|
|
|
|
/**
|
|
* Gets a profile for the holder
|
|
*
|
|
* @param clazz The class of the profile
|
|
* @param <T> The type of the profile
|
|
* @return The profile
|
|
*/
|
|
public abstract <T extends Serializable> T getProfile(Class<T> clazz);
|
|
|
|
/**
|
|
* Gets the profiles for the holder
|
|
* using the provided document
|
|
*
|
|
* @return the profiles
|
|
*/
|
|
@SneakyThrows
|
|
protected <T extends Serializable> T getProfileFromDocument(Class<T> clazz, Document document) {
|
|
Serializable profile = getProfiles().get(clazz.getSimpleName());
|
|
if (profile == null) {
|
|
T newProfile = clazz.cast(clazz.getDeclaredConstructors()[0].newInstance());
|
|
org.bson.Document profiles = document.get("profiles", new org.bson.Document());
|
|
org.bson.Document profileDocument = (org.bson.Document) profiles.getOrDefault(clazz.getSimpleName(), new org.bson.Document());
|
|
|
|
newProfile.load(profileDocument, BatApplication.GSON);
|
|
getProfiles().put(clazz.getSimpleName(), newProfile);
|
|
return newProfile;
|
|
}
|
|
return clazz.cast(profile);
|
|
}
|
|
}
|