Search in sources :

Example 1 with YAMLProcessor

use of com.sk89q.util.yaml.YAMLProcessor in project WorldGuard by EngineHub.

the class YamlRegionFile method loadAll.

@Override
public Set<ProtectedRegion> loadAll(FlagRegistry flagRegistry) throws StorageException {
    Map<String, ProtectedRegion> loaded = new HashMap<>();
    YAMLProcessor config = createYamlProcessor(file);
    try {
        config.load();
    } catch (FileNotFoundException e) {
        return new HashSet<>(loaded.values());
    } catch (IOException | ParserException e) {
        throw new StorageException("Failed to load region data from '" + file + "'", e);
    }
    Map<String, YAMLNode> regionData = config.getNodes("regions");
    if (regionData == null) {
        // No regions are even configured
        return Collections.emptySet();
    }
    Map<ProtectedRegion, String> parentSets = new LinkedHashMap<>();
    for (Map.Entry<String, YAMLNode> entry : regionData.entrySet()) {
        String id = entry.getKey();
        YAMLNode node = entry.getValue();
        String type = node.getString("type");
        ProtectedRegion region;
        try {
            if (type == null) {
                log.warning("Undefined region type for region '" + id + "'!\n" + "Here is what the region data looks like:\n\n" + toYamlOutput(entry.getValue().getMap()) + "\n");
                continue;
            } else if (type.equals("cuboid")) {
                Vector3 pt1 = checkNotNull(node.getVector("min"));
                Vector3 pt2 = checkNotNull(node.getVector("max"));
                BlockVector3 min = pt1.getMinimum(pt2).toBlockPoint();
                BlockVector3 max = pt1.getMaximum(pt2).toBlockPoint();
                region = new ProtectedCuboidRegion(id, min, max);
            } else if (type.equals("poly2d")) {
                Integer minY = checkNotNull(node.getInt("min-y"));
                Integer maxY = checkNotNull(node.getInt("max-y"));
                List<BlockVector2> points = node.getBlockVector2List("points", null);
                region = new ProtectedPolygonalRegion(id, points, minY, maxY);
            } else if (type.equals("global")) {
                region = new GlobalProtectedRegion(id);
            } else {
                log.warning("Unknown region type for region '" + id + "'!\n" + "Here is what the region data looks like:\n\n" + toYamlOutput(entry.getValue().getMap()) + "\n");
                continue;
            }
            Integer priority = checkNotNull(node.getInt("priority"));
            region.setPriority(priority);
            setFlags(flagRegistry, region, node.getNode("flags"));
            region.setOwners(parseDomain(node.getNode("owners")));
            region.setMembers(parseDomain(node.getNode("members")));
            loaded.put(id, region);
            String parentId = node.getString("parent");
            if (parentId != null) {
                parentSets.put(region, parentId);
            }
        } catch (NullPointerException e) {
            log.log(Level.WARNING, "Unexpected NullPointerException encountered during parsing for the region '" + id + "'!\n" + "Here is what the region data looks like:\n\n" + toYamlOutput(entry.getValue().getMap()) + "\n\nNote: This region will disappear as a result!", e);
        }
    }
    // Relink parents
    RegionDatabaseUtils.relinkParents(loaded, parentSets);
    return new HashSet<>(loaded.values());
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) FileNotFoundException(java.io.FileNotFoundException) LinkedHashMap(java.util.LinkedHashMap) ProtectedRegion(com.sk89q.worldguard.protection.regions.ProtectedRegion) GlobalProtectedRegion(com.sk89q.worldguard.protection.regions.GlobalProtectedRegion) ProtectedPolygonalRegion(com.sk89q.worldguard.protection.regions.ProtectedPolygonalRegion) YAMLProcessor(com.sk89q.util.yaml.YAMLProcessor) HashSet(java.util.HashSet) ParserException(org.yaml.snakeyaml.parser.ParserException) BlockVector3(com.sk89q.worldedit.math.BlockVector3) Vector3(com.sk89q.worldedit.math.Vector3) IOException(java.io.IOException) BlockVector3(com.sk89q.worldedit.math.BlockVector3) BlockVector2(com.sk89q.worldedit.math.BlockVector2) GlobalProtectedRegion(com.sk89q.worldguard.protection.regions.GlobalProtectedRegion) ProtectedCuboidRegion(com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion) StorageException(com.sk89q.worldguard.protection.managers.storage.StorageException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) YAMLNode(com.sk89q.util.yaml.YAMLNode)

Example 2 with YAMLProcessor

use of com.sk89q.util.yaml.YAMLProcessor in project WorldGuard by EngineHub.

the class YamlRegionFile method saveAll.

@Override
public void saveAll(Set<ProtectedRegion> regions) throws StorageException {
    checkNotNull(regions);
    File tempFile = new File(file.getParentFile(), file.getName() + ".tmp");
    YAMLProcessor config = createYamlProcessor(tempFile);
    config.clear();
    YAMLNode regionsNode = config.addNode("regions");
    Map<String, Object> map = regionsNode.getMap();
    for (ProtectedRegion region : regions) {
        Map<String, Object> nodeMap = new HashMap<>();
        map.put(region.getId(), nodeMap);
        YAMLNode node = new YAMLNode(nodeMap, false);
        if (region instanceof ProtectedCuboidRegion) {
            ProtectedCuboidRegion cuboid = (ProtectedCuboidRegion) region;
            node.setProperty("type", "cuboid");
            node.setProperty("min", cuboid.getMinimumPoint());
            node.setProperty("max", cuboid.getMaximumPoint());
        } else if (region instanceof ProtectedPolygonalRegion) {
            ProtectedPolygonalRegion poly = (ProtectedPolygonalRegion) region;
            node.setProperty("type", "poly2d");
            node.setProperty("min-y", poly.getMinimumPoint().getBlockY());
            node.setProperty("max-y", poly.getMaximumPoint().getBlockY());
            List<Map<String, Object>> points = new ArrayList<>();
            for (BlockVector2 point : poly.getPoints()) {
                Map<String, Object> data = new HashMap<>();
                data.put("x", point.getBlockX());
                data.put("z", point.getBlockZ());
                points.add(data);
            }
            node.setProperty("points", points);
        } else if (region instanceof GlobalProtectedRegion) {
            node.setProperty("type", "global");
        } else {
            node.setProperty("type", region.getClass().getCanonicalName());
        }
        node.setProperty("priority", region.getPriority());
        node.setProperty("flags", getFlagData(region));
        node.setProperty("owners", getDomainData(region.getOwners()));
        node.setProperty("members", getDomainData(region.getMembers()));
        ProtectedRegion parent = region.getParent();
        if (parent != null) {
            node.setProperty("parent", parent.getId());
        }
    }
    config.setHeader(FILE_HEADER);
    config.save();
    // noinspection ResultOfMethodCallIgnored
    file.delete();
    if (!tempFile.renameTo(file)) {
        throw new StorageException("Failed to rename temporary regions file to " + file.getAbsolutePath());
    }
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) BlockVector2(com.sk89q.worldedit.math.BlockVector2) GlobalProtectedRegion(com.sk89q.worldguard.protection.regions.GlobalProtectedRegion) ProtectedRegion(com.sk89q.worldguard.protection.regions.ProtectedRegion) GlobalProtectedRegion(com.sk89q.worldguard.protection.regions.GlobalProtectedRegion) ProtectedPolygonalRegion(com.sk89q.worldguard.protection.regions.ProtectedPolygonalRegion) YAMLProcessor(com.sk89q.util.yaml.YAMLProcessor) ProtectedCuboidRegion(com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion) ArrayList(java.util.ArrayList) List(java.util.List) File(java.io.File) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) StorageException(com.sk89q.worldguard.protection.managers.storage.StorageException) YAMLNode(com.sk89q.util.yaml.YAMLNode)

Example 3 with YAMLProcessor

use of com.sk89q.util.yaml.YAMLProcessor in project FastAsyncWorldEdit by IntellectualSites.

the class PermissionsResolverManager method loadConfig.

private boolean loadConfig(File file) {
    boolean isUpdated = false;
    if (!file.exists()) {
        try {
            file.createNewFile();
        } catch (IOException e) {
            LOGGER.warn("Failed to create new configuration file", e);
        }
    }
    config = new YAMLProcessor(file, false, YAMLFormat.EXTENDED);
    try {
        config.load();
    } catch (IOException e) {
        LOGGER.warn("Error loading WEPIF configuration", e);
    }
    List<String> keys = config.getKeys(null);
    config.setHeader(CONFIG_HEADER);
    if (!keys.contains("ignore-nijiperms-bridges")) {
        config.setProperty("ignore-nijiperms-bridges", true);
        isUpdated = true;
    }
    if (!keys.contains("resolvers")) {
        // List<String> resolverKeys = config.getKeys("resolvers");
        List<String> resolvers = new ArrayList<>();
        for (Class<?> clazz : availableResolvers) {
            resolvers.add(clazz.getSimpleName());
        }
        enabledResolvers.addAll(Arrays.asList(availableResolvers));
        config.setProperty("resolvers.enabled", resolvers);
        isUpdated = true;
    } else {
        List<String> disabledResolvers = config.getStringList("resolvers.disabled", new ArrayList<>());
        List<String> stagedEnabled = config.getStringList("resolvers.enabled", null);
        for (Iterator<String> i = stagedEnabled.iterator(); i.hasNext(); ) {
            String nextName = i.next();
            Class<?> next = null;
            try {
                next = Class.forName(getClass().getPackage().getName() + "." + nextName);
            } catch (ClassNotFoundException ignored) {
            }
            if (next == null || !PermissionsResolver.class.isAssignableFrom(next)) {
                LOGGER.warn("WEPIF: Invalid or unknown class found in enabled resolvers: " + nextName + ". Moving to disabled resolvers list.");
                i.remove();
                disabledResolvers.add(nextName);
                isUpdated = true;
                continue;
            }
            enabledResolvers.add(next.asSubclass(PermissionsResolver.class));
        }
        for (Class<?> clazz : availableResolvers) {
            if (!stagedEnabled.contains(clazz.getSimpleName()) && !disabledResolvers.contains(clazz.getSimpleName())) {
                disabledResolvers.add(clazz.getSimpleName());
                LOGGER.info("New permissions resolver: " + clazz.getSimpleName() + " detected. " + "Added to disabled resolvers list.");
                isUpdated = true;
            }
        }
        config.setProperty("resolvers.disabled", disabledResolvers);
        config.setProperty("resolvers.enabled", stagedEnabled);
    }
    if (keys.contains("dinner-perms") || keys.contains("dinnerperms")) {
        config.removeProperty("dinner-perms");
        config.removeProperty("dinnerperms");
        isUpdated = true;
    }
    if (!keys.contains("permissions")) {
        ConfigurationPermissionsResolver.generateDefaultPerms(config.addNode("permissions"));
        isUpdated = true;
    }
    if (isUpdated) {
        LOGGER.info("WEPIF: Updated config file");
        config.save();
    }
    return isUpdated;
}
Also used : ArrayList(java.util.ArrayList) YAMLProcessor(com.sk89q.util.yaml.YAMLProcessor) IOException(java.io.IOException)

Example 4 with YAMLProcessor

use of com.sk89q.util.yaml.YAMLProcessor in project FastAsyncWorldEdit by IntellectualSites.

the class WorldEditPlugin method onLoad.

@Override
public void onLoad() {
    // FAWE start
    // This is already covered by Spigot, however, a more pesky warning with a proper explanation over "Ambiguous plugin name..." can't hurt.
    Plugin[] plugins = Bukkit.getServer().getPluginManager().getPlugins();
    for (Plugin p : plugins) {
        if (p.getName().equals("WorldEdit")) {
            LOGGER.warn("You installed WorldEdit alongside FastAsyncWorldEdit. That is unneeded and will cause unforeseen issues, " + "because FastAsyncWorldEdit already provides WorldEdit. " + "Stop your server and delete the 'worldedit-bukkit' jar from your plugins folder.");
        }
    }
    // FAWE end
    INSTANCE = this;
    // noinspection ResultOfMethodCallIgnored
    getDataFolder().mkdirs();
    WorldEdit worldEdit = WorldEdit.getInstance();
    // Setup platform
    platform = new BukkitServerInterface(this, getServer());
    worldEdit.getPlatformManager().register(platform);
    // FAWE start - Migrate from config-legacy to worldedit-config
    migrateLegacyConfig();
    // FAWE end
    // FAWE start - Modify WorldEdit config name
    config = new BukkitConfiguration(new YAMLProcessor(new File(getDataFolder(), "worldedit-config.yml"), true), this);
    // FAWE end
    // FAWE start - Setup permission attachments
    permissionAttachmentManager = new BukkitPermissionAttachmentManager(this);
    // FAWE end
    Path delChunks = Paths.get(getDataFolder().getPath(), DELCHUNKS_FILE_NAME);
    if (Files.exists(delChunks)) {
        ChunkDeleter.runFromFile(delChunks, true);
    }
    // FAWE start - Delete obsolete DummyFawe from pre 1.14 days
    if (this.getDataFolder().getParentFile().listFiles(file -> {
        if (file.getName().equals("DummyFawe.jar")) {
            file.delete();
            return true;
        }
        return false;
    }).length > 0) {
        LOGGER.warn("DummyFawe detected and automatically deleted! This file is no longer necessary.");
    }
// FAWE end
}
Also used : Path(java.nio.file.Path) WorldEdit(com.sk89q.worldedit.WorldEdit) YAMLProcessor(com.sk89q.util.yaml.YAMLProcessor) BukkitPermissionAttachmentManager(com.fastasyncworldedit.bukkit.BukkitPermissionAttachmentManager) File(java.io.File) Plugin(org.bukkit.plugin.Plugin) JavaPlugin(org.bukkit.plugin.java.JavaPlugin)

Example 5 with YAMLProcessor

use of com.sk89q.util.yaml.YAMLProcessor in project WorldGuard by EngineHub.

the class YamlConfigurationManager method load.

@Override
public void load() {
    copyDefaults();
    config = new YAMLProcessor(new File(getDataFolder(), "config.yml"), true, YAMLFormat.EXTENDED);
    try {
        config.load();
    } catch (IOException e) {
        log.severe("Error reading configuration for global config: ");
        e.printStackTrace();
    }
    config.removeProperty("suppress-tick-sync-warnings");
    migrateRegionsToUuid = config.getBoolean("regions.uuid-migration.perform-on-next-start", true);
    keepUnresolvedNames = config.getBoolean("regions.uuid-migration.keep-names-that-lack-uuids", true);
    useRegionsCreatureSpawnEvent = config.getBoolean("regions.use-creature-spawn-event", true);
    disableDefaultBypass = config.getBoolean("regions.disable-bypass-by-default", false);
    announceBypassStatus = config.getBoolean("regions.announce-bypass-status", false);
    useGodPermission = config.getBoolean("auto-invincible", config.getBoolean("auto-invincible-permission", false));
    useGodGroup = config.getBoolean("auto-invincible-group", false);
    useAmphibiousGroup = config.getBoolean("auto-no-drowning-group", false);
    config.removeProperty("auto-invincible-permission");
    usePlayerMove = config.getBoolean("use-player-move-event", true);
    usePlayerTeleports = config.getBoolean("use-player-teleports", true);
    particleEffects = config.getBoolean("use-particle-effects", true);
    disablePermissionCache = config.getBoolean("disable-permission-cache", false);
    deopOnJoin = config.getBoolean("security.deop-everyone-on-join", false);
    blockInGameOp = config.getBoolean("security.block-in-game-op-command", false);
    hostKeys = new HashMap<>();
    Object hostKeysRaw = config.getProperty("host-keys");
    if (!(hostKeysRaw instanceof Map)) {
        config.setProperty("host-keys", new HashMap<String, String>());
    } else {
        for (Map.Entry<Object, Object> entry : ((Map<Object, Object>) hostKeysRaw).entrySet()) {
            String key = String.valueOf(entry.getKey());
            String value = String.valueOf(entry.getValue());
            hostKeys.put(key.toLowerCase(), value);
        }
    }
    hostKeysAllowFMLClients = config.getBoolean("security.host-keys-allow-forge-clients", false);
    // ====================================================================
    // Region store drivers
    // ====================================================================
    boolean useSqlDatabase = config.getBoolean("regions.sql.use", false);
    String sqlDsn = config.getString("regions.sql.dsn", "jdbc:mysql://localhost/worldguard");
    String sqlUsername = config.getString("regions.sql.username", "worldguard");
    String sqlPassword = config.getString("regions.sql.password", "worldguard");
    String sqlTablePrefix = config.getString("regions.sql.table-prefix", "");
    if (!useSqlDatabase) {
        config.removeProperty("regions.sql");
    } else {
        log.warning("SQL support for WorldGuard region storage is deprecated for removal in a future version. Please migrate to YAML storage.");
        log.warning("For details, see https://worldguard.enginehub.org/en/latest/regions/storage/");
    }
    DataSourceConfig dataSourceConfig = new DataSourceConfig(sqlDsn, sqlUsername, sqlPassword, sqlTablePrefix);
    SQLDriver sqlDriver = new SQLDriver(dataSourceConfig);
    DirectoryYamlDriver yamlDriver = new DirectoryYamlDriver(getWorldsDataFolder(), "regions.yml");
    this.regionStoreDriverMap = ImmutableMap.<DriverType, RegionDriver>builder().put(DriverType.MYSQL, sqlDriver).put(DriverType.YAML, yamlDriver).build();
    this.selectedRegionStoreDriver = useSqlDatabase ? sqlDriver : yamlDriver;
    postLoad();
    config.setHeader(CONFIG_HEADER);
}
Also used : DirectoryYamlDriver(com.sk89q.worldguard.protection.managers.storage.file.DirectoryYamlDriver) DataSourceConfig(com.sk89q.worldguard.util.sql.DataSourceConfig) IOException(java.io.IOException) RegionDriver(com.sk89q.worldguard.protection.managers.storage.RegionDriver) YAMLProcessor(com.sk89q.util.yaml.YAMLProcessor) SQLDriver(com.sk89q.worldguard.protection.managers.storage.sql.SQLDriver) DriverType(com.sk89q.worldguard.protection.managers.storage.DriverType) File(java.io.File) ImmutableMap(com.google.common.collect.ImmutableMap) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

YAMLProcessor (com.sk89q.util.yaml.YAMLProcessor)5 File (java.io.File)3 IOException (java.io.IOException)3 HashMap (java.util.HashMap)3 Map (java.util.Map)3 YAMLNode (com.sk89q.util.yaml.YAMLNode)2 BlockVector2 (com.sk89q.worldedit.math.BlockVector2)2 StorageException (com.sk89q.worldguard.protection.managers.storage.StorageException)2 GlobalProtectedRegion (com.sk89q.worldguard.protection.regions.GlobalProtectedRegion)2 ProtectedCuboidRegion (com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion)2 ProtectedPolygonalRegion (com.sk89q.worldguard.protection.regions.ProtectedPolygonalRegion)2 ProtectedRegion (com.sk89q.worldguard.protection.regions.ProtectedRegion)2 ArrayList (java.util.ArrayList)2 LinkedHashMap (java.util.LinkedHashMap)2 BukkitPermissionAttachmentManager (com.fastasyncworldedit.bukkit.BukkitPermissionAttachmentManager)1 ImmutableMap (com.google.common.collect.ImmutableMap)1 WorldEdit (com.sk89q.worldedit.WorldEdit)1 BlockVector3 (com.sk89q.worldedit.math.BlockVector3)1 Vector3 (com.sk89q.worldedit.math.Vector3)1 DriverType (com.sk89q.worldguard.protection.managers.storage.DriverType)1