Here are the examples of the java api codechicken.lib.config.ConfigFile taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
2 Examples
18
Source : SaveManager.java
with MIT License
from TheCBProject
with MIT License
from TheCBProject
public clreplaced SaveManager {
private RandomAccessFile freqMapFile;
private RandomAccessFile smallSectorFile;
private RandomAccessFile largeSectorFile;
private RandomAccessFile rwfile;
protected static SimpleProperties freqProp;
protected static SimpleProperties generalProp;
private static ConfigFile globalconfig;
private static File activeMapFile;
private ArrayList<Boolean> usedSmallSectors;
private ArrayList<Boolean> usedLargeSectors;
private int[] freqMapOffsets;
private long lastcleanuptime;
private int dimension;
private static ArrayList<Entry<Integer, Integer>>[] freqDimensionHashes = new ArrayList[RedstoneEther.numfreqs + 1];
private static boolean hashChanged = false;
private static boolean loadinginfo;
private static HashMap<Integer, SaveManager> managers = new HashMap<>();
private final int largesectorsize = 256;
private final int largesectornodes = largesectorsize / 12;
private final int smallsectorsize = 64;
private final int smallsectornodes = smallsectorsize / 12;
private final int largesectoroffset = 32767;
private final int maxsmallnodes = 5;
// 5 min
private final int cleanuptimeneeded = 300 * 1000;
public static void initConfig(File file) {
globalconfig = new ConfigFile(file).setComment("Wireless Redstone Chicken Bones Edition Configuration File:Deleting any element will restore it to it's default value");
}
public static SaveManager getInstance(int dimension) {
return managers.get(dimension);
}
public static void reloadSave(World world) {
managers.put(CommonUtils.getDimension(world), new SaveManager(world));
}
public static void unloadSave(int dimension) {
SaveManager m = managers.remove(dimension);
if (m != null) {
m.unload();
}
}
public static void resetWorld() {
try {
if (// dim 0 global save stuff
managers.size() == 0) {
File etherdir = getEtherDir(CommonUtils.getSaveLocation(0));
File file = new File(etherdir, "fprop.dat");
if (!file.exists()) {
file.createNewFile();
}
freqProp = new SimpleProperties(file, true);
file = new File(etherdir, "gprop.dat");
if (!file.exists()) {
file.createNewFile();
}
generalProp = new SimpleProperties(file, true);
generalProp.load();
file = new File(etherdir, "dimMap.dat");
if (!file.exists()) {
file.createNewFile();
}
activeMapFile = file;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private SaveManager(World world) {
try {
dimension = CommonUtils.getDimension(world);
File etherdir = getEtherDir(CommonUtils.getSaveLocation(world));
File file = new File(etherdir, "fmap.dat");
boolean newlycreated = false;
if (!file.exists()) {
file.createNewFile();
newlycreated = true;
}
freqMapFile = new RandomAccessFile(file, "rw");
if (newlycreated) {
for (int i = 0; i < 5000; i++) {
freqMapFile.writeShort(-1);
}
}
file = new File(etherdir, "node1.dat");
if (!file.exists()) {
file.createNewFile();
}
smallSectorFile = new RandomAccessFile(file, "rw");
file = new File(etherdir, "node2.dat");
if (!file.exists()) {
file.createNewFile();
}
largeSectorFile = new RandomAccessFile(file, "rw");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static File getEtherDir(File worldsave) {
File dir = new File(worldsave, "RedstoneEther");
if (!dir.exists()) {
dir.mkdirs();
}
return dir;
}
private void setFreqSector(int freq, int sector) {
try {
freqMapOffsets[(freq - 1)] = sector;
freqMapFile.seek((freq - 1) * 2);
freqMapFile.writeShort(sector);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void seekSector(int sector) {
try {
if (sector >= largesectoroffset) {
rwfile = largeSectorFile;
sector -= largesectoroffset;
rwfile.seek(sector * largesectorsize);
} else {
rwfile = smallSectorFile;
rwfile.seek(sector * smallsectorsize);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void setSectorUsed(int sector, boolean used) {
ArrayList<Boolean> usedsectors = (sector >= largesectoroffset) ? usedLargeSectors : usedSmallSectors;
if (sector >= largesectoroffset) {
sector -= largesectoroffset;
}
usedsectors.set(sector, used);
}
private int getNewSector(boolean large) {
try {
if (large) {
RandomAccessFile file = largeSectorFile;
long prevpos = file.getFilePointer();
file.seek(file.length());
// the next sector is not set
file.writeShort(-1);
// fill the rest of this sector with 0's
file.write(new byte[largesectorsize - 2]);
file.seek(prevpos);
usedLargeSectors.add(false);
return ((int) file.length() / largesectorsize) - 1 + largesectoroffset;
}
RandomAccessFile file = smallSectorFile;
long prevpos = file.getFilePointer();
file.seek(file.length());
// the next sector is not set
file.writeShort(-1);
// fill the rest of this sector with 0's
file.write(new byte[smallsectorsize - 2]);
file.seek(prevpos);
usedSmallSectors.add(false);
return ((int) file.length() / smallsectorsize) - 1;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private int getUnusedSector(int numnodes) {
boolean largesector = (numnodes > maxsmallnodes);
ArrayList<Boolean> usedsectors = largesector ? usedLargeSectors : usedSmallSectors;
for (int i = 0; i < usedsectors.size(); i++) {
if (!usedsectors.get(i)) {
return i + (largesector ? largesectoroffset : 0);
}
}
return getNewSector(numnodes > maxsmallnodes);
}
private void setNextSector(int sector, int nextsector) {
seekSector(sector);
try {
rwfile.writeShort((short) nextsector);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void setSectorLength(int sector, int numnodes) {
seekSector(sector);
try {
rwfile.skipBytes(2);
rwfile.writeShort((short) numnodes);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private int getNextSector(int sector) {
seekSector(sector);
try {
int nextsector = rwfile.readShort() & 0xFFFF;
if (// empty handling
nextsector == 0xFFFF) {
nextsector = -1;
}
return nextsector;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private int getSectorLength(int sector) {
seekSector(sector);
try {
rwfile.skipBytes(2);
return rwfile.readShort() & 0xFFFF;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void markSectorStackUnused(int firstsector) {
int nextsector = firstsector;
while (// sector unused setting loop
true) {
if (nextsector == -1) {
break;
}
int sector = nextsector;
setSectorUsed(sector, false);
setNextSector(sector, -1);
nextsector = getNextSector(nextsector);
}
}
private void writeNodes(int freq, int numnodes, ArrayList<BlockPos> nodes) {
try {
int nextsector = freqMapOffsets[freq - 1];
if (nextsector == -1) {
nextsector = getUnusedSector(numnodes);
setSectorUsed(nextsector, true);
setFreqSector(freq, nextsector);
} else {
markSectorStackUnused(nextsector);
setSectorUsed(nextsector, true);
}
int thissector;
int writtennodes;
boolean largesector;
int nodespersector;
while (// sector following / creation loop
true) {
seekSector(nextsector);
// skip the header info
rwfile.skipBytes(4);
thissector = nextsector;
writtennodes = 0;
largesector = nextsector >= largesectoroffset;
nodespersector = largesector ? largesectornodes : smallsectornodes;
while (// sector node writing loop
writtennodes != nodespersector && numnodes > 0) {
BlockPos node = nodes.get(nodes.size() - numnodes);
rwfile.writeInt(node.getX());
rwfile.writeInt(node.getY());
rwfile.writeInt(node.getZ());
numnodes--;
writtennodes++;
}
setSectorLength(thissector, writtennodes);
if (// finished
numnodes == 0) {
setNextSector(thissector, -1);
break;
}
nextsector = getUnusedSector(numnodes);
setSectorUsed(nextsector, true);
setNextSector(thissector, nextsector);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void saveFreq(int freq, int activetransmitters, TreeMap<BlockPos, Boolean> transmittermap, Map<Integer, Integer> dimensionHash) {
try {
freqDimensionHashes[freq] = new ArrayList<>(dimensionHash.entrySet());
hashChanged = true;
int numnodes = 0;
ArrayList<BlockPos> nodes = new ArrayList<>(activetransmitters);
for (Iterator<BlockPos> iterator = transmittermap.keySet().iterator(); iterator.hasNext() && numnodes < activetransmitters; ) {
BlockPos node = iterator.next();
if (transmittermap.get(node)) {
nodes.add(node);
numnodes++;
}
}
if (numnodes == 0) {
setFreqSector(freq, -1);
return;
}
writeNodes(freq, numnodes, nodes);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void loadFreqMap() {
try {
freqMapOffsets = new int[RedstoneEther.numfreqs];
freqMapFile.seek(0);
for (// read freq offsets
int freq = 1; // read freq offsets
freq <= RedstoneEther.numfreqs; // read freq offsets
freq++) {
freqMapOffsets[freq - 1] = freqMapFile.readShort() & 0xFFFF;
if (// empty handling
freqMapOffsets[freq - 1] == 0xFFFF) {
freqMapOffsets[freq - 1] = -1;
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void initSectors() {
int numsmallsectors;
int numlargesectors;
try {
numsmallsectors = (int) (smallSectorFile.length() / smallsectorsize);
numlargesectors = (int) (largeSectorFile.length() / largesectorsize);
} catch (Exception e) {
throw new RuntimeException(e);
}
usedSmallSectors = new ArrayList<>(numsmallsectors);
for (// intialize array
int i = 0; // intialize array
i < numsmallsectors; // intialize array
i++) {
usedSmallSectors.add(false);
}
usedLargeSectors = new ArrayList<>(numlargesectors);
for (// intialize array
int i = 0; // intialize array
i < numlargesectors; // intialize array
i++) {
usedLargeSectors.add(false);
}
}
private void loadNodes() {
for (int freq = 1; freq <= RedstoneEther.numfreqs; freq++) {
RedstoneEther.server().setDimensionTransmitterCount(freq, dimension, 0);
int nextsector = freqMapOffsets[freq - 1];
if (nextsector == -1) {
continue;
}
while (true) {
seekSector(nextsector);
setSectorUsed(nextsector, true);
int numnodes = getSectorLength(nextsector);
for (int j = 0; j < numnodes; j++) {
try {
RedstoneEther.server().loadTransmitter(dimension, rwfile.readInt(), rwfile.readInt(), rwfile.readInt(), freq);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
nextsector = getNextSector(nextsector);
if (// end of list
nextsector == -1) {
break;
}
}
RedstoneEther.server().setFreqClean(freq, dimension);
}
}
public void removeTrailingSectors() {
try {
if (// 0 means loading
lastcleanuptime != 0 && System.currentTimeMillis() - lastcleanuptime < cleanuptimeneeded) {
return;
}
int lastusedsector = -1;
for (// find the last used sector
int i = 0; // find the last used sector
i < usedLargeSectors.size(); // find the last used sector
i++) {
if (usedLargeSectors.get(i)) {
lastusedsector = i;
}
}
for (// remove sectors from list
int i = usedLargeSectors.size() - 1; // remove sectors from list
i > lastusedsector; // remove sectors from list
i--) {
usedLargeSectors.remove(i);
}
// truncate the file
largeSectorFile.setLength((lastusedsector + 1) * largesectorsize);
for (int i = 0; i < usedSmallSectors.size(); i++) {
if (usedSmallSectors.get(i)) {
lastusedsector = i;
}
}
for (int i = usedSmallSectors.size() - 1; i > lastusedsector; i--) {
usedSmallSectors.remove(i);
}
smallSectorFile.setLength((lastusedsector + 1) * smallsectorsize);
lastcleanuptime = System.currentTimeMillis();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void loadEther() {
loadFreqMap();
initSectors();
loadNodes();
lastcleanuptime = 0;
removeTrailingSectors();
}
public static void loadFreqInfo() {
freqProp.load();
loadinginfo = true;
for (Iterator<Entry<String, String>> iterator = freqProp.propertyMap.entrySet().iterator(); iterator.hasNext(); ) {
Entry<String, String> entry = iterator.next();
boolean success = false;
try {
int freq;
{
Integer val = Integer.parseInt(entry.getKey().substring(0, entry.getKey().indexOf('.')));
if (val == null) {
continue;
}
freq = val;
}
if (entry.getKey().endsWith(".colour") || entry.getKey().endsWith(".c")) {
int colourindex;
{
Integer val = Integer.parseInt(entry.getValue());
if (val == null) {
continue;
}
colourindex = val;
}
RedstoneEther.server().setFreqColour(freq, colourindex);
success = true;
} else if (entry.getKey().endsWith(".name") || entry.getKey().endsWith(".n")) {
RedstoneEther.server().setFreqName(freq, entry.getValue());
success = true;
} else if (entry.getKey().endsWith(".owner")) {
RedstoneEther.server().setFreqOwner(freq, entry.getValue());
success = true;
}
} catch (Exception e) {
} finally {
if (!success) {
iterator.remove();
}
}
}
loadinginfo = false;
freqProp.save();
}
public static void loadDimensionHash() {
if (activeMapFile.length() == 0) {
return;
}
DataInputStream din;
try {
din = new DataInputStream(new FileInputStream(activeMapFile));
try {
while (true) {
RedstoneEther.server().setDimensionTransmitterCount(din.readShort(), din.readInt(), din.readInt());
}
} catch (EOFException eof) {
} finally {
din.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static void saveDimensionHash() {
if (!hashChanged) {
return;
}
try {
DataOutputStream dout = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(activeMapFile)));
for (int freq = 1; freq <= RedstoneEther.numfreqs; freq++) {
ArrayList<Entry<Integer, Integer>> map = freqDimensionHashes[freq];
if (map == null) {
continue;
}
for (Entry<Integer, Integer> entry : map) {
if (entry.getValue() > 0) {
dout.writeShort(freq);
dout.writeInt(entry.getKey());
dout.writeInt(entry.getValue());
}
}
}
dout.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static ConfigFile config() {
return globalconfig;
}
public static boolean isLoading() {
return loadinginfo;
}
public static void unloadAll() {
for (SaveManager manager : managers.values()) {
manager.unload();
}
managers.clear();
}
private void unload() {
try {
freqMapFile.close();
smallSectorFile.close();
largeSectorFile.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
18
Source : NEIServerConfig.java
with MIT License
from TheCBProject
with MIT License
from TheCBProject
public clreplaced NEIServerConfig {
private static MinecraftServer server;
public static File saveDir;
public static ConfigFile serverConfig;
public static Map<Integer, NBTTagCompound> dimTags = new HashMap<>();
public static HashMap<String, PlayerSave> playerSaves = new HashMap<>();
public static ItemStackMap<Set<String>> bannedItems = new ItemStackMap<>(null);
public static void load(World world) {
if (ServerUtils.mc() != server) {
LogHelper.debug("Loading NEI Server");
server = ServerUtils.mc();
saveDir = new File(DimensionManager.getCurrentSaveRootDirectory(), "NEI");
dimTags.clear();
loadConfig();
loadBannedItems();
}
loadWorld(world);
}
public static File getSaveDir(World world) {
return new File(CommonUtils.getSaveLocation(world), "NEI");
}
private static void loadWorld(World world) {
try {
File file = new File(getSaveDir(world), "world.dat");
NBTTagCompound tag = NEIServerUtils.readNBT(file);
if (tag == null) {
tag = new NBTTagCompound();
}
dimTags.put(world.provider.getDimension(), tag);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static void loadConfig() {
File file = new File(saveDir, "server.cfg");
serverConfig = new ConfigFile(file);
serverConfig.setNewLineMode(1);
serverConfig.getTag("permissions").useBraces();
serverConfig.getTag("permissions").setComment("List of players who can use these features.\nEg. time=CodeChicken, Friend1");
setDefaultFeature("time");
setDefaultFeature("rain");
setDefaultFeature("heal");
setDefaultFeature("magnet");
setDefaultFeature("creative");
setDefaultFeature("creative+");
setDefaultFeature("adventure");
setDefaultFeature("enchant");
setDefaultFeature("potion");
setDefaultFeature("save-state");
setDefaultFeature("item");
setDefaultFeature("delete");
setDefaultFeature("notify-item", "CONSOLE, OP");
}
private static void setDefaultFeature(String featurename, String... names) {
if (names.length == 0) {
names = new String[] { "OP" };
}
String list = "";
for (int i = 0; i < names.length; i++) {
if (i >= 1) {
list += ", ";
}
list += names[i];
}
serverConfig.getTag("permissions." + featurename).setDefaultValue(list);
}
private static void saveWorld(int dim) {
try {
File file = new File(getSaveDir(DimensionManager.getWorld(dim)), "world.dat");
NEIServerUtils.writeNBT(dimTags.get(dim), file);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Checks if a player has permission to change a specific actions state.
*
* @param playerName The player in question.
* @param name The identifier for the action.
* @return If the player has permission.
*/
public static boolean canPlayerPerformAction(String playerName, String name) {
return isPlayerInList(playerName, getPlayerList("permissions." + NEIActions.base(name)), true);
}
/**
* Checks if a player is in the specified list.
*
* @param playerName The players name.
* @param list The list of players.
* @param allowCards Allows some wild cars when checking, Specifically, OP, Server Owner, and the "ALL" user.
* @return If the player is in the list.
*/
public static boolean isPlayerInList(String playerName, Set<String> list, boolean allowCards) {
if (playerName.equals("CONSOLE")) {
return list.contains(playerName);
}
playerName = playerName.toLowerCase();
if (allowCards) {
if (list.contains("ALL")) {
return true;
}
if ((ServerUtils.isPlayerOP(playerName) || ServerUtils.isPlayerOwner(playerName)) && list.contains("OP")) {
return true;
}
}
return list.contains(playerName);
}
/**
* Checks if the action is disabled.
* For Example. Noon, weather.
*
* @param dim The dimension to check.
* @param name The actions identifier.
* @return If the action is disabled.
*/
public static boolean isActionDisabled(int dim, String name) {
return dimTags.get(dim).getBoolean("disabled" + name);
}
/**
* Disabled a specific action.
* Also notifies all clients in the dimension of the change.
*
* @param dim The dimension the change has happened for.
* @param name The name of the action.
* @param disable The state of the action.
*/
public static void setDisableActionState(int dim, String name, boolean disable) {
dimTags.get(dim).setBoolean("disabled" + name, disable);
NEIServerPacketHandler.sendActionDisabledState(dim, name, disable);
saveWorld(dim);
}
public static HashSet<String> getPlayerList(String tag) {
String[] list = serverConfig.getTag(tag).getValue("").replace(" ", "").split(",");
return new HashSet<>(Arrays.asList(list));
}
public static void addPlayerToList(String playername, String tag) {
HashSet<String> list = getPlayerList(tag);
if (!playername.equals("CONSOLE") && !playername.equals("ALL") && !playername.equals("OP")) {
playername = playername.toLowerCase();
}
list.add(playername);
savePlayerList(tag, list);
}
public static void remPlayerFromList(String playername, String tag) {
HashSet<String> list = getPlayerList(tag);
if (!playername.equals("CONSOLE") && !playername.equals("ALL") && !playername.equals("OP")) {
playername = playername.toLowerCase();
}
list.remove(playername);
savePlayerList(tag, list);
}
private static void savePlayerList(String tag, Collection<String> list) {
StringBuilder sb = new StringBuilder();
int i = 0;
for (Iterator<String> iterator = list.iterator(); iterator.hasNext(); i++) {
if (i != 0) {
sb.append(", ");
}
sb.append(iterator.next());
}
serverConfig.getTag(tag).setValue(sb.toString());
}
private static void loadBannedItems() {
bannedItems.clear();
File file = new File(saveDir, "banneditems.cfg");
if (!file.exists()) {
bannedItems.put(new ItemStack(Blocks.COMMAND_BLOCK), new HashSet<>(Arrays.asList("NONE")));
saveBannedItems();
return;
}
try {
FileReader r = new FileReader(file);
int line = 0;
for (String s : IOUtils.readLines(r)) {
if (s.charAt(0) == '#' || s.trim().length() == 0) {
continue;
}
int delim = s.lastIndexOf('=');
if (delim < 0) {
LogHelper.error("line %s: Missing =", line);
continue;
}
try {
NBTTagCompound key = JsonToNBT.getTagFromJson(s.substring(0, delim));
Set<String> values = new HashSet<>();
for (String s2 : s.substring(delim + 1).split(",")) {
values.add(s2.trim());
}
bannedItems.put(InventoryUtils.loadPersistant(key), values);
} catch (Exception e) {
LogHelper.error("line %s: %s", line, e.getMessage());
}
}
r.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void saveBannedItems() {
File file = new File(saveDir, "banneditems.cfg");
try {
if (!file.exists()) {
file.createNewFile();
}
PrintWriter p = new PrintWriter(file);
p.println("#Saved in this format for external editing. The format isn't that hard to figure out. If you think you're up to it, modify it here!");
for (ItemStackMap.Entry<Set<String>> entry : bannedItems.entries()) {
NBTTagCompound key = InventoryUtils.savePersistant(entry.key, new NBTTagCompound());
key.removeTag("Count");
if (key.getByte("Damage") == 0) {
key.removeTag("Damage");
}
p.print(key.toString());
p.print("=[");
int i = 0;
for (String s : entry.value) {
if (i++ != 0) {
p.print(", ");
}
p.print(s);
}
p.println("]");
}
p.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static PlayerSave getSaveForPlayer(String username) {
return playerSaves.get(username);
}
public static void loadPlayer(EnreplacedyPlayer player) {
LogHelper.debug("Loading Player: " + player.getGameProfile().getName());
playerSaves.put(player.getName(), new PlayerSave((EnreplacedyPlayerMP) player, new File(saveDir, "players")));
}
public static void unloadPlayer(EnreplacedyPlayer player) {
LogHelper.debug("Unloading Player: " + player.getName());
PlayerSave playerSave = playerSaves.remove(player.getName());
if (playerSave != null) {
playerSave.save();
}
}
public static boolean authenticatePacket(EnreplacedyPlayerMP sender, PacketCustom packet) {
switch(packet.getType()) {
case 1:
return canPlayerPerformAction(sender.getName(), "item");
case 4:
return canPlayerPerformAction(sender.getName(), "delete");
case 6:
return canPlayerPerformAction(sender.getName(), "magnet");
case 7:
return canPlayerPerformAction(sender.getName(), "time");
case 8:
return canPlayerPerformAction(sender.getName(), "heal");
case 9:
return canPlayerPerformAction(sender.getName(), "rain");
case 14:
case 23:
return canPlayerPerformAction(sender.getName(), "creative+");
case 21:
case 22:
return canPlayerPerformAction(sender.getName(), "enchant");
case 24:
return canPlayerPerformAction(sender.getName(), "potion");
}
return true;
}
}