Search in sources :

Example 1 with Context

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);
}
Also used : Context(net.robinfriedli.jxp.persist.Context) ClassDescriptorNode(net.robinfriedli.aiode.util.ClassDescriptorNode) Collection(java.util.Collection) Map(java.util.Map) Set(java.util.Set) XmlElement(net.robinfriedli.jxp.api.XmlElement) HashMap(java.util.HashMap) Conditions(net.robinfriedli.jxp.queries.Conditions) Collections(java.util.Collections) Collectors(java.util.stream.Collectors) Sets(com.google.api.client.util.Sets) XmlElement(net.robinfriedli.jxp.api.XmlElement)

Example 2 with Context

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);
    }
}
Also used : CheckedConsumer(net.robinfriedli.aiode.function.CheckedConsumer) Context(net.robinfriedli.jxp.persist.Context) StartupTask(net.robinfriedli.aiode.boot.StartupTask) Logger(org.slf4j.Logger) JDA(net.dv8tion.jda.api.JDA) MessageService(net.robinfriedli.aiode.discord.MessageService) LoggerFactory(org.slf4j.LoggerFactory) VersionManager(net.robinfriedli.aiode.boot.VersionManager) Session(org.hibernate.Session) LoggingThreadFactory(net.robinfriedli.aiode.concurrent.LoggingThreadFactory) StartupTaskContribution(net.robinfriedli.aiode.entities.xml.StartupTaskContribution) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Version(net.robinfriedli.aiode.entities.xml.Version) Conditions(net.robinfriedli.jxp.queries.Conditions) Executors(java.util.concurrent.Executors) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) Guild(net.dv8tion.jda.api.entities.Guild) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) StaticSessionProvider(net.robinfriedli.aiode.persist.StaticSessionProvider) XmlElement(net.robinfriedli.jxp.api.XmlElement) Conditions(net.robinfriedli.aiode.boot.VersionManager.Conditions) Nullable(javax.annotation.Nullable) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) XmlElement(net.robinfriedli.jxp.api.XmlElement) Guild(net.dv8tion.jda.api.entities.Guild) Session(org.hibernate.Session)

Example 3 with Context

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);
}
Also used : Arrays(java.util.Arrays) CommandInterceptorContribution(net.robinfriedli.aiode.entities.xml.CommandInterceptorContribution) ThreadExecutionQueue(net.robinfriedli.aiode.concurrent.ThreadExecutionQueue) JxpBackend(net.robinfriedli.jxp.api.JxpBackend) LoggerFactory(org.slf4j.LoggerFactory) Session(org.hibernate.Session) Preset(net.robinfriedli.aiode.entities.Preset) Value(org.springframework.beans.factory.annotation.Value) ExecutionContext(net.robinfriedli.aiode.concurrent.ExecutionContext) QueryBuilderFactory(net.robinfriedli.aiode.persist.qb.QueryBuilderFactory) Lists(com.google.common.collect.Lists) EventWaiter(net.robinfriedli.aiode.discord.listeners.EventWaiter) CommandInterceptorChain(net.robinfriedli.aiode.command.interceptor.CommandInterceptorChain) ThreadContext(net.robinfriedli.aiode.concurrent.ThreadContext) CommandContribution(net.robinfriedli.aiode.entities.xml.CommandContribution) Resource(org.springframework.core.io.Resource) Context(net.robinfriedli.jxp.persist.Context) CommandListener(net.robinfriedli.aiode.discord.listeners.CommandListener) Logger(org.slf4j.Logger) MessageService(net.robinfriedli.aiode.discord.MessageService) InvalidCommandException(net.robinfriedli.aiode.exceptions.InvalidCommandException) RateLimitException(net.robinfriedli.aiode.exceptions.RateLimitException) Set(java.util.Set) IOException(java.io.IOException) Conditions(net.robinfriedli.jxp.queries.Conditions) Collectors(java.util.stream.Collectors) CommandExceptionHandlerExecutor(net.robinfriedli.aiode.exceptions.handler.CommandExceptionHandlerExecutor) Aiode(net.robinfriedli.aiode.Aiode) List(java.util.List) Component(org.springframework.stereotype.Component) StoredScript(net.robinfriedli.aiode.entities.StoredScript) Optional(java.util.Optional) CommandExecutionTask(net.robinfriedli.aiode.concurrent.CommandExecutionTask) CommandRuntimeException(net.robinfriedli.aiode.exceptions.CommandRuntimeException) ScriptCommandInterceptor(net.robinfriedli.aiode.command.interceptor.interceptors.ScriptCommandInterceptor) StoredScript(net.robinfriedli.aiode.entities.StoredScript) Preset(net.robinfriedli.aiode.entities.Preset) CommandContribution(net.robinfriedli.aiode.entities.xml.CommandContribution)

Example 4 with Context

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();
    }
}
Also used : Context(net.robinfriedli.jxp.persist.Context) Guild(net.dv8tion.jda.api.entities.Guild) File(java.io.File) Session(org.hibernate.Session)

Example 5 with Context

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);
    }
}
Also used : CronJobService(net.robinfriedli.aiode.cron.CronJobService) Context(net.robinfriedli.jxp.persist.Context) CommandManager(net.robinfriedli.aiode.command.CommandManager) InputStream(java.io.InputStream) JxpBackend(net.robinfriedli.jxp.api.JxpBackend) StartupTaskContribution(net.robinfriedli.aiode.entities.xml.StartupTaskContribution) Logger(org.slf4j.Logger) Aiode(net.robinfriedli.aiode.Aiode) HttpServerManager(net.robinfriedli.aiode.servers.HttpServerManager)

Aggregations

Context (net.robinfriedli.jxp.persist.Context)10 XmlElement (net.robinfriedli.jxp.api.XmlElement)4 Logger (org.slf4j.Logger)4 File (java.io.File)3 JxpBackend (net.robinfriedli.jxp.api.JxpBackend)3 Conditions (net.robinfriedli.jxp.queries.Conditions)3 Session (org.hibernate.Session)3 IOException (java.io.IOException)2 InputStream (java.io.InputStream)2 List (java.util.List)2 Set (java.util.Set)2 Collectors (java.util.stream.Collectors)2 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)2 Guild (net.dv8tion.jda.api.entities.Guild)2 Aiode (net.robinfriedli.aiode.Aiode)2 MessageService (net.robinfriedli.aiode.discord.MessageService)2 StartupTaskContribution (net.robinfriedli.aiode.entities.xml.StartupTaskContribution)2 LoggerFactory (org.slf4j.LoggerFactory)2 Sets (com.google.api.client.util.Sets)1 Lists (com.google.common.collect.Lists)1