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());
}
}
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();
}
}
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);
}
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());
}
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);
}
Aggregations