Java Code Examples for org.bukkit.configuration.file.FileConfiguration#load()

The following examples show how to use org.bukkit.configuration.file.FileConfiguration#load() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ConfigurationManager.java    From MineTinker with GNU General Public License v3.0 6 votes vote down vote up
/**
 * creates a config file in the specified folder
 *
 * @param folder The name of the folder
 * @param file   The name of the file
 */
public static void loadConfig(String folder, String file) {
	File customConfigFile = new File(MineTinker.getPlugin().getDataFolder(), folder + file);
	FileConfiguration fileConfiguration = configs.getOrDefault(file, new YamlConfiguration());

	configsFolder.put(fileConfiguration, customConfigFile);
	configs.put(file, fileConfiguration);

	if (customConfigFile.exists()) {
		try {
			fileConfiguration.load(customConfigFile);
		} catch (IOException | InvalidConfigurationException e) {
			e.printStackTrace();
		}
	}
}
 
Example 2
Source File: AllianceManager.java    From Civs with GNU General Public License v3.0 6 votes vote down vote up
private void loadAlliance(File allianceFile) {
    try {
        FileConfiguration config = new YamlConfiguration();
        config.load(allianceFile);
        Alliance alliance = new Alliance();
        alliance.setName(allianceFile.getName().replace(".yml", ""));
        alliance.setMembers(new HashSet<String>(config.getStringList("members")));
        for (String townName : new ArrayList<>(alliance.getMembers())) {
            if (TownManager.getInstance().getTown(townName) == null) {
                alliance.getMembers().remove(townName);
            }
        }
        String uuidString = config.getString("last-rename", null);
        if (uuidString != null) {
            alliance.setLastRenamedBy(UUID.fromString(uuidString));
        }
        alliances.put(alliance.getName(), alliance);
    } catch (Exception e) {
        Civs.logger.severe("Unable to load alliance " + allianceFile.getName());
    }
}
 
Example 3
Source File: TownManager.java    From Civs with GNU General Public License v3.0 6 votes vote down vote up
public void loadAllTowns() {
    File townFolder = new File(Civs.dataLocation, "towns");
    if (!townFolder.exists()) {
        townFolder.mkdir();
    }
    try {
        for (File file : townFolder.listFiles()) {
            FileConfiguration config = new YamlConfiguration();
            try {
                config.load(file);

                loadTown(config);
            } catch (Exception e) {
                Civs.logger.warning("Unable to read from towns/" + file.getName());
                e.printStackTrace();
            }
        }
    } catch (NullPointerException npe) {
        Civs.logger.severe("Unable to read from town folder!");
    }
}
 
Example 4
Source File: AIManager.java    From Civs with GNU General Public License v3.0 5 votes vote down vote up
private void loadAI(File aiFile) {
    FileConfiguration config = new YamlConfiguration();
    try {
        config.load(aiFile);
        // TODO load persistent data

        String townName = aiFile.getName().replace(".yml", "");
        AI ai = new AI(townName);
        ais.put(townName, ai);
    } catch (Exception e) {
        Civs.logger.severe("Unable load ai file " + aiFile.getName());
    }
}
 
Example 5
Source File: WarehouseEffect.java    From Civs with GNU General Public License v3.0 5 votes vote down vote up
private void checkExcessChests(Region r) {
    if ((!invs.containsKey(r) || invs.get(r).isEmpty()) && Civs.getInstance() != null) {
        // Since there isn't a cached list of chests for this warehouse, retrieve it from the data file
        File dataFolder = new File(Civs.dataLocation, Constants.REGIONS);
        if (!dataFolder.exists()) {
            return;
        }
        File dataFile = new File(dataFolder, r.getId() + ".yml");
        if (!dataFile.exists()) {
            Civs.logger.severe("Data file not found " + r.getId() + ".yml");
            return;
        }
        FileConfiguration config = new YamlConfiguration();
        try {
            config.load(dataFile);
            List<CVInventory> tempLocations = processLocationList(config.getStringList(Constants.CHESTS));
            for (CVInventory inventoryLocation : tempLocations) {
                if (!availableItems.containsKey(r)) {
                    availableItems.put(r, new HashMap<>());
                }
                availableItems.get(r).put(Region.locationToString(inventoryLocation.getLocation()),
                        inventoryLocation);
            }
            invs.put(r, tempLocations);
        } catch (Exception e) {
            Civs.logger.log(Level.WARNING, UNABLE_TO_SAVE_CHEST, r.getId());
            e.printStackTrace();
            return;
        }
    }
}
 
Example 6
Source File: FallbackConfigUtil.java    From Civs with GNU General Public License v3.0 5 votes vote down vote up
public static FileConfiguration getConfigFullPath(File originalFile, String url) {
    FileConfiguration config = new YamlConfiguration();
    try {
        InputStream inputStream = FallbackConfigUtil.class.getResourceAsStream(url);
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
        config.load(reader);
        if (originalFile != null && originalFile.exists()) {
            FileConfiguration configOverride = new YamlConfiguration();
            configOverride.load(originalFile);
            for (String key : configOverride.getKeys(true)) {
                if (configOverride.get(key) instanceof ConfigurationSection) {
                    continue;
                }
                config.set(key, configOverride.get(key));
            }
        }
    } catch (Exception e) {
        if (originalFile != null) {
            Civs.logger.log(Level.SEVERE, "File name: {0}", originalFile.getName());
        }
        if (url != null) {
            Civs.logger.log(Level.SEVERE, "Resource path: {0}", url);
        }
        Civs.logger.log(Level.SEVERE, "Unable to load config", e);
    }

    return config;
}
 
Example 7
Source File: ClassManager.java    From Civs with GNU General Public License v3.0 5 votes vote down vote up
void loadClasses() {
    File classFolder = new File(Civs.dataLocation, "class-data");
    if (!classFolder.exists()) {
        classFolder.mkdir();
    }
    try {
        for (File file : classFolder.listFiles()) {
            try {
                FileConfiguration classConfig = new YamlConfiguration();
                classConfig.load(file);
                int id = classConfig.getInt("id");
                UUID uuid = UUID.fromString(classConfig.getString("uuid"));
                String className = classConfig.getString("type");
                if (!civClasses.containsKey(uuid)) {
                    civClasses.put(uuid, new HashSet<CivClass>());
                }
                int manaPerSecond = classConfig.getInt("mana-per-second", 1);
                int maxMana = classConfig.getInt("max-mana", 100);

                civClasses.get(uuid).add(new CivClass(id, uuid, className, manaPerSecond, maxMana));
            } catch (Exception ex) {
                Civs.logger.severe("Unable to load " + file.getName());
                ex.printStackTrace();
                continue;
            }
        }
    } catch (Exception e) {
        Civs.logger.severe("Unable to load class files");
        return;
    }
}
 
Example 8
Source File: RegionManager.java    From Civs with GNU General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private Region loadRegion(File regionFile) {
    FileConfiguration regionConfig = new YamlConfiguration();
    Region region;
    try {
        regionConfig.load(regionFile);
        int[] radii = new int[6];
        radii[0] = regionConfig.getInt("xp-radius");
        radii[1] = regionConfig.getInt("zp-radius");
        radii[2] = regionConfig.getInt("xn-radius");
        radii[3] = regionConfig.getInt("zn-radius");
        radii[4] = regionConfig.getInt("yp-radius");
        radii[5] = regionConfig.getInt("yn-radius");
        Location location = Region.idToLocation(Objects.requireNonNull(regionConfig.getString("location")));
        if (location == null) {
            throw new NullPointerException();
        }

        double exp = regionConfig.getDouble("exp");
        HashMap<UUID, String> people = new HashMap<>();
        for (String s : Objects.requireNonNull(regionConfig.getConfigurationSection("people")).getKeys(false)) {
            people.put(UUID.fromString(s), regionConfig.getString("people." + s));
        }
        RegionType regionType = (RegionType) ItemManager.getInstance()
                .getItemType(Objects.requireNonNull(regionConfig.getString("type")).toLowerCase());
        region = new Region(
                Objects.requireNonNull(regionConfig.getString("type")).toLowerCase(),
                people,
                location,
                radii,
                (HashMap<String, String>) regionType.getEffects().clone(),
                exp);
        region.setWarehouseEnabled(regionConfig.getBoolean("warehouse-enabled", true));
        double forSale = regionConfig.getDouble("sale", -1);
        if (forSale != -1) {
            region.setForSale(forSale);
        }
        long lastActive = regionConfig.getLong(ActiveEffect.LAST_ACTIVE_KEY, -1);
        if (lastActive > -1) {
            region.setLastActive(lastActive);
        }
        if (regionConfig.isSet("upkeep-history")) {
            for (String timeString : Objects.requireNonNull(regionConfig
                    .getConfigurationSection("upkeep-history")).getKeys(false)) {
                Long time = Long.parseLong(timeString);
                region.getUpkeepHistory().put(time, regionConfig.getInt("upkeep-history." + timeString));
            }
        }
    } catch (Exception e) {
        Civs.logger.log(Level.SEVERE, "Unable to read " + regionFile.getName(), e);
        return null;
    }
    return region;
}
 
Example 9
Source File: WarehouseEffect.java    From Civs with GNU General Public License v3.0 4 votes vote down vote up
@EventHandler(ignoreCancelled = true)
public void onChestPlace(BlockPlaceEvent event) {
    if (event.getBlock().getType() != Material.CHEST) {
        return;
    }

    Location l = Region.idToLocation(Region.blockLocationToString(event.getBlock().getLocation()));
    Region r = RegionManager.getInstance().getRegionAt(l);
    if (r == null) {
        return;
    }

    if (!r.getEffects().containsKey(KEY)) {
        return;
    }


    File dataFolder = new File(Civs.dataLocation, Constants.REGIONS);
    if (!dataFolder.exists()) {
        return;
    }
    File dataFile = new File(dataFolder, r.getId() + ".yml");
    if (!dataFile.exists()) {
        return;
    }
    FileConfiguration config = new YamlConfiguration();
    try {
        config.load(dataFile);
        List<String> locationList = config.getStringList(Constants.CHESTS);
        locationList.add(Region.locationToString(l));
        config.set(Constants.CHESTS, locationList);
        config.save(dataFile);
    } catch (Exception e) {
        Civs.logger.log(Level.WARNING, UNABLE_TO_SAVE_CHEST, r.getId());
        return;
    }

    if (!invs.containsKey(r)) {
        invs.put(r, new ArrayList<>());
    }
    CVInventory cvInventory = UnloadedInventoryHandler.getInstance().getChestInventory(event.getBlockPlaced().getLocation());
    invs.get(r).add(cvInventory);
}
 
Example 10
Source File: WarehouseEffect.java    From Civs with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void regionCreatedHandler(Region r) {
    if (!r.getEffects().containsKey(KEY)) {
        return;
    }

    ArrayList<CVInventory> chests = new ArrayList<>();
    chests.add(UnloadedInventoryHandler.getInstance().getChestInventory(r.getLocation()));

    RegionType rt = (RegionType) ItemManager.getInstance().getItemType(r.getType());
    double lx = Math.floor(r.getLocation().getX()) + 0.4;
    double ly = Math.floor(r.getLocation().getY()) + 0.4;
    double lz = Math.floor(r.getLocation().getZ()) + 0.4;
    double buildRadius = rt.getBuildRadius();

    int x = (int) Math.round(lx - buildRadius);
    int y = (int) Math.round(ly - buildRadius);
    y = y < 0 ? 0 : y;
    int z = (int) Math.round(lz - buildRadius);
    int xMax = (int) Math.round(lx + buildRadius);
    int yMax = (int) Math.round(ly + buildRadius);
    World world = r.getLocation().getWorld();
    if (world != null) {
        yMax = yMax > world.getMaxHeight() - 1 ? world.getMaxHeight() - 1 : yMax;
        int zMax = (int) Math.round(lz + buildRadius);

        for (int i = x; i < xMax; i++) {
            for (int j = y; j < yMax; j++) {
                for (int k = z; k < zMax; k++) {
                    Block block = world.getBlockAt(i, j, k);

                    if (block.getType() == Material.CHEST) {
                        chests.add(UnloadedInventoryHandler.getInstance().getChestInventory(block.getLocation()));
                    }
                }
            }
        }
    }


    File dataFolder = new File(Civs.dataLocation, Constants.REGIONS);
    if (!dataFolder.exists()) {
        return;
    }
    File dataFile = new File(dataFolder, r.getId() + ".yml");
    if (!dataFile.exists()) {
        Civs.logger.log(Level.SEVERE, "Warehouse region file does not exist {0}.yml", r.getId());
        return;
    }
    FileConfiguration config = new YamlConfiguration();
    try {
        config.load(dataFile);
        ArrayList<String> locationList = new ArrayList<>();
        for (CVInventory cvInventory : chests) {
            locationList.add(Region.blockLocationToString(cvInventory.getLocation()));
        }
        config.set(Constants.CHESTS, locationList);
        config.save(dataFile);
    } catch (Exception e) {
        e.printStackTrace();
        Civs.logger.log(Level.WARNING, UNABLE_TO_SAVE_CHEST, r.getId());
        return;
    }
    checkExcessChests(r);
}
 
Example 11
Source File: WarehouseEffect.java    From Civs with GNU General Public License v3.0 4 votes vote down vote up
@EventHandler
public void onBlockBreak(BlockBreakEvent event) {
    Region r = RegionManager.getInstance().getRegionAt(event.getBlock().getLocation());
    if (r == null) {
        return;
    }
    boolean deletedSomething = false;

    if (invs.containsKey(r)) {
        CVInventory cvInventory = UnloadedInventoryHandler.getInstance().getChestInventory(event.getBlock().getLocation());
        deletedSomething = invs.get(r).remove(cvInventory);
    }
    if (availableItems.containsKey(r)) {
        deletedSomething = availableItems.get(r).remove(Region.locationToString(event.getBlock().getLocation())) != null ||
                deletedSomething;
    }

    //Remove excess chests from the data file
    deletefromfile: if (deletedSomething) {
        File dataFolder = new File(Civs.dataLocation, Constants.REGIONS);
        if (!dataFolder.exists()) {
            break deletefromfile;
        }
        File dataFile = new File(dataFolder, r.getId() + ".yml");
        if (!dataFile.exists()) {
            break deletefromfile;
        }
        FileConfiguration config = new YamlConfiguration();
        try {
            config.load(dataFile);
            ArrayList<String> locationList = new ArrayList<String>();
            for (CVInventory inventoryLocation : invs.get(r)) {
                locationList.add(Region.blockLocationToString(inventoryLocation.getLocation()));
            }
            config.set(Constants.CHESTS, locationList);
            config.save(dataFile);
        } catch (Exception e) {
            Civs.logger.log(Level.WARNING, UNABLE_TO_SAVE_CHEST, r.getId());
            return;
        }
    }
}
 
Example 12
Source File: CivilianManager.java    From Civs with GNU General Public License v3.0 4 votes vote down vote up
public void saveCivilian(Civilian civilian) {
    File civilianFolder = new File(Civs.dataLocation, "players");
    if (!civilianFolder.exists()) {
        if (!civilianFolder.mkdir()) {
            Civs.logger.severe("Unable to create players folder");
            return;
        }
    }
    File civilianFile = new File(civilianFolder, civilian.getUuid() + ".yml");
    if (!civilianFile.exists()) {
        try {
            civilianFile.createNewFile();
        } catch (IOException ioexception) {
            Civs.logger.severe("Unable to create " + civilian.getUuid() + ".yml");
            return;
        }
    }
    FileConfiguration civConfig = new YamlConfiguration();
    try {
        civConfig.load(civilianFile);

        civConfig.set("locale", civilian.getLocale());
        //TODO save other civilian file properties

        civConfig.set("tutorial-index", civilian.getTutorialIndex());
        civConfig.set("tutorial-path", civilian.getTutorialPath());
        civConfig.set("tutorial-progress", civilian.getTutorialProgress());
        civConfig.set("use-announcements", civilian.isUseAnnouncements());

        civConfig.set("items", null);
        for (String currentName : civilian.getStashItems().keySet()) {
            CivItem civItem = ItemManager.getInstance().getItemType(currentName);
            if (civItem == null) {
                continue;
            }
            if (civItem.getItemType() == CivItem.ItemType.FOLDER) {
                continue;
            }
            civConfig.set("items." + civItem.getProcessedName(), civItem.getQty());
        }
        List<Integer> classes = new ArrayList<>();
        if (civilian.getCivClasses() != null) {
            for (CivClass civClass : civilian.getCivClasses()) {
                if (civClass == null) {
                    continue;
                }
                classes.add(civClass.getId());
            }
        }
        civConfig.set("kills", civilian.getKills());
        civConfig.set("kill-streak", civilian.getKillStreak());
        civConfig.set("deaths", civilian.getDeaths());
        civConfig.set("highest-kill-streak", civilian.getHighestKillStreak());
        civConfig.set("points", civilian.getPoints());
        civConfig.set("karma", civilian.getKarma());
        civConfig.set("classes", classes);
        civConfig.set("locale", civilian.getLocale());
        if (civilian.getBounties() != null && !civilian.getBounties().isEmpty()) {
            for (int i = 0; i < civilian.getBounties().size(); i++) {
                if (civilian.getBounties().get(i).getIssuer() != null) {
                    civConfig.set("bounties." + i + ".issuer", civilian.getBounties().get(i).getIssuer().toString());
                }
                civConfig.set("bounties." + i + ".amount", civilian.getBounties().get(i).getAmount());
            }
        } else {
            civConfig.set("bounties", null);
        }
        if (civilian.getFriends() != null && !civilian.getFriends().isEmpty()) {
            ArrayList<String> friendList = new ArrayList<>();
            for (UUID uuid : civilian.getFriends()) {
                friendList.add(uuid.toString());
            }
            civConfig.set("friends", friendList);
        } else {
            civConfig.set("friends", null);
        }

        for (CivItem item : civilian.getExp().keySet()) {
            int exp = civilian.getExp().get(item);
            if (exp < 1) {
                continue;
            }
            civConfig.set("exp." + item.getProcessedName(), exp);
        }
        if (civilian.getRespawnPoint() != null) {
            civConfig.set("respawn", Region.locationToString(civilian.getRespawnPoint()));
        }
        civConfig.set("last-karma-depreciation", civilian.getLastKarmaDepreciation());

        civConfig.save(civilianFile);
    } catch (Exception ex) {
        Civs.logger.severe("Unable to write " + civilian.getUuid() + ".yml");
        ex.printStackTrace();
        return;
    }
}