Search in sources :

Example 16 with ObjectMappingException

use of ninja.leaping.configurate.objectmapping.ObjectMappingException in project Nucleus by NucleusPowered.

the class WorldCorrector method worldCheck.

public static void worldCheck() throws IOException, ObjectMappingException {
    final Map<String, UUID> m = get();
    // Now get the file out.
    Path path = Nucleus.getNucleus().getDataPath().resolve("worlduuids.json");
    ConfigurationLoader<ConfigurationNode> cl = GsonConfigurationLoader.builder().setPath(path).build();
    Map<String, UUID> ms = cl.load().getValue(new TypeToken<Map<String, UUID>>() {
    }, Maps.newHashMap());
    final Map<UUID, UUID> fromToConverter = Maps.newHashMap();
    for (String r : ms.keySet()) {
        UUID oldUuid = ms.get(r);
        @Nullable UUID newUuid = m.get(r);
        if (newUuid != null && !oldUuid.equals(newUuid)) {
            fromToConverter.put(newUuid, oldUuid);
        }
    }
    cl.save(cl.createEmptyNode().setValue(new TypeToken<Map<String, UUID>>() {
    }, m));
    if (fromToConverter.isEmpty()) {
        return;
    }
    MessageProvider mp = Nucleus.getNucleus().getMessageProvider();
    ConsoleSource cs = Sponge.getServer().getConsole();
    List<Text> msg = Lists.newArrayList();
    Nucleus.getNucleus().addX(msg, 0);
    msg.forEach(cs::sendMessage);
    cs.sendMessage(Text.of(TextColors.RED, "--------------------"));
    cs.sendMessage(mp.getTextMessageWithFormat("worldrepair.detected"));
    for (Map.Entry<UUID, UUID> u : fromToConverter.entrySet()) {
        cs.sendMessage(mp.getTextMessageWithFormat("worldrepair.worldlist", Sponge.getServer().getWorldProperties(u.getKey()).get().getWorldName(), u.getValue().toString(), u.getKey().toString()));
    }
    Method method;
    try {
        method = Sponge.getServer().getDefaultWorld().get().getClass().getDeclaredMethod("setUniqueId", UUID.class);
        method.setAccessible(true);
    } catch (NoSuchMethodException e) {
        cs.sendMessage(mp.getTextMessageWithFormat("worldrepair.whitelist.nocmd"));
        return;
    }
    cs.sendMessage(mp.getTextMessageWithFormat("worldrepair.whitelist.cmd"));
    cs.sendMessage(Text.of(TextColors.RED, "--------------------"));
    cs.sendMessage(mp.getTextMessageWithFormat("worldrepair.whitelist.cmd2"));
    Sponge.getServer().setHasWhitelist(true);
    Sponge.getCommandManager().register(Nucleus.getNucleus(), CommandSpec.builder().executor((s, a) -> {
        MessageProvider mpr = Nucleus.getNucleus().getMessageProvider();
        if (s instanceof ConsoleSource) {
            cs.sendMessage(mpr.getTextMessageWithFormat("worldrepair.repair.start"));
            Sponge.getEventManager().registerListener(Nucleus.getNucleus(), GameStoppedServerEvent.class, event -> {
                for (Map.Entry<UUID, UUID> meuu : fromToConverter.entrySet()) {
                    // Magic!
                    WorldProperties wp = Sponge.getServer().getWorldProperties(meuu.getKey()).orElseThrow(() -> new NoSuchElementException(mpr.getMessageWithFormat("worldrepair.repair.nouuid", meuu.getKey().toString())));
                    final String name = wp.getWorldName();
                    try {
                        cs.sendMessage(mpr.getTextMessageWithFormat("worldrepair.repair.try", name));
                        method.invoke(wp, meuu.getValue());
                        Sponge.getServer().saveWorldProperties(wp);
                        cs.sendMessage(mpr.getTextMessageWithFormat("worldrepair.repair.success", name));
                    } catch (Exception e) {
                        cs.sendMessage(mpr.getTextMessageWithFormat("worldrepair.repair.fail", name));
                        e.printStackTrace();
                    }
                }
                try {
                    cl.save(cl.createEmptyNode().setValue(new TypeToken<Map<String, UUID>>() {
                    }, get()));
                } catch (IOException | ObjectMappingException e) {
                    e.printStackTrace();
                }
            });
            Sponge.getServer().shutdown();
            return CommandResult.success();
        } else {
            s.sendMessage(mpr.getTextMessageWithFormat("command.consoleonly"));
            return CommandResult.empty();
        }
    }).build(), "repairuuids");
}
Also used : UUID(java.util.UUID) ObjectMappingException(ninja.leaping.configurate.objectmapping.ObjectMappingException) Path(java.nio.file.Path) MessageProvider(io.github.nucleuspowered.nucleus.internal.messages.MessageProvider) Text(org.spongepowered.api.text.Text) Method(java.lang.reflect.Method) IOException(java.io.IOException) NoSuchElementException(java.util.NoSuchElementException) IOException(java.io.IOException) ObjectMappingException(ninja.leaping.configurate.objectmapping.ObjectMappingException) ConfigurationNode(ninja.leaping.configurate.ConfigurationNode) TypeToken(com.google.common.reflect.TypeToken) ConsoleSource(org.spongepowered.api.command.source.ConsoleSource) Map(java.util.Map) Nullable(javax.annotation.Nullable) WorldProperties(org.spongepowered.api.world.storage.WorldProperties) NoSuchElementException(java.util.NoSuchElementException)

Example 17 with ObjectMappingException

use of ninja.leaping.configurate.objectmapping.ObjectMappingException in project Nucleus by NucleusPowered.

the class WorldMigrationSettingProcessor method process.

@Override
public void process(ConfigurationNode cn) throws ObjectMappingException {
    try {
        UUID uuid = cn.getValue(uuidTypeToken);
        getServiceUnchecked(UUIDChangeService.class).getMappedUUID(uuid).ifPresent(x -> {
            try {
                cn.setValue(uuidTypeToken, x);
            } catch (ObjectMappingException e) {
            // Don't bother
            }
        });
    } catch (Exception e) {
    // Swallow
    }
}
Also used : UUID(java.util.UUID) ObjectMappingException(ninja.leaping.configurate.objectmapping.ObjectMappingException) ObjectMappingException(ninja.leaping.configurate.objectmapping.ObjectMappingException)

Example 18 with ObjectMappingException

use of ninja.leaping.configurate.objectmapping.ObjectMappingException 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 19 with ObjectMappingException

use of ninja.leaping.configurate.objectmapping.ObjectMappingException in project HuskyCrates-Sponge by codeHusky.

the class CrateRewardHolderParser method itemFromNode.

private static ItemStack itemFromNode(ConfigurationNode itemRoot) {
    try {
        ItemStack item = ItemStack.builder().itemType(itemRoot.getNode("id").getValue(TypeToken.of(ItemType.class))).quantity(itemRoot.getNode("count").getInt(1)).add(Keys.DISPLAY_NAME, TextSerializers.FORMATTING_CODE.deserialize(itemRoot.getNode("name").getString())).build();
        if (!itemRoot.getNode("variant").isVirtual()) {
        //if(Sponge.getRegistry().getType(TreeType.class,itemRoot.getNode("variant").getString()).isPresent()) {
        //System.out.println(item.offer(Keys.TREE_TYPE,getTreeType(itemRoot.getNode("variant").getString("oak"))));
        //System.out.println(itemRoot.getNode("variant").getValue());
        //}
        }
        if (!itemRoot.getNode("lore").isVirtual()) {
            ArrayList<Text> lore = new ArrayList<>();
            for (String ll : itemRoot.getNode("lore").getList(TypeToken.of(String.class))) {
                lore.add(TextSerializers.FORMATTING_CODE.deserialize(ll));
            }
            item.offer(Keys.ITEM_LORE, lore);
        }
        if (!itemRoot.getNode("name").isVirtual()) {
            item.offer(Keys.DISPLAY_NAME, TextSerializers.FORMATTING_CODE.deserialize(itemRoot.getNode("name").getString()));
        }
        if (!itemRoot.getNode("enchants").isVirtual()) {
            ArrayList<ItemEnchantment> enchantments = new ArrayList<>();
            for (Object key : itemRoot.getNode("enchants").getChildrenMap().keySet()) {
                int level = itemRoot.getNode("enchants").getChildrenMap().get(key).getInt();
                String enchantID = (String) key;
                // STRINGS ONLY!
                Enchantment enc = getEnchantment(enchantID);
                ItemEnchantment itemEnchantment = new ItemEnchantment(enc, level);
                enchantments.add(itemEnchantment);
            }
            item.offer(Keys.ITEM_ENCHANTMENTS, enchantments);
        }
        if (!itemRoot.getNode("damage").isVirtual()) {
            //HuskyCrates.instance.logger.info("damage override called");
            item = ItemStack.builder().fromContainer(//OVERRIDE DAMAGE VAL! :)
            item.toContainer().set(DataQuery.of("UnsafeDamage"), itemRoot.getNode("damage").getInt(0))).build();
        }
        if (!itemRoot.getNode("nbt").isVirtual()) {
            //nbt overrrides
            LinkedHashMap items = (LinkedHashMap) itemRoot.getNode("nbt").getValue();
            if (item.toContainer().get(DataQuery.of("UnsafeData")).isPresent()) {
                BiMap real = ((BiMap) item.toContainer().getMap(DataQuery.of("UnsafeData")).get());
                items.putAll(real);
            }
            //System.out.println(item.toContainer().get(DataQuery.of("UnsafeData")).get().getClass());
            item = ItemStack.builder().fromContainer(item.toContainer().set(DataQuery.of("UnsafeData"), items)).build();
        }
        //item.offer(Keys.PICKUP_DELAY,itemRoot.getNode("pickupdelay").getInt())
        return item;
    } catch (ObjectMappingException e) {
        e.printStackTrace();
    }
    return null;
}
Also used : ItemType(org.spongepowered.api.item.ItemType) BiMap(com.google.common.collect.BiMap) ArrayList(java.util.ArrayList) Text(org.spongepowered.api.text.Text) LinkedHashMap(java.util.LinkedHashMap) ItemEnchantment(org.spongepowered.api.data.meta.ItemEnchantment) ItemStack(org.spongepowered.api.item.inventory.ItemStack) ItemEnchantment(org.spongepowered.api.data.meta.ItemEnchantment) Enchantment(org.spongepowered.api.item.Enchantment) ObjectMappingException(ninja.leaping.configurate.objectmapping.ObjectMappingException)

Example 20 with ObjectMappingException

use of ninja.leaping.configurate.objectmapping.ObjectMappingException in project ClearMob by axle2005.

the class Config method getList.

public List<String> getList(String node) {
    activeConfig = new File(getConfigDir().toFile(), "ClearMob.conf");
    configManager = HoconConfigurationLoader.builder().setFile(activeConfig).build();
    try {
        rootnode = configManager.load();
        if (!activeConfig.exists()) {
            // defaults(activeConfig, rootnode);
            saveConfig(rootnode, configManager);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    entitylist = new ArrayList<String>();
    try {
        String x = "";
        if (node.contains(",")) {
            String[] y = node.split(",");
            if (y.length == 2) {
                entitylist = rootnode.getNode(y[0], y[1]).getList(TypeToken.of(String.class));
            } else if (y.length == 3) {
                entitylist = rootnode.getNode(y[0], y[1], y[2]).getList(TypeToken.of(String.class));
            }
        } else
            entitylist = rootnode.getNode(node).getList(TypeToken.of(String.class));
    } catch (ObjectMappingException e) {
        e.printStackTrace();
    }
    return entitylist;
}
Also used : IOException(java.io.IOException) File(java.io.File) ObjectMappingException(ninja.leaping.configurate.objectmapping.ObjectMappingException)

Aggregations

ObjectMappingException (ninja.leaping.configurate.objectmapping.ObjectMappingException)30 IOException (java.io.IOException)21 ConfigurationNode (ninja.leaping.configurate.ConfigurationNode)10 CommentedConfigurationNode (ninja.leaping.configurate.commented.CommentedConfigurationNode)8 Map (java.util.Map)7 GsonConfigurationLoader (ninja.leaping.configurate.gson.GsonConfigurationLoader)6 Optional (java.util.Optional)5 Detection (com.ichorpowered.guardianapi.detection.Detection)4 Path (java.nio.file.Path)4 Set (java.util.Set)4 Text (org.spongepowered.api.text.Text)4 Maps (com.google.common.collect.Maps)3 ConfigurationAssignment (com.ichorpowered.guardian.content.assignment.ConfigurationAssignment)3 GuardianMapValue (com.ichorpowered.guardian.util.item.mutable.GuardianMapValue)3 GuardianValue (com.ichorpowered.guardian.util.item.mutable.GuardianValue)3 ContentContainer (com.ichorpowered.guardianapi.content.ContentContainer)3 ContentKey (com.ichorpowered.guardianapi.content.key.ContentKey)3 DetectionContentLoader (com.ichorpowered.guardianapi.detection.DetectionContentLoader)3 Key (com.ichorpowered.guardianapi.util.item.key.Key)3 MapValue (com.ichorpowered.guardianapi.util.item.value.mutable.MapValue)3