Search in sources :

Example 1 with NexusException

use of gg.projecteden.nexus.framework.exceptions.NexusException in project Nexus by ProjectEdenGG.

the class ICustomCommand method convert.

@SneakyThrows
private Object convert(String value, Object context, Class<?> type, Parameter parameter, String name, CommandEvent event, boolean required) {
    Arg annotation = parameter.getDeclaredAnnotation(Arg.class);
    double argMinDefault = (Double) Arg.class.getDeclaredMethod("min").getDefaultValue();
    double argMaxDefault = (Double) Arg.class.getDeclaredMethod("max").getDefaultValue();
    if (annotation != null) {
        if (annotation.regex().length() > 0)
            if (!value.matches(annotation.regex()))
                throw new InvalidInputException(camelCase(name) + " must match regex " + annotation.regex());
        if (!isNumber(type))
            if (isNullOrEmpty(annotation.minMaxBypass()) || !event.getSender().hasPermission(annotation.minMaxBypass()))
                if (value.length() < annotation.min() || value.length() > annotation.max()) {
                    DecimalFormat formatter = StringUtils.getFormatter(Integer.class);
                    String min = formatter.format(annotation.min());
                    String max = formatter.format(annotation.max());
                    double minDefault = (Double) Arg.class.getDeclaredMethod("min").getDefaultValue();
                    double maxDefault = (Double) Arg.class.getDeclaredMethod("max").getDefaultValue();
                    String error = camelCase(name) + " length must be ";
                    if (annotation.min() == minDefault && annotation.max() != maxDefault)
                        throw new InvalidInputException(error + "&e" + max + " &ccharacters or shorter");
                    else if (annotation.min() != minDefault && annotation.max() == maxDefault)
                        throw new InvalidInputException(error + "&e" + min + " &ccharacters or longer");
                    else
                        throw new InvalidInputException(error + "between &e" + min + " &cand &e" + max + " &ccharacters");
                }
    }
    if (Collection.class.isAssignableFrom(type)) {
        if (annotation == null)
            throw new InvalidInputException("Collection parameter must define concrete type with @Arg");
        List<Object> values = new ArrayList<>();
        for (String index : value.split(COMMA_SPLIT_REGEX)) values.add(convert(index, context, annotation.type(), parameter, name, event, required));
        values.removeIf(Objects::isNull);
        return values;
    }
    try {
        CustomCommand command = event.getCommand();
        if (Commands.getConverters().containsKey(type)) {
            Method converter = Commands.getConverters().get(type);
            boolean isAbstract = Modifier.isAbstract(converter.getDeclaringClass().getModifiers());
            if (!(isAbstract || converter.getDeclaringClass().equals(command.getClass())))
                command = getNewCommand(command.getEvent(), converter.getDeclaringClass());
            if (converter.getParameterCount() == 1)
                return converter.invoke(command, value);
            else if (converter.getParameterCount() == 2)
                return converter.invoke(command, value, context);
            else
                throw new NexusException("Unknown converter parameters in " + converter.getName());
        } else if (type.isEnum()) {
            return convertToEnum(value, (Class<? extends Enum<?>>) type);
        } else if (PlayerOwnedObject.class.isAssignableFrom(type)) {
            return convertToPlayerOwnedObject(value, (Class<? extends PlayerOwnedObject>) type);
        }
    } catch (InvocationTargetException ex) {
        if (Nexus.isDebug())
            ex.printStackTrace();
        if (required)
            if (!isNullOrEmpty(value) && conversionExceptions.contains(ex.getCause().getClass()))
                throw ex;
            else
                throw new MissingArgumentException();
        else
            return null;
    }
    if (isNullOrEmpty(value))
        if (required)
            throw new MissingArgumentException();
        else if (type.isPrimitive())
            return getDefaultPrimitiveValue(type);
        else
            return null;
    if (Boolean.class == type || Boolean.TYPE == type) {
        if (Arrays.asList("enable", "on", "yes", "1").contains(value))
            value = "true";
        return Boolean.parseBoolean(value);
    }
    try {
        Number number = null;
        if (Integer.class == type || Integer.TYPE == type)
            number = Integer.parseInt(value);
        if (Double.class == type || Double.TYPE == type)
            number = Double.parseDouble(value);
        if (Float.class == type || Float.TYPE == type)
            number = Float.parseFloat(value);
        if (Short.class == type || Short.TYPE == type)
            number = Short.parseShort(value);
        if (Long.class == type || Long.TYPE == type)
            number = Long.parseLong(value);
        if (Byte.class == type || Byte.TYPE == type)
            number = Byte.parseByte(value);
        if (BigDecimal.class == type)
            number = BigDecimal.valueOf(Double.parseDouble(asParsableDecimal(value)));
        if (number != null) {
            if (annotation != null) {
                if (isNullOrEmpty(annotation.minMaxBypass()) || !event.getSender().hasPermission(annotation.minMaxBypass())) {
                    double annotationDefaultMin = (Double) Arg.class.getDeclaredMethod("min").getDefaultValue();
                    double annotationDefaultMax = (Double) Arg.class.getDeclaredMethod("max").getDefaultValue();
                    double annotationConfiguredMin = annotation.min();
                    double annotationConfiguredMax = annotation.max();
                    Number classDefaultMin = getMinValue(type);
                    Number classDefaultMax = getMaxValue(type);
                    BigDecimal min = (annotationConfiguredMin != annotationDefaultMin ? BigDecimal.valueOf(annotationConfiguredMin) : new BigDecimal(classDefaultMin.toString()));
                    BigDecimal max = (annotationConfiguredMax != annotationDefaultMax ? BigDecimal.valueOf(annotationConfiguredMax) : new BigDecimal(classDefaultMax.toString()));
                    int minComparison = BigDecimal.valueOf(number.doubleValue()).compareTo(min);
                    int maxComparison = BigDecimal.valueOf(number.doubleValue()).compareTo(max);
                    if (minComparison < 0 || maxComparison > 0) {
                        DecimalFormat formatter = StringUtils.getFormatter(type);
                        boolean usingDefaultMin = annotationDefaultMin == annotationConfiguredMin;
                        boolean usingDefaultMax = annotationDefaultMax == annotationConfiguredMax;
                        String minFormatted = formatter.format(annotation.min());
                        String maxFormatted = formatter.format(annotation.max());
                        String error = camelCase(name) + " must be ";
                        if (usingDefaultMin && !usingDefaultMax)
                            throw new InvalidInputException(error + "&e" + maxFormatted + " &cor less");
                        else if (!usingDefaultMin && usingDefaultMax)
                            throw new InvalidInputException(error + "&e" + minFormatted + " &cor greater");
                        else
                            throw new InvalidInputException(error + "between &e" + minFormatted + " &cand &e" + maxFormatted);
                    }
                }
            }
            return number;
        }
    } catch (NumberFormatException ex) {
        throw new InvalidInputException("&e" + value + " &cis not a valid " + (type == BigDecimal.class ? "number" : type.getSimpleName().toLowerCase()));
    }
    return value;
}
Also used : DecimalFormat(java.text.DecimalFormat) ArrayList(java.util.ArrayList) PathParser.getPathString(gg.projecteden.nexus.framework.commands.models.PathParser.getPathString) Utils.isBoolean(gg.projecteden.nexus.utils.Utils.isBoolean) InvalidInputException(gg.projecteden.nexus.framework.exceptions.postconfigured.InvalidInputException) MissingArgumentException(gg.projecteden.nexus.framework.exceptions.preconfigured.MissingArgumentException) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException) BigDecimal(java.math.BigDecimal) Arg(gg.projecteden.nexus.framework.commands.models.annotations.Arg) Objects(java.util.Objects) PlayerOwnedObject(gg.projecteden.interfaces.PlayerOwnedObject) NexusException(gg.projecteden.nexus.framework.exceptions.NexusException) SneakyThrows(lombok.SneakyThrows)

Example 2 with NexusException

use of gg.projecteden.nexus.framework.exceptions.NexusException in project Nexus by ProjectEdenGG.

the class ReactionVoter method run.

public void run() {
    getChannel().retrieveMessageById(messageId).queue(message -> {
        MessageReaction white_check_mark = null;
        MessageReaction x = null;
        String unicode_white_check_mark = EmojiManager.getForAlias("white_check_mark").getUnicode();
        String unicode_x = EmojiManager.getForAlias("x").getUnicode();
        for (MessageReaction reaction : message.getReactions()) {
            String name = reaction.getReactionEmote().getName();
            if (unicode_x.equals(name))
                x = reaction;
            else if (unicode_white_check_mark.equals(name))
                white_check_mark = reaction;
        }
        if (x == null) {
            message.addReaction(unicode_x).queue();
        } else if (x.getCount() > 1) {
            if (onDeny != null)
                onDeny.accept(message);
            if (onFinally != null)
                onFinally.run();
            return;
        }
        if (white_check_mark == null) {
            message.addReaction(unicode_white_check_mark).queue();
        } else {
            white_check_mark.retrieveUsers().queue(users -> {
                Map<Role, Integer> votesByRole = new HashMap<>();
                // TODO Better logic
                users.forEach(user -> {
                    Member member = Discord.getGuild().getMember(user);
                    if (member == null)
                        throw new NexusException("Member from " + Discord.getName(user) + " not found");
                    Role role = Role.of(member.getRoles().get(0));
                    if (Role.OWNER.equals(role))
                        role = Role.ADMINS;
                    if (Role.OPERATORS.equals(role) || Role.BUILDERS.equals(role) || Role.ARCHITECTS.equals(role))
                        role = Role.MODERATORS;
                    votesByRole.put(role, votesByRole.getOrDefault(role, 0) + 1);
                });
                AtomicBoolean passed = new AtomicBoolean(true);
                requiredVotes.forEach((role, required) -> {
                    if (!votesByRole.containsKey(role))
                        passed.set(false);
                    else if (votesByRole.get(role) < required)
                        passed.set(false);
                });
                if (passed.get()) {
                    if (onAccept != null)
                        onAccept.accept(message);
                    if (onFinally != null)
                        onFinally.run();
                }
            });
        }
    }, error -> {
        if (onError != null)
            onError.accept(error);
        if (onFinally != null)
            onFinally.run();
    });
}
Also used : Role(gg.projecteden.utils.DiscordId.Role) MessageReaction(net.dv8tion.jda.api.entities.MessageReaction) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) Member(net.dv8tion.jda.api.entities.Member) NexusException(gg.projecteden.nexus.framework.exceptions.NexusException)

Example 3 with NexusException

use of gg.projecteden.nexus.framework.exceptions.NexusException in project Nexus by ProjectEdenGG.

the class Crates method onClickWithKey.

@EventHandler
public void onClickWithKey(PlayerInteractEvent event) {
    try {
        if (!Utils.ActionGroup.CLICK_BLOCK.applies(event))
            return;
        if (event.getClickedBlock() == null)
            return;
        CrateType locationType = CrateType.fromLocation(event.getClickedBlock().getLocation());
        if (locationType == null)
            return;
        event.setCancelled(true);
        Location location = LocationUtils.getCenteredLocation(event.getClickedBlock().getLocation());
        if (event.getHand() == null)
            return;
        if (!event.getHand().equals(EquipmentSlot.HAND))
            return;
        if (!enabled)
            throw new CrateOpeningException("Crates are temporarily disabled");
        if (RebootCommand.isQueued())
            throw new CrateOpeningException("Server reboot is queued, cannot open crates");
        CrateType keyType = CrateType.fromKey(event.getItem());
        if (locationType != keyType && locationType != CrateType.ALL)
            if (Crates.getLootByType(locationType).stream().filter(CrateLoot::isActive).toArray().length == 0)
                throw new CrateOpeningException("&3Coming soon...");
            else
                locationType.previewDrops(null).open(event.getPlayer());
        else if (keyType != null)
            try {
                if (event.getPlayer().isSneaking() && event.getItem().getAmount() > 1)
                    keyType.getCrateClass().openMultiple(location, event.getPlayer(), event.getItem().getAmount());
                else
                    keyType.getCrateClass().openCrate(location, event.getPlayer());
            } catch (CrateOpeningException ex) {
                if (ex.getMessage() != null)
                    PlayerUtils.send(event.getPlayer(), Crates.PREFIX + ex.getMessage());
                keyType.getCrateClass().reset();
            }
    } catch (NexusException ex) {
        PlayerUtils.send(event.getPlayer(), ex.withPrefix(Crates.PREFIX));
    }
}
Also used : CrateType(gg.projecteden.nexus.features.crates.models.CrateType) CrateLoot(gg.projecteden.nexus.features.crates.models.CrateLoot) CrateOpeningException(gg.projecteden.nexus.framework.exceptions.postconfigured.CrateOpeningException) Location(org.bukkit.Location) NexusException(gg.projecteden.nexus.framework.exceptions.NexusException) EventHandler(org.bukkit.event.EventHandler)

Example 4 with NexusException

use of gg.projecteden.nexus.framework.exceptions.NexusException in project Nexus by ProjectEdenGG.

the class EndOfMonth method run.

public static CompletableFuture<Void> run(YearMonth yearMonth) {
    CompletableFuture<Void> future = new CompletableFuture<>();
    Tasks.async(() -> {
        try {
            TopVoterData data = new TopVoterData(yearMonth);
            final String discordMessage = data.getDiscordMessage();
            Nexus.log(discordMessage);
            Koda.announce(discordMessage);
            Votes.write();
            if (data.getMysteryChestWinner() != null)
                CrateType.MYSTERY.give(PlayerUtils.getPlayer(data.getMysteryChestWinner().getVoter()));
            Tasks.sync(() -> {
                BankerService bankerService = new BankerService();
                data.getEco30kWinners().forEach(topVoter -> bankerService.deposit(topVoter.getVoter(), 30000, ShopGroup.SURVIVAL, TransactionCause.VOTE_REWARD));
                data.getEco20kWinners().forEach(topVoter -> bankerService.deposit(topVoter.getVoter(), 20000, ShopGroup.SURVIVAL, TransactionCause.VOTE_REWARD));
                data.getEco15kWinners().forEach(topVoter -> bankerService.deposit(topVoter.getVoter(), 15000, ShopGroup.SURVIVAL, TransactionCause.VOTE_REWARD));
                future.complete(null);
            });
        } catch (NexusException ex) {
            Nexus.warn("[Votes] [End Of Month] " + ex.getMessage());
        }
    });
    return future;
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) BankerService(gg.projecteden.nexus.models.banker.BankerService) NexusException(gg.projecteden.nexus.framework.exceptions.NexusException)

Example 5 with NexusException

use of gg.projecteden.nexus.framework.exceptions.NexusException in project Nexus by ProjectEdenGG.

the class WorldUtils method getWorldSetting.

public static int getWorldSetting(World world, String setting) {
    ConfigurationSection section = Bukkit.getServer().spigot().getSpigotConfig().getConfigurationSection("world-settings");
    if (section == null)
        throw new NexusException("Could not find `world-settings` section in spigot.yml");
    ConfigurationSection worldSection = section.getConfigurationSection(world.getName());
    if (worldSection != null)
        if (worldSection.contains(setting))
            return worldSection.getInt(setting);
    ConfigurationSection defaultSection = section.getConfigurationSection("default");
    if (defaultSection == null)
        throw new NexusException("Could not find `world-settings.default` section in spigot.yml");
    if (!defaultSection.contains(setting))
        throw new NexusException("Could not find `world-settings.default." + setting + "` in spigot.yml");
    return defaultSection.getInt(setting);
}
Also used : ConfigurationSection(org.bukkit.configuration.ConfigurationSection) NexusException(gg.projecteden.nexus.framework.exceptions.NexusException)

Aggregations

NexusException (gg.projecteden.nexus.framework.exceptions.NexusException)6 ProfileProperty (com.destroystokyo.paper.profile.ProfileProperty)1 PlayerOwnedObject (gg.projecteden.interfaces.PlayerOwnedObject)1 CrateLoot (gg.projecteden.nexus.features.crates.models.CrateLoot)1 CrateType (gg.projecteden.nexus.features.crates.models.CrateType)1 PathParser.getPathString (gg.projecteden.nexus.framework.commands.models.PathParser.getPathString)1 Arg (gg.projecteden.nexus.framework.commands.models.annotations.Arg)1 CrateOpeningException (gg.projecteden.nexus.framework.exceptions.postconfigured.CrateOpeningException)1 InvalidInputException (gg.projecteden.nexus.framework.exceptions.postconfigured.InvalidInputException)1 MissingArgumentException (gg.projecteden.nexus.framework.exceptions.preconfigured.MissingArgumentException)1 BankerService (gg.projecteden.nexus.models.banker.BankerService)1 Utils.isBoolean (gg.projecteden.nexus.utils.Utils.isBoolean)1 Role (gg.projecteden.utils.DiscordId.Role)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 Method (java.lang.reflect.Method)1 BigDecimal (java.math.BigDecimal)1 DecimalFormat (java.text.DecimalFormat)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 Objects (java.util.Objects)1