forked from Fascinated/Bat
56 lines
1.7 KiB
Java
56 lines
1.7 KiB
Java
package cc.fascinated.bat.common;
|
|
|
|
import cc.fascinated.bat.BatApplication;
|
|
import lombok.Getter;
|
|
import lombok.SneakyThrows;
|
|
import org.bson.Document;
|
|
import org.slf4j.Logger;
|
|
import org.slf4j.LoggerFactory;
|
|
|
|
import java.util.HashMap;
|
|
import java.util.Map;
|
|
|
|
/**
|
|
* @author Fascinated (fascinated7)
|
|
*/
|
|
@Getter
|
|
public abstract class ProfileHolder {
|
|
private static final Logger log = LoggerFactory.getLogger(ProfileHolder.class);
|
|
/**
|
|
* 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());
|
|
|
|
log.info("instance of profiles: {}", document.get("profiles").getClass().getSimpleName());
|
|
Document profiles = document.get("profiles", new org.bson.Document());
|
|
Document profileDocument = (Document) profiles.get(clazz.getSimpleName());
|
|
|
|
newProfile.load(profileDocument == null ? new Document() : profileDocument, BatApplication.GSON);
|
|
getProfiles().put(clazz.getSimpleName(), newProfile);
|
|
return newProfile;
|
|
}
|
|
return clazz.cast(profile);
|
|
}
|
|
}
|