Search in sources :

Example 16 with EMPTY

use of org.apache.commons.lang3.StringUtils.EMPTY in project MantaroBot by Mantaro.

the class CustomCmds method custom.

@Subscribe
public void custom(CommandRegistry cr) {
    String any = "[\\d\\D]*?";
    cr.register("custom", new SimpleCommand(Category.UTILS) {

        @Override
        public void call(GuildMessageReceivedEvent event, String content, String[] args) {
            if (args.length < 1) {
                onHelp(event);
                return;
            }
            String action = args[0];
            if (action.equals("list") || action.equals("ls")) {
                if (!MantaroCore.hasLoadedCompletely()) {
                    event.getChannel().sendMessage("The bot hasn't been fully booted up yet... custom commands will be available shortly!").queue();
                    return;
                }
                String filter = event.getGuild().getId() + ":";
                List<String> commands = customCommands.keySet().stream().filter(s -> s.startsWith(filter)).map(s -> s.substring(filter.length())).collect(Collectors.toList());
                EmbedBuilder builder = new EmbedBuilder().setAuthor("Commands for this guild", null, event.getGuild().getIconUrl()).setColor(event.getMember().getColor());
                builder.setDescription(commands.isEmpty() ? "There is nothing here, just dust." : checkString(forType(commands)));
                event.getChannel().sendMessage(builder.build()).queue();
                return;
            }
            if (action.equals("view")) {
                if (args.length < 2) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "You need to specify the command and the response number!").queue();
                    return;
                }
                String cmd = args[1];
                CustomCommand command = db().getCustomCommand(event.getGuild(), cmd);
                if (command == null) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "There isn't a custom command with that name here!").queue();
                    return;
                }
                int number;
                try {
                    number = Integer.parseInt(args[2]) - 1;
                } catch (NumberFormatException e) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "That's not a number...").queue();
                    return;
                }
                if (command.getValues().size() < number) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "This commands has less responses than the number you specified...").queue();
                    return;
                }
                event.getChannel().sendMessage(String.format("**Response `%d` for custom command `%s`:** \n```\n%s```", (number + 1), command.getName(), command.getValues().get(number))).queue();
                return;
            }
            if (action.equals("raw")) {
                if (args.length < 2) {
                    onHelp(event);
                    return;
                }
                String cmd = args[1];
                if (!NAME_PATTERN.matcher(cmd).matches()) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "Not allowed character.").queue();
                    return;
                }
                CustomCommand custom = db().getCustomCommand(event.getGuild(), cmd);
                if (custom == null) {
                    event.getChannel().sendMessage(EmoteReference.ERROR2 + "There's no Custom Command ``" + cmd + "`` in this Guild.").queue();
                    return;
                }
                Pair<String, Integer> pair = DiscordUtils.embedList(custom.getValues(), Object::toString);
                String pasted = null;
                if (pair.getRight() < custom.getValues().size()) {
                    AtomicInteger i = new AtomicInteger();
                    pasted = Utils.paste(custom.getValues().stream().map(s -> i.incrementAndGet() + s).collect(Collectors.joining("\n")));
                }
                EmbedBuilder embed = baseEmbed(event, "Command \"" + cmd + "\":").setDescription(pair.getLeft()).setFooter("(Showing " + pair.getRight() + " responses of " + custom.getValues().size() + ")", null);
                if (pasted != null && pasted.contains("hastebin.com")) {
                    embed.addField("Pasted content", pasted, false);
                }
                event.getChannel().sendMessage(embed.build()).queue();
                return;
            }
            if (db().getGuild(event.getGuild()).getData().isCustomAdminLock() && !CommandPermission.ADMIN.test(event.getMember())) {
                event.getChannel().sendMessage("This guild only accepts custom command creation, edits, imports and eval from administrators.").queue();
                return;
            }
            if (action.equals("clear")) {
                if (!CommandPermission.ADMIN.test(event.getMember())) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot do that, silly.").queue();
                    return;
                }
                List<CustomCommand> customCommands = db().getCustomCommands(event.getGuild());
                if (customCommands.isEmpty()) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "There's no Custom Commands registered in this Guild, just dust.").queue();
                }
                int size = customCommands.size();
                customCommands.forEach(CustomCommand::deleteAsync);
                customCommands.forEach(c -> CustomCmds.customCommands.remove(c.getId()));
                event.getChannel().sendMessage(EmoteReference.PENCIL + "Cleared **" + size + " Custom Commands**!").queue();
                return;
            }
            if (args.length < 2) {
                onHelp(event);
                return;
            }
            String cmd = args[1];
            if (action.equals("make")) {
                if (!NAME_PATTERN.matcher(cmd).matches()) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "Not allowed character.").queue();
                    return;
                }
                List<String> responses = new ArrayList<>();
                boolean created = InteractiveOperations.create(event.getChannel(), 60, e -> {
                    if (!e.getAuthor().equals(event.getAuthor()))
                        return Operation.IGNORED;
                    String c = e.getMessage().getContentRaw();
                    if (!c.startsWith("&"))
                        return Operation.IGNORED;
                    c = c.substring(1);
                    if (c.startsWith("~>cancel") || c.startsWith("~>stop")) {
                        event.getChannel().sendMessage(EmoteReference.CORRECT + "Command Creation canceled.").queue();
                        return Operation.COMPLETED;
                    }
                    if (c.startsWith("~>save")) {
                        String arg = c.substring(6).trim();
                        String saveTo = !arg.isEmpty() ? arg : cmd;
                        if (!NAME_PATTERN.matcher(cmd).matches()) {
                            event.getChannel().sendMessage(EmoteReference.ERROR + "Not allowed character.").queue();
                            return Operation.RESET_TIMEOUT;
                        }
                        if (cmd.length() >= 100) {
                            event.getChannel().sendMessage(EmoteReference.ERROR + "Name is too long.").queue();
                            return Operation.RESET_TIMEOUT;
                        }
                        if (DefaultCommandProcessor.REGISTRY.commands().containsKey(saveTo) && !DefaultCommandProcessor.REGISTRY.commands().get(saveTo).equals(customCommand)) {
                            event.getChannel().sendMessage(EmoteReference.ERROR + "A command already exists with this name!").queue();
                            return Operation.RESET_TIMEOUT;
                        }
                        if (responses.isEmpty()) {
                            event.getChannel().sendMessage(EmoteReference.ERROR + "No responses were added. Stopping creation without saving...").queue();
                        } else {
                            CustomCommand custom = CustomCommand.of(event.getGuild().getId(), cmd, responses);
                            // save at DB
                            custom.saveAsync();
                            // reflect at local
                            customCommands.put(custom.getId(), custom.getValues());
                            // add mini-hack
                            DefaultCommandProcessor.REGISTRY.commands().put(cmd, customCommand);
                            event.getChannel().sendMessage(EmoteReference.CORRECT + "Saved to command ``" + cmd + "``!").queue();
                            // easter egg :D
                            TextChannelGround.of(event).dropItemWithChance(8, 2);
                        }
                        return Operation.COMPLETED;
                    }
                    responses.add(c.replace("@everyone", "[nice meme]").replace("@here", "[you tried]"));
                    e.getMessage().addReaction(EmoteReference.CORRECT.getUnicode()).queue();
                    return Operation.RESET_TIMEOUT;
                }) != null;
                if (created) {
                    event.getChannel().sendMessage(EmoteReference.PENCIL + "Started **\"Creation of Custom Command ``" + cmd + "``\"**!\nSend ``&~>stop`` to stop creation **without saving**.\nSend ``&~>save`` to stop creation an **save the new Command**. Send any text beginning with ``&`` to be added to the Command Responses.\nThis Interactive Operation ends without saving after 60 seconds of inactivity.").queue();
                } else {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "There's already an Interactive Operation happening on this channel.").queue();
                }
                return;
            }
            if (action.equals("eval")) {
                try {
                    runCustom(content.replace("eval ", ""), event);
                } catch (Exception e) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "There was an error while evaluating your command!" + (e.getMessage() == null ? "" : " (E: " + e.getMessage() + ")")).queue();
                }
                return;
            }
            if (action.equals("remove") || action.equals("rm")) {
                if (!NAME_PATTERN.matcher(cmd).matches()) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "Not allowed character.").queue();
                    return;
                }
                CustomCommand custom = db().getCustomCommand(event.getGuild(), cmd);
                if (custom == null) {
                    event.getChannel().sendMessage(EmoteReference.ERROR2 + "There's no Custom Command ``" + cmd + "`` in this Guild.").queue();
                    return;
                }
                // delete at DB
                custom.deleteAsync();
                // reflect at local
                customCommands.remove(custom.getId());
                // clear commands if none
                if (customCommands.keySet().stream().noneMatch(s -> s.endsWith(":" + cmd)))
                    DefaultCommandProcessor.REGISTRY.commands().remove(cmd);
                event.getChannel().sendMessage(EmoteReference.PENCIL + "Removed Custom Command ``" + cmd + "``!").queue();
                return;
            }
            if (action.equals("import")) {
                if (!NAME_WILDCARD_PATTERN.matcher(cmd).matches()) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "Not allowed character.").queue();
                    return;
                }
                Map<String, Guild> mapped = MantaroBot.getInstance().getMutualGuilds(event.getAuthor()).stream().collect(Collectors.toMap(ISnowflake::getId, g -> g));
                List<Pair<Guild, CustomCommand>> filtered = MantaroData.db().getCustomCommandsByName(("*" + cmd + "*").replace("*", any)).stream().map(customCommand -> {
                    Guild guild = mapped.get(customCommand.getGuildId());
                    return guild == null ? null : Pair.of(guild, customCommand);
                }).filter(Objects::nonNull).collect(Collectors.toList());
                if (filtered.size() == 0) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "There are no custom commands matching your search query.").queue();
                    return;
                }
                DiscordUtils.selectList(event, filtered, pair -> "``" + pair.getValue().getName() + "`` - Guild: ``" + pair.getKey() + "``", s -> baseEmbed(event, "Select the Command:").setDescription(s).setFooter("(You can only select custom commands from guilds that you are a member of)", null).build(), pair -> {
                    String cmdName = pair.getValue().getName();
                    List<String> responses = pair.getValue().getValues();
                    CustomCommand custom = CustomCommand.of(event.getGuild().getId(), cmdName, responses);
                    // save at DB
                    custom.saveAsync();
                    // reflect at local
                    customCommands.put(custom.getId(), custom.getValues());
                    event.getChannel().sendMessage(String.format("Imported custom command ``%s`` from guild `%s` with responses ``%s``", cmdName, pair.getKey().getName(), String.join("``, ``", responses))).queue();
                    // easter egg :D
                    TextChannelGround.of(event).dropItemWithChance(8, 2);
                });
                return;
            }
            if (args.length < 3) {
                onHelp(event);
                return;
            }
            String value = args[2];
            if (action.equals("edit")) {
                CustomCommand custom = db().getCustomCommand(event.getGuild(), cmd);
                if (custom == null) {
                    event.getChannel().sendMessage(EmoteReference.ERROR2 + "There's no Custom Command ``" + cmd + "`` in this Guild.").queue();
                    return;
                }
                String[] vals = StringUtils.splitArgs(value, 2);
                int where;
                try {
                    where = Math.abs(Integer.parseInt(vals[0]));
                } catch (NumberFormatException e) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "You need to specify a correct number to change!").queue();
                    return;
                }
                List<String> values = custom.getValues();
                if (where - 1 > values.size()) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot edit a non-existent index!").queue();
                    return;
                }
                if (vals[1].isEmpty()) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "Cannot edit to an empty response!").queue();
                    return;
                }
                custom.getValues().set(where - 1, vals[1]);
                custom.saveAsync();
                customCommands.put(custom.getId(), custom.getValues());
                event.getChannel().sendMessage(EmoteReference.CORRECT + "Edited response **#" + where + "** of the command `" + custom.getName() + "` correctly!").queue();
                return;
            }
            if (action.equals("rename")) {
                if (!NAME_PATTERN.matcher(cmd).matches() || !NAME_PATTERN.matcher(value).matches()) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "Not allowed character.").queue();
                    return;
                }
                if (DefaultCommandProcessor.REGISTRY.commands().containsKey(value) && !DefaultCommandProcessor.REGISTRY.commands().get(value).equals(customCommand)) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "A command already exists with this name!").queue();
                    return;
                }
                CustomCommand oldCustom = db().getCustomCommand(event.getGuild(), cmd);
                if (oldCustom == null) {
                    event.getChannel().sendMessage(EmoteReference.ERROR2 + "There's no Custom Command ``" + cmd + "`` in this Guild.").queue();
                    return;
                }
                CustomCommand newCustom = CustomCommand.of(event.getGuild().getId(), value, oldCustom.getValues());
                // change at DB
                oldCustom.deleteAsync();
                newCustom.saveAsync();
                // reflect at local
                customCommands.remove(oldCustom.getId());
                customCommands.put(newCustom.getId(), newCustom.getValues());
                // add mini-hack
                DefaultCommandProcessor.REGISTRY.commands().put(value, customCommand);
                // clear commands if none
                if (customCommands.keySet().stream().noneMatch(s -> s.endsWith(":" + cmd)))
                    DefaultCommandProcessor.REGISTRY.commands().remove(cmd);
                event.getChannel().sendMessage(EmoteReference.CORRECT + "Renamed command ``" + cmd + "`` to ``" + value + "``!").queue();
                // easter egg :D
                TextChannelGround.of(event).dropItemWithChance(8, 2);
                return;
            }
            if (action.equals("add") || action.equals("new")) {
                if (!NAME_PATTERN.matcher(cmd).matches()) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "Not allowed character.").queue();
                    return;
                }
                if (cmd.length() >= 100) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "Name is too long.").queue();
                    return;
                }
                if (DefaultCommandProcessor.REGISTRY.commands().containsKey(cmd) && !DefaultCommandProcessor.REGISTRY.commands().get(cmd).equals(customCommand)) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "A command already exists with this name!").queue();
                    return;
                }
                CustomCommand custom = CustomCommand.of(event.getGuild().getId(), cmd, Collections.singletonList(value.replace("@everyone", "[nice meme]").replace("@here", "[you tried]")));
                if (action.equals("add")) {
                    CustomCommand c = db().getCustomCommand(event, cmd);
                    if (c != null)
                        custom.getValues().addAll(c.getValues());
                }
                // save at DB
                custom.saveAsync();
                // reflect at local
                customCommands.put(custom.getId(), custom.getValues());
                // add mini-hack
                DefaultCommandProcessor.REGISTRY.commands().put(cmd, customCommand);
                event.getChannel().sendMessage(EmoteReference.CORRECT + "Saved to command ``" + cmd + "``!").queue();
                // easter egg :D
                TextChannelGround.of(event).dropItemWithChance(8, 2);
                return;
            }
            onHelp(event);
        }

        @Override
        public String[] splitArgs(String content) {
            return SPLIT_PATTERN.split(content, 3);
        }

        @Override
        public MessageEmbed help(GuildMessageReceivedEvent event) {
            return helpEmbed(event, "CustomCommand Manager").setDescription("**Manages the Custom Commands of the Guild.**").addField("Guide", "https://github.com/Mantaro/MantaroBot/wiki/Custom-Commands", false).addField("Usage:", "`~>custom` - Shows this help\n" + "`~>custom <list|ls>` - **List all commands. If detailed is supplied, it prints the responses of each command.**\n" + "`~>custom clear` - **Remove all Custom Commands from this Guild. (ADMIN-ONLY)**\n" + "`~>custom add <name> <response>` - **Creates or adds the response provided to a custom command.**\n" + "`~>custom make <name>` - **Starts a Interactive Operation to create a command with the specified name.**\n" + "`~>custom <remove|rm> <name>` - **Removes a command with an specific name.**\n" + "`~>custom import <search>` - **Imports a command from another guild you're in.**\n" + "`~>custom eval <response>` - **Tests how a custom command response will look**\n" + "`~>custom edit <name> <response number> <new content>` - **Edits one response of the specified command**\n" + "`~>custom view <name> <response number>` - **Views the content of one response**\n" + "`~>custom rename <previous name> <new name>` - **Renames a custom command**", false).addField("Considerations", "If you wish to dissallow normal people from making custom commands, run `~>opts admincustom true`", false).build();
        }
    });
}
Also used : CustomCommandStatsManager(net.kodehawa.mantarobot.commands.info.stats.manager.CustomCommandStatsManager) Module(net.kodehawa.mantarobot.core.modules.Module) java.util(java.util) DefaultCommandProcessor(net.kodehawa.mantarobot.core.processor.DefaultCommandProcessor) PostLoadEvent(net.kodehawa.mantarobot.core.listeners.events.PostLoadEvent) StringUtils(net.kodehawa.mantarobot.utils.StringUtils) Async(br.com.brjdevs.java.utils.async.Async) URL(java.net.URL) Utils(net.kodehawa.mantarobot.utils.Utils) DiscordUtils(net.kodehawa.mantarobot.utils.DiscordUtils) CategoryStatsManager(net.kodehawa.mantarobot.commands.info.stats.manager.CategoryStatsManager) MantaroBot(net.kodehawa.mantarobot.MantaroBot) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Pair(org.apache.commons.lang3.tuple.Pair) CommandRegistry(net.kodehawa.mantarobot.core.CommandRegistry) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ISnowflake(net.dv8tion.jda.core.entities.ISnowflake) Subscribe(com.google.common.eventbus.Subscribe) CommandStatsManager(net.kodehawa.mantarobot.commands.info.stats.manager.CommandStatsManager) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) MantaroCore(net.kodehawa.mantarobot.core.MantaroCore) TextChannelGround(net.kodehawa.mantarobot.commands.currency.TextChannelGround) CustomCommand(net.kodehawa.mantarobot.db.entities.CustomCommand) MantaroData.db(net.kodehawa.mantarobot.data.MantaroData.db) ConditionalCustoms(net.kodehawa.mantarobot.commands.custom.ConditionalCustoms) InteractiveOperations(net.kodehawa.mantarobot.core.listeners.operations.InteractiveOperations) AbstractCommand(net.kodehawa.mantarobot.core.modules.commands.base.AbstractCommand) Category(net.kodehawa.mantarobot.core.modules.commands.base.Category) SPLIT_PATTERN(net.kodehawa.mantarobot.utils.StringUtils.SPLIT_PATTERN) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Mapifier.map(net.kodehawa.mantarobot.commands.custom.Mapifier.map) GsonDataManager(net.kodehawa.mantarobot.utils.data.GsonDataManager) Collectors(java.util.stream.Collectors) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) Guild(net.dv8tion.jda.core.entities.Guild) Slf4j(lombok.extern.slf4j.Slf4j) CommandPermission(net.kodehawa.mantarobot.core.modules.commands.base.CommandPermission) CollectionUtils.random(br.com.brjdevs.java.utils.collections.CollectionUtils.random) Mapifier.dynamicResolve(net.kodehawa.mantarobot.commands.custom.Mapifier.dynamicResolve) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) EmbedJSON(net.kodehawa.mantarobot.commands.custom.EmbedJSON) MantaroData(net.kodehawa.mantarobot.data.MantaroData) HelpUtils.forType(net.kodehawa.mantarobot.commands.info.HelpUtils.forType) Pattern(java.util.regex.Pattern) Operation(net.kodehawa.mantarobot.core.listeners.operations.core.Operation) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) Guild(net.dv8tion.jda.core.entities.Guild) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) CustomCommand(net.kodehawa.mantarobot.db.entities.CustomCommand) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Pair(org.apache.commons.lang3.tuple.Pair) ISnowflake(net.dv8tion.jda.core.entities.ISnowflake) Subscribe(com.google.common.eventbus.Subscribe)

Example 17 with EMPTY

use of org.apache.commons.lang3.StringUtils.EMPTY in project metron by apache.

the class BasicStellarTest method testLogicalFunctions.

@Test
public void testLogicalFunctions() throws Exception {
    final Map<String, String> variableMap = new HashMap<String, String>() {

        {
            put("foo", "casey");
            put("ip", "192.168.0.1");
            put("ip_src_addr", "192.168.0.1");
            put("ip_dst_addr", "10.0.0.1");
            put("other_ip", "10.168.0.1");
            put("empty", "");
            put("spaced", "metron is great");
        }
    };
    Assert.assertTrue(runPredicate("IN_SUBNET(ip, '192.168.0.0/24')", new DefaultVariableResolver(v -> variableMap.get(v), v -> variableMap.containsKey(v))));
    Assert.assertTrue(runPredicate("IN_SUBNET(ip, '192.168.0.0/24', '11.0.0.0/24')", new DefaultVariableResolver(v -> variableMap.get(v), v -> variableMap.containsKey(v))));
    Assert.assertTrue(runPredicate("IN_SUBNET(ip, '192.168.0.0/24', '11.0.0.0/24') in [true]", new DefaultVariableResolver(v -> variableMap.get(v), v -> variableMap.containsKey(v))));
    Assert.assertTrue(runPredicate("true in IN_SUBNET(ip, '192.168.0.0/24', '11.0.0.0/24')", new DefaultVariableResolver(v -> variableMap.get(v), v -> variableMap.containsKey(v))));
    Assert.assertFalse(runPredicate("IN_SUBNET(ip_dst_addr, '192.168.0.0/24', '11.0.0.0/24')", new DefaultVariableResolver(v -> variableMap.get(v), v -> variableMap.containsKey(v))));
    Assert.assertFalse(runPredicate("IN_SUBNET(other_ip, '192.168.0.0/24')", new DefaultVariableResolver(v -> variableMap.get(v), v -> variableMap.containsKey(v))));
    boolean thrown = false;
    try {
        runPredicate("IN_SUBNET(blah, '192.168.0.0/24')", new DefaultVariableResolver(v -> variableMap.get(v), v -> variableMap.containsKey(v)));
    } catch (ParseException pe) {
        thrown = true;
    }
    Assert.assertTrue(thrown);
    Assert.assertTrue(runPredicate("true and STARTS_WITH(foo, 'ca')", new DefaultVariableResolver(v -> variableMap.get(v), v -> variableMap.containsKey(v))));
    Assert.assertTrue(runPredicate("true and STARTS_WITH(TO_UPPER(foo), 'CA')", new DefaultVariableResolver(v -> variableMap.get(v), v -> variableMap.containsKey(v))));
    Assert.assertTrue(runPredicate("(true and STARTS_WITH(TO_UPPER(foo), 'CA')) || true", new DefaultVariableResolver(v -> variableMap.get(v), v -> variableMap.containsKey(v))));
    Assert.assertTrue(runPredicate("true and ENDS_WITH(foo, 'sey')", new DefaultVariableResolver(v -> variableMap.get(v), v -> variableMap.containsKey(v))));
    Assert.assertTrue(runPredicate("not(IN_SUBNET(ip_src_addr, '192.168.0.0/24') and IN_SUBNET(ip_dst_addr, '192.168.0.0/24'))", new DefaultVariableResolver(v -> variableMap.get(v), v -> variableMap.containsKey(v))));
    Assert.assertTrue(runPredicate("IN_SUBNET(ip_src_addr, '192.168.0.0/24')", new DefaultVariableResolver(v -> variableMap.get(v), v -> variableMap.containsKey(v))));
    Assert.assertFalse(runPredicate("not(IN_SUBNET(ip_src_addr, '192.168.0.0/24'))", new DefaultVariableResolver(v -> variableMap.get(v), v -> variableMap.containsKey(v))));
    Assert.assertFalse(runPredicate("IN_SUBNET(ip_dst_addr, '192.168.0.0/24')", new DefaultVariableResolver(v -> variableMap.get(v), v -> variableMap.containsKey(v))));
    Assert.assertTrue(runPredicate("not(IN_SUBNET(ip_dst_addr, '192.168.0.0/24'))", new DefaultVariableResolver(v -> variableMap.get(v), v -> variableMap.containsKey(v))));
}
Also used : StellarProcessorUtils.run(org.apache.metron.stellar.common.utils.StellarProcessorUtils.run) java.util(java.util) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) StellarProcessorUtils.runPredicate(org.apache.metron.stellar.common.utils.StellarProcessorUtils.runPredicate) StellarProcessor(org.apache.metron.stellar.common.StellarProcessor) StellarFunction(org.apache.metron.stellar.dsl.StellarFunction) StellarProcessorUtils.validate(org.apache.metron.stellar.common.utils.StellarProcessorUtils.validate) Test(org.junit.Test) StringUtils(org.apache.commons.lang3.StringUtils) DefaultVariableResolver(org.apache.metron.stellar.dsl.DefaultVariableResolver) Stellar(org.apache.metron.stellar.dsl.Stellar) ClasspathFunctionResolver(org.apache.metron.stellar.dsl.functions.resolver.ClasspathFunctionResolver) Rule(org.junit.Rule) Ignore(org.junit.Ignore) Assert(org.junit.Assert) ParseException(org.apache.metron.stellar.dsl.ParseException) ExpectedException(org.junit.rules.ExpectedException) Joiner(com.google.common.base.Joiner) Context(org.apache.metron.stellar.dsl.Context) DefaultVariableResolver(org.apache.metron.stellar.dsl.DefaultVariableResolver) ParseException(org.apache.metron.stellar.dsl.ParseException) Test(org.junit.Test)

Example 18 with EMPTY

use of org.apache.commons.lang3.StringUtils.EMPTY in project apex-malhar by apache.

the class GPOUtils method serialize.

/**
 * Serializes the given {@link GPOMutable} object to an array of bytes.
 * @param gpo The {@link GPOMutable} object to serialize.
 * @param byteArrayList A byte array list to pack serialized data into. Note that
 * it is assumed that the byteArrayList is empty when passed to this method.
 * @return The serialized {@link GPOMutable} object.
 */
public static byte[] serialize(GPOMutable gpo, GPOByteArrayList byteArrayList) {
    int slength = serializedLength(gpo);
    byte[] sbytes = new byte[slength];
    MutableInt offset = new MutableInt(0);
    boolean[] fieldsBoolean = gpo.getFieldsBoolean();
    if (fieldsBoolean != null) {
        for (int index = 0; index < fieldsBoolean.length; index++) {
            serializeBoolean(fieldsBoolean[index], sbytes, offset);
        }
    }
    char[] fieldsCharacter = gpo.getFieldsCharacter();
    if (fieldsCharacter != null) {
        for (int index = 0; index < fieldsCharacter.length; index++) {
            serializeChar(fieldsCharacter[index], sbytes, offset);
        }
    }
    byte[] fieldsByte = gpo.getFieldsByte();
    if (fieldsByte != null) {
        for (int index = 0; index < fieldsByte.length; index++) {
            serializeByte(fieldsByte[index], sbytes, offset);
        }
    }
    short[] fieldsShort = gpo.getFieldsShort();
    if (fieldsShort != null) {
        for (int index = 0; index < fieldsShort.length; index++) {
            serializeShort(fieldsShort[index], sbytes, offset);
        }
    }
    int[] fieldsInteger = gpo.getFieldsInteger();
    if (fieldsInteger != null) {
        for (int index = 0; index < fieldsInteger.length; index++) {
            serializeInt(fieldsInteger[index], sbytes, offset);
        }
    }
    long[] fieldsLong = gpo.getFieldsLong();
    if (fieldsLong != null) {
        for (int index = 0; index < fieldsLong.length; index++) {
            serializeLong(fieldsLong[index], sbytes, offset);
        }
    }
    float[] fieldsFloat = gpo.getFieldsFloat();
    if (fieldsFloat != null) {
        for (int index = 0; index < fieldsFloat.length; index++) {
            serializeFloat(fieldsFloat[index], sbytes, offset);
        }
    }
    double[] fieldsDouble = gpo.getFieldsDouble();
    if (fieldsDouble != null) {
        for (int index = 0; index < fieldsDouble.length; index++) {
            serializeDouble(fieldsDouble[index], sbytes, offset);
        }
    }
    String[] fieldsString = gpo.getFieldsString();
    if (fieldsString != null) {
        for (int index = 0; index < fieldsString.length; index++) {
            serializeString(fieldsString[index], sbytes, offset);
        }
    }
    if (sbytes.length > 0) {
        byteArrayList.add(sbytes);
    }
    Object[] fieldsObject = gpo.getFieldsObject();
    Serde[] serdes = gpo.getFieldDescriptor().getSerdes();
    if (fieldsObject != null) {
        for (int index = 0; index < fieldsObject.length; index++) {
            byteArrayList.add(serdes[index].serializeObject(fieldsObject[index]));
        }
    }
    byte[] bytes = byteArrayList.toByteArray();
    byteArrayList.clear();
    return bytes;
}
Also used : MutableInt(org.apache.commons.lang3.mutable.MutableInt) JSONObject(org.codehaus.jettison.json.JSONObject)

Example 19 with EMPTY

use of org.apache.commons.lang3.StringUtils.EMPTY in project magnolia-vanity-url by aperto.

the class VanityUrlService method createRedirectUrl.

/**
 * Creates the redirect url for uri mapping.
 * Without context path, because of Magnolia's {@link info.magnolia.cms.util.RequestDispatchUtil}.
 *
 * @param node vanity url node
 * @return redirect url
 */
protected String createRedirectUrl(final Node node) {
    String result;
    String type = getString(node, PN_TYPE, EMPTY);
    String prefix;
    if ("forward".equals(type)) {
        result = createForwardLink(node);
        prefix = FORWARD_PREFIX;
    } else {
        result = createTargetLink(node);
        prefix = "301".equals(type) ? PERMANENT_PREFIX : REDIRECT_PREFIX;
    }
    if (isNotEmpty(result)) {
        result = prefix + result;
    }
    return result;
}
Also used : PropertyUtil.getString(info.magnolia.jcr.util.PropertyUtil.getString) StringUtils.defaultString(org.apache.commons.lang3.StringUtils.defaultString)

Example 20 with EMPTY

use of org.apache.commons.lang3.StringUtils.EMPTY in project alf.io by alfio-event.

the class DynamicResourcesController method getGoogleAnalyticsScript.

@RequestMapping("/resources/js/google-analytics")
public void getGoogleAnalyticsScript(HttpSession session, HttpServletResponse response, @RequestParam("e") Integer eventId) throws IOException {
    response.setContentType("application/javascript");
    Optional<Event> ev = Optional.ofNullable(eventId).flatMap(id -> Optional.ofNullable(eventRepository.findById(id)));
    ConfigurationPathKey pathKey = ev.map(e -> Configuration.from(e.getOrganizationId(), e.getId(), GOOGLE_ANALYTICS_KEY)).orElseGet(() -> Configuration.getSystemConfiguration(GOOGLE_ANALYTICS_KEY));
    final Optional<String> id = configurationManager.getStringConfigValue(pathKey);
    final String script;
    ConfigurationPathKey anonymousPathKey = ev.map(e -> Configuration.from(e.getOrganizationId(), e.getId(), GOOGLE_ANALYTICS_ANONYMOUS_MODE)).orElseGet(() -> Configuration.getSystemConfiguration(GOOGLE_ANALYTICS_ANONYMOUS_MODE));
    if (id.isPresent() && configurationManager.getBooleanConfigValue(anonymousPathKey, true)) {
        String trackingId = Optional.ofNullable(StringUtils.trimToNull((String) session.getAttribute("GA_TRACKING_ID"))).orElseGet(() -> UUID.randomUUID().toString());
        Map<String, Object> model = new HashMap<>();
        model.put("clientId", trackingId);
        model.put("account", id.get());
        script = templateManager.renderTemplate(TemplateResource.GOOGLE_ANALYTICS, model, Locale.ENGLISH);
    } else {
        script = id.map(x -> String.format(GOOGLE_ANALYTICS_SCRIPT, x)).orElse(EMPTY);
    }
    response.getWriter().write(script);
}
Also used : ConfigurationPathKey(alfio.model.system.Configuration.ConfigurationPathKey) HttpSession(javax.servlet.http.HttpSession) RequestParam(org.springframework.web.bind.annotation.RequestParam) java.util(java.util) ConfigurationPathKey(alfio.model.system.Configuration.ConfigurationPathKey) GOOGLE_ANALYTICS_KEY(alfio.model.system.ConfigurationKeys.GOOGLE_ANALYTICS_KEY) TemplateManager(alfio.util.TemplateManager) HttpServletResponse(javax.servlet.http.HttpServletResponse) Autowired(org.springframework.beans.factory.annotation.Autowired) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) IOException(java.io.IOException) ConfigurationManager(alfio.manager.system.ConfigurationManager) Controller(org.springframework.stereotype.Controller) EventRepository(alfio.repository.EventRepository) StringUtils(org.apache.commons.lang3.StringUtils) GOOGLE_ANALYTICS_ANONYMOUS_MODE(alfio.model.system.ConfigurationKeys.GOOGLE_ANALYTICS_ANONYMOUS_MODE) Configuration(alfio.model.system.Configuration) Event(alfio.model.Event) TemplateResource(alfio.util.TemplateResource) Event(alfio.model.Event) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

List (java.util.List)44 Map (java.util.Map)42 ArrayList (java.util.ArrayList)41 StringUtils (org.apache.commons.lang3.StringUtils)38 Collectors (java.util.stream.Collectors)37 HashMap (java.util.HashMap)33 IOException (java.io.IOException)27 Set (java.util.Set)25 HashSet (java.util.HashSet)22 LoggerFactory (org.slf4j.LoggerFactory)22 Pair (org.apache.commons.lang3.tuple.Pair)20 Logger (org.slf4j.Logger)20 Optional (java.util.Optional)19 Collections (java.util.Collections)17 ImmutablePair (org.apache.commons.lang3.tuple.ImmutablePair)17 java.util (java.util)15 Arrays.asList (java.util.Arrays.asList)14 Collection (java.util.Collection)14 Stream (java.util.stream.Stream)14 Arrays (java.util.Arrays)12