use of net.robinfriedli.jxp.persist.Context in project aiode by robinfriedli.
the class GroovyWhitelistManager method createFromConfiguration.
public static GroovyWhitelistManager createFromConfiguration(Context configuration) {
Map<Class<?>, WhitelistedClassContribution> whitelistContributions = configuration.query(tagName("whitelistClass")).getResultStream().map(elem -> {
try {
return new WhitelistedClassContribution(true, elem.getAttribute("onlyGenerated").getBool() ? ClassAccessMode.GENERATED : ClassAccessMode.FULL, Class.forName(elem.getAttribute("class").getValue()), elem.getAttribute("maxMethodInvocations").getInt());
} catch (ClassNotFoundException e) {
throw new RuntimeException("Invalid whitelist configuration, invalid class encountered", e);
}
}).collect(Collectors.toMap(WhitelistedClassContribution::getType, contribution -> contribution));
for (XmlElement methodWhitelist : configuration.query(tagName("whitelistMethods")).collect()) {
Class<?> allowedClass;
try {
allowedClass = Class.forName(methodWhitelist.getAttribute("class").getValue());
} catch (ClassNotFoundException e) {
throw new RuntimeException("Invalid whitelist configuration, invalid class encountered", e);
}
WhitelistedClassContribution allowedClassContribution = new WhitelistedClassContribution(methodWhitelist.getAttribute("allowConstructorCall").getBool(), ClassAccessMode.METHODS, allowedClass, methodWhitelist.getAttribute("maxMethodInvocations").getInt());
methodWhitelist.query(tagName("method")).getResultStream().forEach(elem -> new WhitelistedMethodContribution(elem.getAttribute("name").getValue(), !elem.hasAttribute("inheritable") || elem.getAttribute("inheritable").getBool(), elem.getAttribute("onlyGenerated").getBool(), elem.getAttribute("maxInvocationCount").getInt(), allowedClassContribution));
methodWhitelist.query(tagName("writeProperty")).getResultStream().forEach(elem -> new WhitelistedPropertyWriteAccessContribution(elem.getAttribute("name").getValue(), !elem.hasAttribute("inheritable") || elem.getAttribute("inheritable").getBool(), allowedClassContribution));
whitelistContributions.put(allowedClassContribution.getType(), allowedClassContribution);
}
// set the parent contribution of all contributions to the contribution describing the closest superclass
Collection<WhitelistedClassContribution> allWhitelistContributions = whitelistContributions.values();
for (WhitelistedClassContribution whitelistContribution : allWhitelistContributions) {
Class<?> currentType = whitelistContribution.getType();
for (WhitelistedClassContribution otherContribution : allWhitelistContributions) {
if (whitelistContribution == otherContribution) {
continue;
}
Class<?> otherType = otherContribution.getType();
if (otherType.isAssignableFrom(currentType)) {
Collection<WhitelistedClassContribution> parentContributions = whitelistContribution.getParentContributions();
if (parentContributions == null || parentContributions.isEmpty()) {
whitelistContribution.setParentContributions(Collections.singleton(otherContribution));
} else {
Set<WhitelistedClassContribution> contendingContributions = Sets.newHashSet();
contendingContributions.addAll(parentContributions);
contendingContributions.add(otherContribution);
whitelistContribution.setParentContributions(selectClosestNodes(contendingContributions, currentType));
}
}
}
}
return new GroovyWhitelistManager(whitelistContributions);
}
use of net.robinfriedli.jxp.persist.Context in project aiode by robinfriedli.
the class VersionUpdateAlertTask method sendUpdateAlert.
private void sendUpdateAlert(Context context, Version versionElem, JDA shard) {
List<XmlElement> lowerLaunchedVersions = context.query(and(tagName("version"), attribute("launched").is(true), lowerVersionThan(versionElem.getVersion()))).collect();
if (!lowerLaunchedVersions.isEmpty()) {
String message = "Aiode has been updated to " + versionElem.getVersion() + ". [Check the releases here](" + "https://github.com/robinfriedli/botify/releases)";
EmbedBuilder embedBuilder = new EmbedBuilder();
embedBuilder.setTitle("Update");
embedBuilder.setDescription(message);
List<XmlElement> features = versionElem.query(tagName("feature")).collect();
if (!features.isEmpty()) {
embedBuilder.addField("**Features**", "Changes in this update", false);
for (XmlElement feature : features) {
embedBuilder.addField(feature.getAttribute("title").getValue(), feature.getTextContent(), false);
}
}
List<Guild> guilds = shard.getGuilds();
long delaySecs = OFFSET++ * (guilds.size() / MESSAGES_PER_SECOND);
if (delaySecs > 0) {
delaySecs += 10;
}
MESSAGE_DISPATCH.schedule(() -> {
// with the other shards
synchronized (DISPATCH_LOCK) {
// setup current thread session and handle all guilds within one session instead of opening a new session for each
StaticSessionProvider.consumeSession((CheckedConsumer<Session>) session -> {
int counter = 0;
long currentTimeMillis = System.currentTimeMillis();
for (Guild guild : guilds) {
messageService.sendWithLogo(embedBuilder, guild);
if (++counter % MESSAGES_PER_SECOND == 0) {
long delta = System.currentTimeMillis() - currentTimeMillis;
if (delta < 1000) {
Thread.sleep(1000 - delta);
}
currentTimeMillis = System.currentTimeMillis();
}
}
});
}
}, delaySecs, TimeUnit.SECONDS);
}
}
use of net.robinfriedli.jxp.persist.Context in project aiode by robinfriedli.
the class CommandManager method instantiateCommandForContext.
public Optional<AbstractCommand> instantiateCommandForContext(CommandContext context, Session session, boolean includeScripts) {
String commandBody = context.getCommandBody();
if (commandBody.isBlank()) {
return Optional.empty();
}
String formattedCommandInput = commandBody.toLowerCase();
CommandContribution commandContribution = getCommandContributionForInput(commandBody);
AbstractCommand commandInstance;
// find a preset where the preset name matches the beginning of the command, find the longest matching preset name
// corresponds to lower(name) = substring(lower('" + commandBody.replaceAll("'", "''") + "'), 0, length(name) + 1)
Optional<Preset> optionalPreset = queryBuilderFactory.find(Preset.class).where((cb, root) -> cb.equal(cb.lower(root.get("name")), cb.substring(cb.literal(formattedCommandInput), cb.literal(1), cb.length(root.get("name"))))).orderBy((root, cb) -> cb.desc(cb.length(root.get("name")))).build(session).setMaxResults(1).setCacheable(true).uniqueResultOptional();
Optional<StoredScript> optionalStoredScript;
if (includeScripts) {
optionalStoredScript = queryBuilderFactory.find(StoredScript.class).where(((cb, root, subQueryFactory) -> cb.and(cb.equal(cb.lower(root.get("identifier")), cb.substring(cb.literal(formattedCommandInput), cb.literal(1), cb.length(root.get("identifier")))), cb.equal(root.get("scriptUsage"), subQueryFactory.createUncorrelatedSubQuery(StoredScript.ScriptUsage.class, "pk").where((cb1, root1) -> cb1.equal(root1.get("uniqueId"), "script")).build(session))))).orderBy((root, cb) -> cb.desc(cb.length(root.get("identifier")))).build(session).setMaxResults(1).setCacheable(true).uniqueResultOptional();
} else {
optionalStoredScript = Optional.empty();
}
// A ∧ B ∧ C
if (commandContribution != null && optionalPreset.isPresent() && optionalStoredScript.isPresent()) {
Preset preset = optionalPreset.get();
String identifier = commandContribution.getIdentifier();
StoredScript storedScript = optionalStoredScript.get();
if (preset.getName().length() > identifier.length() && preset.getName().length() >= storedScript.getIdentifier().length()) {
commandInstance = preset.instantiateCommand(this, context, commandBody);
} else if (storedScript.getIdentifier().length() > identifier.length() && storedScript.getIdentifier().length() > preset.getName().length()) {
commandInstance = storedScript.asCommand(this, context, commandBody);
} else {
String commandInput = commandBody.substring(identifier.length()).trim();
commandInstance = commandContribution.instantiate(this, context, commandInput);
}
} else if (commandContribution != null && optionalPreset.isPresent()) {
// A ∧ B ∧ !C
String identifier = commandContribution.getIdentifier();
Preset preset = optionalPreset.get();
if (preset.getName().length() > identifier.length()) {
commandInstance = preset.instantiateCommand(this, context, commandBody);
} else {
String commandInput = commandBody.substring(identifier.length()).trim();
commandInstance = commandContribution.instantiate(this, context, commandInput);
}
} else if (optionalPreset.isPresent() && optionalStoredScript.isPresent()) {
// !A ∧ B ∧ C
Preset preset = optionalPreset.get();
StoredScript storedScript = optionalStoredScript.get();
if (storedScript.getIdentifier().length() > preset.getName().length()) {
commandInstance = storedScript.asCommand(this, context, commandBody);
} else {
commandInstance = preset.instantiateCommand(this, context, commandBody);
}
} else if (commandContribution != null && optionalStoredScript.isPresent()) {
// A ∧ !B ∧ C
StoredScript storedScript = optionalStoredScript.get();
String identifier = commandContribution.getIdentifier();
if (storedScript.getIdentifier().length() > identifier.length()) {
commandInstance = storedScript.asCommand(this, context, commandBody);
} else {
String commandInput = commandBody.substring(identifier.length()).trim();
commandInstance = commandContribution.instantiate(this, context, commandInput);
}
} else if (optionalStoredScript.isPresent()) {
// !A ∧ !B ∧ C
commandInstance = optionalStoredScript.get().asCommand(this, context, commandBody);
} else if (optionalPreset.isPresent()) {
// !A ∧ B ∧ !C
commandInstance = optionalPreset.get().instantiateCommand(this, context, commandBody);
} else if (commandContribution != null) {
// A ∧ !B ∧ !C
String commandInput = commandBody.substring(commandContribution.getIdentifier().length()).trim();
commandInstance = commandContribution.instantiate(this, context, commandInput);
} else {
// !A ∧ !B ∧ !C
return Optional.empty();
}
return Optional.of(commandInstance);
}
use of net.robinfriedli.jxp.persist.Context in project aiode by robinfriedli.
the class MigratePlaylistsTask method perform.
@Override
public void perform(@Nullable JDA shard) throws Exception {
try (Session session = sessionFactory.withOptions().interceptor(InterceptorChain.of(PlaylistItemTimestampInterceptor.class, VerifyPlaylistInterceptor.class)).openSession()) {
session.beginTransaction();
for (Guild guild : Objects.requireNonNull(shard).getGuilds()) {
String path = String.format("./resources/%splaylists.xml", guild.getId());
File xmlFile = new File(path);
if (xmlFile.exists()) {
try (Context context = jxpBackend.getContext(xmlFile)) {
migrateFile(session, context, guild, spotifyApi);
}
}
}
session.getTransaction().commit();
}
}
use of net.robinfriedli.jxp.persist.Context in project aiode by robinfriedli.
the class SpringBootstrap method run.
@Override
public void run(String... args) {
Logger logger = LoggerFactory.getLogger(SpringBootstrap.class);
logger.info("Using java version " + System.getProperty("java.runtime.version"));
try {
Aiode aiode = Aiode.get();
CommandManager commandManager = aiode.getCommandManager();
HttpServerManager serverManager = aiode.getHttpServerManager();
JxpBackend jxpBackend = aiode.getJxpBackend();
CronJobService cronJobService = aiode.getCronJobService();
commandManager.initializeInterceptorChain();
serverManager.start();
// run startup tasks
InputStream startupTasksFile = getClass().getResourceAsStream("/xml-contributions/startupTasks.xml");
Context context = jxpBackend.createContext(startupTasksFile);
for (StartupTaskContribution element : context.getInstancesOf(StartupTaskContribution.class)) {
if (!aiode.isMainInstance() && element.getAttribute("mainInstanceOnly").getBool()) {
continue;
}
if (!element.getAttribute("runForEachShard").getBool()) {
element.instantiate().runTask(null);
}
}
cronJobService.scheduleAll();
Aiode.registerListeners();
logger.info("All starters done");
} catch (Throwable e) {
logger.error("Exception in starter. Application will terminate.", e);
System.exit(1);
}
}
Aggregations