Search in sources :

Example 6 with Tuple

use of org.spongepowered.api.util.Tuple in project Nucleus by NucleusPowered.

the class SanityTests method testKeysAreNotParents.

private void testKeysAreNotParents(String bundle) throws Exception {
    // Get the resource
    ResourceBundle rb = ResourceBundle.getBundle(bundle, Locale.getDefault());
    Enumeration<String> keys = rb.getKeys();
    Set<String> s = new HashSet<>();
    while (keys.hasMoreElements()) {
        s.add(keys.nextElement());
    }
    Map<String, List<String>> filter = s.parallelStream().map(x -> Tuple.of(x.toLowerCase(), s.stream().filter(y -> x.toLowerCase().startsWith(y.toLowerCase() + ".") && !x.equalsIgnoreCase(y)).collect(Collectors.toList()))).filter(x -> !x.getSecond().isEmpty()).sorted(Comparator.comparing(Tuple::getFirst)).collect(Collectors.toMap(Tuple::getFirst, Tuple::getSecond));
    if (!filter.isEmpty()) {
        StringBuilder sb = new StringBuilder("Some keys are parents of others!").append(System.lineSeparator());
        filter.forEach((x, y) -> sb.append(x).append("->").append(y).append(System.lineSeparator()));
        Assert.fail(sb.toString());
    }
}
Also used : Enumeration(java.util.Enumeration) Constructor(java.lang.reflect.Constructor) RegisterServices(io.github.nucleuspowered.nucleus.internal.annotations.RegisterServices) HashSet(java.util.HashSet) Inject(javax.inject.Inject) Lists(com.google.common.collect.Lists) ResourceBundle(java.util.ResourceBundle) Locale(java.util.Locale) Map(java.util.Map) NucleusConfigAdapter(io.github.nucleuspowered.nucleus.internal.qsml.NucleusConfigAdapter) ClassPath(com.google.common.reflect.ClassPath) ModuleData(uk.co.drnaylor.quickstart.annotations.ModuleData) AbstractConfigAdapter(uk.co.drnaylor.quickstart.config.AbstractConfigAdapter) StandardModule(io.github.nucleuspowered.nucleus.internal.qsml.module.StandardModule) Set(java.util.Set) Test(org.junit.Test) IOException(java.io.IOException) Tuple(org.spongepowered.api.util.Tuple) Collectors(java.util.stream.Collectors) List(java.util.List) AbstractCommand(io.github.nucleuspowered.nucleus.internal.command.AbstractCommand) Stream(java.util.stream.Stream) RegisterService(io.github.nucleuspowered.nucleus.internal.annotations.RegisterService) Modifier(java.lang.reflect.Modifier) Assert(org.junit.Assert) Comparator(java.util.Comparator) ResourceBundle(java.util.ResourceBundle) List(java.util.List) Tuple(org.spongepowered.api.util.Tuple) HashSet(java.util.HashSet)

Example 7 with Tuple

use of org.spongepowered.api.util.Tuple in project Nucleus by NucleusPowered.

the class AbstractCommand method process.

private CommandResult process(CommandSource source, String command, String arguments, CommandArgs args) throws CommandException {
    // Phase one: child command processing. Keep track of all thrown arguments.
    List<Tuple<String, CommandException>> thrown = Lists.newArrayList();
    final CommandContext context = new CommandContext();
    T castedSource;
    try {
        // If we have a child command to execute, then we execute it.
        if (args.hasNext() && this.dispatcher.containsAlias(args.peek())) {
            Object state = args.getState();
            String next = args.next();
            try {
                // If this works, then we're A-OK.
                CommandCallable callable = this.dispatcher.get(next.toLowerCase()).get().getCallable();
                if (callable instanceof AbstractCommand) {
                    return ((AbstractCommand) callable).process(source, command + " " + next, arguments, args);
                }
                return callable.process(source, arguments);
            } catch (NucleusCommandException e) {
                // Didn't work out. Let's move on.
                thrown.addAll(e.getExceptions());
                if (!e.isAllowFallback()) {
                    throw e;
                }
            } catch (CommandException e) {
                // If the Exception is _not_ of right type, wrap it and add it. This shouldn't happen though.
                thrown.add(Tuple.of(command + " " + next, e));
            } finally {
                args.setState(state);
            }
        }
        // Phase one: test for what is required
        if (requiresEconomy && !plugin.getEconHelper().economyServiceExists()) {
            source.sendMessage(NucleusPlugin.getNucleus().getMessageProvider().getTextMessageWithFormat("command.economyrequired"));
            return CommandResult.empty();
        }
        // Phase two: source type - test to see if the person in question can execute this command.
        castedSource = checkSourceType(source);
        // Phase three - test the permission.
        if (!testPermissionOnSubject(castedSource)) {
            throw new CommandPermissionException();
        }
        if (!this.hasExecutor) {
            if (thrown.isEmpty()) {
                // OK, we just process the usage command instead.
                return this.usageCommand.process(source, "", args.nextIfPresent().map(String::toLowerCase).orElse(null));
            } else {
                throw new NucleusCommandException(thrown);
            }
        }
        // Phase four - create the context and parse the arguments.
        this.argumentParser.parse(source, args, context);
        if (args.hasNext()) {
            thrown.add(Tuple.of(command, new NucleusArgumentParseException(Text.of(TextColors.RED, "Too many arguments"), args.getRaw(), args.getRawPosition(), Text.of(getSimpleUsage(source)), getChildrenUsage(source).orElse(null), true)));
            throw new NucleusCommandException(thrown, allowFallback(source, args, context));
        }
    } catch (NucleusCommandException nce) {
        throw nce;
    } catch (ArgumentParseException ape) {
        // get the command to get the usage/subs from.
        thrown.add(Tuple.of(command, NucleusArgumentParseException.from(ape, Text.of(getSimpleUsage(source)), getChildrenUsage(source).orElse(null))));
        throw new NucleusCommandException(thrown, allowFallback(source, args, context));
    } catch (CommandException ex) {
        // Errors at this point are expected, so we'll run with it - no need for debug mode checks.
        thrown.add(Tuple.of(command, ex));
        throw new NucleusCommandException(thrown, allowFallback(source, args, context));
    } catch (Throwable throwable) {
        String m;
        if (throwable.getMessage() == null) {
            m = "null";
        } else {
            m = throwable.getMessage();
        }
        thrown.add(Tuple.of(command, new CommandException(Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("command.exception.unexpected", m), throwable)));
        // this is on demand, so we should throw it.
        throwable.printStackTrace();
        throw new NucleusCommandException(thrown, allowFallback(source, args, context));
    }
    try {
        commandTimings.startTimingIfSync();
        ContinueMode mode = preProcessChecks(castedSource, context);
        if (!mode.cont) {
            return mode.returnType;
        }
        if (castedSource instanceof Player) {
            @SuppressWarnings("unchecked") ContinueMode cm = runChecks((Player) castedSource, context);
            if (!cm.cont) {
                return cm.returnType;
            }
        }
        // If we're running async...
        if (isAsync) {
            // Create an executor that runs the command async.
            plugin.getLogger().debug("Running " + this.getClass().getName() + " in async mode.");
            Sponge.getScheduler().createAsyncExecutor(plugin).execute(() -> onExecute(castedSource, context));
            // Tell Sponge we're done.
            return CommandResult.success();
        }
        return onExecute(castedSource, context);
    } finally {
        commandTimings.stopTimingIfSync();
    }
}
Also used : CommandPermissionException(org.spongepowered.api.command.CommandPermissionException) Player(org.spongepowered.api.entity.living.player.Player) CommandContext(org.spongepowered.api.command.args.CommandContext) ArgumentParseException(org.spongepowered.api.command.args.ArgumentParseException) CommandException(org.spongepowered.api.command.CommandException) CommandCallable(org.spongepowered.api.command.CommandCallable) Tuple(org.spongepowered.api.util.Tuple)

Example 8 with Tuple

use of org.spongepowered.api.util.Tuple in project Nucleus by NucleusPowered.

the class NucleusCommandException method getText.

@Nullable
@Override
public Text getText() {
    if (exceptions.isEmpty()) {
        // Unable to get the error.
        return Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("command.exception.nomoreinfo");
    }
    MessageProvider mp = Nucleus.getNucleus().getMessageProvider();
    // Is it only command permission exceptions?
    if (exceptions.stream().allMatch(x -> CommandPermissionException.class.isInstance(x.getSecond()))) {
        return exceptions.get(0).getSecond().getText();
    }
    if (exceptions.stream().allMatch(x -> {
        CommandException e = x.getSecond();
        return e instanceof NucleusArgumentParseException && ((NucleusArgumentParseException) e).isEnd();
    })) {
        if (exceptions.size() == 1) {
            Tuple<String, CommandException> exceptionTuple = exceptions.get(0);
            return Text.of(mp.getTextMessageWithFormat("command.exception.fromcommand", exceptionTuple.getFirst()), Text.NEW_LINE, TextColors.RED, exceptionTuple.getSecond().getText());
        } else {
            return print(exceptions);
        }
    }
    List<Tuple<String, CommandException>> lce = exceptions.stream().filter(x -> {
        CommandException e = x.getSecond();
        return !(e instanceof NucleusArgumentParseException) || !((NucleusArgumentParseException) e).isEnd();
    }).filter(x -> !CommandPermissionException.class.isInstance(x)).collect(Collectors.toList());
    if (lce.size() == 1) {
        Tuple<String, CommandException> exceptionTuple = exceptions.get(0);
        return Text.of(mp.getTextMessageWithFormat("command.exception.fromcommand", exceptionTuple.getFirst()), Text.NEW_LINE, TextColors.RED, exceptionTuple.getSecond().getText());
    }
    return print(lce);
}
Also used : CommandException(org.spongepowered.api.command.CommandException) List(java.util.List) MessageProvider(io.github.nucleuspowered.nucleus.internal.messages.MessageProvider) CommandPermissionException(org.spongepowered.api.command.CommandPermissionException) Nucleus(io.github.nucleuspowered.nucleus.Nucleus) Text(org.spongepowered.api.text.Text) Tuple(org.spongepowered.api.util.Tuple) TextColors(org.spongepowered.api.text.format.TextColors) Collectors(java.util.stream.Collectors) Nullable(javax.annotation.Nullable) CommandPermissionException(org.spongepowered.api.command.CommandPermissionException) MessageProvider(io.github.nucleuspowered.nucleus.internal.messages.MessageProvider) CommandException(org.spongepowered.api.command.CommandException) Tuple(org.spongepowered.api.util.Tuple) Nullable(javax.annotation.Nullable)

Example 9 with Tuple

use of org.spongepowered.api.util.Tuple in project Nucleus by NucleusPowered.

the class NucleusItemStackSnapshotSerialiser method deserialize.

@Override
public NucleusItemStackSnapshot deserialize(TypeToken<?> type, ConfigurationNode value) throws ObjectMappingException {
    // Process enchantments, temporary fix before Sponge gets a more general fix in.
    boolean emptyEnchant = false;
    ConfigurationNode ench = value.getNode("UnsafeData", "ench");
    if (!ench.isVirtual()) {
        List<? extends ConfigurationNode> enchantments = ench.getChildrenList();
        if (enchantments.isEmpty()) {
            // Remove empty enchantment list.
            value.getNode("UnsafeData").removeChild("ench");
        } else {
            enchantments.forEach(x -> {
                try {
                    short id = Short.parseShort(x.getNode("id").getString());
                    short lvl = Short.parseShort(x.getNode("lvl").getString());
                    x.getNode("id").setValue(id);
                    x.getNode("lvl").setValue(lvl);
                } catch (NumberFormatException e) {
                    x.setValue(null);
                }
            });
        }
    }
    ConfigurationNode data = value.getNode("Data");
    if (!data.isVirtual() && data.hasListChildren()) {
        List<? extends ConfigurationNode> n = data.getChildrenList().stream().filter(x -> !x.getNode("DataClass").getString("").endsWith("SpongeEnchantmentData") || (!x.getNode("ManipulatorData", "ItemEnchantments").isVirtual() && x.getNode("ManipulatorData", "ItemEnchantments").hasListChildren())).collect(Collectors.toList());
        emptyEnchant = n.size() != data.getChildrenList().size();
        if (emptyEnchant) {
            if (n.isEmpty()) {
                value.removeChild("Data");
            } else {
                value.getNode("Data").setValue(n);
            }
        }
    }
    DataContainer dataContainer = DataTranslators.CONFIGURATION_NODE.translate(value);
    Set<DataQuery> ldq = dataContainer.getKeys(true);
    for (DataQuery dataQuery : ldq) {
        String el = dataQuery.asString(".");
        if (el.contains("$Array$")) {
            try {
                Tuple<DataQuery, Object> r = TypeHelper.getArray(dataQuery, dataContainer);
                dataContainer.set(r.getFirst(), r.getSecond());
            } catch (Exception e) {
                e.printStackTrace();
            }
            dataContainer.remove(dataQuery);
        }
    }
    ItemStack snapshot;
    try {
        snapshot = ItemStack.builder().fromContainer(dataContainer).build();
    } catch (Exception e) {
        return NucleusItemStackSnapshot.NONE;
    }
    if (emptyEnchant) {
        snapshot.offer(Keys.ITEM_ENCHANTMENTS, Lists.newArrayList());
        return new NucleusItemStackSnapshot(snapshot.createSnapshot());
    }
    if (snapshot.get(Keys.ITEM_ENCHANTMENTS).isPresent()) {
        // Reset the data.
        snapshot.offer(Keys.ITEM_ENCHANTMENTS, snapshot.get(Keys.ITEM_ENCHANTMENTS).get());
        return new NucleusItemStackSnapshot(snapshot.createSnapshot());
    }
    return new NucleusItemStackSnapshot(snapshot.createSnapshot());
}
Also used : TypeHelper(io.github.nucleuspowered.nucleus.util.TypeHelper) Keys(org.spongepowered.api.data.key.Keys) DataContainer(org.spongepowered.api.data.DataContainer) Set(java.util.Set) ItemStackSnapshot(org.spongepowered.api.item.inventory.ItemStackSnapshot) TypeToken(com.google.common.reflect.TypeToken) NucleusItemStackSnapshot(io.github.nucleuspowered.nucleus.configurate.wrappers.NucleusItemStackSnapshot) Tuple(org.spongepowered.api.util.Tuple) TypeSerializer(ninja.leaping.configurate.objectmapping.serialize.TypeSerializer) DataQuery(org.spongepowered.api.data.DataQuery) Collectors(java.util.stream.Collectors) ItemStack(org.spongepowered.api.item.inventory.ItemStack) List(java.util.List) Lists(com.google.common.collect.Lists) ObjectMappingException(ninja.leaping.configurate.objectmapping.ObjectMappingException) DataTranslators(org.spongepowered.api.data.persistence.DataTranslators) Map(java.util.Map) ConfigurationNode(ninja.leaping.configurate.ConfigurationNode) NucleusItemStackSnapshot(io.github.nucleuspowered.nucleus.configurate.wrappers.NucleusItemStackSnapshot) ObjectMappingException(ninja.leaping.configurate.objectmapping.ObjectMappingException) DataContainer(org.spongepowered.api.data.DataContainer) ConfigurationNode(ninja.leaping.configurate.ConfigurationNode) DataQuery(org.spongepowered.api.data.DataQuery) ItemStack(org.spongepowered.api.item.inventory.ItemStack)

Example 10 with Tuple

use of org.spongepowered.api.util.Tuple in project SpongeCommon by SpongePowered.

the class GetValueFilterSourceDelegate method write.

@Override
public Tuple<Integer, Integer> write(final ClassWriter cw, final MethodVisitor mv, final ListenerClassVisitor.DiscoveredMethod method, final int paramIdx, int local, final int[] plocals, final ListenerClassVisitor.ListenerParameter[] params) throws ClassNotFoundException {
    final Field targetField;
    try {
        targetField = this.anno.container().getField(this.anno.value());
    } catch (final NoSuchFieldException ex) {
        throw new IllegalArgumentException(String.format("Field %s specified by GetValue annotation was not found in container %s", this.anno.value(), this.anno.container()));
    }
    if (!Key.class.isAssignableFrom(targetField.getType())) {
        throw new IllegalArgumentException(String.format("Field %s.%s was not a Key", targetField.getName(), targetField.getType()));
    }
    final Type paramType = params[paramIdx].type();
    final Type eventType = params[0].type();
    // key := <container>.<value>
    final int keyIdx = local++;
    mv.visitFieldInsn(GETSTATIC, Type.getInternalName(this.anno.container()), this.anno.value(), Type.getDescriptor(Key.class));
    mv.visitVarInsn(ASTORE, keyIdx);
    final Label success = new Label();
    final Label failure = new Label();
    // for all parameters p' before `param` that inherit from ValueContainer, excluding the event itself
    for (int i = paramIdx - 1; i > 0; --i) {
        final ListenerClassVisitor.ListenerParameter param = params[i];
        if (!ValueContainer.class.isAssignableFrom(method.classByLoader(param.type().getClassName()))) {
            continue;
        }
        // p'
        mv.visitVarInsn(ALOAD, plocals[i - 1]);
        mv.visitVarInsn(ALOAD, keyIdx);
        // x = p'.get(key)
        mv.visitMethodInsn(INVOKEINTERFACE, param.type().getInternalName(), "get", GetValueFilterSourceDelegate.VALUE_CONTAINER_GET, true);
        // if (x.isPresent()) goto success
        mv.visitInsn(DUP);
        mv.visitMethodInsn(INVOKEVIRTUAL, GetValueFilterSourceDelegate.OPTIONAL.getInternalName(), "isPresent", GetValueFilterSourceDelegate.OPTIONAL_IS_PRESENT, false);
        mv.visitJumpInsn(IFNE, success);
        // drop the optional from the stack if we're unsuccessful
        mv.visitInsn(POP);
    }
    // since none have been reached yet
    // x = locals[1].cause().first(ValueContainer.class)
    mv.visitVarInsn(ALOAD, 1);
    mv.visitMethodInsn(INVOKEINTERFACE, eventType.getInternalName(), "cause", "()" + GetValueFilterSourceDelegate.CAUSE.getDescriptor(), true);
    mv.visitLdcInsn(GetValueFilterSourceDelegate.VALUE_CONTAINER);
    mv.visitMethodInsn(INVOKEVIRTUAL, GetValueFilterSourceDelegate.CAUSE.getInternalName(), "first", Type.getMethodDescriptor(GetValueFilterSourceDelegate.OPTIONAL, Type.getType(Class.class)), false);
    mv.visitInsn(DUP);
    // if (!x.isPresent()) goto failure;
    mv.visitMethodInsn(INVOKEVIRTUAL, GetValueFilterSourceDelegate.OPTIONAL.getInternalName(), "isPresent", GetValueFilterSourceDelegate.OPTIONAL_IS_PRESENT, false);
    mv.visitJumpInsn(IFEQ, failure);
    // event:
    // x = x.get().get(key)
    mv.visitMethodInsn(INVOKEVIRTUAL, GetValueFilterSourceDelegate.OPTIONAL.getInternalName(), "get", GetValueFilterSourceDelegate.OPTIONAL_GET, false);
    // Optional<ValueContainer>
    mv.visitVarInsn(ALOAD, keyIdx);
    mv.visitMethodInsn(INVOKEINTERFACE, GetValueFilterSourceDelegate.VALUE_CONTAINER.getInternalName(), "get", GetValueFilterSourceDelegate.VALUE_CONTAINER_GET, true);
    // if (x.isPresent()) goto success;
    mv.visitInsn(DUP);
    mv.visitMethodInsn(INVOKEVIRTUAL, GetValueFilterSourceDelegate.OPTIONAL.getInternalName(), "isPresent", GetValueFilterSourceDelegate.OPTIONAL_IS_PRESENT, false);
    mv.visitJumpInsn(IFNE, success);
    mv.visitLabel(failure);
    mv.visitInsn(ACONST_NULL);
    mv.visitInsn(ARETURN);
    mv.visitLabel(success);
    // x = x.get()
    mv.visitMethodInsn(INVOKEVIRTUAL, GetValueFilterSourceDelegate.OPTIONAL.getInternalName(), "get", GetValueFilterSourceDelegate.OPTIONAL_GET, false);
    if (paramType.getSort() < Type.ARRAY) {
        GeneratorUtils.visitUnboxingMethod(mv, paramType);
    } else {
        final Label success2 = new Label();
        mv.visitInsn(DUP);
        mv.visitTypeInsn(INSTANCEOF, paramType.getInternalName());
        mv.visitJumpInsn(IFNE, success2);
        mv.visitInsn(ACONST_NULL);
        mv.visitInsn(ARETURN);
        mv.visitLabel(success2);
    }
    final int paramLocal = local;
    local += paramType.getSize();
    mv.visitVarInsn(paramType.getOpcode(ISTORE), paramLocal);
    return new Tuple<>(local, paramLocal);
}
Also used : Field(java.lang.reflect.Field) Type(org.objectweb.asm.Type) ListenerClassVisitor(org.spongepowered.common.event.manager.ListenerClassVisitor) Label(org.objectweb.asm.Label) ValueContainer(org.spongepowered.api.data.value.ValueContainer) Key(org.spongepowered.api.data.Key) Tuple(org.spongepowered.api.util.Tuple)

Aggregations

Tuple (org.spongepowered.api.util.Tuple)23 List (java.util.List)9 Map (java.util.Map)8 ArrayList (java.util.ArrayList)7 Optional (java.util.Optional)7 Type (org.objectweb.asm.Type)7 IOException (java.io.IOException)6 Collectors (java.util.stream.Collectors)6 Text (org.spongepowered.api.text.Text)5 Vector3d (com.flowpowered.math.vector.Vector3d)3 Nucleus (io.github.nucleuspowered.nucleus.Nucleus)3 HashMap (java.util.HashMap)3 Set (java.util.Set)3 Label (org.objectweb.asm.Label)3 Lists (com.google.common.collect.Lists)2 Maps (com.google.common.collect.Maps)2 TypeToken (com.google.common.reflect.TypeToken)2 Util (io.github.nucleuspowered.nucleus.Util)2 Reloadable (io.github.nucleuspowered.nucleus.internal.interfaces.Reloadable)2 File (java.io.File)2